StoragesServiceTest.php 17 KB

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