storagesservicetest.php 16 KB

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