diff options
Diffstat (limited to 'apps/encryption/tests/lib')
-rw-r--r-- | apps/encryption/tests/lib/HookManagerTest.php | 75 | ||||
-rw-r--r-- | apps/encryption/tests/lib/KeyManagerTest.php | 650 | ||||
-rw-r--r-- | apps/encryption/tests/lib/MigrationTest.php | 586 | ||||
-rw-r--r-- | apps/encryption/tests/lib/RecoveryTest.php | 323 | ||||
-rw-r--r-- | apps/encryption/tests/lib/SessionTest.php | 197 | ||||
-rw-r--r-- | apps/encryption/tests/lib/UtilTest.php | 206 | ||||
-rw-r--r-- | apps/encryption/tests/lib/crypto/cryptTest.php | 457 | ||||
-rw-r--r-- | apps/encryption/tests/lib/crypto/decryptalltest.php | 133 | ||||
-rw-r--r-- | apps/encryption/tests/lib/crypto/encryptalltest.php | 291 | ||||
-rw-r--r-- | apps/encryption/tests/lib/crypto/encryptionTest.php | 425 | ||||
-rw-r--r-- | apps/encryption/tests/lib/users/SetupTest.php | 84 |
11 files changed, 0 insertions, 3427 deletions
diff --git a/apps/encryption/tests/lib/HookManagerTest.php b/apps/encryption/tests/lib/HookManagerTest.php deleted file mode 100644 index d69674faec0..00000000000 --- a/apps/encryption/tests/lib/HookManagerTest.php +++ /dev/null @@ -1,75 +0,0 @@ -<?php -/** - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Joas Schilling <nickvergessen@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - - -namespace OCA\Encryption\Tests; - - -use OCA\Encryption\HookManager; -use Test\TestCase; - -class HookManagerTest extends TestCase { - - /** - * @var HookManager - */ - private static $instance; - - /** - * - */ - public function testRegisterHookWithArray() { - self::$instance->registerHook([ - $this->getMockBuilder('OCA\Encryption\Hooks\Contracts\IHook')->disableOriginalConstructor()->getMock(), - $this->getMockBuilder('OCA\Encryption\Hooks\Contracts\IHook')->disableOriginalConstructor()->getMock(), - $this->getMock('NotIHook') - ]); - - $hookInstances = self::invokePrivate(self::$instance, 'hookInstances'); - // Make sure our type checking works - $this->assertCount(2, $hookInstances); - } - - - /** - * - */ - public static function setUpBeforeClass() { - parent::setUpBeforeClass(); - // have to make instance static to preserve data between tests - self::$instance = new HookManager(); - - } - - /** - * - */ - public function testRegisterHooksWithInstance() { - $mock = $this->getMockBuilder('OCA\Encryption\Hooks\Contracts\IHook')->disableOriginalConstructor()->getMock(); - self::$instance->registerHook($mock); - - $hookInstances = self::invokePrivate(self::$instance, 'hookInstances'); - $this->assertCount(3, $hookInstances); - - } - -} diff --git a/apps/encryption/tests/lib/KeyManagerTest.php b/apps/encryption/tests/lib/KeyManagerTest.php deleted file mode 100644 index 7ede6177deb..00000000000 --- a/apps/encryption/tests/lib/KeyManagerTest.php +++ /dev/null @@ -1,650 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Joas Schilling <nickvergessen@owncloud.com> - * @author Lukas Reschke <lukas@owncloud.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - -namespace OCA\Encryption\Tests; - - -use OCA\Encryption\KeyManager; -use OCA\Encryption\Session; -use Test\TestCase; - -class KeyManagerTest extends TestCase { - /** - * @var KeyManager - */ - private $instance; - /** - * @var string - */ - private $userId; - - /** @var string */ - private $systemKeyId; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $keyStorageMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $cryptMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $userMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $sessionMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $logMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $utilMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $configMock; - - public function setUp() { - parent::setUp(); - $this->userId = 'user1'; - $this->systemKeyId = 'systemKeyId'; - $this->keyStorageMock = $this->getMock('OCP\Encryption\Keys\IStorage'); - $this->cryptMock = $this->getMockBuilder('OCA\Encryption\Crypto\Crypt') - ->disableOriginalConstructor() - ->getMock(); - $this->configMock = $this->getMock('OCP\IConfig'); - $this->configMock->expects($this->any()) - ->method('getAppValue') - ->willReturn($this->systemKeyId); - $this->userMock = $this->getMock('OCP\IUserSession'); - $this->sessionMock = $this->getMockBuilder('OCA\Encryption\Session') - ->disableOriginalConstructor() - ->getMock(); - $this->logMock = $this->getMock('OCP\ILogger'); - $this->utilMock = $this->getMockBuilder('OCA\Encryption\Util') - ->disableOriginalConstructor() - ->getMock(); - - $this->instance = new KeyManager( - $this->keyStorageMock, - $this->cryptMock, - $this->configMock, - $this->userMock, - $this->sessionMock, - $this->logMock, - $this->utilMock); - } - - public function testDeleteShareKey() { - $this->keyStorageMock->expects($this->any()) - ->method('deleteFileKey') - ->with($this->equalTo('/path'), $this->equalTo('keyId.shareKey')) - ->willReturn(true); - - $this->assertTrue( - $this->instance->deleteShareKey('/path', 'keyId') - ); - } - - public function testGetPrivateKey() { - $this->keyStorageMock->expects($this->any()) - ->method('getUserKey') - ->with($this->equalTo($this->userId), $this->equalTo('privateKey')) - ->willReturn('privateKey'); - - - $this->assertSame('privateKey', - $this->instance->getPrivateKey($this->userId) - ); - } - - public function testGetPublicKey() { - $this->keyStorageMock->expects($this->any()) - ->method('getUserKey') - ->with($this->equalTo($this->userId), $this->equalTo('publicKey')) - ->willReturn('publicKey'); - - - $this->assertSame('publicKey', - $this->instance->getPublicKey($this->userId) - ); - } - - public function testRecoveryKeyExists() { - $this->keyStorageMock->expects($this->any()) - ->method('getSystemUserKey') - ->with($this->equalTo($this->systemKeyId . '.publicKey')) - ->willReturn('recoveryKey'); - - - $this->assertTrue($this->instance->recoveryKeyExists()); - } - - public function testCheckRecoveryKeyPassword() { - $this->keyStorageMock->expects($this->any()) - ->method('getSystemUserKey') - ->with($this->equalTo($this->systemKeyId . '.privateKey')) - ->willReturn('recoveryKey'); - $this->cryptMock->expects($this->any()) - ->method('decryptPrivateKey') - ->with($this->equalTo('recoveryKey'), $this->equalTo('pass')) - ->willReturn('decryptedRecoveryKey'); - - $this->assertTrue($this->instance->checkRecoveryPassword('pass')); - } - - public function testSetPublicKey() { - $this->keyStorageMock->expects($this->any()) - ->method('setUserKey') - ->with( - $this->equalTo($this->userId), - $this->equalTo('publicKey'), - $this->equalTo('key')) - ->willReturn(true); - - - $this->assertTrue( - $this->instance->setPublicKey($this->userId, 'key') - ); - } - - public function testSetPrivateKey() { - $this->keyStorageMock->expects($this->any()) - ->method('setUserKey') - ->with( - $this->equalTo($this->userId), - $this->equalTo('privateKey'), - $this->equalTo('key')) - ->willReturn(true); - - - $this->assertTrue( - $this->instance->setPrivateKey($this->userId, 'key') - ); - } - - /** - * @dataProvider dataTestUserHasKeys - */ - public function testUserHasKeys($key, $expected) { - $this->keyStorageMock->expects($this->exactly(2)) - ->method('getUserKey') - ->with($this->equalTo($this->userId), $this->anything()) - ->willReturn($key); - - - $this->assertSame($expected, - $this->instance->userHasKeys($this->userId) - ); - } - - public function dataTestUserHasKeys() { - return [ - ['key', true], - ['', false] - ]; - } - - /** - * @expectedException \OCA\Encryption\Exceptions\PrivateKeyMissingException - */ - public function testUserHasKeysMissingPrivateKey() { - $this->keyStorageMock->expects($this->exactly(2)) - ->method('getUserKey') - ->willReturnCallback(function ($uid, $keyID, $encryptionModuleId) { - if ($keyID=== 'privateKey') { - return ''; - } - return 'key'; - }); - - $this->instance->userHasKeys($this->userId); - } - - /** - * @expectedException \OCA\Encryption\Exceptions\PublicKeyMissingException - */ - public function testUserHasKeysMissingPublicKey() { - $this->keyStorageMock->expects($this->exactly(2)) - ->method('getUserKey') - ->willReturnCallback(function ($uid, $keyID, $encryptionModuleId){ - if ($keyID === 'publicKey') { - return ''; - } - return 'key'; - }); - - $this->instance->userHasKeys($this->userId); - - } - - /** - * @dataProvider dataTestInit - * - * @param bool $useMasterKey - */ - public function testInit($useMasterKey) { - - $instance = $this->getMockBuilder('OCA\Encryption\KeyManager') - ->setConstructorArgs( - [ - $this->keyStorageMock, - $this->cryptMock, - $this->configMock, - $this->userMock, - $this->sessionMock, - $this->logMock, - $this->utilMock - ] - )->setMethods(['getMasterKeyId', 'getMasterKeyPassword', 'getSystemPrivateKey', 'getPrivateKey']) - ->getMock(); - - $this->utilMock->expects($this->once())->method('isMasterKeyEnabled') - ->willReturn($useMasterKey); - - $this->sessionMock->expects($this->at(0))->method('setStatus') - ->with(Session::INIT_EXECUTED); - - $instance->expects($this->any())->method('getMasterKeyId')->willReturn('masterKeyId'); - $instance->expects($this->any())->method('getMasterKeyPassword')->willReturn('masterKeyPassword'); - $instance->expects($this->any())->method('getSystemPrivateKey')->with('masterKeyId')->willReturn('privateMasterKey'); - $instance->expects($this->any())->method('getPrivateKey')->with($this->userId)->willReturn('privateUserKey'); - - if($useMasterKey) { - $this->cryptMock->expects($this->once())->method('decryptPrivateKey') - ->with('privateMasterKey', 'masterKeyPassword', 'masterKeyId') - ->willReturn('key'); - } else { - $this->cryptMock->expects($this->once())->method('decryptPrivateKey') - ->with('privateUserKey', 'pass', $this->userId) - ->willReturn('key'); - } - - $this->sessionMock->expects($this->once())->method('setPrivateKey') - ->with('key'); - - $this->assertTrue($instance->init($this->userId, 'pass')); - } - - public function dataTestInit() { - return [ - [true], - [false] - ]; - } - - - public function testSetRecoveryKey() { - $this->keyStorageMock->expects($this->exactly(2)) - ->method('setSystemUserKey') - ->willReturn(true); - $this->cryptMock->expects($this->any()) - ->method('encryptPrivateKey') - ->with($this->equalTo('privateKey'), $this->equalTo('pass')) - ->willReturn('decryptedPrivateKey'); - - - $this->assertTrue( - $this->instance->setRecoveryKey('pass', - array('publicKey' => 'publicKey', 'privateKey' => 'privateKey')) - ); - } - - public function testSetSystemPrivateKey() { - $this->keyStorageMock->expects($this->exactly(1)) - ->method('setSystemUserKey') - ->with($this->equalTo('keyId.privateKey'), $this->equalTo('key')) - ->willReturn(true); - - - $this->assertTrue( - $this->instance->setSystemPrivateKey('keyId', 'key') - ); - } - - public function testGetSystemPrivateKey() { - $this->keyStorageMock->expects($this->exactly(1)) - ->method('getSystemUserKey') - ->with($this->equalTo('keyId.privateKey')) - ->willReturn('systemPrivateKey'); - - - $this->assertSame('systemPrivateKey', - $this->instance->getSystemPrivateKey('keyId') - ); - } - - public function testGetEncryptedFileKey() { - $this->keyStorageMock->expects($this->once()) - ->method('getFileKey') - ->with('/', 'fileKey') - ->willReturn(true); - - $this->assertTrue($this->instance->getEncryptedFileKey('/')); - } - - /** - * @dataProvider dataTestGetFileKey - * - * @param $uid - * @param $isMasterKeyEnabled - * @param $privateKey - * @param $expected - */ - public function testGetFileKey($uid, $isMasterKeyEnabled, $privateKey, $expected) { - - $path = '/foo.txt'; - - if ($isMasterKeyEnabled) { - $expectedUid = 'masterKeyId'; - } else { - $expectedUid = $uid; - } - - $this->invokePrivate($this->instance, 'masterKeyId', ['masterKeyId']); - - $this->keyStorageMock->expects($this->at(0)) - ->method('getFileKey') - ->with($path, 'fileKey', 'OC_DEFAULT_MODULE') - ->willReturn(true); - - $this->keyStorageMock->expects($this->at(1)) - ->method('getFileKey') - ->with($path, $expectedUid . '.shareKey', 'OC_DEFAULT_MODULE') - ->willReturn(true); - - if (is_null($uid)) { - $this->keyStorageMock->expects($this->once()) - ->method('getSystemUserKey') - ->willReturn(true); - $this->cryptMock->expects($this->once()) - ->method('decryptPrivateKey') - ->willReturn($privateKey); - } else { - $this->keyStorageMock->expects($this->never()) - ->method('getSystemUserKey'); - $this->utilMock->expects($this->once())->method('isMasterKeyEnabled') - ->willReturn($isMasterKeyEnabled); - $this->sessionMock->expects($this->once())->method('getPrivateKey')->willReturn($privateKey); - } - - if($privateKey) { - $this->cryptMock->expects($this->once()) - ->method('multiKeyDecrypt') - ->willReturn(true); - } else { - $this->cryptMock->expects($this->never()) - ->method('multiKeyDecrypt'); - } - - $this->assertSame($expected, - $this->instance->getFileKey($path, $uid) - ); - - } - - public function dataTestGetFileKey() { - return [ - ['user1', false, 'privateKey', true], - ['user1', false, false, ''], - ['user1', true, 'privateKey', true], - ['user1', true, false, ''], - ['', false, 'privateKey', true], - ['', false, false, ''], - ['', true, 'privateKey', true], - ['', true, false, ''] - ]; - } - - public function testDeletePrivateKey() { - $this->keyStorageMock->expects($this->once()) - ->method('deleteUserKey') - ->with('user1', 'privateKey') - ->willReturn(true); - - $this->assertTrue(self::invokePrivate($this->instance, - 'deletePrivateKey', - [$this->userId])); - } - - public function testDeleteAllFileKeys() { - $this->keyStorageMock->expects($this->once()) - ->method('deleteAllFileKeys') - ->willReturn(true); - - $this->assertTrue($this->instance->deleteAllFileKeys('/')); - } - - /** - * test add public share key and or recovery key to the list of public keys - * - * @dataProvider dataTestAddSystemKeys - * - * @param array $accessList - * @param array $publicKeys - * @param string $uid - * @param array $expectedKeys - */ - public function testAddSystemKeys($accessList, $publicKeys, $uid, $expectedKeys) { - - $publicShareKeyId = 'publicShareKey'; - $recoveryKeyId = 'recoveryKey'; - - $this->keyStorageMock->expects($this->any()) - ->method('getSystemUserKey') - ->willReturnCallback(function($keyId, $encryptionModuleId) { - return $keyId; - }); - - $this->utilMock->expects($this->any()) - ->method('isRecoveryEnabledForUser') - ->willReturnCallback(function($uid) { - if ($uid === 'user1') { - return true; - } - return false; - }); - - // set key IDs - self::invokePrivate($this->instance, 'publicShareKeyId', [$publicShareKeyId]); - self::invokePrivate($this->instance, 'recoveryKeyId', [$recoveryKeyId]); - - $result = $this->instance->addSystemKeys($accessList, $publicKeys, $uid); - - foreach ($expectedKeys as $expected) { - $this->assertArrayHasKey($expected, $result); - } - - $this->assertSameSize($expectedKeys, $result); - } - - /** - * data provider for testAddSystemKeys() - * - * @return array - */ - public function dataTestAddSystemKeys() { - return array( - array(['public' => true],[], 'user1', ['publicShareKey', 'recoveryKey']), - array(['public' => false], [], 'user1', ['recoveryKey']), - array(['public' => true],[], 'user2', ['publicShareKey']), - array(['public' => false], [], 'user2', []), - ); - } - - public function testGetMasterKeyId() { - $this->assertSame('systemKeyId', $this->instance->getMasterKeyId()); - } - - public function testGetPublicMasterKey() { - $this->keyStorageMock->expects($this->once())->method('getSystemUserKey') - ->with('systemKeyId.publicKey', \OCA\Encryption\Crypto\Encryption::ID) - ->willReturn(true); - - $this->assertTrue( - $this->instance->getPublicMasterKey() - ); - } - - public function testGetMasterKeyPassword() { - $this->configMock->expects($this->once())->method('getSystemValue')->with('secret') - ->willReturn('password'); - - $this->assertSame('password', - $this->invokePrivate($this->instance, 'getMasterKeyPassword', []) - ); - } - - /** - * @expectedException \Exception - */ - public function testGetMasterKeyPasswordException() { - $this->configMock->expects($this->once())->method('getSystemValue')->with('secret') - ->willReturn(''); - - $this->invokePrivate($this->instance, 'getMasterKeyPassword', []); - } - - /** - * @dataProvider dataTestValidateMasterKey - * - * @param $masterKey - */ - public function testValidateMasterKey($masterKey) { - - /** @var \OCA\Encryption\KeyManager | \PHPUnit_Framework_MockObject_MockObject $instance */ - $instance = $this->getMockBuilder('OCA\Encryption\KeyManager') - ->setConstructorArgs( - [ - $this->keyStorageMock, - $this->cryptMock, - $this->configMock, - $this->userMock, - $this->sessionMock, - $this->logMock, - $this->utilMock - ] - )->setMethods(['getPublicMasterKey', 'setSystemPrivateKey', 'getMasterKeyPassword']) - ->getMock(); - - $instance->expects($this->once())->method('getPublicMasterKey') - ->willReturn($masterKey); - - $instance->expects($this->any())->method('getMasterKeyPassword')->willReturn('masterKeyPassword'); - $this->cryptMock->expects($this->any())->method('generateHeader')->willReturn('header'); - - if(empty($masterKey)) { - $this->cryptMock->expects($this->once())->method('createKeyPair') - ->willReturn(['publicKey' => 'public', 'privateKey' => 'private']); - $this->keyStorageMock->expects($this->once())->method('setSystemUserKey') - ->with('systemKeyId.publicKey', 'public', \OCA\Encryption\Crypto\Encryption::ID); - $this->cryptMock->expects($this->once())->method('encryptPrivateKey') - ->with('private', 'masterKeyPassword', 'systemKeyId') - ->willReturn('EncryptedKey'); - $instance->expects($this->once())->method('setSystemPrivateKey') - ->with('systemKeyId', 'headerEncryptedKey'); - } else { - $this->cryptMock->expects($this->never())->method('createKeyPair'); - $this->keyStorageMock->expects($this->never())->method('setSystemUserKey'); - $this->cryptMock->expects($this->never())->method('encryptPrivateKey'); - $instance->expects($this->never())->method('setSystemPrivateKey'); - } - - $instance->validateMasterKey(); - } - - public function dataTestValidateMasterKey() { - return [ - ['masterKey'], - [''] - ]; - } - - public function testGetVersionWithoutFileInfo() { - $view = $this->getMockBuilder('\\OC\\Files\\View') - ->disableOriginalConstructor()->getMock(); - $view->expects($this->once()) - ->method('getFileInfo') - ->with('/admin/files/myfile.txt') - ->willReturn(false); - - $this->assertSame(0, $this->instance->getVersion('/admin/files/myfile.txt', $view)); - } - - public function testGetVersionWithFileInfo() { - $view = $this->getMockBuilder('\\OC\\Files\\View') - ->disableOriginalConstructor()->getMock(); - $fileInfo = $this->getMockBuilder('\\OC\\Files\\FileInfo') - ->disableOriginalConstructor()->getMock(); - $fileInfo->expects($this->once()) - ->method('getEncryptedVersion') - ->willReturn(1337); - $view->expects($this->once()) - ->method('getFileInfo') - ->with('/admin/files/myfile.txt') - ->willReturn($fileInfo); - - $this->assertSame(1337, $this->instance->getVersion('/admin/files/myfile.txt', $view)); - } - - public function testSetVersionWithFileInfo() { - $view = $this->getMockBuilder('\\OC\\Files\\View') - ->disableOriginalConstructor()->getMock(); - $cache = $this->getMockBuilder('\\OCP\\Files\\Cache\\ICache') - ->disableOriginalConstructor()->getMock(); - $cache->expects($this->once()) - ->method('update') - ->with(123, ['encrypted' => 5, 'encryptedVersion' => 5]); - $storage = $this->getMockBuilder('\\OCP\\Files\\Storage') - ->disableOriginalConstructor()->getMock(); - $storage->expects($this->once()) - ->method('getCache') - ->willReturn($cache); - $fileInfo = $this->getMockBuilder('\\OC\\Files\\FileInfo') - ->disableOriginalConstructor()->getMock(); - $fileInfo->expects($this->once()) - ->method('getStorage') - ->willReturn($storage); - $fileInfo->expects($this->once()) - ->method('getId') - ->willReturn(123); - $view->expects($this->once()) - ->method('getFileInfo') - ->with('/admin/files/myfile.txt') - ->willReturn($fileInfo); - - $this->instance->setVersion('/admin/files/myfile.txt', 5, $view); - } - - public function testSetVersionWithoutFileInfo() { - $view = $this->getMockBuilder('\\OC\\Files\\View') - ->disableOriginalConstructor()->getMock(); - $view->expects($this->once()) - ->method('getFileInfo') - ->with('/admin/files/myfile.txt') - ->willReturn(false); - - $this->instance->setVersion('/admin/files/myfile.txt', 5, $view); - } - -} diff --git a/apps/encryption/tests/lib/MigrationTest.php b/apps/encryption/tests/lib/MigrationTest.php deleted file mode 100644 index 6edb8624e70..00000000000 --- a/apps/encryption/tests/lib/MigrationTest.php +++ /dev/null @@ -1,586 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Joas Schilling <nickvergessen@owncloud.com> - * @author Robin Appelman <icewind@owncloud.com> - * @author Roeland Jago Douma <rullzer@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - -namespace OCA\Encryption\Tests; - -use OCA\Encryption\Migration; -use OCP\ILogger; - -class MigrationTest extends \Test\TestCase { - - const TEST_ENCRYPTION_MIGRATION_USER1='test_encryption_user1'; - const TEST_ENCRYPTION_MIGRATION_USER2='test_encryption_user2'; - const TEST_ENCRYPTION_MIGRATION_USER3='test_encryption_user3'; - - /** @var \OC\Files\View */ - private $view; - private $public_share_key_id = 'share_key_id'; - private $recovery_key_id = 'recovery_key_id'; - private $moduleId; - - /** @var PHPUnit_Framework_MockObject_MockObject | ILogger */ - private $logger; - - public static function setUpBeforeClass() { - parent::setUpBeforeClass(); - \OC::$server->getUserManager()->createUser(self::TEST_ENCRYPTION_MIGRATION_USER1, 'foo'); - \OC::$server->getUserManager()->createUser(self::TEST_ENCRYPTION_MIGRATION_USER2, 'foo'); - \OC::$server->getUserManager()->createUser(self::TEST_ENCRYPTION_MIGRATION_USER3, 'foo'); - } - - public static function tearDownAfterClass() { - $user = \OC::$server->getUserManager()->get(self::TEST_ENCRYPTION_MIGRATION_USER1); - if ($user !== null) { $user->delete(); } - $user = \OC::$server->getUserManager()->get(self::TEST_ENCRYPTION_MIGRATION_USER2); - if ($user !== null) { $user->delete(); } - $user = \OC::$server->getUserManager()->get(self::TEST_ENCRYPTION_MIGRATION_USER3); - if ($user !== null) { $user->delete(); } - parent::tearDownAfterClass(); - } - - - public function setUp() { - $this->logger = $this->getMockBuilder('\OCP\ILogger')->disableOriginalConstructor()->getMock(); - $this->view = new \OC\Files\View(); - $this->moduleId = \OCA\Encryption\Crypto\Encryption::ID; - } - - /** - * @param string $uid - */ - protected function createDummyShareKeys($uid) { - $this->loginAsUser($uid); - - $this->view->mkdir($uid . '/files_encryption/keys/folder1/folder2/folder3/file3'); - $this->view->mkdir($uid . '/files_encryption/keys/folder1/folder2/file2'); - $this->view->mkdir($uid . '/files_encryption/keys/folder1/file.1'); - $this->view->mkdir($uid . '/files_encryption/keys/folder2/file.2.1'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/folder2/folder3/file3/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/folder2/folder3/file3/' . self::TEST_ENCRYPTION_MIGRATION_USER2 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/folder2/folder3/file3/' . self::TEST_ENCRYPTION_MIGRATION_USER3 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/folder2/file2/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/folder2/file2/' . self::TEST_ENCRYPTION_MIGRATION_USER2 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/folder2/file2/' . self::TEST_ENCRYPTION_MIGRATION_USER3 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/file.1/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/file.1/' . self::TEST_ENCRYPTION_MIGRATION_USER2 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/file.1/' . self::TEST_ENCRYPTION_MIGRATION_USER3 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder2/file.2.1/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder2/file.2.1/' . self::TEST_ENCRYPTION_MIGRATION_USER2 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder2/file.2.1/' . self::TEST_ENCRYPTION_MIGRATION_USER3 . '.shareKey' , 'data'); - if ($this->public_share_key_id) { - $this->view->file_put_contents($uid . '/files_encryption/keys/folder2/file.2.1/' . $this->public_share_key_id . '.shareKey' , 'data'); - } - if ($this->recovery_key_id) { - $this->view->file_put_contents($uid . '/files_encryption/keys/folder2/file.2.1/' . $this->recovery_key_id . '.shareKey' , 'data'); - } - } - - /** - * @param string $uid - */ - protected function createDummyUserKeys($uid) { - $this->loginAsUser($uid); - - $this->view->mkdir($uid . '/files_encryption/'); - $this->view->mkdir('/files_encryption/public_keys'); - $this->view->file_put_contents($uid . '/files_encryption/' . $uid . '.privateKey', 'privateKey'); - $this->view->file_put_contents('/files_encryption/public_keys/' . $uid . '.publicKey', 'publicKey'); - } - - /** - * @param string $uid - */ - protected function createDummyFileKeys($uid) { - $this->loginAsUser($uid); - - $this->view->mkdir($uid . '/files_encryption/keys/folder1/folder2/folder3/file3'); - $this->view->mkdir($uid . '/files_encryption/keys/folder1/folder2/file2'); - $this->view->mkdir($uid . '/files_encryption/keys/folder1/file.1'); - $this->view->mkdir($uid . '/files_encryption/keys/folder2/file.2.1'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/folder2/folder3/file3/fileKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/folder2/file2/fileKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder1/file.1/fileKey' , 'data'); - $this->view->file_put_contents($uid . '/files_encryption/keys/folder2/file.2.1/fileKey' , 'data'); - } - - /** - * @param string $uid - */ - protected function createDummyFiles($uid) { - $this->loginAsUser($uid); - - $this->view->mkdir($uid . '/files/folder1/folder2/folder3/file3'); - $this->view->mkdir($uid . '/files/folder1/folder2/file2'); - $this->view->mkdir($uid . '/files/folder1/file.1'); - $this->view->mkdir($uid . '/files/folder2/file.2.1'); - $this->view->file_put_contents($uid . '/files/folder1/folder2/folder3/file3/fileKey' , 'data'); - $this->view->file_put_contents($uid . '/files/folder1/folder2/file2/fileKey' , 'data'); - $this->view->file_put_contents($uid . '/files/folder1/file.1/fileKey' , 'data'); - $this->view->file_put_contents($uid . '/files/folder2/file.2.1/fileKey' , 'data'); - } - - /** - * @param string $uid - */ - protected function createDummyFilesInTrash($uid) { - $this->loginAsUser($uid); - - $this->view->mkdir($uid . '/files_trashbin/keys/file1.d5457864'); - $this->view->mkdir($uid . '/files_trashbin/keys/folder1.d7437648723/file2'); - $this->view->file_put_contents($uid . '/files_trashbin/keys/file1.d5457864/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_trashbin/keys/file1.d5457864/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey' , 'data'); - $this->view->file_put_contents($uid . '/files_trashbin/keys/folder1.d7437648723/file2/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey' , 'data'); - - $this->view->file_put_contents($uid . '/files_trashbin/keys/file1.d5457864/fileKey' , 'data'); - $this->view->file_put_contents($uid . '/files_trashbin/keys/folder1.d7437648723/file2/fileKey' , 'data'); - - // create the files itself - $this->view->mkdir($uid . '/files_trashbin/folder1.d7437648723'); - $this->view->file_put_contents($uid . '/files_trashbin/file1.d5457864' , 'data'); - $this->view->file_put_contents($uid . '/files_trashbin/folder1.d7437648723/file2' , 'data'); - } - - protected function createDummySystemWideKeys() { - $this->view->mkdir('files_encryption'); - $this->view->mkdir('files_encryption/public_keys'); - $this->view->file_put_contents('files_encryption/systemwide_1.privateKey', 'data'); - $this->view->file_put_contents('files_encryption/systemwide_2.privateKey', 'data'); - $this->view->file_put_contents('files_encryption/public_keys/systemwide_1.publicKey', 'data'); - $this->view->file_put_contents('files_encryption/public_keys/systemwide_2.publicKey', 'data'); - } - - public function testMigrateToNewFolderStructure() { - $this->createDummyUserKeys(self::TEST_ENCRYPTION_MIGRATION_USER1); - $this->createDummyUserKeys(self::TEST_ENCRYPTION_MIGRATION_USER2); - $this->createDummyUserKeys(self::TEST_ENCRYPTION_MIGRATION_USER3); - - $this->createDummyShareKeys(self::TEST_ENCRYPTION_MIGRATION_USER1); - $this->createDummyShareKeys(self::TEST_ENCRYPTION_MIGRATION_USER2); - $this->createDummyShareKeys(self::TEST_ENCRYPTION_MIGRATION_USER3); - - $this->createDummyFileKeys(self::TEST_ENCRYPTION_MIGRATION_USER1); - $this->createDummyFileKeys(self::TEST_ENCRYPTION_MIGRATION_USER2); - $this->createDummyFileKeys(self::TEST_ENCRYPTION_MIGRATION_USER3); - - $this->createDummyFiles(self::TEST_ENCRYPTION_MIGRATION_USER1); - $this->createDummyFiles(self::TEST_ENCRYPTION_MIGRATION_USER2); - $this->createDummyFiles(self::TEST_ENCRYPTION_MIGRATION_USER3); - - $this->createDummyFilesInTrash(self::TEST_ENCRYPTION_MIGRATION_USER2); - - // no user for system wide mount points - $this->createDummyFileKeys(''); - $this->createDummyShareKeys(''); - - $this->createDummySystemWideKeys(); - - /** @var \PHPUnit_Framework_MockObject_MockObject|\OCA\Encryption\Migration $m */ - $m = $this->getMockBuilder('OCA\Encryption\Migration') - ->setConstructorArgs( - [ - \OC::$server->getConfig(), - new \OC\Files\View(), - \OC::$server->getDatabaseConnection(), - $this->logger - ] - )->setMethods(['getSystemMountPoints'])->getMock(); - - $m->expects($this->any())->method('getSystemMountPoints') - ->will($this->returnValue([['mountpoint' => 'folder1'], ['mountpoint' => 'folder2']])); - - $m->reorganizeFolderStructure(); - // even if it runs twice folder should always move only once - $m->reorganizeFolderStructure(); - - $this->loginAsUser(self::TEST_ENCRYPTION_MIGRATION_USER1); - - $this->assertTrue( - $this->view->file_exists( - self::TEST_ENCRYPTION_MIGRATION_USER1 . '/files_encryption/' . - $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.publicKey') - ); - - $this->loginAsUser(self::TEST_ENCRYPTION_MIGRATION_USER2); - - $this->assertTrue( - $this->view->file_exists( - self::TEST_ENCRYPTION_MIGRATION_USER2 . '/files_encryption/' . - $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER2 . '.publicKey') - ); - - $this->loginAsUser(self::TEST_ENCRYPTION_MIGRATION_USER3); - - $this->assertTrue( - $this->view->file_exists( - self::TEST_ENCRYPTION_MIGRATION_USER3 . '/files_encryption/' . - $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER3 . '.publicKey') - ); - - $this->loginAsUser(self::TEST_ENCRYPTION_MIGRATION_USER1); - - $this->assertTrue( - $this->view->file_exists( - '/files_encryption/' . $this->moduleId . '/systemwide_1.publicKey') - ); - $this->assertTrue( - $this->view->file_exists( - '/files_encryption/' . $this->moduleId . '/systemwide_2.publicKey') - ); - - $this->verifyNewKeyPath(self::TEST_ENCRYPTION_MIGRATION_USER1); - $this->verifyNewKeyPath(self::TEST_ENCRYPTION_MIGRATION_USER2); - $this->verifyNewKeyPath(self::TEST_ENCRYPTION_MIGRATION_USER3); - // system wide keys - $this->verifyNewKeyPath(''); - // trash - $this->verifyFilesInTrash(self::TEST_ENCRYPTION_MIGRATION_USER2); - - } - - /** - * @param string $uid - */ - protected function verifyFilesInTrash($uid) { - $this->loginAsUser($uid); - - // share keys - $this->assertTrue( - $this->view->file_exists($uid . '/files_encryption/keys/files_trashbin/file1.d5457864/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey') - ); - $this->assertTrue( - $this->view->file_exists($uid . '/files_encryption/keys/files_trashbin/file1.d5457864/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey') - ); - $this->assertTrue( - $this->view->file_exists($uid . '/files_encryption/keys/files_trashbin/folder1.d7437648723/file2/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey') - ); - - // file keys - $this->assertTrue( - $this->view->file_exists($uid . '/files_encryption/keys/files_trashbin/file1.d5457864/' . $this->moduleId . '/fileKey') - ); - - $this->assertTrue( - $this->view->file_exists($uid . '/files_encryption/keys/files_trashbin/file1.d5457864/' . $this->moduleId . '/fileKey') - ); - $this->assertTrue( - $this->view->file_exists($uid . '/files_encryption/keys/files_trashbin/folder1.d7437648723/file2/' . $this->moduleId . '/fileKey') - ); - } - - /** - * @param string $uid - */ - protected function verifyNewKeyPath($uid) { - // private key - if ($uid !== '') { - $this->loginAsUser($uid); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/' . $this->moduleId . '/'. $uid . '.privateKey')); - } - // file keys - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/folder2/folder3/file3/' . $this->moduleId . '/fileKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/folder2/file2/' . $this->moduleId . '/fileKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/file.1/' . $this->moduleId . '/fileKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder2/file.2.1/' .$this->moduleId . '/fileKey')); - // share keys - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/folder2/folder3/file3/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/folder2/folder3/file3/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER2 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/folder2/folder3/file3/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER3 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/folder2/file2/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/folder2/file2/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER2 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/folder2/file2/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER3 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/file.1/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/file.1/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER2 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder1/file.1/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER3 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder2/file.2.1/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER1 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder2/file.2.1/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER2 . '.shareKey')); - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder2/file.2.1/' . $this->moduleId . '/' . self::TEST_ENCRYPTION_MIGRATION_USER3 . '.shareKey')); - if ($this->public_share_key_id) { - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder2/file.2.1/' . $this->moduleId . '/' . $this->public_share_key_id . '.shareKey')); - } - if ($this->recovery_key_id) { - $this->assertTrue($this->view->file_exists($uid . '/files_encryption/keys/files/folder2/file.2.1/' . $this->moduleId . '/' . $this->recovery_key_id . '.shareKey')); - } - } - - private function prepareDB() { - $config = \OC::$server->getConfig(); - $config->setAppValue('files_encryption', 'recoveryKeyId', 'recovery_id'); - $config->setAppValue('files_encryption', 'publicShareKeyId', 'share_id'); - $config->setAppValue('files_encryption', 'recoveryAdminEnabled', '1'); - $config->setUserValue(self::TEST_ENCRYPTION_MIGRATION_USER1, 'files_encryption', 'recoverKeyEnabled', '1'); - - //$this->invokePrivate($config, 'cache', [[]]); - $cache = $this->invokePrivate(\OC::$server->getAppConfig(), 'cache'); - unset($cache['encryption']); - unset($cache['files_encryption']); - $this->invokePrivate(\OC::$server->getAppConfig(), 'cache', [$cache]); - - // delete default values set by the encryption app during initialization - - /** @var \OCP\IDBConnection $connection */ - $connection = \OC::$server->getDatabaseConnection(); - $query = $connection->getQueryBuilder(); - $query->delete('appconfig') - ->where($query->expr()->eq('appid', $query->createParameter('appid'))) - ->setParameter('appid', 'encryption'); - $query->execute(); - $query = $connection->getQueryBuilder(); - $query->delete('preferences') - ->where($query->expr()->eq('appid', $query->createParameter('appid'))) - ->setParameter('appid', 'encryption'); - $query->execute(); - } - - public function testUpdateDB() { - $this->prepareDB(); - - $m = new Migration(\OC::$server->getConfig(), new \OC\Files\View(), \OC::$server->getDatabaseConnection(), $this->logger); - $this->invokePrivate($m, 'installedVersion', ['0.7']); - $m->updateDB(); - - $this->verifyDB('appconfig', 'files_encryption', 0); - $this->verifyDB('preferences', 'files_encryption', 0); - $this->verifyDB('appconfig', 'encryption', 3); - $this->verifyDB('preferences', 'encryption', 1); - - } - - /** - * test update db if the db already contain some existing new values - */ - public function testUpdateDBExistingNewConfig() { - $this->prepareDB(); - $config = \OC::$server->getConfig(); - $config->setAppValue('encryption', 'publicShareKeyId', 'wrong_share_id'); - $config->setUserValue(self::TEST_ENCRYPTION_MIGRATION_USER1, 'encryption', 'recoverKeyEnabled', '9'); - - $m = new Migration(\OC::$server->getConfig(), new \OC\Files\View(), \OC::$server->getDatabaseConnection(), $this->logger); - $this->invokePrivate($m, 'installedVersion', ['0.7']); - $m->updateDB(); - - $this->verifyDB('appconfig', 'files_encryption', 0); - $this->verifyDB('preferences', 'files_encryption', 0); - $this->verifyDB('appconfig', 'encryption', 3); - $this->verifyDB('preferences', 'encryption', 1); - - // check if the existing values where overwritten correctly - /** @var \OC\DB\Connection $connection */ - $connection = \OC::$server->getDatabaseConnection(); - $query = $connection->getQueryBuilder(); - $query->select('configvalue') - ->from('appconfig') - ->where($query->expr()->andX( - $query->expr()->eq('appid', $query->createParameter('appid')), - $query->expr()->eq('configkey', $query->createParameter('configkey')) - )) - ->setParameter('appid', 'encryption') - ->setParameter('configkey', 'publicShareKeyId'); - $result = $query->execute(); - $value = $result->fetch(); - $this->assertTrue(isset($value['configvalue'])); - $this->assertSame('share_id', $value['configvalue']); - - $query = $connection->getQueryBuilder(); - $query->select('configvalue') - ->from('preferences') - ->where($query->expr()->andX( - $query->expr()->eq('appid', $query->createParameter('appid')), - $query->expr()->eq('configkey', $query->createParameter('configkey')), - $query->expr()->eq('userid', $query->createParameter('userid')) - )) - ->setParameter('appid', 'encryption') - ->setParameter('configkey', 'recoverKeyEnabled') - ->setParameter('userid', self::TEST_ENCRYPTION_MIGRATION_USER1); - $result = $query->execute(); - $value = $result->fetch(); - $this->assertTrue(isset($value['configvalue'])); - $this->assertSame('1', $value['configvalue']); - - } - - /** - * @param string $table - * @param string $appid - * @param integer $expected - */ - public function verifyDB($table, $appid, $expected) { - /** @var \OCP\IDBConnection $connection */ - $connection = \OC::$server->getDatabaseConnection(); - $query = $connection->getQueryBuilder(); - $query->select('appid') - ->from($table) - ->where($query->expr()->eq('appid', $query->createParameter('appid'))) - ->setParameter('appid', $appid); - $result = $query->execute(); - $values = $result->fetchAll(); - $this->assertSame($expected, - count($values) - ); - } - - /** - * test update of the file cache - */ - public function testUpdateFileCache() { - $this->prepareFileCache(); - $m = new Migration(\OC::$server->getConfig(), new \OC\Files\View(), \OC::$server->getDatabaseConnection(), $this->logger); - $this->invokePrivate($m, 'installedVersion', ['0.7']); - self::invokePrivate($m, 'updateFileCache'); - - // check results - - /** @var \OCP\IDBConnection $connection */ - $connection = \OC::$server->getDatabaseConnection(); - $query = $connection->getQueryBuilder(); - $query->select('*') - ->from('filecache'); - $result = $query->execute(); - $entries = $result->fetchAll(); - foreach($entries as $entry) { - if ((int)$entry['encrypted'] === 1) { - $this->assertSame((int)$entry['unencrypted_size'], (int)$entry['size']); - } else { - $this->assertSame((int)$entry['unencrypted_size'] - 2, (int)$entry['size']); - } - } - - - } - - public function prepareFileCache() { - /** @var \OCP\IDBConnection $connection */ - $connection = \OC::$server->getDatabaseConnection(); - $query = $connection->getQueryBuilder(); - $query->delete('filecache'); - $query->execute(); - $query = $connection->getQueryBuilder(); - $result = $query->select('fileid') - ->from('filecache') - ->setMaxResults(1)->execute()->fetchAll(); - $this->assertEmpty($result); - $query = $connection->getQueryBuilder(); - $query->insert('filecache') - ->values( - array( - 'storage' => $query->createParameter('storage'), - 'path_hash' => $query->createParameter('path_hash'), - 'encrypted' => $query->createParameter('encrypted'), - 'size' => $query->createParameter('size'), - 'unencrypted_size' => $query->createParameter('unencrypted_size'), - ) - ); - for ($i = 1; $i < 20; $i++) { - $query->setParameter('storage', 1) - ->setParameter('path_hash', $i) - ->setParameter('encrypted', $i % 2) - ->setParameter('size', $i) - ->setParameter('unencrypted_size', $i + 2); - $this->assertSame(1, - $query->execute() - ); - } - $query = $connection->getQueryBuilder(); - $result = $query->select('fileid') - ->from('filecache') - ->execute()->fetchAll(); - $this->assertSame(19, count($result)); - } - - /** - * @dataProvider dataTestGetTargetDir - */ - public function testGetTargetDir($user, $keyPath, $filename, $trash, $systemMounts, $expected) { - - $updater = $this->getMockBuilder('\OC\Files\Cache\Updater') - ->disableOriginalConstructor()->getMock(); - $view = $this->getMockBuilder('\OC\Files\View') - ->disableOriginalConstructor()->getMock(); - $view->expects($this->any())->method('file_exists')->willReturn(true); - $view->expects($this->any())->method('getUpdater')->willReturn($updater); - - - $m = $this->getMockBuilder('OCA\Encryption\Migration') - ->setConstructorArgs( - [ - \OC::$server->getConfig(), - $view, - \OC::$server->getDatabaseConnection(), - $this->logger - ] - )->setMethods(['getSystemMountPoints'])->getMock(); - - $m->expects($this->any())->method('getSystemMountPoints') - ->willReturn($systemMounts); - - $this->assertSame($expected, - $this->invokePrivate($m, 'getTargetDir', [$user, $keyPath, $filename, $trash]) - ); - } - - public function dataTestGetTargetDir() { - return [ - [ - 'user1', - '/files_encryption/keys/foo/bar.txt', - 'user1.shareKey', - false, - [], - 'user1/files_encryption/keys/files/foo/bar.txt/OC_DEFAULT_MODULE/user1.shareKey' - ], - [ - 'user1', - '/files_trashbin/keys/foo/bar.txt', - 'user1.shareKey', - true, - [], - 'user1/files_encryption/keys/files_trashbin/foo/bar.txt/OC_DEFAULT_MODULE/user1.shareKey' - ], - [ - '', - '/files_encryption/keys/foo/bar.txt', - 'user1.shareKey', - false, - [['mountpoint' => 'foo']], - '/files_encryption/keys/files/foo/bar.txt/OC_DEFAULT_MODULE/user1.shareKey' - ], - [ - '', - '/files_encryption/keys/foo/bar.txt', - 'user1.shareKey', - false, - [['mountpoint' => 'foobar']], - false - ], - [ - '', - '/files_encryption/keys/foobar/bar.txt', - 'user1.shareKey', - false, - [['mountpoint' => 'foo']], - false - ] - ]; - } - -} diff --git a/apps/encryption/tests/lib/RecoveryTest.php b/apps/encryption/tests/lib/RecoveryTest.php deleted file mode 100644 index 68c21c80b34..00000000000 --- a/apps/encryption/tests/lib/RecoveryTest.php +++ /dev/null @@ -1,323 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Joas Schilling <nickvergessen@owncloud.com> - * @author Lukas Reschke <lukas@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - - -namespace OCA\Encryption\Tests; - - -use OCA\Encryption\Recovery; -use Test\TestCase; - -class RecoveryTest extends TestCase { - private static $tempStorage = []; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $fileMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $viewMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $userSessionMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $keyManagerMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $configMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $cryptMock; - /** - * @var Recovery - */ - private $instance; - - public function testEnableAdminRecoverySuccessful() { - $this->keyManagerMock->expects($this->exactly(2)) - ->method('recoveryKeyExists') - ->willReturnOnConsecutiveCalls(false, true); - - $this->cryptMock->expects($this->once()) - ->method('createKeyPair') - ->willReturn([ - 'publicKey' => 'privateKey', - 'privateKey' => 'publicKey', - ]); - - $this->keyManagerMock->expects($this->once()) - ->method('setRecoveryKey') - ->willReturn(false); - - $this->keyManagerMock->expects($this->exactly(2)) - ->method('checkRecoveryPassword') - ->willReturnOnConsecutiveCalls(true, true); - - $this->assertTrue($this->instance->enableAdminRecovery('password')); - $this->assertArrayHasKey('recoveryAdminEnabled', self::$tempStorage); - $this->assertEquals(1, self::$tempStorage['recoveryAdminEnabled']); - - $this->assertTrue($this->instance->enableAdminRecovery('password')); - } - - public function testEnableAdminRecoveryCouldNotCheckPassword() { - $this->keyManagerMock->expects($this->exactly(2)) - ->method('recoveryKeyExists') - ->willReturnOnConsecutiveCalls(false, true); - - $this->cryptMock->expects($this->once()) - ->method('createKeyPair') - ->willReturn([ - 'publicKey' => 'privateKey', - 'privateKey' => 'publicKey', - ]); - - $this->keyManagerMock->expects($this->once()) - ->method('setRecoveryKey') - ->willReturn(false); - - $this->keyManagerMock->expects($this->exactly(2)) - ->method('checkRecoveryPassword') - ->willReturnOnConsecutiveCalls(true, false); - - $this->assertTrue($this->instance->enableAdminRecovery('password')); - $this->assertArrayHasKey('recoveryAdminEnabled', self::$tempStorage); - $this->assertEquals(1, self::$tempStorage['recoveryAdminEnabled']); - - $this->assertFalse($this->instance->enableAdminRecovery('password')); - } - - public function testEnableAdminRecoveryCouldNotCreateKey() { - $this->keyManagerMock->expects($this->once()) - ->method('recoveryKeyExists') - ->willReturn(false); - - $this->cryptMock->expects($this->once()) - ->method('createKeyPair') - ->willReturn(false); - - $this->assertFalse($this->instance->enableAdminRecovery('password')); - } - - public function testChangeRecoveryKeyPasswordSuccessful() { - $this->assertFalse($this->instance->changeRecoveryKeyPassword('password', - 'passwordOld')); - - $this->keyManagerMock->expects($this->once()) - ->method('getSystemPrivateKey'); - - $this->cryptMock->expects($this->once()) - ->method('decryptPrivateKey'); - - $this->cryptMock->expects($this->once()) - ->method('encryptPrivateKey') - ->willReturn(true); - - $this->assertTrue($this->instance->changeRecoveryKeyPassword('password', - 'passwordOld')); - } - - public function testChangeRecoveryKeyPasswordCouldNotDecryptPrivateRecoveryKey() { - $this->assertFalse($this->instance->changeRecoveryKeyPassword('password', 'passwordOld')); - - $this->keyManagerMock->expects($this->once()) - ->method('getSystemPrivateKey'); - - $this->cryptMock->expects($this->once()) - ->method('decryptPrivateKey') - ->will($this->returnValue(false)); - - $this->assertFalse($this->instance->changeRecoveryKeyPassword('password', 'passwordOld')); - } - - public function testDisableAdminRecovery() { - - $this->keyManagerMock->expects($this->exactly(2)) - ->method('checkRecoveryPassword') - ->willReturnOnConsecutiveCalls(true, false); - - $this->assertArrayHasKey('recoveryAdminEnabled', self::$tempStorage); - $this->assertTrue($this->instance->disableAdminRecovery('password')); - $this->assertEquals(0, self::$tempStorage['recoveryAdminEnabled']); - - $this->assertFalse($this->instance->disableAdminRecovery('password')); - } - - public function testIsRecoveryEnabledForUser() { - - $this->configMock->expects($this->exactly(2)) - ->method('getUserValue') - ->willReturnOnConsecutiveCalls('1', '0'); - - $this->assertTrue($this->instance->isRecoveryEnabledForUser()); - $this->assertFalse($this->instance->isRecoveryEnabledForUser('admin')); - } - - public function testIsRecoveryKeyEnabled() { - $this->assertFalse($this->instance->isRecoveryKeyEnabled()); - self::$tempStorage['recoveryAdminEnabled'] = '1'; - $this->assertTrue($this->instance->isRecoveryKeyEnabled()); - } - - public function testSetRecoveryFolderForUser() { - $this->viewMock->expects($this->exactly(2)) - ->method('getDirectoryContent') - ->willReturn([]); - $this->assertTrue($this->instance->setRecoveryForUser(0)); - $this->assertTrue($this->instance->setRecoveryForUser('1')); - } - - public function testRecoverUserFiles() { - $this->viewMock->expects($this->once()) - ->method('getDirectoryContent') - ->willReturn([]); - - $this->cryptMock->expects($this->once()) - ->method('decryptPrivateKey'); - $this->assertNull($this->instance->recoverUsersFiles('password', 'admin')); - } - - public function testRecoverFile() { - $this->keyManagerMock->expects($this->once()) - ->method('getEncryptedFileKey') - ->willReturn(true); - - $this->keyManagerMock->expects($this->once()) - ->method('getShareKey') - ->willReturn(true); - - $this->cryptMock->expects($this->once()) - ->method('multiKeyDecrypt') - ->willReturn(true); - - $this->fileMock->expects($this->once()) - ->method('getAccessList') - ->willReturn(['users' => ['admin']]); - - $this->keyManagerMock->expects($this->once()) - ->method('getPublicKey') - ->willReturn('publicKey'); - - $this->keyManagerMock->expects($this->once()) - ->method('addSystemKeys') - ->with($this->anything(), $this->anything(), $this->equalTo('admin')) - ->willReturn(['admin' => 'publicKey']); - - - $this->cryptMock->expects($this->once()) - ->method('multiKeyEncrypt'); - - $this->keyManagerMock->expects($this->once()) - ->method('setAllFileKeys'); - - $this->assertNull(self::invokePrivate($this->instance, - 'recoverFile', - ['/', 'testkey', 'admin'])); - } - - protected function setUp() { - parent::setUp(); - - - $this->userSessionMock = $this->getMockBuilder('OCP\IUserSession') - ->disableOriginalConstructor() - ->setMethods([ - 'isLoggedIn', - 'getUID', - 'login', - 'logout', - 'setUser', - 'getUser' - ]) - ->getMock(); - - $this->userSessionMock->expects($this->any())->method('getUID')->will($this->returnValue('admin')); - - $this->userSessionMock->expects($this->any()) - ->method($this->anything()) - ->will($this->returnSelf()); - - $this->cryptMock = $this->getMockBuilder('OCA\Encryption\Crypto\Crypt')->disableOriginalConstructor()->getMock(); - $randomMock = $this->getMock('OCP\Security\ISecureRandom'); - $this->keyManagerMock = $this->getMockBuilder('OCA\Encryption\KeyManager')->disableOriginalConstructor()->getMock(); - $this->configMock = $this->getMock('OCP\IConfig'); - $keyStorageMock = $this->getMock('OCP\Encryption\Keys\IStorage'); - $this->fileMock = $this->getMock('OCP\Encryption\IFile'); - $this->viewMock = $this->getMock('OC\Files\View'); - - $this->configMock->expects($this->any()) - ->method('setAppValue') - ->will($this->returnCallback([$this, 'setValueTester'])); - - $this->configMock->expects($this->any()) - ->method('getAppValue') - ->will($this->returnCallback([$this, 'getValueTester'])); - - $this->instance = new Recovery($this->userSessionMock, - $this->cryptMock, - $randomMock, - $this->keyManagerMock, - $this->configMock, - $keyStorageMock, - $this->fileMock, - $this->viewMock); - } - - - /** - * @param $app - * @param $key - * @param $value - */ - public function setValueTester($app, $key, $value) { - self::$tempStorage[$key] = $value; - } - - /** - * @param $key - */ - public function removeValueTester($key) { - unset(self::$tempStorage[$key]); - } - - /** - * @param $app - * @param $key - * @return mixed - */ - public function getValueTester($app, $key) { - if (!empty(self::$tempStorage[$key])) { - return self::$tempStorage[$key]; - } - return null; - } - - -} diff --git a/apps/encryption/tests/lib/SessionTest.php b/apps/encryption/tests/lib/SessionTest.php deleted file mode 100644 index f7a8a0369bb..00000000000 --- a/apps/encryption/tests/lib/SessionTest.php +++ /dev/null @@ -1,197 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - - -namespace OCA\Encryption\Tests; - - -use OCA\Encryption\Session; -use Test\TestCase; - -class SessionTest extends TestCase { - private static $tempStorage = []; - /** - * @var Session - */ - private $instance; - private $sessionMock; - - /** - * @expectedException \OCA\Encryption\Exceptions\PrivateKeyMissingException - * @expectedExceptionMessage Private Key missing for user: please try to log-out and log-in again - */ - public function testThatGetPrivateKeyThrowsExceptionWhenNotSet() { - $this->instance->getPrivateKey(); - } - - /** - * @depends testThatGetPrivateKeyThrowsExceptionWhenNotSet - */ - public function testSetAndGetPrivateKey() { - $this->instance->setPrivateKey('dummyPrivateKey'); - $this->assertEquals('dummyPrivateKey', $this->instance->getPrivateKey()); - - } - - /** - * @depends testSetAndGetPrivateKey - */ - public function testIsPrivateKeySet() { - $this->instance->setPrivateKey('dummyPrivateKey'); - $this->assertTrue($this->instance->isPrivateKeySet()); - - unset(self::$tempStorage['privateKey']); - $this->assertFalse($this->instance->isPrivateKeySet()); - - // Set private key back so we can test clear method - self::$tempStorage['privateKey'] = 'dummyPrivateKey'; - } - - public function testDecryptAllModeActivated() { - $this->instance->prepareDecryptAll('user1', 'usersKey'); - $this->assertTrue($this->instance->decryptAllModeActivated()); - $this->assertSame('user1', $this->instance->getDecryptAllUid()); - $this->assertSame('usersKey', $this->instance->getDecryptAllKey()); - } - - public function testDecryptAllModeDeactivated() { - $this->assertFalse($this->instance->decryptAllModeActivated()); - } - - /** - * @expectedException \Exception - * @expectExceptionMessage 'Please activate decrypt all mode first' - */ - public function testGetDecryptAllUidException() { - $this->instance->getDecryptAllUid(); - } - - /** - * @expectedException \Exception - * @expectExceptionMessage 'No uid found while in decrypt all mode' - */ - public function testGetDecryptAllUidException2() { - $this->instance->prepareDecryptAll(null, 'key'); - $this->instance->getDecryptAllUid(); - } - - /** - * @expectedException \OCA\Encryption\Exceptions\PrivateKeyMissingException - * @expectExceptionMessage 'Please activate decrypt all mode first' - */ - public function testGetDecryptAllKeyException() { - $this->instance->getDecryptAllKey(); - } - - /** - * @expectedException \OCA\Encryption\Exceptions\PrivateKeyMissingException - * @expectExceptionMessage 'No key found while in decrypt all mode' - */ - public function testGetDecryptAllKeyException2() { - $this->instance->prepareDecryptAll('user', null); - $this->instance->getDecryptAllKey(); - } - - /** - * - */ - public function testSetAndGetStatusWillSetAndReturn() { - // Check if get status will return 0 if it has not been set before - $this->assertEquals(0, $this->instance->getStatus()); - - $this->instance->setStatus(Session::NOT_INITIALIZED); - $this->assertEquals(0, $this->instance->getStatus()); - - $this->instance->setStatus(Session::INIT_EXECUTED); - $this->assertEquals(1, $this->instance->getStatus()); - - $this->instance->setStatus(Session::INIT_SUCCESSFUL); - $this->assertEquals(2, $this->instance->getStatus()); - } - - /** - * @param $key - * @param $value - */ - public function setValueTester($key, $value) { - self::$tempStorage[$key] = $value; - } - - /** - * @param $key - */ - public function removeValueTester($key) { - unset(self::$tempStorage[$key]); - } - - /** - * @param $key - * @return mixed - */ - public function getValueTester($key) { - if (!empty(self::$tempStorage[$key])) { - return self::$tempStorage[$key]; - } - return null; - } - - /** - * - */ - public function testClearWillRemoveValues() { - $this->instance->setPrivateKey('privateKey'); - $this->instance->setStatus('initStatus'); - $this->instance->prepareDecryptAll('user', 'key'); - $this->assertNotEmpty(self::$tempStorage); - $this->instance->clear(); - $this->assertEmpty(self::$tempStorage); - } - - /** - * - */ - protected function setUp() { - parent::setUp(); - $this->sessionMock = $this->getMock('OCP\ISession'); - - $this->sessionMock->expects($this->any()) - ->method('set') - ->will($this->returnCallback([$this, "setValueTester"])); - - $this->sessionMock->expects($this->any()) - ->method('get') - ->will($this->returnCallback([$this, "getValueTester"])); - - $this->sessionMock->expects($this->any()) - ->method('remove') - ->will($this->returnCallback([$this, "removeValueTester"])); - - - $this->instance = new Session($this->sessionMock); - } - - protected function tearDown() { - self::$tempStorage = []; - parent::tearDown(); - } -} diff --git a/apps/encryption/tests/lib/UtilTest.php b/apps/encryption/tests/lib/UtilTest.php deleted file mode 100644 index fa90125d6e9..00000000000 --- a/apps/encryption/tests/lib/UtilTest.php +++ /dev/null @@ -1,206 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Clark Tomlinson <fallen013@gmail.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - - -namespace OCA\Encryption\Tests; - - -use OCA\Encryption\Util; -use Test\TestCase; - -class UtilTest extends TestCase { - private static $tempStorage = []; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $configMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $filesMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $userManagerMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $mountMock; - - /** @var Util */ - private $instance; - - public function testSetRecoveryForUser() { - $this->instance->setRecoveryForUser('1'); - $this->assertArrayHasKey('recoveryEnabled', self::$tempStorage); - } - - public function testIsRecoveryEnabledForUser() { - $this->assertTrue($this->instance->isRecoveryEnabledForUser('admin')); - - // Assert recovery will return default value if not set - unset(self::$tempStorage['recoveryEnabled']); - $this->assertEquals(0, $this->instance->isRecoveryEnabledForUser('admin')); - } - - public function testUserHasFiles() { - $this->filesMock->expects($this->once()) - ->method('file_exists') - ->will($this->returnValue(true)); - - $this->assertTrue($this->instance->userHasFiles('admin')); - } - - protected function setUp() { - parent::setUp(); - $this->mountMock = $this->getMock('\OCP\Files\Mount\IMountPoint'); - $this->filesMock = $this->getMock('OC\Files\View'); - $this->userManagerMock = $this->getMock('\OCP\IUserManager'); - - $cryptMock = $this->getMockBuilder('OCA\Encryption\Crypto\Crypt') - ->disableOriginalConstructor() - ->getMock(); - $loggerMock = $this->getMock('OCP\ILogger'); - $userSessionMock = $this->getMockBuilder('OCP\IUserSession') - ->disableOriginalConstructor() - ->setMethods([ - 'isLoggedIn', - 'getUID', - 'login', - 'logout', - 'setUser', - 'getUser' - ]) - ->getMock(); - - $userSessionMock->method('isLoggedIn')->will($this->returnValue(true)); - - $userSessionMock->method('getUID')->will($this->returnValue('admin')); - - $userSessionMock->expects($this->any()) - ->method($this->anything()) - ->will($this->returnSelf()); - - - $this->configMock = $configMock = $this->getMock('OCP\IConfig'); - - $this->configMock->expects($this->any()) - ->method('getUserValue') - ->will($this->returnCallback([$this, 'getValueTester'])); - - $this->configMock->expects($this->any()) - ->method('setUserValue') - ->will($this->returnCallback([$this, 'setValueTester'])); - - $this->instance = new Util($this->filesMock, $cryptMock, $loggerMock, $userSessionMock, $configMock, $this->userManagerMock); - } - - /** - * @param $userId - * @param $app - * @param $key - * @param $value - */ - public function setValueTester($userId, $app, $key, $value) { - self::$tempStorage[$key] = $value; - } - - /** - * @param $userId - * @param $app - * @param $key - * @param $default - * @return mixed - */ - public function getValueTester($userId, $app, $key, $default) { - if (!empty(self::$tempStorage[$key])) { - return self::$tempStorage[$key]; - } - return $default ?: null; - } - - /** - * @dataProvider dataTestIsMasterKeyEnabled - * - * @param string $value - * @param bool $expect - */ - public function testIsMasterKeyEnabled($value, $expect) { - $this->configMock->expects($this->once())->method('getAppValue') - ->with('encryption', 'useMasterKey', '0')->willReturn($value); - $this->assertSame($expect, - $this->instance->isMasterKeyEnabled() - ); - } - - public function dataTestIsMasterKeyEnabled() { - return [ - ['0', false], - ['1', true] - ]; - } - - /** - * @dataProvider dataTestShouldEncryptHomeStorage - * @param $returnValue return value from getAppValue() - * @param $expected - */ - public function testShouldEncryptHomeStorage($returnValue, $expected) { - $this->configMock->expects($this->once())->method('getAppValue') - ->with('encryption', 'encryptHomeStorage', '1') - ->willReturn($returnValue); - - $this->assertSame($expected, - $this->instance->shouldEncryptHomeStorage()); - } - - public function dataTestShouldEncryptHomeStorage() { - return [ - ['1', true], - ['0', false] - ]; - } - - /** - * @dataProvider dataTestSetEncryptHomeStorage - * @param $value - * @param $expected - */ - public function testSetEncryptHomeStorage($value, $expected) { - $this->configMock->expects($this->once())->method('setAppValue') - ->with('encryption', 'encryptHomeStorage', $expected); - $this->instance->setEncryptHomeStorage($value); - } - - public function dataTestSetEncryptHomeStorage() { - return [ - [true, '1'], - [false, '0'] - ]; - } - - public function testGetStorage() { - $path = '/foo/bar.txt'; - $this->filesMock->expects($this->once())->method('getMount')->with($path) - ->willReturn($this->mountMock); - $this->mountMock->expects($this->once())->method('getStorage')->willReturn(true); - - $this->assertTrue($this->instance->getStorage($path)); - } - -} diff --git a/apps/encryption/tests/lib/crypto/cryptTest.php b/apps/encryption/tests/lib/crypto/cryptTest.php deleted file mode 100644 index 2f290db21a1..00000000000 --- a/apps/encryption/tests/lib/crypto/cryptTest.php +++ /dev/null @@ -1,457 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Joas Schilling <nickvergessen@owncloud.com> - * @author Lukas Reschke <lukas@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - - -namespace OCA\Encryption\Tests\lib\Crypto; - - -use OCA\Encryption\Crypto\Crypt; -use Test\TestCase; - -class cryptTest extends TestCase { - - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $logger; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $userSession; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $config; - - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $l; - - /** @var Crypt */ - private $crypt; - - public function setUp() { - parent::setUp(); - - $this->logger = $this->getMockBuilder('OCP\ILogger') - ->disableOriginalConstructor() - ->getMock(); - $this->logger->expects($this->any()) - ->method('warning') - ->willReturn(true); - $this->userSession = $this->getMockBuilder('OCP\IUserSession') - ->disableOriginalConstructor() - ->getMock(); - $this->config = $this->getMockBuilder('OCP\IConfig') - ->disableOriginalConstructor() - ->getMock(); - $this->l = $this->getMock('OCP\IL10N'); - - $this->crypt = new Crypt($this->logger, $this->userSession, $this->config, $this->l); - } - - /** - * test getOpenSSLConfig without any additional parameters - */ - public function testGetOpenSSLConfigBasic() { - - $this->config->expects($this->once()) - ->method('getSystemValue') - ->with($this->equalTo('openssl'), $this->equalTo([])) - ->willReturn(array()); - - $result = self::invokePrivate($this->crypt, 'getOpenSSLConfig'); - $this->assertSame(1, count($result)); - $this->assertArrayHasKey('private_key_bits', $result); - $this->assertSame(4096, $result['private_key_bits']); - } - - /** - * test getOpenSSLConfig with additional parameters defined in config.php - */ - public function testGetOpenSSLConfig() { - - $this->config->expects($this->once()) - ->method('getSystemValue') - ->with($this->equalTo('openssl'), $this->equalTo([])) - ->willReturn(array('foo' => 'bar', 'private_key_bits' => 1028)); - - $result = self::invokePrivate($this->crypt, 'getOpenSSLConfig'); - $this->assertSame(2, count($result)); - $this->assertArrayHasKey('private_key_bits', $result); - $this->assertArrayHasKey('foo', $result); - $this->assertSame(1028, $result['private_key_bits']); - $this->assertSame('bar', $result['foo']); - } - - - /** - * test generateHeader with valid key formats - * - * @dataProvider dataTestGenerateHeader - */ - public function testGenerateHeader($keyFormat, $expected) { - - $this->config->expects($this->once()) - ->method('getSystemValue') - ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) - ->willReturn('AES-128-CFB'); - - if ($keyFormat) { - $result = $this->crypt->generateHeader($keyFormat); - } else { - $result = $this->crypt->generateHeader(); - } - - $this->assertSame($expected, $result); - } - - /** - * test generateHeader with invalid key format - * - * @expectedException \InvalidArgumentException - */ - public function testGenerateHeaderInvalid() { - $this->crypt->generateHeader('unknown'); - } - - /** - * @return array - */ - public function dataTestGenerateHeader() { - return [ - [null, 'HBEGIN:cipher:AES-128-CFB:keyFormat:hash:HEND'], - ['password', 'HBEGIN:cipher:AES-128-CFB:keyFormat:password:HEND'], - ['hash', 'HBEGIN:cipher:AES-128-CFB:keyFormat:hash:HEND'] - ]; - } - - public function testGetCipherWithInvalidCipher() { - $this->config->expects($this->once()) - ->method('getSystemValue') - ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) - ->willReturn('Not-Existing-Cipher'); - $this->logger - ->expects($this->once()) - ->method('warning') - ->with('Unsupported cipher (Not-Existing-Cipher) defined in config.php supported. Falling back to AES-256-CTR'); - - $this->assertSame('AES-256-CTR', $this->crypt->getCipher()); - } - - /** - * @dataProvider dataProviderGetCipher - * @param string $configValue - * @param string $expected - */ - public function testGetCipher($configValue, $expected) { - $this->config->expects($this->once()) - ->method('getSystemValue') - ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) - ->willReturn($configValue); - - $this->assertSame($expected, - $this->crypt->getCipher() - ); - - } - - /** - * data provider for testGetCipher - * - * @return array - */ - public function dataProviderGetCipher() { - return array( - array('AES-128-CFB', 'AES-128-CFB'), - array('AES-256-CFB', 'AES-256-CFB'), - array('AES-128-CTR', 'AES-128-CTR'), - array('AES-256-CTR', 'AES-256-CTR'), - - array('unknown', 'AES-256-CTR') - ); - } - - /** - * test concatIV() - */ - public function testConcatIV() { - - $result = self::invokePrivate( - $this->crypt, - 'concatIV', - array('content', 'my_iv')); - - $this->assertSame('content00iv00my_iv', - $result - ); - } - - /** - * @dataProvider dataTestSplitMetaData - */ - public function testSplitMetaData($data, $expected) { - $result = self::invokePrivate($this->crypt, 'splitMetaData', array($data, 'AES-256-CFB')); - $this->assertTrue(is_array($result)); - $this->assertSame(3, count($result)); - $this->assertArrayHasKey('encrypted', $result); - $this->assertArrayHasKey('iv', $result); - $this->assertArrayHasKey('signature', $result); - $this->assertSame($expected['encrypted'], $result['encrypted']); - $this->assertSame($expected['iv'], $result['iv']); - $this->assertSame($expected['signature'], $result['signature']); - } - - public function dataTestSplitMetaData() { - return [ - ['encryptedContent00iv001234567890123456xx', - ['encrypted' => 'encryptedContent', 'iv' => '1234567890123456', 'signature' => false]], - ['encryptedContent00iv00123456789012345600sig00e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86xxx', - ['encrypted' => 'encryptedContent', 'iv' => '1234567890123456', 'signature' => 'e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86']], - ]; - } - - /** - * @dataProvider dataTestHasSignature - */ - public function testHasSignature($data, $expected) { - $this->assertSame($expected, - $this->invokePrivate($this->crypt, 'hasSignature', array($data, 'AES-256-CFB')) - ); - } - - public function dataTestHasSignature() { - return [ - ['encryptedContent00iv001234567890123456xx', false], - ['encryptedContent00iv00123456789012345600sig00e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86xxx', true] - ]; - } - - /** - * @dataProvider dataTestHasSignatureFail - * @expectedException \OC\HintException - */ - public function testHasSignatureFail($cipher) { - $data = 'encryptedContent00iv001234567890123456xx'; - $this->invokePrivate($this->crypt, 'hasSignature', array($data, $cipher)); - } - - public function dataTestHasSignatureFail() { - return [ - ['AES-256-CTR'], - ['aes-256-ctr'], - ['AES-128-CTR'], - ['ctr-256-ctr'] - ]; - } - - /** - * test addPadding() - */ - public function testAddPadding() { - $result = self::invokePrivate($this->crypt, 'addPadding', array('data')); - $this->assertSame('dataxxx', $result); - } - - /** - * test removePadding() - * - * @dataProvider dataProviderRemovePadding - * @param $data - * @param $expected - */ - public function testRemovePadding($data, $expected) { - $result = self::invokePrivate($this->crypt, 'removePadding', array($data)); - $this->assertSame($expected, $result); - } - - /** - * data provider for testRemovePadding - * - * @return array - */ - public function dataProviderRemovePadding() { - return array( - array('dataxx', 'data'), - array('data', false) - ); - } - - /** - * test parseHeader() - */ - public function testParseHeader() { - - $header= 'HBEGIN:foo:bar:cipher:AES-256-CFB:HEND'; - $result = self::invokePrivate($this->crypt, 'parseHeader', array($header)); - - $this->assertTrue(is_array($result)); - $this->assertSame(2, count($result)); - $this->assertArrayHasKey('foo', $result); - $this->assertArrayHasKey('cipher', $result); - $this->assertSame('bar', $result['foo']); - $this->assertSame('AES-256-CFB', $result['cipher']); - } - - /** - * test encrypt() - * - * @return string - */ - public function testEncrypt() { - - $decrypted = 'content'; - $password = 'password'; - $iv = self::invokePrivate($this->crypt, 'generateIv'); - - $this->assertTrue(is_string($iv)); - $this->assertSame(16, strlen($iv)); - - $result = self::invokePrivate($this->crypt, 'encrypt', array($decrypted, $iv, $password)); - - $this->assertTrue(is_string($result)); - - return array( - 'password' => $password, - 'iv' => $iv, - 'encrypted' => $result, - 'decrypted' => $decrypted); - - } - - /** - * test decrypt() - * - * @depends testEncrypt - */ - public function testDecrypt($data) { - - $result = self::invokePrivate( - $this->crypt, - 'decrypt', - array($data['encrypted'], $data['iv'], $data['password'])); - - $this->assertSame($data['decrypted'], $result); - - } - - /** - * test return values of valid ciphers - * - * @dataProvider dataTestGetKeySize - */ - public function testGetKeySize($cipher, $expected) { - $result = $this->invokePrivate($this->crypt, 'getKeySize', [$cipher]); - $this->assertSame($expected, $result); - } - - /** - * test exception if cipher is unknown - * - * @expectedException \InvalidArgumentException - */ - public function testGetKeySizeFailure() { - $this->invokePrivate($this->crypt, 'getKeySize', ['foo']); - } - - /** - * @return array - */ - public function dataTestGetKeySize() { - return [ - ['AES-256-CFB', 32], - ['AES-128-CFB', 16], - ['AES-256-CTR', 32], - ['AES-128-CTR', 16], - ]; - } - - /** - * @dataProvider dataTestDecryptPrivateKey - */ - public function testDecryptPrivateKey($header, $privateKey, $expectedCipher, $isValidKey, $expected) { - /** @var \OCA\Encryption\Crypto\Crypt | \PHPUnit_Framework_MockObject_MockObject $crypt */ - $crypt = $this->getMockBuilder('OCA\Encryption\Crypto\Crypt') - ->setConstructorArgs( - [ - $this->logger, - $this->userSession, - $this->config, - $this->l - ] - ) - ->setMethods( - [ - 'parseHeader', - 'generatePasswordHash', - 'symmetricDecryptFileContent', - 'isValidPrivateKey' - ] - ) - ->getMock(); - - $crypt->expects($this->once())->method('parseHeader')->willReturn($header); - if (isset($header['keyFormat']) && $header['keyFormat'] === 'hash') { - $crypt->expects($this->once())->method('generatePasswordHash')->willReturn('hash'); - $password = 'hash'; - } else { - $crypt->expects($this->never())->method('generatePasswordHash'); - $password = 'password'; - } - - $crypt->expects($this->once())->method('symmetricDecryptFileContent') - ->with('privateKey', $password, $expectedCipher)->willReturn('key'); - $crypt->expects($this->once())->method('isValidPrivateKey')->willReturn($isValidKey); - - $result = $crypt->decryptPrivateKey($privateKey, 'password'); - - $this->assertSame($expected, $result); - } - - /** - * @return array - */ - public function dataTestDecryptPrivateKey() { - return [ - [['cipher' => 'AES-128-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-128-CFB', true, 'key'], - [['cipher' => 'AES-256-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'], - [['cipher' => 'AES-256-CFB', 'keyFormat' => 'password'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', false, false], - [['cipher' => 'AES-256-CFB', 'keyFormat' => 'hash'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'], - [['cipher' => 'AES-256-CFB'], 'HBEGIN:HENDprivateKey', 'AES-256-CFB', true, 'key'], - [[], 'privateKey', 'AES-128-CFB', true, 'key'], - ]; - } - - public function testIsValidPrivateKey() { - $res = openssl_pkey_new(); - openssl_pkey_export($res, $privateKey); - - // valid private key - $this->assertTrue( - $this->invokePrivate($this->crypt, 'isValidPrivateKey', [$privateKey]) - ); - - // invalid private key - $this->assertFalse( - $this->invokePrivate($this->crypt, 'isValidPrivateKey', ['foo']) - ); - } - -} diff --git a/apps/encryption/tests/lib/crypto/decryptalltest.php b/apps/encryption/tests/lib/crypto/decryptalltest.php deleted file mode 100644 index 0945692e427..00000000000 --- a/apps/encryption/tests/lib/crypto/decryptalltest.php +++ /dev/null @@ -1,133 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - - -namespace OCA\Encryption\Tests\lib\Crypto; - - -use OCA\Encryption\Crypto\Crypt; -use OCA\Encryption\Crypto\DecryptAll; -use OCA\Encryption\KeyManager; -use OCA\Encryption\Session; -use OCA\Encryption\Util; -use Symfony\Component\Console\Helper\QuestionHelper; -use Test\TestCase; - -class DecryptAllTest extends TestCase { - - /** @var DecryptAll */ - protected $instance; - - /** @var Util | \PHPUnit_Framework_MockObject_MockObject */ - protected $util; - - /** @var KeyManager | \PHPUnit_Framework_MockObject_MockObject */ - protected $keyManager; - - /** @var Crypt | \PHPUnit_Framework_MockObject_MockObject */ - protected $crypt; - - /** @var Session | \PHPUnit_Framework_MockObject_MockObject */ - protected $session; - - /** @var QuestionHelper | \PHPUnit_Framework_MockObject_MockObject */ - protected $questionHelper; - - public function setUp() { - parent::setUp(); - - $this->util = $this->getMockBuilder('OCA\Encryption\Util') - ->disableOriginalConstructor()->getMock(); - $this->keyManager = $this->getMockBuilder('OCA\Encryption\KeyManager') - ->disableOriginalConstructor()->getMock(); - $this->crypt = $this->getMockBuilder('OCA\Encryption\Crypto\Crypt') - ->disableOriginalConstructor()->getMock(); - $this->session = $this->getMockBuilder('OCA\Encryption\Session') - ->disableOriginalConstructor()->getMock(); - $this->questionHelper = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') - ->disableOriginalConstructor()->getMock(); - - $this->instance = new DecryptAll( - $this->util, - $this->keyManager, - $this->crypt, - $this->session, - $this->questionHelper - ); - } - - public function testUpdateSession() { - $this->session->expects($this->once())->method('prepareDecryptAll') - ->with('user1', 'key1'); - - $this->invokePrivate($this->instance, 'updateSession', ['user1', 'key1']); - } - - /** - * @dataProvider dataTestGetPrivateKey - * - * @param string $user - * @param string $recoveryKeyId - */ - public function testGetPrivateKey($user, $recoveryKeyId, $masterKeyId) { - $password = 'passwd'; - $recoveryKey = 'recoveryKey'; - $userKey = 'userKey'; - $unencryptedKey = 'unencryptedKey'; - - $this->keyManager->expects($this->any())->method('getRecoveryKeyId') - ->willReturn($recoveryKeyId); - - if ($user === $recoveryKeyId) { - $this->keyManager->expects($this->once())->method('getSystemPrivateKey') - ->with($recoveryKeyId)->willReturn($recoveryKey); - $this->keyManager->expects($this->never())->method('getPrivateKey'); - $this->crypt->expects($this->once())->method('decryptPrivateKey') - ->with($recoveryKey, $password)->willReturn($unencryptedKey); - } elseif ($user === $masterKeyId) { - $this->keyManager->expects($this->once())->method('getSystemPrivateKey') - ->with($masterKeyId)->willReturn($masterKey); - $this->keyManager->expects($this->never())->method('getPrivateKey'); - $this->crypt->expects($this->once())->method('decryptPrivateKey') - ->with($masterKey, $password, $masterKeyId)->willReturn($unencryptedKey); - - } else { - $this->keyManager->expects($this->never())->method('getSystemPrivateKey'); - $this->keyManager->expects($this->once())->method('getPrivateKey') - ->with($user)->willReturn($userKey); - $this->crypt->expects($this->once())->method('decryptPrivateKey') - ->with($userKey, $password, $user)->willReturn($unencryptedKey); - } - - $this->assertSame($unencryptedKey, - $this->invokePrivate($this->instance, 'getPrivateKey', [$user, $password]) - ); - } - - public function dataTestGetPrivateKey() { - return [ - ['user1', 'recoveryKey', 'masterKeyId'], - ['recoveryKeyId', 'recoveryKeyId', 'masterKeyId'], - ['masterKeyId', 'masterKeyId', 'masterKeyId'] - ]; - } - -} diff --git a/apps/encryption/tests/lib/crypto/encryptalltest.php b/apps/encryption/tests/lib/crypto/encryptalltest.php deleted file mode 100644 index 04d931342a7..00000000000 --- a/apps/encryption/tests/lib/crypto/encryptalltest.php +++ /dev/null @@ -1,291 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - - -namespace OCA\Encryption\Tests\lib\Crypto; - - -use OCA\Encryption\Crypto\EncryptAll; -use Test\TestCase; - -class EncryptAllTest extends TestCase { - - /** @var \PHPUnit_Framework_MockObject_MockObject | \OCA\Encryption\KeyManager */ - protected $keyManager; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \OCP\IUserManager */ - protected $userManager; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \OCA\Encryption\Users\Setup */ - protected $setupUser; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \OC\Files\View */ - protected $view; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \OCP\IConfig */ - protected $config; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \OCP\Mail\IMailer */ - protected $mailer; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \OCP\IL10N */ - protected $l; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \Symfony\Component\Console\Helper\QuestionHelper */ - protected $questionHelper; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \Symfony\Component\Console\Input\InputInterface */ - protected $inputInterface; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \Symfony\Component\Console\Output\OutputInterface */ - protected $outputInterface; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \OCP\UserInterface */ - protected $userInterface; - - /** @var \PHPUnit_Framework_MockObject_MockObject | \OCP\Security\ISecureRandom */ - protected $secureRandom; - - /** @var EncryptAll */ - protected $encryptAll; - - function setUp() { - parent::setUp(); - $this->setupUser = $this->getMockBuilder('OCA\Encryption\Users\Setup') - ->disableOriginalConstructor()->getMock(); - $this->keyManager = $this->getMockBuilder('OCA\Encryption\KeyManager') - ->disableOriginalConstructor()->getMock(); - $this->userManager = $this->getMockBuilder('OCP\IUserManager') - ->disableOriginalConstructor()->getMock(); - $this->view = $this->getMockBuilder('OC\Files\View') - ->disableOriginalConstructor()->getMock(); - $this->config = $this->getMockBuilder('OCP\IConfig') - ->disableOriginalConstructor()->getMock(); - $this->mailer = $this->getMockBuilder('OCP\Mail\IMailer') - ->disableOriginalConstructor()->getMock(); - $this->l = $this->getMockBuilder('OCP\IL10N') - ->disableOriginalConstructor()->getMock(); - $this->questionHelper = $this->getMockBuilder('Symfony\Component\Console\Helper\QuestionHelper') - ->disableOriginalConstructor()->getMock(); - $this->inputInterface = $this->getMockBuilder('Symfony\Component\Console\Input\InputInterface') - ->disableOriginalConstructor()->getMock(); - $this->outputInterface = $this->getMockBuilder('Symfony\Component\Console\Output\OutputInterface') - ->disableOriginalConstructor()->getMock(); - $this->userInterface = $this->getMockBuilder('OCP\UserInterface') - ->disableOriginalConstructor()->getMock(); - - - $this->outputInterface->expects($this->any())->method('getFormatter') - ->willReturn($this->getMock('\Symfony\Component\Console\Formatter\OutputFormatterInterface')); - - $this->userManager->expects($this->any())->method('getBackends')->willReturn([$this->userInterface]); - $this->userInterface->expects($this->any())->method('getUsers')->willReturn(['user1', 'user2']); - - $this->secureRandom = $this->getMockBuilder('OCP\Security\ISecureRandom')->disableOriginalConstructor()->getMock(); - $this->secureRandom->expects($this->any())->method('getMediumStrengthGenerator')->willReturn($this->secureRandom); - $this->secureRandom->expects($this->any())->method('getLowStrengthGenerator')->willReturn($this->secureRandom); - $this->secureRandom->expects($this->any())->method('generate')->willReturn('12345678'); - - - $this->encryptAll = new EncryptAll( - $this->setupUser, - $this->userManager, - $this->view, - $this->keyManager, - $this->config, - $this->mailer, - $this->l, - $this->questionHelper, - $this->secureRandom - ); - } - - public function testEncryptAll() { - /** @var EncryptAll | \PHPUnit_Framework_MockObject_MockObject $encryptAll */ - $encryptAll = $this->getMockBuilder('OCA\Encryption\Crypto\EncryptAll') - ->setConstructorArgs( - [ - $this->setupUser, - $this->userManager, - $this->view, - $this->keyManager, - $this->config, - $this->mailer, - $this->l, - $this->questionHelper, - $this->secureRandom - ] - ) - ->setMethods(['createKeyPairs', 'encryptAllUsersFiles', 'outputPasswords']) - ->getMock(); - - $encryptAll->expects($this->at(0))->method('createKeyPairs')->with(); - $encryptAll->expects($this->at(1))->method('encryptAllUsersFiles')->with(); - $encryptAll->expects($this->at(2))->method('outputPasswords')->with(); - - $encryptAll->encryptAll($this->inputInterface, $this->outputInterface); - - } - - public function testCreateKeyPairs() { - /** @var EncryptAll | \PHPUnit_Framework_MockObject_MockObject $encryptAll */ - $encryptAll = $this->getMockBuilder('OCA\Encryption\Crypto\EncryptAll') - ->setConstructorArgs( - [ - $this->setupUser, - $this->userManager, - $this->view, - $this->keyManager, - $this->config, - $this->mailer, - $this->l, - $this->questionHelper, - $this->secureRandom - ] - ) - ->setMethods(['setupUserFS', 'generateOneTimePassword']) - ->getMock(); - - - // set protected property $output - $this->invokePrivate($encryptAll, 'output', [$this->outputInterface]); - - $this->keyManager->expects($this->exactly(2))->method('userHasKeys') - ->willReturnCallback( - function ($user) { - if ($user === 'user1') { - return false; - } - return true; - } - ); - - $encryptAll->expects($this->once())->method('setupUserFS')->with('user1'); - $encryptAll->expects($this->once())->method('generateOneTimePassword')->with('user1')->willReturn('password'); - $this->setupUser->expects($this->once())->method('setupUser')->with('user1', 'password'); - - $this->invokePrivate($encryptAll, 'createKeyPairs'); - - $userPasswords = $this->invokePrivate($encryptAll, 'userPasswords'); - - // we only expect the skipped user, because generateOneTimePassword which - // would set the user with the new password was mocked. - // This method will be tested separately - $this->assertSame(1, count($userPasswords)); - $this->assertSame('', $userPasswords['user2']); - } - - public function testEncryptAllUsersFiles() { - /** @var EncryptAll | \PHPUnit_Framework_MockObject_MockObject $encryptAll */ - $encryptAll = $this->getMockBuilder('OCA\Encryption\Crypto\EncryptAll') - ->setConstructorArgs( - [ - $this->setupUser, - $this->userManager, - $this->view, - $this->keyManager, - $this->config, - $this->mailer, - $this->l, - $this->questionHelper, - $this->secureRandom - ] - ) - ->setMethods(['encryptUsersFiles']) - ->getMock(); - - // set protected property $output - $this->invokePrivate($encryptAll, 'output', [$this->outputInterface]); - $this->invokePrivate($encryptAll, 'userPasswords', [['user1' => 'pwd1', 'user2' => 'pwd2']]); - - $encryptAll->expects($this->at(0))->method('encryptUsersFiles')->with('user1'); - $encryptAll->expects($this->at(1))->method('encryptUsersFiles')->with('user2'); - - $this->invokePrivate($encryptAll, 'encryptAllUsersFiles'); - - } - - public function testEncryptUsersFiles() { - /** @var EncryptAll | \PHPUnit_Framework_MockObject_MockObject $encryptAll */ - $encryptAll = $this->getMockBuilder('OCA\Encryption\Crypto\EncryptAll') - ->setConstructorArgs( - [ - $this->setupUser, - $this->userManager, - $this->view, - $this->keyManager, - $this->config, - $this->mailer, - $this->l, - $this->questionHelper, - $this->secureRandom - ] - ) - ->setMethods(['encryptFile']) - ->getMock(); - - - $this->view->expects($this->at(0))->method('getDirectoryContent') - ->with('/user1/files')->willReturn( - [ - ['name' => 'foo', 'type'=>'dir'], - ['name' => 'bar', 'type'=>'file'], - ] - ); - - $this->view->expects($this->at(3))->method('getDirectoryContent') - ->with('/user1/files/foo')->willReturn( - [ - ['name' => 'subfile', 'type'=>'file'] - ] - ); - - $this->view->expects($this->any())->method('is_dir') - ->willReturnCallback( - function($path) { - if ($path === '/user1/files/foo') { - return true; - } - return false; - } - ); - - $encryptAll->expects($this->at(0))->method('encryptFile')->with('/user1/files/bar'); - $encryptAll->expects($this->at(1))->method('encryptFile')->with('/user1/files/foo/subfile'); - - $progressBar = $this->getMockBuilder('Symfony\Component\Console\Helper\ProgressBar') - ->disableOriginalConstructor()->getMock(); - - $this->invokePrivate($encryptAll, 'encryptUsersFiles', ['user1', $progressBar, '']); - - } - - public function testGenerateOneTimePassword() { - $password = $this->invokePrivate($this->encryptAll, 'generateOneTimePassword', ['user1']); - $this->assertTrue(is_string($password)); - $this->assertSame(8, strlen($password)); - - $userPasswords = $this->invokePrivate($this->encryptAll, 'userPasswords'); - $this->assertSame(1, count($userPasswords)); - $this->assertSame($password, $userPasswords['user1']); - } - -} diff --git a/apps/encryption/tests/lib/crypto/encryptionTest.php b/apps/encryption/tests/lib/crypto/encryptionTest.php deleted file mode 100644 index 8a228c2c215..00000000000 --- a/apps/encryption/tests/lib/crypto/encryptionTest.php +++ /dev/null @@ -1,425 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Joas Schilling <nickvergessen@owncloud.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - -namespace OCA\Encryption\Tests\lib\Crypto; - -use OCA\Encryption\Exceptions\PublicKeyMissingException; -use Test\TestCase; -use OCA\Encryption\Crypto\Encryption; - -class EncryptionTest extends TestCase { - - /** @var Encryption */ - private $instance; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $keyManagerMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $encryptAllMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $decryptAllMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $sessionMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $cryptMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $utilMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $loggerMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $l10nMock; - - /** @var \PHPUnit_Framework_MockObject_MockObject */ - private $storageMock; - - public function setUp() { - parent::setUp(); - - $this->storageMock = $this->getMockBuilder('OCP\Files\Storage') - ->disableOriginalConstructor()->getMock(); - $this->cryptMock = $this->getMockBuilder('OCA\Encryption\Crypto\Crypt') - ->disableOriginalConstructor() - ->getMock(); - $this->utilMock = $this->getMockBuilder('OCA\Encryption\Util') - ->disableOriginalConstructor() - ->getMock(); - $this->keyManagerMock = $this->getMockBuilder('OCA\Encryption\KeyManager') - ->disableOriginalConstructor() - ->getMock(); - $this->sessionMock = $this->getMockBuilder('OCA\Encryption\Session') - ->disableOriginalConstructor() - ->getMock(); - $this->encryptAllMock = $this->getMockBuilder('OCA\Encryption\Crypto\EncryptAll') - ->disableOriginalConstructor() - ->getMock(); - $this->decryptAllMock = $this->getMockBuilder('OCA\Encryption\Crypto\DecryptAll') - ->disableOriginalConstructor() - ->getMock(); - $this->loggerMock = $this->getMockBuilder('OCP\ILogger') - ->disableOriginalConstructor() - ->getMock(); - $this->l10nMock = $this->getMockBuilder('OCP\IL10N') - ->disableOriginalConstructor() - ->getMock(); - $this->l10nMock->expects($this->any()) - ->method('t') - ->with($this->anything()) - ->willReturnArgument(0); - - $this->instance = new Encryption( - $this->cryptMock, - $this->keyManagerMock, - $this->utilMock, - $this->sessionMock, - $this->encryptAllMock, - $this->decryptAllMock, - $this->loggerMock, - $this->l10nMock - ); - - } - - /** - * test if public key from one of the recipients is missing - */ - public function testEndUser1() { - $this->instance->begin('/foo/bar', 'user1', 'r', array(), array('users' => array('user1', 'user2', 'user3'))); - $this->endTest(); - } - - /** - * test if public key from owner is missing - * - * @expectedException \OCA\Encryption\Exceptions\PublicKeyMissingException - */ - public function testEndUser2() { - $this->instance->begin('/foo/bar', 'user2', 'r', array(), array('users' => array('user1', 'user2', 'user3'))); - $this->endTest(); - } - - /** - * common part of testEndUser1 and testEndUser2 - * - * @throws PublicKeyMissingException - */ - public function endTest() { - // prepare internal variables - self::invokePrivate($this->instance, 'isWriteOperation', [true]); - self::invokePrivate($this->instance, 'writeCache', ['']); - - $this->keyManagerMock->expects($this->any()) - ->method('getPublicKey') - ->will($this->returnCallback([$this, 'getPublicKeyCallback'])); - $this->keyManagerMock->expects($this->any()) - ->method('addSystemKeys') - ->will($this->returnCallback([$this, 'addSystemKeysCallback'])); - $this->cryptMock->expects($this->any()) - ->method('multiKeyEncrypt') - ->willReturn(true); - $this->cryptMock->expects($this->any()) - ->method('setAllFileKeys') - ->willReturn(true); - - $this->instance->end('/foo/bar'); - } - - - public function getPublicKeyCallback($uid) { - if ($uid === 'user2') { - throw new PublicKeyMissingException($uid); - } - return $uid; - } - - public function addSystemKeysCallback($accessList, $publicKeys) { - $this->assertSame(2, count($publicKeys)); - $this->assertArrayHasKey('user1', $publicKeys); - $this->assertArrayHasKey('user3', $publicKeys); - return $publicKeys; - } - - /** - * @dataProvider dataProviderForTestGetPathToRealFile - */ - public function testGetPathToRealFile($path, $expected) { - $this->assertSame($expected, - self::invokePrivate($this->instance, 'getPathToRealFile', array($path)) - ); - } - - public function dataProviderForTestGetPathToRealFile() { - return array( - array('/user/files/foo/bar.txt', '/user/files/foo/bar.txt'), - array('/user/files/foo.txt', '/user/files/foo.txt'), - array('/user/files_versions/foo.txt.v543534', '/user/files/foo.txt'), - array('/user/files_versions/foo/bar.txt.v5454', '/user/files/foo/bar.txt'), - ); - } - - /** - * @dataProvider dataTestBegin - */ - public function testBegin($mode, $header, $legacyCipher, $defaultCipher, $fileKey, $expected) { - - $this->sessionMock->expects($this->once()) - ->method('decryptAllModeActivated') - ->willReturn(false); - - $this->sessionMock->expects($this->never())->method('getDecryptAllUid'); - $this->sessionMock->expects($this->never())->method('getDecryptAllKey'); - $this->keyManagerMock->expects($this->never())->method('getEncryptedFileKey'); - $this->keyManagerMock->expects($this->never())->method('getShareKey'); - $this->cryptMock->expects($this->never())->method('multiKeyDecrypt'); - - $this->cryptMock->expects($this->any()) - ->method('getCipher') - ->willReturn($defaultCipher); - $this->cryptMock->expects($this->any()) - ->method('getLegacyCipher') - ->willReturn($legacyCipher); - if (empty($fileKey)) { - $this->cryptMock->expects($this->once()) - ->method('generateFileKey') - ->willReturn('fileKey'); - } else { - $this->cryptMock->expects($this->never()) - ->method('generateFileKey'); - } - - $this->keyManagerMock->expects($this->once()) - ->method('getFileKey') - ->willReturn($fileKey); - - $result = $this->instance->begin('/user/files/foo.txt', 'user', $mode, $header, []); - - $this->assertArrayHasKey('cipher', $result); - $this->assertSame($expected, $result['cipher']); - if ($mode === 'w') { - $this->assertTrue(self::invokePrivate($this->instance, 'isWriteOperation')); - } else { - $this->assertFalse(self::invokePrivate($this->instance, 'isWriteOperation')); - } - } - - public function dataTestBegin() { - return array( - array('w', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'defaultCipher'), - array('r', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'myCipher'), - array('w', [], 'legacyCipher', 'defaultCipher', '', 'defaultCipher'), - array('r', [], 'legacyCipher', 'defaultCipher', 'file_key', 'legacyCipher'), - ); - } - - - /** - * test begin() if decryptAll mode was activated - */ - public function testBeginDecryptAll() { - - $path = '/user/files/foo.txt'; - $recoveryKeyId = 'recoveryKeyId'; - $recoveryShareKey = 'recoveryShareKey'; - $decryptAllKey = 'decryptAllKey'; - $fileKey = 'fileKey'; - - $this->sessionMock->expects($this->once()) - ->method('decryptAllModeActivated') - ->willReturn(true); - $this->sessionMock->expects($this->once()) - ->method('getDecryptAllUid') - ->willReturn($recoveryKeyId); - $this->sessionMock->expects($this->once()) - ->method('getDecryptAllKey') - ->willReturn($decryptAllKey); - - $this->keyManagerMock->expects($this->once()) - ->method('getEncryptedFileKey') - ->willReturn('encryptedFileKey'); - $this->keyManagerMock->expects($this->once()) - ->method('getShareKey') - ->with($path, $recoveryKeyId) - ->willReturn($recoveryShareKey); - $this->cryptMock->expects($this->once()) - ->method('multiKeyDecrypt') - ->with('encryptedFileKey', $recoveryShareKey, $decryptAllKey) - ->willReturn($fileKey); - - $this->keyManagerMock->expects($this->never())->method('getFileKey'); - - $this->instance->begin($path, 'user', 'r', [], []); - - $this->assertSame($fileKey, - $this->invokePrivate($this->instance, 'fileKey') - ); - } - - /** - * @dataProvider dataTestUpdate - * - * @param string $fileKey - * @param boolean $expected - */ - public function testUpdate($fileKey, $expected) { - $this->keyManagerMock->expects($this->once()) - ->method('getFileKey')->willReturn($fileKey); - - $this->keyManagerMock->expects($this->any()) - ->method('getPublicKey')->willReturn('publicKey'); - - $this->keyManagerMock->expects($this->any()) - ->method('addSystemKeys') - ->willReturnCallback(function($accessList, $publicKeys) { - return $publicKeys; - }); - - $this->keyManagerMock->expects($this->never())->method('getVersion'); - $this->keyManagerMock->expects($this->never())->method('setVersion'); - - $this->assertSame($expected, - $this->instance->update('path', 'user1', ['users' => ['user1']]) - ); - } - - public function dataTestUpdate() { - return array( - array('', false), - array('fileKey', true) - ); - } - - public function testUpdateNoUsers() { - - $this->invokePrivate($this->instance, 'rememberVersion', [['path' => 2]]); - - $this->keyManagerMock->expects($this->never())->method('getFileKey'); - $this->keyManagerMock->expects($this->never())->method('getPublicKey'); - $this->keyManagerMock->expects($this->never())->method('addSystemKeys'); - $this->keyManagerMock->expects($this->once())->method('setVersion') - ->willReturnCallback(function($path, $version, $view) { - $this->assertSame('path', $path); - $this->assertSame(2, $version); - $this->assertTrue($view instanceof \OC\Files\View); - }); - $this->instance->update('path', 'user1', []); - } - - /** - * Test case if the public key is missing. ownCloud should still encrypt - * the file for the remaining users - */ - public function testUpdateMissingPublicKey() { - $this->keyManagerMock->expects($this->once()) - ->method('getFileKey')->willReturn('fileKey'); - - $this->keyManagerMock->expects($this->any()) - ->method('getPublicKey')->willReturnCallback( - function($user) { - throw new PublicKeyMissingException($user); - } - ); - - $this->keyManagerMock->expects($this->any()) - ->method('addSystemKeys') - ->willReturnCallback(function($accessList, $publicKeys) { - return $publicKeys; - }); - - $this->cryptMock->expects($this->once())->method('multiKeyEncrypt') - ->willReturnCallback( - function($fileKey, $publicKeys) { - $this->assertEmpty($publicKeys); - $this->assertSame('fileKey', $fileKey); - } - ); - - $this->keyManagerMock->expects($this->never())->method('getVersion'); - $this->keyManagerMock->expects($this->never())->method('setVersion'); - - $this->assertTrue( - $this->instance->update('path', 'user1', ['users' => ['user1']]) - ); - } - - /** - * by default the encryption module should encrypt regular files, files in - * files_versions and files in files_trashbin - * - * @dataProvider dataTestShouldEncrypt - */ - public function testShouldEncrypt($path, $shouldEncryptHomeStorage, $isHomeStorage, $expected) { - $this->utilMock->expects($this->once())->method('shouldEncryptHomeStorage') - ->willReturn($shouldEncryptHomeStorage); - - if ($shouldEncryptHomeStorage === false) { - $this->storageMock->expects($this->once())->method('instanceOfStorage') - ->with('\OCP\Files\IHomeStorage')->willReturn($isHomeStorage); - $this->utilMock->expects($this->once())->method('getStorage')->with($path) - ->willReturn($this->storageMock); - } - - $this->assertSame($expected, - $this->instance->shouldEncrypt($path) - ); - } - - public function dataTestShouldEncrypt() { - return array( - array('/user1/files/foo.txt', true, true, true), - array('/user1/files_versions/foo.txt', true, true, true), - array('/user1/files_trashbin/foo.txt', true, true, true), - array('/user1/some_folder/foo.txt', true, true, false), - array('/user1/foo.txt', true, true, false), - array('/user1/files', true, true, false), - array('/user1/files_trashbin', true, true, false), - array('/user1/files_versions', true, true, false), - // test if shouldEncryptHomeStorage is set to false - array('/user1/files/foo.txt', false, true, false), - array('/user1/files_versions/foo.txt', false, false, true), - ); - } - - /** - * @expectedException \OC\Encryption\Exceptions\DecryptionFailedException - * @expectedExceptionMessage Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you. - */ - public function testDecrypt() { - $this->instance->decrypt('abc'); - } - - public function testPrepareDecryptAll() { - $input = $this->getMock('Symfony\Component\Console\Input\InputInterface'); - $output = $this->getMock('Symfony\Component\Console\Output\OutputInterface'); - - $this->decryptAllMock->expects($this->once())->method('prepare') - ->with($input, $output, 'user'); - - $this->instance->prepareDecryptAll($input, $output, 'user'); - } - -} diff --git a/apps/encryption/tests/lib/users/SetupTest.php b/apps/encryption/tests/lib/users/SetupTest.php deleted file mode 100644 index 0cc59384b16..00000000000 --- a/apps/encryption/tests/lib/users/SetupTest.php +++ /dev/null @@ -1,84 +0,0 @@ -<?php -/** - * @author Björn Schießle <schiessle@owncloud.com> - * @author Clark Tomlinson <fallen013@gmail.com> - * - * @copyright Copyright (c) 2016, ownCloud, Inc. - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * - */ - - -namespace OCA\Encryption\Tests\Users; - - -use OCA\Encryption\Users\Setup; -use Test\TestCase; - -class SetupTest extends TestCase { - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $keyManagerMock; - /** - * @var \PHPUnit_Framework_MockObject_MockObject - */ - private $cryptMock; - /** - * @var Setup - */ - private $instance; - - public function testSetupServerSide() { - $this->keyManagerMock->expects($this->exactly(2))->method('validateShareKey'); - $this->keyManagerMock->expects($this->exactly(2))->method('validateMasterKey'); - $this->keyManagerMock->expects($this->exactly(2)) - ->method('userHasKeys') - ->with('admin') - ->willReturnOnConsecutiveCalls(true, false); - - $this->assertTrue($this->instance->setupServerSide('admin', - 'password')); - - $this->keyManagerMock->expects($this->once()) - ->method('storeKeyPair') - ->with('admin', 'password') - ->willReturn(false); - - $this->assertFalse($this->instance->setupServerSide('admin', - 'password')); - } - - protected function setUp() { - parent::setUp(); - $logMock = $this->getMock('OCP\ILogger'); - $userSessionMock = $this->getMockBuilder('OCP\IUserSession') - ->disableOriginalConstructor() - ->getMock(); - $this->cryptMock = $this->getMockBuilder('OCA\Encryption\Crypto\Crypt') - ->disableOriginalConstructor() - ->getMock(); - - $this->keyManagerMock = $this->getMockBuilder('OCA\Encryption\KeyManager') - ->disableOriginalConstructor() - ->getMock(); - - $this->instance = new Setup($logMock, - $userSessionMock, - $this->cryptMock, - $this->keyManagerMock); - } - -} |