1
0

EncryptionTest.php 13 KB

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