StoragesServiceTest.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. * @author Robin McCorkell <robin@mccorkell.me.uk>
  10. * @author Roeland Jago Douma <roeland@famdouma.nl>
  11. * @author Vincent Petry <vincent@nextcloud.com>
  12. *
  13. * @license AGPL-3.0
  14. *
  15. * This code is free software: you can redistribute it and/or modify
  16. * it under the terms of the GNU Affero General Public License, version 3,
  17. * as published by the Free Software Foundation.
  18. *
  19. * This program is distributed in the hope that it will be useful,
  20. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. * GNU Affero General Public License for more details.
  23. *
  24. * You should have received a copy of the GNU Affero General Public License, version 3,
  25. * along with this program. If not, see <http://www.gnu.org/licenses/>
  26. *
  27. */
  28. namespace OCA\Files_External\Tests\Service;
  29. use OC\Files\Filesystem;
  30. use OCA\Files_External\Lib\Auth\AuthMechanism;
  31. use OCA\Files_External\Lib\Auth\InvalidAuth;
  32. use OCA\Files_External\Lib\Backend\Backend;
  33. use OCA\Files_External\Lib\Backend\InvalidBackend;
  34. use OCA\Files_External\Lib\StorageConfig;
  35. use OCA\Files_External\NotFoundException;
  36. use OCA\Files_External\Service\BackendService;
  37. use OCA\Files_External\Service\DBConfigService;
  38. use OCA\Files_External\Service\StoragesService;
  39. use OCP\AppFramework\IAppContainer;
  40. use OCP\EventDispatcher\IEventDispatcher;
  41. use OCP\Files\Cache\ICache;
  42. use OCP\Files\Config\IUserMountCache;
  43. use OCP\Files\Mount\IMountPoint;
  44. use OCP\Files\Storage\IStorage;
  45. use OCP\IUser;
  46. class CleaningDBConfig extends DBConfigService {
  47. private $mountIds = [];
  48. public function addMount($mountPoint, $storageBackend, $authBackend, $priority, $type) {
  49. $id = parent::addMount($mountPoint, $storageBackend, $authBackend, $priority, $type); // TODO: Change the autogenerated stub
  50. $this->mountIds[] = $id;
  51. return $id;
  52. }
  53. public function clean() {
  54. foreach ($this->mountIds as $id) {
  55. $this->removeMount($id);
  56. }
  57. }
  58. }
  59. /**
  60. * @group DB
  61. */
  62. abstract class StoragesServiceTest extends \Test\TestCase {
  63. /**
  64. * @var StoragesService
  65. */
  66. protected $service;
  67. /** @var BackendService */
  68. protected $backendService;
  69. /**
  70. * Data directory
  71. *
  72. * @var string
  73. */
  74. protected $dataDir;
  75. /** @var CleaningDBConfig */
  76. protected $dbConfig;
  77. /**
  78. * Hook calls
  79. *
  80. * @var array
  81. */
  82. protected static $hookCalls;
  83. /**
  84. * @var \PHPUnit\Framework\MockObject\MockObject|\OCP\Files\Config\IUserMountCache
  85. */
  86. protected $mountCache;
  87. /**
  88. * @var \PHPUnit\Framework\MockObject\MockObject|IEventDispatcher
  89. */
  90. protected IEventDispatcher $eventDispatcher;
  91. protected function setUp(): void {
  92. parent::setUp();
  93. $this->dbConfig = new CleaningDBConfig(\OC::$server->getDatabaseConnection(), \OC::$server->getCrypto());
  94. self::$hookCalls = [];
  95. $config = \OC::$server->getConfig();
  96. $this->dataDir = $config->getSystemValue(
  97. 'datadirectory',
  98. \OC::$SERVERROOT . '/data/'
  99. );
  100. \OCA\Files_External\MountConfig::$skipTest = true;
  101. $this->mountCache = $this->createMock(IUserMountCache::class);
  102. $this->eventDispatcher = $this->createMock(IEventDispatcher::class);
  103. // prepare BackendService mock
  104. $this->backendService =
  105. $this->getMockBuilder('\OCA\Files_External\Service\BackendService')
  106. ->disableOriginalConstructor()
  107. ->getMock();
  108. $authMechanisms = [
  109. 'identifier:\Auth\Mechanism' => $this->getAuthMechMock('null', '\Auth\Mechanism'),
  110. 'identifier:\Other\Auth\Mechanism' => $this->getAuthMechMock('null', '\Other\Auth\Mechanism'),
  111. 'identifier:\OCA\Files_External\Lib\Auth\NullMechanism' => $this->getAuthMechMock(),
  112. ];
  113. $this->backendService->method('getAuthMechanism')
  114. ->willReturnCallback(function ($class) use ($authMechanisms) {
  115. if (isset($authMechanisms[$class])) {
  116. return $authMechanisms[$class];
  117. }
  118. return null;
  119. });
  120. $this->backendService->method('getAuthMechanismsByScheme')
  121. ->willReturnCallback(function ($schemes) use ($authMechanisms) {
  122. return array_filter($authMechanisms, function ($authMech) use ($schemes) {
  123. return in_array($authMech->getScheme(), $schemes, true);
  124. });
  125. });
  126. $this->backendService->method('getAuthMechanisms')
  127. ->willReturn($authMechanisms);
  128. $sftpBackend = $this->getBackendMock('\OCA\Files_External\Lib\Backend\SFTP', '\OCA\Files_External\Lib\Storage\SFTP');
  129. $backends = [
  130. 'identifier:\OCA\Files_External\Lib\Backend\DAV' => $this->getBackendMock('\OCA\Files_External\Lib\Backend\DAV', '\OC\Files\Storage\DAV'),
  131. 'identifier:\OCA\Files_External\Lib\Backend\SMB' => $this->getBackendMock('\OCA\Files_External\Lib\Backend\SMB', '\OCA\Files_External\Lib\Storage\SMB'),
  132. 'identifier:\OCA\Files_External\Lib\Backend\SFTP' => $sftpBackend,
  133. 'identifier:sftp_alias' => $sftpBackend,
  134. ];
  135. $backends['identifier:\OCA\Files_External\Lib\Backend\SFTP']->method('getLegacyAuthMechanism')
  136. ->willReturn($authMechanisms['identifier:\Other\Auth\Mechanism']);
  137. $this->backendService->method('getBackend')
  138. ->willReturnCallback(function ($backendClass) use ($backends) {
  139. if (isset($backends[$backendClass])) {
  140. return $backends[$backendClass];
  141. }
  142. return null;
  143. });
  144. $this->backendService->method('getBackends')
  145. ->willReturn($backends);
  146. $this->overwriteService(BackendService::class, $this->backendService);
  147. \OCP\Util::connectHook(
  148. Filesystem::CLASSNAME,
  149. Filesystem::signal_create_mount,
  150. get_class($this), 'createHookCallback');
  151. \OCP\Util::connectHook(
  152. Filesystem::CLASSNAME,
  153. Filesystem::signal_delete_mount,
  154. get_class($this), 'deleteHookCallback');
  155. $containerMock = $this->createMock(IAppContainer::class);
  156. $containerMock->method('query')
  157. ->willReturnCallback(function ($name) {
  158. if ($name === 'OCA\Files_External\Service\BackendService') {
  159. return $this->backendService;
  160. }
  161. });
  162. }
  163. protected function tearDown(): void {
  164. \OCA\Files_External\MountConfig::$skipTest = false;
  165. self::$hookCalls = [];
  166. if ($this->dbConfig) {
  167. $this->dbConfig->clean();
  168. }
  169. }
  170. protected function getBackendMock($class = '\OCA\Files_External\Lib\Backend\SMB', $storageClass = '\OCA\Files_External\Lib\Storage\SMB') {
  171. $backend = $this->getMockBuilder(Backend::class)
  172. ->disableOriginalConstructor()
  173. ->getMock();
  174. $backend->method('getStorageClass')
  175. ->willReturn($storageClass);
  176. $backend->method('getIdentifier')
  177. ->willReturn('identifier:' . $class);
  178. return $backend;
  179. }
  180. protected function getAuthMechMock($scheme = 'null', $class = '\OCA\Files_External\Lib\Auth\NullMechanism') {
  181. $authMech = $this->getMockBuilder(AuthMechanism::class)
  182. ->disableOriginalConstructor()
  183. ->getMock();
  184. $authMech->method('getScheme')
  185. ->willReturn($scheme);
  186. $authMech->method('getIdentifier')
  187. ->willReturn('identifier:' . $class);
  188. return $authMech;
  189. }
  190. /**
  191. * Creates a StorageConfig instance based on array data
  192. *
  193. * @param array $data
  194. *
  195. * @return StorageConfig storage config instance
  196. */
  197. protected function makeStorageConfig($data) {
  198. $storage = new StorageConfig();
  199. if (isset($data['id'])) {
  200. $storage->setId($data['id']);
  201. }
  202. $storage->setMountPoint($data['mountPoint']);
  203. if (!isset($data['backend'])) {
  204. // data providers are run before $this->backendService is initialised
  205. // so $data['backend'] can be specified directly
  206. $data['backend'] = $this->backendService->getBackend($data['backendIdentifier']);
  207. }
  208. if (!isset($data['backend'])) {
  209. throw new \Exception('oops, no backend');
  210. }
  211. if (!isset($data['authMechanism'])) {
  212. $data['authMechanism'] = $this->backendService->getAuthMechanism($data['authMechanismIdentifier']);
  213. }
  214. if (!isset($data['authMechanism'])) {
  215. throw new \Exception('oops, no auth mechanism');
  216. }
  217. $storage->setBackend($data['backend']);
  218. $storage->setAuthMechanism($data['authMechanism']);
  219. $storage->setBackendOptions($data['backendOptions']);
  220. if (isset($data['applicableUsers'])) {
  221. $storage->setApplicableUsers($data['applicableUsers']);
  222. }
  223. if (isset($data['applicableGroups'])) {
  224. $storage->setApplicableGroups($data['applicableGroups']);
  225. }
  226. if (isset($data['priority'])) {
  227. $storage->setPriority($data['priority']);
  228. }
  229. if (isset($data['mountOptions'])) {
  230. $storage->setMountOptions($data['mountOptions']);
  231. }
  232. return $storage;
  233. }
  234. protected function ActualNonExistingStorageTest() {
  235. $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
  236. $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism');
  237. $storage = new StorageConfig(255);
  238. $storage->setMountPoint('mountpoint');
  239. $storage->setBackend($backend);
  240. $storage->setAuthMechanism($authMechanism);
  241. $this->service->updateStorage($storage);
  242. }
  243. public function testNonExistingStorage() {
  244. $this->expectException(\OCA\Files_External\NotFoundException::class);
  245. $this->ActualNonExistingStorageTest();
  246. }
  247. public function deleteStorageDataProvider() {
  248. return [
  249. // regular case, can properly delete the oc_storages entry
  250. [
  251. [
  252. 'host' => 'example.com',
  253. 'user' => 'test',
  254. 'password' => 'testPassword',
  255. 'root' => 'someroot',
  256. ],
  257. 'webdav::test@example.com//someroot/'
  258. ],
  259. [
  260. [
  261. 'host' => 'example.com',
  262. 'user' => '$user',
  263. 'password' => 'testPassword',
  264. 'root' => 'someroot',
  265. ],
  266. 'webdav::someone@example.com//someroot/'
  267. ],
  268. ];
  269. }
  270. /**
  271. * @dataProvider deleteStorageDataProvider
  272. */
  273. public function testDeleteStorage($backendOptions, $rustyStorageId) {
  274. $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\DAV');
  275. $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism');
  276. $storage = new StorageConfig(255);
  277. $storage->setMountPoint('mountpoint');
  278. $storage->setBackend($backend);
  279. $storage->setAuthMechanism($authMechanism);
  280. $storage->setBackendOptions($backendOptions);
  281. $newStorage = $this->service->addStorage($storage);
  282. $id = $newStorage->getId();
  283. // manually trigger storage entry because normally it happens on first
  284. // access, which isn't possible within this test
  285. $storageCache = new \OC\Files\Cache\Storage($rustyStorageId);
  286. /** @var IUserMountCache $mountCache */
  287. $mountCache = \OC::$server->get(IUserMountCache::class);
  288. $mountCache->clear();
  289. $user = $this->createMock(IUser::class);
  290. $user->method('getUID')->willReturn('test');
  291. $cache = $this->createMock(ICache::class);
  292. $storage = $this->createMock(IStorage::class);
  293. $storage->method('getCache')->willReturn($cache);
  294. $mount = $this->createMock(IMountPoint::class);
  295. $mount->method('getStorage')
  296. ->willReturn($storage);
  297. $mount->method('getStorageId')
  298. ->willReturn($rustyStorageId);
  299. $mount->method('getNumericStorageId')
  300. ->willReturn($storageCache->getNumericId());
  301. $mount->method('getStorageRootId')
  302. ->willReturn(1);
  303. $mount->method('getMountPoint')
  304. ->willReturn('dummy');
  305. $mount->method('getMountId')
  306. ->willReturn($id);
  307. $mountCache->registerMounts($user, [
  308. $mount
  309. ]);
  310. // get numeric id for later check
  311. $numericId = $storageCache->getNumericId();
  312. $this->service->removeStorage($id);
  313. $caught = false;
  314. try {
  315. $this->service->getStorage(1);
  316. } catch (NotFoundException $e) {
  317. $caught = true;
  318. }
  319. $this->assertTrue($caught);
  320. // storage id was removed from oc_storages
  321. $qb = \OC::$server->getDatabaseConnection()->getQueryBuilder();
  322. $storageCheckQuery = $qb->select('*')
  323. ->from('storages')
  324. ->where($qb->expr()->eq('numeric_id', $qb->expr()->literal($numericId)));
  325. $result = $storageCheckQuery->execute();
  326. $storages = $result->fetchAll();
  327. $result->closeCursor();
  328. $this->assertCount(0, $storages, "expected 0 storages, got " . json_encode($storages));
  329. }
  330. protected function actualDeletedUnexistingStorageTest() {
  331. $this->service->removeStorage(255);
  332. }
  333. public function testDeleteUnexistingStorage() {
  334. $this->expectException(\OCA\Files_External\NotFoundException::class);
  335. $this->actualDeletedUnexistingStorageTest();
  336. }
  337. public function testCreateStorage() {
  338. $mountPoint = 'mount';
  339. $backendIdentifier = 'identifier:\OCA\Files_External\Lib\Backend\SMB';
  340. $authMechanismIdentifier = 'identifier:\Auth\Mechanism';
  341. $backendOptions = ['param' => 'foo', 'param2' => 'bar'];
  342. $mountOptions = ['option' => 'foobar'];
  343. $applicableUsers = ['user1', 'user2'];
  344. $applicableGroups = ['group'];
  345. $priority = 123;
  346. $backend = $this->backendService->getBackend($backendIdentifier);
  347. $authMechanism = $this->backendService->getAuthMechanism($authMechanismIdentifier);
  348. $storage = $this->service->createStorage(
  349. $mountPoint,
  350. $backendIdentifier,
  351. $authMechanismIdentifier,
  352. $backendOptions,
  353. $mountOptions,
  354. $applicableUsers,
  355. $applicableGroups,
  356. $priority
  357. );
  358. $this->assertEquals('/' . $mountPoint, $storage->getMountPoint());
  359. $this->assertEquals($backend, $storage->getBackend());
  360. $this->assertEquals($authMechanism, $storage->getAuthMechanism());
  361. $this->assertEquals($backendOptions, $storage->getBackendOptions());
  362. $this->assertEquals($mountOptions, $storage->getMountOptions());
  363. $this->assertEquals($applicableUsers, $storage->getApplicableUsers());
  364. $this->assertEquals($applicableGroups, $storage->getApplicableGroups());
  365. $this->assertEquals($priority, $storage->getPriority());
  366. }
  367. public function testCreateStorageInvalidClass() {
  368. $storage = $this->service->createStorage(
  369. 'mount',
  370. 'identifier:\OC\Not\A\Backend',
  371. 'identifier:\Auth\Mechanism',
  372. []
  373. );
  374. $this->assertInstanceOf(InvalidBackend::class, $storage->getBackend());
  375. }
  376. public function testCreateStorageInvalidAuthMechanismClass() {
  377. $storage = $this->service->createStorage(
  378. 'mount',
  379. 'identifier:\OCA\Files_External\Lib\Backend\SMB',
  380. 'identifier:\Not\An\Auth\Mechanism',
  381. []
  382. );
  383. $this->assertInstanceOf(InvalidAuth::class, $storage->getAuthMechanism());
  384. }
  385. public function testGetStoragesBackendNotVisible() {
  386. $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
  387. $backend->expects($this->once())
  388. ->method('isVisibleFor')
  389. ->with($this->service->getVisibilityType())
  390. ->willReturn(false);
  391. $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism');
  392. $authMechanism->method('isVisibleFor')
  393. ->with($this->service->getVisibilityType())
  394. ->willReturn(true);
  395. $storage = new StorageConfig(255);
  396. $storage->setMountPoint('mountpoint');
  397. $storage->setBackend($backend);
  398. $storage->setAuthMechanism($authMechanism);
  399. $storage->setBackendOptions(['password' => 'testPassword']);
  400. $newStorage = $this->service->addStorage($storage);
  401. $this->assertCount(1, $this->service->getAllStorages());
  402. $this->assertEmpty($this->service->getStorages());
  403. }
  404. public function testGetStoragesAuthMechanismNotVisible() {
  405. $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
  406. $backend->method('isVisibleFor')
  407. ->with($this->service->getVisibilityType())
  408. ->willReturn(true);
  409. $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism');
  410. $authMechanism->expects($this->once())
  411. ->method('isVisibleFor')
  412. ->with($this->service->getVisibilityType())
  413. ->willReturn(false);
  414. $storage = new StorageConfig(255);
  415. $storage->setMountPoint('mountpoint');
  416. $storage->setBackend($backend);
  417. $storage->setAuthMechanism($authMechanism);
  418. $storage->setBackendOptions(['password' => 'testPassword']);
  419. $newStorage = $this->service->addStorage($storage);
  420. $this->assertCount(1, $this->service->getAllStorages());
  421. $this->assertEmpty($this->service->getStorages());
  422. }
  423. public static function createHookCallback($params) {
  424. self::$hookCalls[] = [
  425. 'signal' => Filesystem::signal_create_mount,
  426. 'params' => $params
  427. ];
  428. }
  429. public static function deleteHookCallback($params) {
  430. self::$hookCalls[] = [
  431. 'signal' => Filesystem::signal_delete_mount,
  432. 'params' => $params
  433. ];
  434. }
  435. /**
  436. * Asserts hook call
  437. *
  438. * @param array $callData hook call data to check
  439. * @param string $signal signal name
  440. * @param string $mountPath mount path
  441. * @param string $mountType mount type
  442. * @param string $applicable applicable users
  443. */
  444. protected function assertHookCall($callData, $signal, $mountPath, $mountType, $applicable) {
  445. $this->assertEquals($signal, $callData['signal']);
  446. $params = $callData['params'];
  447. $this->assertEquals(
  448. $mountPath,
  449. $params[Filesystem::signal_param_path]
  450. );
  451. $this->assertEquals(
  452. $mountType,
  453. $params[Filesystem::signal_param_mount_type]
  454. );
  455. $this->assertEquals(
  456. $applicable,
  457. $params[Filesystem::signal_param_users]
  458. );
  459. }
  460. public function testUpdateStorageMountPoint() {
  461. $backend = $this->backendService->getBackend('identifier:\OCA\Files_External\Lib\Backend\SMB');
  462. $authMechanism = $this->backendService->getAuthMechanism('identifier:\Auth\Mechanism');
  463. $storage = new StorageConfig();
  464. $storage->setMountPoint('mountpoint');
  465. $storage->setBackend($backend);
  466. $storage->setAuthMechanism($authMechanism);
  467. $storage->setBackendOptions(['password' => 'testPassword']);
  468. $savedStorage = $this->service->addStorage($storage);
  469. $newAuthMechanism = $this->backendService->getAuthMechanism('identifier:\Other\Auth\Mechanism');
  470. $updatedStorage = new StorageConfig($savedStorage->getId());
  471. $updatedStorage->setMountPoint('mountpoint2');
  472. $updatedStorage->setBackend($backend);
  473. $updatedStorage->setAuthMechanism($newAuthMechanism);
  474. $updatedStorage->setBackendOptions(['password' => 'password2']);
  475. $this->service->updateStorage($updatedStorage);
  476. $savedStorage = $this->service->getStorage($updatedStorage->getId());
  477. $this->assertEquals('/mountpoint2', $savedStorage->getMountPoint());
  478. $this->assertEquals($newAuthMechanism, $savedStorage->getAuthMechanism());
  479. $this->assertEquals('password2', $savedStorage->getBackendOption('password'));
  480. }
  481. }