EncryptionTest.php 13 KB

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