EncryptionTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. namespace Test\Files\Stream;
  3. use OC\Files\Cache\CacheEntry;
  4. use OC\Files\View;
  5. use OC\Memcache\ArrayCache;
  6. use OCP\Files\Cache\ICache;
  7. use OCP\IConfig;
  8. class EncryptionTest extends \Test\TestCase {
  9. /** @var \OCP\Encryption\IEncryptionModule | \PHPUnit_Framework_MockObject_MockObject */
  10. private $encryptionModule;
  11. /**
  12. * @param string $fileName
  13. * @param string $mode
  14. * @param integer $unencryptedSize
  15. * @return resource
  16. */
  17. protected function getStream($fileName, $mode, $unencryptedSize, $wrapper = '\OC\Files\Stream\Encryption') {
  18. clearstatcache();
  19. $size = filesize($fileName);
  20. $source = fopen($fileName, $mode);
  21. $internalPath = $fileName;
  22. $fullPath = $fileName;
  23. $header = [];
  24. $uid = '';
  25. $this->encryptionModule = $this->buildMockModule();
  26. $cache = $this->createMock(ICache::class);
  27. $storage = $this->getMockBuilder('\OC\Files\Storage\Storage')
  28. ->disableOriginalConstructor()->getMock();
  29. $encStorage = $this->getMockBuilder('\OC\Files\Storage\Wrapper\Encryption')
  30. ->disableOriginalConstructor()->getMock();
  31. $config = $this->getMockBuilder(IConfig::class)
  32. ->disableOriginalConstructor()
  33. ->getMock();
  34. $arrayCache = $this->createMock(ArrayCache::class);
  35. $groupManager = $this->getMockBuilder('\OC\Group\Manager')
  36. ->disableOriginalConstructor()
  37. ->getMock();
  38. $file = $this->getMockBuilder('\OC\Encryption\File')
  39. ->disableOriginalConstructor()
  40. ->setMethods(['getAccessList'])
  41. ->getMock();
  42. $file->expects($this->any())->method('getAccessList')->willReturn([]);
  43. $util = $this->getMockBuilder('\OC\Encryption\Util')
  44. ->setMethods(['getUidAndFilename'])
  45. ->setConstructorArgs([new View(), new \OC\User\Manager($config), $groupManager, $config, $arrayCache])
  46. ->getMock();
  47. $util->expects($this->any())
  48. ->method('getUidAndFilename')
  49. ->willReturn(['user1', $internalPath]);
  50. $storage->expects($this->any())->method('getCache')->willReturn($cache);
  51. $entry = new CacheEntry([
  52. 'fileid' => 5,
  53. 'encryptedVersion' => 2,
  54. ]);
  55. $cache->expects($this->any())->method('get')->willReturn($entry );
  56. $cache->expects($this->any())->method('update')->with(5, ['encrypted' => 3, 'encryptedVersion' => 3]);
  57. return $wrapper::wrap($source, $internalPath,
  58. $fullPath, $header, $uid, $this->encryptionModule, $storage, $encStorage,
  59. $util, $file, $mode, $size, $unencryptedSize, 8192, $wrapper);
  60. }
  61. /**
  62. * @dataProvider dataProviderStreamOpen()
  63. */
  64. public function testStreamOpen($isMasterKeyUsed,
  65. $mode,
  66. $fullPath,
  67. $fileExists,
  68. $expectedSharePath,
  69. $expectedSize,
  70. $expectedUnencryptedSize,
  71. $expectedReadOnly) {
  72. // build mocks
  73. $encryptionModuleMock = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
  74. ->disableOriginalConstructor()->getMock();
  75. $encryptionModuleMock->expects($this->any())->method('needDetailedAccessList')->willReturn(!$isMasterKeyUsed);
  76. $encryptionModuleMock->expects($this->once())
  77. ->method('getUnencryptedBlockSize')->willReturn(99);
  78. $encryptionModuleMock->expects($this->once())
  79. ->method('begin')->willReturn(true);
  80. $storageMock = $this->getMockBuilder('\OC\Files\Storage\Storage')
  81. ->disableOriginalConstructor()->getMock();
  82. $storageMock->expects($this->once())->method('file_exists')->willReturn($fileExists);
  83. $fileMock = $this->getMockBuilder('\OC\Encryption\File')
  84. ->disableOriginalConstructor()->getMock();
  85. if ($isMasterKeyUsed) {
  86. $fileMock->expects($this->never())->method('getAccessList');
  87. } else {
  88. $fileMock->expects($this->once())->method('getAccessList')
  89. ->will($this->returnCallback(function ($sharePath) use ($expectedSharePath) {
  90. $this->assertSame($expectedSharePath, $sharePath);
  91. return array();
  92. }));
  93. }
  94. $utilMock = $this->getMockBuilder('\OC\Encryption\Util')
  95. ->disableOriginalConstructor()->getMock();
  96. $utilMock->expects($this->any())
  97. ->method('getHeaderSize')
  98. ->willReturn(8192);
  99. // get a instance of the stream wrapper
  100. $streamWrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption')
  101. ->setMethods(['loadContext', 'writeHeader', 'skipHeader'])->disableOriginalConstructor()->getMock();
  102. // set internal properties of the stream wrapper
  103. $stream = new \ReflectionClass('\OC\Files\Stream\Encryption');
  104. $encryptionModule = $stream->getProperty('encryptionModule');
  105. $encryptionModule->setAccessible(true);
  106. $encryptionModule->setValue($streamWrapper, $encryptionModuleMock);
  107. $encryptionModule->setAccessible(false);
  108. $storage = $stream->getProperty('storage');
  109. $storage->setAccessible(true);
  110. $storage->setValue($streamWrapper, $storageMock);
  111. $storage->setAccessible(false);
  112. $file = $stream->getProperty('file');
  113. $file->setAccessible(true);
  114. $file->setValue($streamWrapper, $fileMock);
  115. $file->setAccessible(false);
  116. $util = $stream->getProperty('util');
  117. $util->setAccessible(true);
  118. $util->setValue($streamWrapper, $utilMock);
  119. $util->setAccessible(false);
  120. $fullPathP = $stream->getProperty('fullPath');
  121. $fullPathP->setAccessible(true);
  122. $fullPathP->setValue($streamWrapper, $fullPath);
  123. $fullPathP->setAccessible(false);
  124. $header = $stream->getProperty('header');
  125. $header->setAccessible(true);
  126. $header->setValue($streamWrapper, array());
  127. $header->setAccessible(false);
  128. $this->invokePrivate($streamWrapper, 'signed', [true]);
  129. // call stream_open, that's the method we want to test
  130. $dummyVar = 'foo';
  131. $streamWrapper->stream_open('', $mode, '', $dummyVar);
  132. // check internal properties
  133. $size = $stream->getProperty('size');
  134. $size->setAccessible(true);
  135. $this->assertSame($expectedSize,
  136. $size->getValue($streamWrapper)
  137. );
  138. $size->setAccessible(false);
  139. $unencryptedSize = $stream->getProperty('unencryptedSize');
  140. $unencryptedSize->setAccessible(true);
  141. $this->assertSame($expectedUnencryptedSize,
  142. $unencryptedSize->getValue($streamWrapper)
  143. );
  144. $unencryptedSize->setAccessible(false);
  145. $readOnly = $stream->getProperty('readOnly');
  146. $readOnly->setAccessible(true);
  147. $this->assertSame($expectedReadOnly,
  148. $readOnly->getValue($streamWrapper)
  149. );
  150. $readOnly->setAccessible(false);
  151. }
  152. public function dataProviderStreamOpen() {
  153. return [
  154. [false, 'r', '/foo/bar/test.txt', true, '/foo/bar/test.txt', null, null, true],
  155. [false, 'r', '/foo/bar/test.txt', false, '/foo/bar', null, null, true],
  156. [false, 'w', '/foo/bar/test.txt', true, '/foo/bar/test.txt', 8192, 0, false],
  157. [true, 'r', '/foo/bar/test.txt', true, '/foo/bar/test.txt', null, null, true],
  158. [true, 'r', '/foo/bar/test.txt', false, '/foo/bar', null, null, true],
  159. [true, 'w', '/foo/bar/test.txt', true, '/foo/bar/test.txt', 8192, 0, false],
  160. ];
  161. }
  162. public function testWriteRead() {
  163. $fileName = tempnam("/tmp", "FOO");
  164. $stream = $this->getStream($fileName, 'w+', 0);
  165. $this->assertEquals(6, fwrite($stream, 'foobar'));
  166. fclose($stream);
  167. $stream = $this->getStream($fileName, 'r', 6);
  168. $this->assertEquals('foobar', fread($stream, 100));
  169. fclose($stream);
  170. $stream = $this->getStream($fileName, 'r+', 6);
  171. $this->assertEquals(3, fwrite($stream, 'bar'));
  172. fclose($stream);
  173. $stream = $this->getStream($fileName, 'r', 6);
  174. $this->assertEquals('barbar', fread($stream, 100));
  175. fclose($stream);
  176. unlink($fileName);
  177. }
  178. public function testRewind() {
  179. $fileName = tempnam("/tmp", "FOO");
  180. $stream = $this->getStream($fileName, 'w+', 0);
  181. $this->assertEquals(6, fwrite($stream, 'foobar'));
  182. $this->assertEquals(TRUE, rewind($stream));
  183. $this->assertEquals('foobar', fread($stream, 100));
  184. $this->assertEquals(TRUE, rewind($stream));
  185. $this->assertEquals(3, fwrite($stream, 'bar'));
  186. fclose($stream);
  187. $stream = $this->getStream($fileName, 'r', 6);
  188. $this->assertEquals('barbar', fread($stream, 100));
  189. fclose($stream);
  190. unlink($fileName);
  191. }
  192. public function testSeek() {
  193. $fileName = tempnam("/tmp", "FOO");
  194. $stream = $this->getStream($fileName, 'w+', 0);
  195. $this->assertEquals(6, fwrite($stream, 'foobar'));
  196. $this->assertEquals(0, fseek($stream, 3));
  197. $this->assertEquals(6, fwrite($stream, 'foobar'));
  198. fclose($stream);
  199. $stream = $this->getStream($fileName, 'r', 9);
  200. $this->assertEquals('foofoobar', fread($stream, 100));
  201. $this->assertEquals(-1, fseek($stream, 10));
  202. $this->assertEquals(0, fseek($stream, 9));
  203. $this->assertEquals(-1, fseek($stream, -10, SEEK_CUR));
  204. $this->assertEquals(0, fseek($stream, -9, SEEK_CUR));
  205. $this->assertEquals(-1, fseek($stream, -10, SEEK_END));
  206. $this->assertEquals(0, fseek($stream, -9, SEEK_END));
  207. fclose($stream);
  208. unlink($fileName);
  209. }
  210. function dataFilesProvider() {
  211. return [
  212. ['lorem-big.txt'],
  213. ['block-aligned.txt'],
  214. ['block-aligned-plus-one.txt'],
  215. ];
  216. }
  217. /**
  218. * @dataProvider dataFilesProvider
  219. */
  220. public function testWriteReadBigFile($testFile) {
  221. $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
  222. // write it
  223. $fileName = tempnam("/tmp", "FOO");
  224. $stream = $this->getStream($fileName, 'w+', 0);
  225. // while writing the file from the beginning to the end we should never try
  226. // to read parts of the file. This should only happen for write operations
  227. // in the middle of a file
  228. $this->encryptionModule->expects($this->never())->method('decrypt');
  229. fwrite($stream, $expectedData);
  230. fclose($stream);
  231. // read it all
  232. $stream = $this->getStream($fileName, 'r', strlen($expectedData));
  233. $data = stream_get_contents($stream);
  234. fclose($stream);
  235. $this->assertEquals($expectedData, $data);
  236. // another read test with a loop like we do in several places:
  237. $stream = $this->getStream($fileName, 'r', strlen($expectedData));
  238. $data = '';
  239. while (!feof($stream)) {
  240. $data .= fread($stream, 8192);
  241. }
  242. fclose($stream);
  243. $this->assertEquals($expectedData, $data);
  244. unlink($fileName);
  245. }
  246. /**
  247. * simulate a non-seekable storage
  248. *
  249. * @dataProvider dataFilesProvider
  250. */
  251. public function testWriteToNonSeekableStorage($testFile) {
  252. $wrapper = $this->getMockBuilder('\OC\Files\Stream\Encryption')
  253. ->setMethods(['parentSeekStream'])->getMock();
  254. $wrapper->expects($this->any())->method('parentSeekStream')->willReturn(false);
  255. $expectedData = file_get_contents(\OC::$SERVERROOT . '/tests/data/' . $testFile);
  256. // write it
  257. $fileName = tempnam("/tmp", "FOO");
  258. $stream = $this->getStream($fileName, 'w+', 0, '\Test\Files\Stream\DummyEncryptionWrapper');
  259. // while writing the file from the beginning to the end we should never try
  260. // to read parts of the file. This should only happen for write operations
  261. // in the middle of a file
  262. $this->encryptionModule->expects($this->never())->method('decrypt');
  263. fwrite($stream, $expectedData);
  264. fclose($stream);
  265. // read it all
  266. $stream = $this->getStream($fileName, 'r', strlen($expectedData), '\Test\Files\Stream\DummyEncryptionWrapper');
  267. $data = stream_get_contents($stream);
  268. fclose($stream);
  269. $this->assertEquals($expectedData, $data);
  270. // another read test with a loop like we do in several places:
  271. $stream = $this->getStream($fileName, 'r', strlen($expectedData));
  272. $data = '';
  273. while (!feof($stream)) {
  274. $data .= fread($stream, 8192);
  275. }
  276. fclose($stream);
  277. $this->assertEquals($expectedData, $data);
  278. unlink($fileName);
  279. }
  280. /**
  281. * @return \PHPUnit_Framework_MockObject_MockObject
  282. */
  283. protected function buildMockModule() {
  284. $encryptionModule = $this->getMockBuilder('\OCP\Encryption\IEncryptionModule')
  285. ->disableOriginalConstructor()
  286. ->setMethods(['getId', 'getDisplayName', 'begin', 'end', 'encrypt', 'decrypt', 'update', 'shouldEncrypt', 'getUnencryptedBlockSize', 'isReadable', 'encryptAll', 'prepareDecryptAll', 'isReadyForUser', 'needDetailedAccessList'])
  287. ->getMock();
  288. $encryptionModule->expects($this->any())->method('getId')->willReturn('UNIT_TEST_MODULE');
  289. $encryptionModule->expects($this->any())->method('getDisplayName')->willReturn('Unit test module');
  290. $encryptionModule->expects($this->any())->method('begin')->willReturn([]);
  291. $encryptionModule->expects($this->any())->method('end')->willReturn('');
  292. $encryptionModule->expects($this->any())->method('isReadable')->willReturn(true);
  293. $encryptionModule->expects($this->any())->method('needDetailedAccessList')->willReturn(false);
  294. $encryptionModule->expects($this->any())->method('encrypt')->willReturnCallback(function($data) {
  295. // simulate different block size by adding some padding to the data
  296. if (isset($data[6125])) {
  297. return str_pad($data, 8192, 'X');
  298. }
  299. // last block
  300. return $data;
  301. });
  302. $encryptionModule->expects($this->any())->method('decrypt')->willReturnCallback(function($data) {
  303. if (isset($data[8191])) {
  304. return substr($data, 0, 6126);
  305. }
  306. // last block
  307. return $data;
  308. });
  309. $encryptionModule->expects($this->any())->method('update')->willReturn(true);
  310. $encryptionModule->expects($this->any())->method('shouldEncrypt')->willReturn(true);
  311. $encryptionModule->expects($this->any())->method('getUnencryptedBlockSize')->willReturn(6126);
  312. return $encryptionModule;
  313. }
  314. }