EncryptionTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OCA\Encryption\Tests\Crypto;
  27. use OCA\Encryption\Crypto\Crypt;
  28. use OCA\Encryption\Crypto\DecryptAll;
  29. use OCA\Encryption\Crypto\EncryptAll;
  30. use OCA\Encryption\Exceptions\PublicKeyMissingException;
  31. use OCA\Encryption\KeyManager;
  32. use OCA\Encryption\Session;
  33. use OCA\Encryption\Util;
  34. use OCP\Files\Storage;
  35. use OCP\IL10N;
  36. use OCP\ILogger;
  37. use Symfony\Component\Console\Input\InputInterface;
  38. use Symfony\Component\Console\Output\OutputInterface;
  39. use Test\TestCase;
  40. use OCA\Encryption\Crypto\Encryption;
  41. class EncryptionTest extends TestCase {
  42. /** @var Encryption */
  43. private $instance;
  44. /** @var \OCA\Encryption\KeyManager|\PHPUnit_Framework_MockObject_MockObject */
  45. private $keyManagerMock;
  46. /** @var \OCA\Encryption\Crypto\EncryptAll|\PHPUnit_Framework_MockObject_MockObject */
  47. private $encryptAllMock;
  48. /** @var \OCA\Encryption\Crypto\DecryptAll|\PHPUnit_Framework_MockObject_MockObject */
  49. private $decryptAllMock;
  50. /** @var \OCA\Encryption\Session|\PHPUnit_Framework_MockObject_MockObject */
  51. private $sessionMock;
  52. /** @var \OCA\Encryption\Crypto\Crypt|\PHPUnit_Framework_MockObject_MockObject */
  53. private $cryptMock;
  54. /** @var \OCA\Encryption\Util|\PHPUnit_Framework_MockObject_MockObject */
  55. private $utilMock;
  56. /** @var \OCP\ILogger|\PHPUnit_Framework_MockObject_MockObject */
  57. private $loggerMock;
  58. /** @var \OCP\IL10N|\PHPUnit_Framework_MockObject_MockObject */
  59. private $l10nMock;
  60. /** @var \OCP\Files\Storage|\PHPUnit_Framework_MockObject_MockObject */
  61. private $storageMock;
  62. public function setUp() {
  63. parent::setUp();
  64. $this->storageMock = $this->getMockBuilder(Storage::class)
  65. ->disableOriginalConstructor()->getMock();
  66. $this->cryptMock = $this->getMockBuilder(Crypt::class)
  67. ->disableOriginalConstructor()
  68. ->getMock();
  69. $this->utilMock = $this->getMockBuilder(Util::class)
  70. ->disableOriginalConstructor()
  71. ->getMock();
  72. $this->keyManagerMock = $this->getMockBuilder(KeyManager::class)
  73. ->disableOriginalConstructor()
  74. ->getMock();
  75. $this->sessionMock = $this->getMockBuilder(Session::class)
  76. ->disableOriginalConstructor()
  77. ->getMock();
  78. $this->encryptAllMock = $this->getMockBuilder(EncryptAll::class)
  79. ->disableOriginalConstructor()
  80. ->getMock();
  81. $this->decryptAllMock = $this->getMockBuilder(DecryptAll::class)
  82. ->disableOriginalConstructor()
  83. ->getMock();
  84. $this->loggerMock = $this->getMockBuilder(ILogger::class)
  85. ->disableOriginalConstructor()
  86. ->getMock();
  87. $this->l10nMock = $this->getMockBuilder(IL10N::class)
  88. ->disableOriginalConstructor()
  89. ->getMock();
  90. $this->l10nMock->expects($this->any())
  91. ->method('t')
  92. ->with($this->anything())
  93. ->willReturnArgument(0);
  94. $this->instance = new Encryption(
  95. $this->cryptMock,
  96. $this->keyManagerMock,
  97. $this->utilMock,
  98. $this->sessionMock,
  99. $this->encryptAllMock,
  100. $this->decryptAllMock,
  101. $this->loggerMock,
  102. $this->l10nMock
  103. );
  104. }
  105. /**
  106. * test if public key from one of the recipients is missing
  107. */
  108. public function testEndUser1() {
  109. $this->instance->begin('/foo/bar', 'user1', 'r', array(), array('users' => array('user1', 'user2', 'user3')));
  110. $this->endTest();
  111. }
  112. /**
  113. * test if public key from owner is missing
  114. *
  115. * @expectedException \OCA\Encryption\Exceptions\PublicKeyMissingException
  116. */
  117. public function testEndUser2() {
  118. $this->instance->begin('/foo/bar', 'user2', 'r', array(), array('users' => array('user1', 'user2', 'user3')));
  119. $this->endTest();
  120. }
  121. /**
  122. * common part of testEndUser1 and testEndUser2
  123. *
  124. * @throws PublicKeyMissingException
  125. */
  126. public function endTest() {
  127. // prepare internal variables
  128. self::invokePrivate($this->instance, 'isWriteOperation', [true]);
  129. self::invokePrivate($this->instance, 'writeCache', ['']);
  130. $this->keyManagerMock->expects($this->any())
  131. ->method('getPublicKey')
  132. ->will($this->returnCallback([$this, 'getPublicKeyCallback']));
  133. $this->keyManagerMock->expects($this->any())
  134. ->method('addSystemKeys')
  135. ->will($this->returnCallback([$this, 'addSystemKeysCallback']));
  136. $this->cryptMock->expects($this->any())
  137. ->method('multiKeyEncrypt')
  138. ->willReturn(true);
  139. $this->instance->end('/foo/bar');
  140. }
  141. public function getPublicKeyCallback($uid) {
  142. if ($uid === 'user2') {
  143. throw new PublicKeyMissingException($uid);
  144. }
  145. return $uid;
  146. }
  147. public function addSystemKeysCallback($accessList, $publicKeys) {
  148. $this->assertSame(2, count($publicKeys));
  149. $this->assertArrayHasKey('user1', $publicKeys);
  150. $this->assertArrayHasKey('user3', $publicKeys);
  151. return $publicKeys;
  152. }
  153. /**
  154. * @dataProvider dataProviderForTestGetPathToRealFile
  155. */
  156. public function testGetPathToRealFile($path, $expected) {
  157. $this->assertSame($expected,
  158. self::invokePrivate($this->instance, 'getPathToRealFile', array($path))
  159. );
  160. }
  161. public function dataProviderForTestGetPathToRealFile() {
  162. return array(
  163. array('/user/files/foo/bar.txt', '/user/files/foo/bar.txt'),
  164. array('/user/files/foo.txt', '/user/files/foo.txt'),
  165. array('/user/files_versions/foo.txt.v543534', '/user/files/foo.txt'),
  166. array('/user/files_versions/foo/bar.txt.v5454', '/user/files/foo/bar.txt'),
  167. );
  168. }
  169. /**
  170. * @dataProvider dataTestBegin
  171. */
  172. public function testBegin($mode, $header, $legacyCipher, $defaultCipher, $fileKey, $expected) {
  173. $this->sessionMock->expects($this->once())
  174. ->method('decryptAllModeActivated')
  175. ->willReturn(false);
  176. $this->sessionMock->expects($this->never())->method('getDecryptAllUid');
  177. $this->sessionMock->expects($this->never())->method('getDecryptAllKey');
  178. $this->keyManagerMock->expects($this->never())->method('getEncryptedFileKey');
  179. $this->keyManagerMock->expects($this->never())->method('getShareKey');
  180. $this->cryptMock->expects($this->never())->method('multiKeyDecrypt');
  181. $this->cryptMock->expects($this->any())
  182. ->method('getCipher')
  183. ->willReturn($defaultCipher);
  184. $this->cryptMock->expects($this->any())
  185. ->method('getLegacyCipher')
  186. ->willReturn($legacyCipher);
  187. if (empty($fileKey)) {
  188. $this->cryptMock->expects($this->once())
  189. ->method('generateFileKey')
  190. ->willReturn('fileKey');
  191. } else {
  192. $this->cryptMock->expects($this->never())
  193. ->method('generateFileKey');
  194. }
  195. $this->keyManagerMock->expects($this->once())
  196. ->method('getFileKey')
  197. ->willReturn($fileKey);
  198. $result = $this->instance->begin('/user/files/foo.txt', 'user', $mode, $header, []);
  199. $this->assertArrayHasKey('cipher', $result);
  200. $this->assertSame($expected, $result['cipher']);
  201. if ($mode === 'w') {
  202. $this->assertTrue(self::invokePrivate($this->instance, 'isWriteOperation'));
  203. } else {
  204. $this->assertFalse(self::invokePrivate($this->instance, 'isWriteOperation'));
  205. }
  206. }
  207. public function dataTestBegin() {
  208. return array(
  209. array('w', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'defaultCipher'),
  210. array('r', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'myCipher'),
  211. array('w', [], 'legacyCipher', 'defaultCipher', '', 'defaultCipher'),
  212. array('r', [], 'legacyCipher', 'defaultCipher', 'file_key', 'legacyCipher'),
  213. );
  214. }
  215. /**
  216. * test begin() if decryptAll mode was activated
  217. */
  218. public function testBeginDecryptAll() {
  219. $path = '/user/files/foo.txt';
  220. $recoveryKeyId = 'recoveryKeyId';
  221. $recoveryShareKey = 'recoveryShareKey';
  222. $decryptAllKey = 'decryptAllKey';
  223. $fileKey = 'fileKey';
  224. $this->sessionMock->expects($this->once())
  225. ->method('decryptAllModeActivated')
  226. ->willReturn(true);
  227. $this->sessionMock->expects($this->once())
  228. ->method('getDecryptAllUid')
  229. ->willReturn($recoveryKeyId);
  230. $this->sessionMock->expects($this->once())
  231. ->method('getDecryptAllKey')
  232. ->willReturn($decryptAllKey);
  233. $this->keyManagerMock->expects($this->once())
  234. ->method('getEncryptedFileKey')
  235. ->willReturn('encryptedFileKey');
  236. $this->keyManagerMock->expects($this->once())
  237. ->method('getShareKey')
  238. ->with($path, $recoveryKeyId)
  239. ->willReturn($recoveryShareKey);
  240. $this->cryptMock->expects($this->once())
  241. ->method('multiKeyDecrypt')
  242. ->with('encryptedFileKey', $recoveryShareKey, $decryptAllKey)
  243. ->willReturn($fileKey);
  244. $this->keyManagerMock->expects($this->never())->method('getFileKey');
  245. $this->instance->begin($path, 'user', 'r', [], []);
  246. $this->assertSame($fileKey,
  247. $this->invokePrivate($this->instance, 'fileKey')
  248. );
  249. }
  250. /**
  251. * test begin() if encryption is not initialized but the master key is enabled
  252. * in this case we can initialize the encryption without a username/password
  253. * and continue
  254. */
  255. public function testBeginInitMasterKey() {
  256. $this->sessionMock->expects($this->once())->method('isReady')->willReturn(false);
  257. $this->utilMock->expects($this->once())->method('isMasterKeyEnabled')
  258. ->willReturn(true);
  259. $this->keyManagerMock->expects($this->once())->method('init')->with('', '');
  260. $this->instance->begin('/user/files/welcome.txt', 'user', 'r', [], []);
  261. }
  262. /**
  263. * @dataProvider dataTestUpdate
  264. *
  265. * @param string $fileKey
  266. * @param boolean $expected
  267. */
  268. public function testUpdate($fileKey, $expected) {
  269. $this->keyManagerMock->expects($this->once())
  270. ->method('getFileKey')->willReturn($fileKey);
  271. $this->keyManagerMock->expects($this->any())
  272. ->method('getPublicKey')->willReturn('publicKey');
  273. $this->keyManagerMock->expects($this->any())
  274. ->method('addSystemKeys')
  275. ->willReturnCallback(function($accessList, $publicKeys) {
  276. return $publicKeys;
  277. });
  278. $this->keyManagerMock->expects($this->never())->method('getVersion');
  279. $this->keyManagerMock->expects($this->never())->method('setVersion');
  280. $this->assertSame($expected,
  281. $this->instance->update('path', 'user1', ['users' => ['user1']])
  282. );
  283. }
  284. public function dataTestUpdate() {
  285. return array(
  286. array('', false),
  287. array('fileKey', true)
  288. );
  289. }
  290. public function testUpdateNoUsers() {
  291. $this->invokePrivate($this->instance, 'rememberVersion', [['path' => 2]]);
  292. $this->keyManagerMock->expects($this->never())->method('getFileKey');
  293. $this->keyManagerMock->expects($this->never())->method('getPublicKey');
  294. $this->keyManagerMock->expects($this->never())->method('addSystemKeys');
  295. $this->keyManagerMock->expects($this->once())->method('setVersion')
  296. ->willReturnCallback(function($path, $version, $view) {
  297. $this->assertSame('path', $path);
  298. $this->assertSame(2, $version);
  299. $this->assertTrue($view instanceof \OC\Files\View);
  300. });
  301. $this->instance->update('path', 'user1', []);
  302. }
  303. /**
  304. * Test case if the public key is missing. Nextcloud should still encrypt
  305. * the file for the remaining users
  306. */
  307. public function testUpdateMissingPublicKey() {
  308. $this->keyManagerMock->expects($this->once())
  309. ->method('getFileKey')->willReturn('fileKey');
  310. $this->keyManagerMock->expects($this->any())
  311. ->method('getPublicKey')->willReturnCallback(
  312. function($user) {
  313. throw new PublicKeyMissingException($user);
  314. }
  315. );
  316. $this->keyManagerMock->expects($this->any())
  317. ->method('addSystemKeys')
  318. ->willReturnCallback(function($accessList, $publicKeys) {
  319. return $publicKeys;
  320. });
  321. $this->cryptMock->expects($this->once())->method('multiKeyEncrypt')
  322. ->willReturnCallback(
  323. function($fileKey, $publicKeys) {
  324. $this->assertEmpty($publicKeys);
  325. $this->assertSame('fileKey', $fileKey);
  326. }
  327. );
  328. $this->keyManagerMock->expects($this->never())->method('getVersion');
  329. $this->keyManagerMock->expects($this->never())->method('setVersion');
  330. $this->assertTrue(
  331. $this->instance->update('path', 'user1', ['users' => ['user1']])
  332. );
  333. }
  334. /**
  335. * by default the encryption module should encrypt regular files, files in
  336. * files_versions and files in files_trashbin
  337. *
  338. * @dataProvider dataTestShouldEncrypt
  339. */
  340. public function testShouldEncrypt($path, $shouldEncryptHomeStorage, $isHomeStorage, $expected) {
  341. $this->utilMock->expects($this->once())->method('shouldEncryptHomeStorage')
  342. ->willReturn($shouldEncryptHomeStorage);
  343. if ($shouldEncryptHomeStorage === false) {
  344. $this->storageMock->expects($this->once())->method('instanceOfStorage')
  345. ->with('\OCP\Files\IHomeStorage')->willReturn($isHomeStorage);
  346. $this->utilMock->expects($this->once())->method('getStorage')->with($path)
  347. ->willReturn($this->storageMock);
  348. }
  349. $this->assertSame($expected,
  350. $this->instance->shouldEncrypt($path)
  351. );
  352. }
  353. public function dataTestShouldEncrypt() {
  354. return array(
  355. array('/user1/files/foo.txt', true, true, true),
  356. array('/user1/files_versions/foo.txt', true, true, true),
  357. array('/user1/files_trashbin/foo.txt', true, true, true),
  358. array('/user1/some_folder/foo.txt', true, true, false),
  359. array('/user1/foo.txt', true, true, false),
  360. array('/user1/files', true, true, false),
  361. array('/user1/files_trashbin', true, true, false),
  362. array('/user1/files_versions', true, true, false),
  363. // test if shouldEncryptHomeStorage is set to false
  364. array('/user1/files/foo.txt', false, true, false),
  365. array('/user1/files_versions/foo.txt', false, false, true),
  366. );
  367. }
  368. /**
  369. * @expectedException \OC\Encryption\Exceptions\DecryptionFailedException
  370. * @expectedExceptionMessage Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.
  371. */
  372. public function testDecrypt() {
  373. $this->instance->decrypt('abc');
  374. }
  375. public function testPrepareDecryptAll() {
  376. /** @var \Symfony\Component\Console\Input\InputInterface $input */
  377. $input = $this->createMock(InputInterface::class);
  378. /** @var \Symfony\Component\Console\Output\OutputInterface $output */
  379. $output = $this->createMock(OutputInterface::class);
  380. $this->decryptAllMock->expects($this->once())->method('prepare')
  381. ->with($input, $output, 'user');
  382. $this->instance->prepareDecryptAll($input, $output, 'user');
  383. }
  384. }