StoragesServiceTest.php 17 KB

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