diff options
Diffstat (limited to 'apps/encryption/tests')
20 files changed, 1078 insertions, 1484 deletions
diff --git a/apps/encryption/tests/Command/FixEncryptedVersionTest.php b/apps/encryption/tests/Command/FixEncryptedVersionTest.php index 54e8b41ed6c..d0af359183b 100644 --- a/apps/encryption/tests/Command/FixEncryptedVersionTest.php +++ b/apps/encryption/tests/Command/FixEncryptedVersionTest.php @@ -1,22 +1,11 @@ <?php + +declare(strict_types=1); + /** - * @author Sujith Haridasan <sharidasan@owncloud.com> - * - * @copyright Copyright (c) 2019, ownCloud GmbH - * @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/> - * + * SPDX-FileCopyrightText: 2021-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2019 ownCloud GmbH + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Command; @@ -24,6 +13,12 @@ namespace OCA\Encryption\Tests\Command; use OC\Files\View; use OCA\Encryption\Command\FixEncryptedVersion; use OCA\Encryption\Util; +use OCP\Files\IRootFolder; +use OCP\IConfig; +use OCP\ITempManager; +use OCP\IUserManager; +use OCP\Server; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Symfony\Component\Console\Tester\CommandTester; use Test\TestCase; @@ -42,21 +37,18 @@ class FixEncryptedVersionTest extends TestCase { use EncryptionTrait; use UserTrait; - private $userId; + private string $userId; - /** @var FixEncryptedVersion */ - private $fixEncryptedVersion; + private FixEncryptedVersion $fixEncryptedVersion; - /** @var CommandTester */ - private $commandTester; + private CommandTester $commandTester; - /** @var Util|\PHPUnit\Framework\MockObject\MockObject */ - protected $util; + protected Util&MockObject $util; public function setUp(): void { parent::setUp(); - \OC::$server->getConfig()->setAppValue('encryption', 'useMasterKey', '1'); + Server::get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '1'); $this->util = $this->getMockBuilder(Util::class) ->disableOriginalConstructor()->getMock(); @@ -64,35 +56,35 @@ class FixEncryptedVersionTest extends TestCase { $this->userId = $this->getUniqueId('user_'); $this->createUser($this->userId, 'foo12345678'); - $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); + $tmpFolder = Server::get(ITempManager::class)->getTemporaryFolder(); $this->registerMount($this->userId, '\OC\Files\Storage\Local', '/' . $this->userId, ['datadir' => $tmpFolder]); $this->setupForUser($this->userId, 'foo12345678'); $this->loginWithEncryption($this->userId); $this->fixEncryptedVersion = new FixEncryptedVersion( - \OC::$server->getConfig(), - \OC::$server->get(LoggerInterface::class), - \OC::$server->getRootFolder(), - \OC::$server->getUserManager(), + Server::get(IConfig::class), + Server::get(LoggerInterface::class), + Server::get(IRootFolder::class), + Server::get(IUserManager::class), $this->util, new View('/') ); $this->commandTester = new CommandTester($this->fixEncryptedVersion); - $this->assertTrue(\OC::$server->getEncryptionManager()->isEnabled()); - $this->assertTrue(\OC::$server->getEncryptionManager()->isReady()); - $this->assertTrue(\OC::$server->getEncryptionManager()->isReadyForUser($this->userId)); + $this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isEnabled()); + $this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isReady()); + $this->assertTrue(Server::get(\OCP\Encryption\IManager::class)->isReadyForUser($this->userId)); } /** * In this test the encrypted version of the file is less than the original value * but greater than zero */ - public function testEncryptedVersionLessThanOriginalValue() { + public function testEncryptedVersionLessThanOriginalValue(): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->touch('hello.txt'); $view->touch('world.txt'); @@ -156,11 +148,11 @@ Fixed the file: \"/$this->userId/files/world.txt\" with version 4", $output); * In this test the encrypted version of the file is greater than the original value * but greater than zero */ - public function testEncryptedVersionGreaterThanOriginalValue() { + public function testEncryptedVersionGreaterThanOriginalValue(): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->touch('hello.txt'); $view->touch('world.txt'); @@ -215,11 +207,11 @@ The file \"/$this->userId/files/world.txt\" is: OK Fixed the file: \"/$this->userId/files/world.txt\" with version 4", $output); } - public function testVersionIsRestoredToOriginalIfNoFixIsFound() { + public function testVersionIsRestoredToOriginalIfNoFixIsFound(): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->touch('bar.txt'); for ($i = 0; $i < 40; $i++) { @@ -240,16 +232,16 @@ Fixed the file: \"/$this->userId/files/world.txt\" with version 4", $output); ]); $cacheInfo = $cache->get($fileInfo->getId()); - $encryptedVersion = $cacheInfo["encryptedVersion"]; + $encryptedVersion = $cacheInfo['encryptedVersion']; $this->assertEquals(15, $encryptedVersion); } - public function testRepairUnencryptedFileWhenVersionIsSet() { + public function testRepairUnencryptedFileWhenVersionIsSet(): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); // create a file, it's encrypted and also the version is set in the database $view->touch('hello.txt'); @@ -264,7 +256,7 @@ Fixed the file: \"/$this->userId/files/world.txt\" with version 4", $output); $cacheInfo = ['encryptedVersion' => 1, 'encrypted' => 1]; $cache1->put($fileCache1->getPath(), $cacheInfo); - $absPath = $storage1->getSourcePath('').$fileInfo1->getInternalPath(); + $absPath = $storage1->getSourcePath('') . $fileInfo1->getInternalPath(); // create unencrypted file on disk, the version stays file_put_contents($absPath, 'hello contents'); @@ -288,18 +280,18 @@ Fixed the file: \"/$this->userId/files/hello.txt\" with version 0 (unencrypted)" /** * Test commands with a file path */ - public function testExecuteWithFilePathOption() { + public function testExecuteWithFilePathOption(): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->touch('hello.txt'); $view->touch('world.txt'); $this->commandTester->execute([ 'user' => $this->userId, - '--path' => "/hello.txt" + '--path' => '/hello.txt' ]); $output = $this->commandTester->getDisplay(); @@ -312,11 +304,11 @@ The file \"/$this->userId/files/hello.txt\" is: OK", $output); /** * Test commands with a directory path */ - public function testExecuteWithDirectoryPathOption() { + public function testExecuteWithDirectoryPathOption(): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); - $view = new View("/" . $this->userId . "/files"); + $view = new View('/' . $this->userId . '/files'); $view->mkdir('sub'); $view->touch('sub/hello.txt'); @@ -324,7 +316,7 @@ The file \"/$this->userId/files/hello.txt\" is: OK", $output); $this->commandTester->execute([ 'user' => $this->userId, - '--path' => "/sub" + '--path' => '/sub' ]); $output = $this->commandTester->getDisplay(); @@ -334,13 +326,13 @@ The file \"/$this->userId/files/sub/hello.txt\" is: OK", $output); $this->assertStringNotContainsString('world.txt', $output); } - public function testExecuteWithNoUser() { + public function testExecuteWithNoUser(): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); $this->commandTester->execute([ 'user' => null, - '--path' => "/" + '--path' => '/' ]); $output = $this->commandTester->getDisplay(); @@ -348,13 +340,13 @@ The file \"/$this->userId/files/sub/hello.txt\" is: OK", $output); $this->assertStringContainsString('Either a user id or --all needs to be provided', $output); } - public function testExecuteWithBadUser() { + public function testExecuteWithBadUser(): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); $this->commandTester->execute([ 'user' => 'nonexisting', - '--path' => "/" + '--path' => '/' ]); $output = $this->commandTester->getDisplay(); @@ -365,7 +357,7 @@ The file \"/$this->userId/files/sub/hello.txt\" is: OK", $output); /** * Test commands with a directory path */ - public function testExecuteWithNonExistentPath() { + public function testExecuteWithNonExistentPath(): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); @@ -382,8 +374,8 @@ The file \"/$this->userId/files/sub/hello.txt\" is: OK", $output); /** * Test commands without master key */ - public function testExecuteWithNoMasterKey() { - \OC::$server->getConfig()->setAppValue('encryption', 'useMasterKey', '0'); + public function testExecuteWithNoMasterKey(): void { + Server::get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '0'); $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(false); diff --git a/apps/encryption/tests/Command/TestEnableMasterKey.php b/apps/encryption/tests/Command/TestEnableMasterKey.php index 269e99eae4b..ead3dfd0195 100644 --- a/apps/encryption/tests/Command/TestEnableMasterKey.php +++ b/apps/encryption/tests/Command/TestEnableMasterKey.php @@ -1,26 +1,11 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Command; @@ -34,22 +19,22 @@ use Test\TestCase; class TestEnableMasterKey extends TestCase { - /** @var EnableMasterKey */ + /** @var EnableMasterKey */ protected $enableMasterKey; - /** @var Util | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Util | \PHPUnit\Framework\MockObject\MockObject */ protected $util; - /** @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ protected $config; /** @var \Symfony\Component\Console\Helper\QuestionHelper | \PHPUnit\Framework\MockObject\MockObject */ protected $questionHelper; - /** @var \Symfony\Component\Console\Output\OutputInterface | \PHPUnit\Framework\MockObject\MockObject */ + /** @var \Symfony\Component\Console\Output\OutputInterface | \PHPUnit\Framework\MockObject\MockObject */ protected $output; - /** @var \Symfony\Component\Console\Input\InputInterface | \PHPUnit\Framework\MockObject\MockObject */ + /** @var \Symfony\Component\Console\Input\InputInterface | \PHPUnit\Framework\MockObject\MockObject */ protected $input; protected function setUp(): void { @@ -70,12 +55,12 @@ class TestEnableMasterKey extends TestCase { } /** - * @dataProvider dataTestExecute * * @param bool $isAlreadyEnabled * @param string $answer */ - public function testExecute($isAlreadyEnabled, $answer) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestExecute')] + public function testExecute($isAlreadyEnabled, $answer): void { $this->util->expects($this->once())->method('isMasterKeyEnabled') ->willReturn($isAlreadyEnabled); @@ -96,7 +81,7 @@ class TestEnableMasterKey extends TestCase { $this->invokePrivate($this->enableMasterKey, 'execute', [$this->input, $this->output]); } - public function dataTestExecute() { + public static function dataTestExecute() { return [ [true, ''], [false, 'y'], diff --git a/apps/encryption/tests/Controller/RecoveryControllerTest.php b/apps/encryption/tests/Controller/RecoveryControllerTest.php index 7a33b4b1346..0fec3f4d6a9 100644 --- a/apps/encryption/tests/Controller/RecoveryControllerTest.php +++ b/apps/encryption/tests/Controller/RecoveryControllerTest.php @@ -1,27 +1,11 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Controller; @@ -31,39 +15,36 @@ use OCP\AppFramework\Http; use OCP\IConfig; use OCP\IL10N; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RecoveryControllerTest extends TestCase { - /** @var RecoveryController */ - private $controller; - /** @var \OCP\IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $requestMock; - /** @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $configMock; - /** @var \OCP\IL10N|\PHPUnit\Framework\MockObject\MockObject */ - private $l10nMock; - /** @var \OCA\Encryption\Recovery|\PHPUnit\Framework\MockObject\MockObject */ - private $recoveryMock; - - public function adminRecoveryProvider() { + protected RecoveryController $controller; + + protected IRequest&MockObject $requestMock; + protected IConfig&MockObject $configMock; + protected IL10N&MockObject $l10nMock; + protected Recovery&MockObject $recoveryMock; + + public static function adminRecoveryProvider(): array { return [ ['test', 'test', '1', 'Recovery key successfully enabled', Http::STATUS_OK], ['', 'test', '1', 'Missing recovery key password', Http::STATUS_BAD_REQUEST], ['test', '', '1', 'Please repeat the recovery key password', Http::STATUS_BAD_REQUEST], - ['test', 'soimething that doesn\'t match', '1', 'Repeated recovery key password does not match the provided recovery key password', Http::STATUS_BAD_REQUEST], + ['test', 'something that doesn\'t match', '1', 'Repeated recovery key password does not match the provided recovery key password', Http::STATUS_BAD_REQUEST], ['test', 'test', '0', 'Recovery key successfully disabled', Http::STATUS_OK], ]; } /** - * @dataProvider adminRecoveryProvider * @param $recoveryPassword * @param $passConfirm * @param $enableRecovery * @param $expectedMessage * @param $expectedStatus */ - public function testAdminRecovery($recoveryPassword, $passConfirm, $enableRecovery, $expectedMessage, $expectedStatus) { + #[\PHPUnit\Framework\Attributes\DataProvider('adminRecoveryProvider')] + public function testAdminRecovery($recoveryPassword, $passConfirm, $enableRecovery, $expectedMessage, $expectedStatus): void { $this->recoveryMock->expects($this->any()) ->method('enableAdminRecovery') ->willReturn(true); @@ -81,7 +62,7 @@ class RecoveryControllerTest extends TestCase { $this->assertEquals($expectedStatus, $response->getStatus()); } - public function changeRecoveryPasswordProvider() { + public static function changeRecoveryPasswordProvider(): array { return [ ['test', 'test', 'oldtestFail', 'Could not change the password. Maybe the old password was not correct.', Http::STATUS_BAD_REQUEST], ['test', 'test', 'oldtest', 'Password successfully changed.', Http::STATUS_OK], @@ -92,14 +73,14 @@ class RecoveryControllerTest extends TestCase { } /** - * @dataProvider changeRecoveryPasswordProvider * @param $password * @param $confirmPassword * @param $oldPassword * @param $expectedMessage * @param $expectedStatus */ - public function testChangeRecoveryPassword($password, $confirmPassword, $oldPassword, $expectedMessage, $expectedStatus) { + #[\PHPUnit\Framework\Attributes\DataProvider('changeRecoveryPasswordProvider')] + public function testChangeRecoveryPassword($password, $confirmPassword, $oldPassword, $expectedMessage, $expectedStatus): void { $this->recoveryMock->expects($this->any()) ->method('changeRecoveryKeyPassword') ->with($password, $oldPassword) @@ -116,7 +97,7 @@ class RecoveryControllerTest extends TestCase { $this->assertEquals($expectedStatus, $response->getStatus()); } - public function userSetRecoveryProvider() { + public static function userSetRecoveryProvider(): array { return [ ['1', 'Recovery Key enabled', Http::STATUS_OK], ['0', 'Could not enable the recovery key, please try again or contact your administrator', Http::STATUS_BAD_REQUEST] @@ -124,12 +105,12 @@ class RecoveryControllerTest extends TestCase { } /** - * @dataProvider userSetRecoveryProvider * @param $enableRecovery * @param $expectedMessage * @param $expectedStatus */ - public function testUserSetRecovery($enableRecovery, $expectedMessage, $expectedStatus) { + #[\PHPUnit\Framework\Attributes\DataProvider('userSetRecoveryProvider')] + public function testUserSetRecovery($enableRecovery, $expectedMessage, $expectedStatus): void { $this->recoveryMock->expects($this->any()) ->method('setRecoveryForUser') ->with($enableRecovery) diff --git a/apps/encryption/tests/Controller/SettingsControllerTest.php b/apps/encryption/tests/Controller/SettingsControllerTest.php index 219e2c6ae0f..bee20f67cec 100644 --- a/apps/encryption/tests/Controller/SettingsControllerTest.php +++ b/apps/encryption/tests/Controller/SettingsControllerTest.php @@ -1,27 +1,11 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Controller; @@ -42,37 +26,18 @@ use Test\TestCase; class SettingsControllerTest extends TestCase { - /** @var SettingsController */ - private $controller; - - /** @var \OCP\IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $requestMock; - - /** @var \OCP\IL10N|\PHPUnit\Framework\MockObject\MockObject */ - private $l10nMock; - - /** @var \OCP\IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - private $userManagerMock; - - /** @var \OCP\IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSessionMock; + protected SettingsController $controller; - /** @var \OCA\Encryption\KeyManager|\PHPUnit\Framework\MockObject\MockObject */ - private $keyManagerMock; - - /** @var \OCA\Encryption\Crypto\Crypt|\PHPUnit\Framework\MockObject\MockObject */ - private $cryptMock; - - /** @var \OCA\Encryption\Session|\PHPUnit\Framework\MockObject\MockObject */ - private $sessionMock; - /** @var MockObject|IUser */ - private $user; - - /** @var \OCP\ISession|\PHPUnit\Framework\MockObject\MockObject */ - private $ocSessionMock; - - /** @var \OCA\Encryption\Util|\PHPUnit\Framework\MockObject\MockObject */ - private $utilMock; + protected IRequest&MockObject $requestMock; + protected IL10N&MockObject $l10nMock; + protected IUserManager&MockObject $userManagerMock; + protected IUserSession&MockObject $userSessionMock; + protected KeyManager&MockObject $keyManagerMock; + protected Crypt&MockObject $cryptMock; + protected Session&MockObject $sessionMock; + protected IUser&MockObject $user; + protected ISession&MockObject $ocSessionMock; + protected Util&MockObject $utilMock; protected function setUp(): void { parent::setUp(); @@ -133,7 +98,7 @@ class SettingsControllerTest extends TestCase { /** * test updatePrivateKeyPassword() if wrong new password was entered */ - public function testUpdatePrivateKeyPasswordWrongNewPassword() { + public function testUpdatePrivateKeyPasswordWrongNewPassword(): void { $oldPassword = 'old'; $newPassword = 'new'; @@ -158,7 +123,7 @@ class SettingsControllerTest extends TestCase { /** * test updatePrivateKeyPassword() if wrong old password was entered */ - public function testUpdatePrivateKeyPasswordWrongOldPassword() { + public function testUpdatePrivateKeyPasswordWrongOldPassword(): void { $oldPassword = 'old'; $newPassword = 'new'; @@ -184,26 +149,22 @@ class SettingsControllerTest extends TestCase { /** * test updatePrivateKeyPassword() with the correct old and new password */ - public function testUpdatePrivateKeyPassword() { + public function testUpdatePrivateKeyPassword(): void { $oldPassword = 'old'; $newPassword = 'new'; $this->ocSessionMock->expects($this->once()) - ->method('get')->with('loginname')->willReturn('testUser'); + ->method('get') + ->with('loginname') + ->willReturn('testUser'); $this->userManagerMock ->expects($this->exactly(2)) ->method('checkPassword') - ->withConsecutive( - ['testUserUid', 'new'], - ['testUser', 'new'], - ) - ->willReturnOnConsecutiveCalls( - false, - true, - ); - - + ->willReturnMap([ + ['testUserUid', 'new', false], + ['testUser', 'new', true], + ]); $this->cryptMock ->expects($this->once()) @@ -245,7 +206,7 @@ class SettingsControllerTest extends TestCase { $data['message']); } - public function testSetEncryptHomeStorage() { + public function testSetEncryptHomeStorage(): void { $value = true; $this->utilMock->expects($this->once())->method('setEncryptHomeStorage')->with($value); $this->controller->setEncryptHomeStorage($value); diff --git a/apps/encryption/tests/Controller/StatusControllerTest.php b/apps/encryption/tests/Controller/StatusControllerTest.php index dffc4a97718..1bbcad77411 100644 --- a/apps/encryption/tests/Controller/StatusControllerTest.php +++ b/apps/encryption/tests/Controller/StatusControllerTest.php @@ -1,28 +1,11 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Controller; @@ -31,24 +14,17 @@ use OCA\Encryption\Session; use OCP\Encryption\IManager; use OCP\IL10N; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class StatusControllerTest extends TestCase { - /** @var \OCP\IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $requestMock; - - /** @var \OCP\IL10N|\PHPUnit\Framework\MockObject\MockObject */ - private $l10nMock; - - /** @var \OCA\Encryption\Session | \PHPUnit\Framework\MockObject\MockObject */ - protected $sessionMock; - - /** @var IManager | \PHPUnit\Framework\MockObject\MockObject */ - protected $encryptionManagerMock; + protected IRequest&MockObject $requestMock; + protected IL10N&MockObject $l10nMock; + protected Session&MockObject $sessionMock; + protected IManager&MockObject $encryptionManagerMock; - /** @var StatusController */ - protected $controller; + protected StatusController $controller; protected function setUp(): void { parent::setUp(); @@ -74,12 +50,12 @@ class StatusControllerTest extends TestCase { } /** - * @dataProvider dataTestGetStatus * * @param string $status * @param string $expectedStatus */ - public function testGetStatus($status, $expectedStatus) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetStatus')] + public function testGetStatus($status, $expectedStatus): void { $this->sessionMock->expects($this->once()) ->method('getStatus')->willReturn($status); $result = $this->controller->getStatus(); @@ -87,7 +63,7 @@ class StatusControllerTest extends TestCase { $this->assertSame($expectedStatus, $data['status']); } - public function dataTestGetStatus() { + public static function dataTestGetStatus(): array { return [ [Session::INIT_EXECUTED, 'interactionNeeded'], [Session::INIT_SUCCESSFUL, 'success'], diff --git a/apps/encryption/tests/Crypto/CryptTest.php b/apps/encryption/tests/Crypto/CryptTest.php index f5a173cca83..1355e2c855d 100644 --- a/apps/encryption/tests/Crypto/CryptTest.php +++ b/apps/encryption/tests/Crypto/CryptTest.php @@ -1,53 +1,30 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Crypto; use OCA\Encryption\Crypto\Crypt; +use OCP\Encryption\Exceptions\GenericEncryptionException; use OCP\IConfig; use OCP\IL10N; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class CryptTest extends TestCase { - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; - - /** @var \OCP\IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSession; - - /** @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $config; + protected LoggerInterface&MockObject $logger; + protected IUserSession&MockObject $userSession; + protected IConfig&MockObject $config; + protected IL10N&MockObject $l; - /** @var \OCP\IL10N|\PHPUnit\Framework\MockObject\MockObject */ - private $l; - - /** @var Crypt */ - private $crypt; + protected Crypt $crypt; protected function setUp(): void { parent::setUp(); @@ -56,8 +33,7 @@ class CryptTest extends TestCase { ->disableOriginalConstructor() ->getMock(); $this->logger->expects($this->any()) - ->method('warning') - ->willReturn(true); + ->method('warning'); $this->userSession = $this->getMockBuilder(IUserSession::class) ->disableOriginalConstructor() ->getMock(); @@ -72,7 +48,7 @@ class CryptTest extends TestCase { /** * test getOpenSSLConfig without any additional parameters */ - public function testGetOpenSSLConfigBasic() { + public function testGetOpenSSLConfigBasic(): void { $this->config->expects($this->once()) ->method('getSystemValue') ->with($this->equalTo('openssl'), $this->equalTo([])) @@ -87,7 +63,7 @@ class CryptTest extends TestCase { /** * test getOpenSSLConfig with additional parameters defined in config.php */ - public function testGetOpenSSLConfig() { + public function testGetOpenSSLConfig(): void { $this->config->expects($this->once()) ->method('getSystemValue') ->with($this->equalTo('openssl'), $this->equalTo([])) @@ -104,10 +80,9 @@ class CryptTest extends TestCase { /** * test generateHeader with valid key formats - * - * @dataProvider dataTestGenerateHeader */ - public function testGenerateHeader($keyFormat, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGenerateHeader')] + public function testGenerateHeader($keyFormat, $expected): void { $this->config->expects($this->once()) ->method('getSystemValueString') ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) @@ -126,16 +101,13 @@ class CryptTest extends TestCase { * test generateHeader with invalid key format * */ - public function testGenerateHeaderInvalid() { + public function testGenerateHeaderInvalid(): void { $this->expectException(\InvalidArgumentException::class); $this->crypt->generateHeader('unknown'); } - /** - * @return array - */ - public function dataTestGenerateHeader() { + public static function dataTestGenerateHeader(): array { return [ [null, 'HBEGIN:cipher:AES-128-CFB:keyFormat:hash2:encoding:binary:HEND'], ['password', 'HBEGIN:cipher:AES-128-CFB:keyFormat:password:encoding:binary:HEND'], @@ -143,11 +115,11 @@ class CryptTest extends TestCase { ]; } - public function testGetCipherWithInvalidCipher() { + public function testGetCipherWithInvalidCipher(): void { $this->config->expects($this->once()) - ->method('getSystemValueString') - ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) - ->willReturn('Not-Existing-Cipher'); + ->method('getSystemValueString') + ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) + ->willReturn('Not-Existing-Cipher'); $this->logger ->expects($this->once()) ->method('warning') @@ -157,11 +129,11 @@ class CryptTest extends TestCase { } /** - * @dataProvider dataProviderGetCipher * @param string $configValue * @param string $expected */ - public function testGetCipher($configValue, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderGetCipher')] + public function testGetCipher($configValue, $expected): void { $this->config->expects($this->once()) ->method('getSystemValueString') ->with($this->equalTo('cipher'), $this->equalTo('AES-256-CTR')) @@ -174,10 +146,8 @@ class CryptTest extends TestCase { /** * data provider for testGetCipher - * - * @return array */ - public function dataProviderGetCipher() { + public static function dataProviderGetCipher(): array { return [ ['AES-128-CFB', 'AES-128-CFB'], ['AES-256-CFB', 'AES-256-CFB'], @@ -191,7 +161,7 @@ class CryptTest extends TestCase { /** * test concatIV() */ - public function testConcatIV() { + public function testConcatIV(): void { $result = self::invokePrivate( $this->crypt, 'concatIV', @@ -202,10 +172,8 @@ class CryptTest extends TestCase { ); } - /** - * @dataProvider dataTestSplitMetaData - */ - public function testSplitMetaData($data, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestSplitMetaData')] + public function testSplitMetaData($data, $expected): void { $this->config->method('getSystemValueBool') ->with('encryption_skip_signature_check', false) ->willReturn(true); @@ -220,7 +188,7 @@ class CryptTest extends TestCase { $this->assertSame($expected['signature'], $result['signature']); } - public function dataTestSplitMetaData() { + public static function dataTestSplitMetaData(): array { return [ ['encryptedContent00iv001234567890123456xx', ['encrypted' => 'encryptedContent', 'iv' => '1234567890123456', 'signature' => false]], @@ -229,10 +197,8 @@ class CryptTest extends TestCase { ]; } - /** - * @dataProvider dataTestHasSignature - */ - public function testHasSignature($data, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestHasSignature')] + public function testHasSignature($data, $expected): void { $this->config->method('getSystemValueBool') ->with('encryption_skip_signature_check', false) ->willReturn(true); @@ -241,24 +207,22 @@ class CryptTest extends TestCase { ); } - public function dataTestHasSignature() { + public static function dataTestHasSignature(): array { return [ ['encryptedContent00iv001234567890123456xx', false], ['encryptedContent00iv00123456789012345600sig00e1992521e437f6915f9173b190a512cfc38a00ac24502db44e0ba10c2bb0cc86xxx', true] ]; } - /** - * @dataProvider dataTestHasSignatureFail - */ - public function testHasSignatureFail($cipher) { - $this->expectException(\OCP\Encryption\Exceptions\GenericEncryptionException::class); + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestHasSignatureFail')] + public function testHasSignatureFail($cipher): void { + $this->expectException(GenericEncryptionException::class); $data = 'encryptedContent00iv001234567890123456xx'; $this->invokePrivate($this->crypt, 'hasSignature', [$data, $cipher]); } - public function dataTestHasSignatureFail() { + public static function dataTestHasSignatureFail(): array { return [ ['AES-256-CTR'], ['aes-256-ctr'], @@ -270,7 +234,7 @@ class CryptTest extends TestCase { /** * test addPadding() */ - public function testAddPadding() { + public function testAddPadding(): void { $result = self::invokePrivate($this->crypt, 'addPadding', ['data']); $this->assertSame('dataxxx', $result); } @@ -278,21 +242,19 @@ class CryptTest extends TestCase { /** * test removePadding() * - * @dataProvider dataProviderRemovePadding * @param $data * @param $expected */ - public function testRemovePadding($data, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderRemovePadding')] + public function testRemovePadding($data, $expected): void { $result = self::invokePrivate($this->crypt, 'removePadding', [$data]); $this->assertSame($expected, $result); } /** * data provider for testRemovePadding - * - * @return array */ - public function dataProviderRemovePadding() { + public static function dataProviderRemovePadding(): array { return [ ['dataxx', 'data'], ['data', false] @@ -302,7 +264,7 @@ class CryptTest extends TestCase { /** * test parseHeader() */ - public function testParseHeader() { + public function testParseHeader(): void { $header = 'HBEGIN:foo:bar:cipher:AES-256-CFB:encoding:binary:HEND'; $result = self::invokePrivate($this->crypt, 'parseHeader', [$header]); @@ -347,7 +309,7 @@ class CryptTest extends TestCase { * * @depends testEncrypt */ - public function testDecrypt($data) { + public function testDecrypt($data): void { $result = self::invokePrivate( $this->crypt, 'decrypt', @@ -358,10 +320,9 @@ class CryptTest extends TestCase { /** * test return values of valid ciphers - * - * @dataProvider dataTestGetKeySize */ - public function testGetKeySize($cipher, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetKeySize')] + public function testGetKeySize($cipher, $expected): void { $result = $this->invokePrivate($this->crypt, 'getKeySize', [$cipher]); $this->assertSame($expected, $result); } @@ -370,16 +331,13 @@ class CryptTest extends TestCase { * test exception if cipher is unknown * */ - public function testGetKeySizeFailure() { + public function testGetKeySizeFailure(): void { $this->expectException(\InvalidArgumentException::class); $this->invokePrivate($this->crypt, 'getKeySize', ['foo']); } - /** - * @return array - */ - public function dataTestGetKeySize() { + public static function dataTestGetKeySize(): array { return [ ['AES-256-CFB', 32], ['AES-128-CFB', 16], @@ -388,33 +346,28 @@ class CryptTest extends TestCase { ]; } - /** - * @dataProvider dataTestDecryptPrivateKey - */ - public function testDecryptPrivateKey($header, $privateKey, $expectedCipher, $isValidKey, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestDecryptPrivateKey')] + public function testDecryptPrivateKey($header, $privateKey, $expectedCipher, $isValidKey, $expected): void { $this->config->method('getSystemValueBool') - ->withConsecutive(['encryption.legacy_format_support', false], - ['encryption.use_legacy_base64_encoding', false]) - ->willReturnOnConsecutiveCalls(true, false); + ->willReturnMap([ + ['encryption.legacy_format_support', false, true], + ['encryption.use_legacy_base64_encoding', false, false], + ]); - /** @var \OCA\Encryption\Crypto\Crypt | \PHPUnit\Framework\MockObject\MockObject $crypt */ + /** @var Crypt|\PHPUnit\Framework\MockObject\MockObject $crypt */ $crypt = $this->getMockBuilder(Crypt::class) - ->setConstructorArgs( - [ - $this->logger, - $this->userSession, - $this->config, - $this->l - ] - ) - ->setMethods( - [ - 'parseHeader', - 'generatePasswordHash', - 'symmetricDecryptFileContent', - 'isValidPrivateKey' - ] - ) + ->setConstructorArgs([ + $this->logger, + $this->userSession, + $this->config, + $this->l + ]) + ->onlyMethods([ + 'parseHeader', + 'generatePasswordHash', + 'symmetricDecryptFileContent', + 'isValidPrivateKey' + ]) ->getMock(); $crypt->expects($this->once())->method('parseHeader')->willReturn($header); @@ -435,10 +388,7 @@ class CryptTest extends TestCase { $this->assertSame($expected, $result); } - /** - * @return array - */ - public function dataTestDecryptPrivateKey() { + public static function dataTestDecryptPrivateKey(): array { 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'], @@ -449,7 +399,7 @@ class CryptTest extends TestCase { ]; } - public function testIsValidPrivateKey() { + public function testIsValidPrivateKey(): void { $res = openssl_pkey_new(); openssl_pkey_export($res, $privateKey); @@ -464,7 +414,7 @@ class CryptTest extends TestCase { ); } - public function testMultiKeyEncrypt() { + public function testMultiKeyEncrypt(): void { $res = openssl_pkey_new(); openssl_pkey_export($res, $privateKey); $publicKeyPem = openssl_pkey_get_details($res)['key']; diff --git a/apps/encryption/tests/Crypto/DecryptAllTest.php b/apps/encryption/tests/Crypto/DecryptAllTest.php index 68b49307f31..82e6100bce5 100644 --- a/apps/encryption/tests/Crypto/DecryptAllTest.php +++ b/apps/encryption/tests/Crypto/DecryptAllTest.php @@ -1,26 +1,11 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Crypto; @@ -29,28 +14,19 @@ use OCA\Encryption\Crypto\DecryptAll; use OCA\Encryption\KeyManager; use OCA\Encryption\Session; use OCA\Encryption\Util; +use PHPUnit\Framework\MockObject\MockObject; 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; + protected DecryptAll $instance; - /** @var QuestionHelper | \PHPUnit\Framework\MockObject\MockObject */ - protected $questionHelper; + protected Util&MockObject $util; + protected KeyManager&MockObject $keyManager; + protected Crypt&MockObject $crypt; + protected Session&MockObject $session; + protected QuestionHelper&MockObject $questionHelper; protected function setUp(): void { parent::setUp(); @@ -75,7 +51,7 @@ class DecryptAllTest extends TestCase { ); } - public function testUpdateSession() { + public function testUpdateSession(): void { $this->session->expects($this->once())->method('prepareDecryptAll') ->with('user1', 'key1'); @@ -83,15 +59,16 @@ class DecryptAllTest extends TestCase { } /** - * @dataProvider dataTestGetPrivateKey * * @param string $user * @param string $recoveryKeyId */ - public function testGetPrivateKey($user, $recoveryKeyId, $masterKeyId) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetPrivateKey')] + public function testGetPrivateKey($user, $recoveryKeyId, $masterKeyId): void { $password = 'passwd'; $recoveryKey = 'recoveryKey'; $userKey = 'userKey'; + $masterKey = 'userKey'; $unencryptedKey = 'unencryptedKey'; $this->keyManager->expects($this->any())->method('getRecoveryKeyId') @@ -122,7 +99,7 @@ class DecryptAllTest extends TestCase { ); } - public function dataTestGetPrivateKey() { + public static function dataTestGetPrivateKey() { return [ ['user1', 'recoveryKey', 'masterKeyId'], ['recoveryKeyId', 'recoveryKeyId', 'masterKeyId'], diff --git a/apps/encryption/tests/Crypto/EncryptAllTest.php b/apps/encryption/tests/Crypto/EncryptAllTest.php index 459f680a374..c56e3375a73 100644 --- a/apps/encryption/tests/Crypto/EncryptAllTest.php +++ b/apps/encryption/tests/Crypto/EncryptAllTest.php @@ -1,29 +1,11 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Kenneth Newwood <kenneth@newwood.name> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Crypto; @@ -40,6 +22,8 @@ use OCP\L10N\IFactory; use OCP\Mail\IMailer; use OCP\Security\ISecureRandom; use OCP\UserInterface; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; use Symfony\Component\Console\Formatter\OutputFormatterInterface; use Symfony\Component\Console\Helper\ProgressBar; use Symfony\Component\Console\Helper\QuestionHelper; @@ -49,47 +33,23 @@ use Test\TestCase; class EncryptAllTest extends TestCase { - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Encryption\KeyManager */ - protected $keyManager; - - /** @var \PHPUnit\Framework\MockObject\MockObject | \OCA\Encryption\Util */ - protected $util; - - /** @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; + protected KeyManager&MockObject $keyManager; + protected Util&MockObject $util; + protected IUserManager&MockObject $userManager; + protected Setup&MockObject $setupUser; + protected View&MockObject $view; + protected IConfig&MockObject $config; + protected IMailer&MockObject $mailer; + protected IL10N&MockObject $l; + protected IFactory&MockObject $l10nFactory; + protected \Symfony\Component\Console\Helper\QuestionHelper&MockObject $questionHelper; + protected \Symfony\Component\Console\Input\InputInterface&MockObject $inputInterface; + protected \Symfony\Component\Console\Output\OutputInterface&MockObject $outputInterface; + protected UserInterface&MockObject $userInterface; + protected ISecureRandom&MockObject $secureRandom; + protected LoggerInterface&MockObject $logger; + + protected EncryptAll $encryptAll; protected function setUp(): void { parent::setUp(); @@ -118,8 +78,12 @@ class EncryptAllTest extends TestCase { ->disableOriginalConstructor()->getMock(); $this->userInterface = $this->getMockBuilder(UserInterface::class) ->disableOriginalConstructor()->getMock(); + $this->logger = $this->createMock(LoggerInterface::class); - /* We need format method to return a string */ + /** + * We need format method to return a string + * @var OutputFormatterInterface&MockObject + */ $outputFormatter = $this->createMock(OutputFormatterInterface::class); $outputFormatter->method('isDecorated')->willReturn(false); $outputFormatter->method('format')->willReturnArgument(0); @@ -145,12 +109,20 @@ class EncryptAllTest extends TestCase { $this->l, $this->l10nFactory, $this->questionHelper, - $this->secureRandom + $this->secureRandom, + $this->logger, ); } - public function testEncryptAll() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + protected function createFileInfoMock($type, string $name): FileInfo&MockObject { + $fileInfo = $this->createMock(FileInfo::class); + $fileInfo->method('getType')->willReturn($type); + $fileInfo->method('getName')->willReturn($name); + return $fileInfo; + } + + public function testEncryptAll(): void { + /** @var EncryptAll&MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ @@ -164,10 +136,11 @@ class EncryptAllTest extends TestCase { $this->l, $this->l10nFactory, $this->questionHelper, - $this->secureRandom + $this->secureRandom, + $this->logger, ] ) - ->setMethods(['createKeyPairs', 'encryptAllUsersFiles', 'outputPasswords']) + ->onlyMethods(['createKeyPairs', 'encryptAllUsersFiles', 'outputPasswords']) ->getMock(); $this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false); @@ -178,8 +151,8 @@ class EncryptAllTest extends TestCase { $encryptAll->encryptAll($this->inputInterface, $this->outputInterface); } - public function testEncryptAllWithMasterKey() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + public function testEncryptAllWithMasterKey(): void { + /** @var EncryptAll&MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ @@ -193,10 +166,11 @@ class EncryptAllTest extends TestCase { $this->l, $this->l10nFactory, $this->questionHelper, - $this->secureRandom + $this->secureRandom, + $this->logger, ] ) - ->setMethods(['createKeyPairs', 'encryptAllUsersFiles', 'outputPasswords']) + ->onlyMethods(['createKeyPairs', 'encryptAllUsersFiles', 'outputPasswords']) ->getMock(); $this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(true); @@ -208,8 +182,8 @@ class EncryptAllTest extends TestCase { $encryptAll->encryptAll($this->inputInterface, $this->outputInterface); } - public function testCreateKeyPairs() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + public function testCreateKeyPairs(): void { + /** @var EncryptAll&MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ @@ -223,10 +197,11 @@ class EncryptAllTest extends TestCase { $this->l, $this->l10nFactory, $this->questionHelper, - $this->secureRandom + $this->secureRandom, + $this->logger, ] ) - ->setMethods(['setupUserFS', 'generateOneTimePassword']) + ->onlyMethods(['setupUserFS', 'generateOneTimePassword']) ->getMock(); @@ -258,8 +233,8 @@ class EncryptAllTest extends TestCase { $this->assertSame('', $userPasswords['user2']); } - public function testEncryptAllUsersFiles() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + public function testEncryptAllUsersFiles(): void { + /** @var EncryptAll&MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ @@ -273,10 +248,11 @@ class EncryptAllTest extends TestCase { $this->l, $this->l10nFactory, $this->questionHelper, - $this->secureRandom + $this->secureRandom, + $this->logger, ] ) - ->setMethods(['encryptUsersFiles']) + ->onlyMethods(['encryptUsersFiles']) ->getMock(); $this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false); @@ -285,17 +261,22 @@ class EncryptAllTest extends TestCase { $this->invokePrivate($encryptAll, 'output', [$this->outputInterface]); $this->invokePrivate($encryptAll, 'userPasswords', [['user1' => 'pwd1', 'user2' => 'pwd2']]); - $encryptAll->expects($this->exactly(2))->method('encryptUsersFiles') - ->withConsecutive( - ['user1'], - ['user2'], - ); + $encryptAllCalls = []; + $encryptAll->expects($this->exactly(2)) + ->method('encryptUsersFiles') + ->willReturnCallback(function ($uid) use (&$encryptAllCalls): void { + $encryptAllCalls[] = $uid; + }); $this->invokePrivate($encryptAll, 'encryptAllUsersFiles'); + self::assertEquals([ + 'user1', + 'user2', + ], $encryptAllCalls); } - public function testEncryptUsersFiles() { - /** @var EncryptAll | \PHPUnit\Framework\MockObject\MockObject $encryptAll */ + public function testEncryptUsersFiles(): void { + /** @var EncryptAll&MockObject $encryptAll */ $encryptAll = $this->getMockBuilder(EncryptAll::class) ->setConstructorArgs( [ @@ -309,43 +290,43 @@ class EncryptAllTest extends TestCase { $this->l, $this->l10nFactory, $this->questionHelper, - $this->secureRandom + $this->secureRandom, + $this->logger, ] ) - ->setMethods(['encryptFile', 'setupUserFS']) + ->onlyMethods(['encryptFile', 'setupUserFS']) ->getMock(); $this->util->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false); $this->view->expects($this->exactly(2))->method('getDirectoryContent') - ->withConsecutive( - ['/user1/files'], - ['/user1/files/foo'], - )->willReturnOnConsecutiveCalls( + ->willReturnMap([ [ - ['name' => 'foo', 'type' => 'dir'], - ['name' => 'bar', 'type' => 'file'], + '/user1/files', + '', + null, + [ + $this->createFileInfoMock(FileInfo::TYPE_FOLDER, 'foo'), + $this->createFileInfoMock(FileInfo::TYPE_FILE, 'bar'), + ], ], [ - ['name' => 'subfile', 'type' => 'file'] - ] - ); - - $this->view->expects($this->any())->method('is_dir') - ->willReturnCallback( - function ($path) { - if ($path === '/user1/files/foo') { - return true; - } - return false; - } - ); + '/user1/files/foo', + '', + null, + [ + $this->createFileInfoMock(FileInfo::TYPE_FILE, 'subfile'), + ], + ], + ]); - $encryptAll->expects($this->exactly(2))->method('encryptFile') - ->withConsecutive( - ['/user1/files/bar'], - ['/user1/files/foo/subfile'], - ); + $encryptAllCalls = []; + $encryptAll->expects($this->exactly(2)) + ->method('encryptFile') + ->willReturnCallback(function (FileInfo $file, string $path) use (&$encryptAllCalls): bool { + $encryptAllCalls[] = $path; + return true; + }); $outputFormatter = $this->createMock(OutputFormatterInterface::class); $outputFormatter->method('isDecorated')->willReturn(false); @@ -355,9 +336,13 @@ class EncryptAllTest extends TestCase { $progressBar = new ProgressBar($this->outputInterface); $this->invokePrivate($encryptAll, 'encryptUsersFiles', ['user1', $progressBar, '']); + self::assertEquals([ + '/user1/files/bar', + '/user1/files/foo/subfile', + ], $encryptAllCalls); } - public function testGenerateOneTimePassword() { + public function testGenerateOneTimePassword(): void { $password = $this->invokePrivate($this->encryptAll, 'generateOneTimePassword', ['user1']); $this->assertTrue(is_string($password)); $this->assertSame(8, strlen($password)); @@ -368,15 +353,14 @@ class EncryptAllTest extends TestCase { } /** - * @dataProvider dataTestEncryptFile * @param $isEncrypted */ - public function testEncryptFile($isEncrypted) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestEncryptFile')] + public function testEncryptFile($isEncrypted): void { $fileInfo = $this->createMock(FileInfo::class); $fileInfo->expects($this->any())->method('isEncrypted') ->willReturn($isEncrypted); - $this->view->expects($this->any())->method('getFileInfo') - ->willReturn($fileInfo); + $this->view->expects($this->never())->method('getFileInfo'); if ($isEncrypted) { @@ -388,11 +372,11 @@ class EncryptAllTest extends TestCase { } $this->assertTrue( - $this->invokePrivate($this->encryptAll, 'encryptFile', ['foo.txt']) + $this->invokePrivate($this->encryptAll, 'encryptFile', [$fileInfo, 'foo.txt']) ); } - public function dataTestEncryptFile() { + public static function dataTestEncryptFile(): array { return [ [true], [false], diff --git a/apps/encryption/tests/Crypto/EncryptionTest.php b/apps/encryption/tests/Crypto/EncryptionTest.php index 115b9054278..37e484550ef 100644 --- a/apps/encryption/tests/Crypto/EncryptionTest.php +++ b/apps/encryption/tests/Crypto/EncryptionTest.php @@ -1,31 +1,16 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Crypto; +use OC\Encryption\Exceptions\DecryptionFailedException; +use OC\Files\View; use OCA\Encryption\Crypto\Crypt; use OCA\Encryption\Crypto\DecryptAll; use OCA\Encryption\Crypto\EncryptAll; @@ -34,48 +19,32 @@ use OCA\Encryption\Exceptions\PublicKeyMissingException; use OCA\Encryption\KeyManager; use OCA\Encryption\Session; use OCA\Encryption\Util; -use OCP\Files\Storage; +use OCP\Files\Storage\IStorage; use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Test\TestCase; class EncryptionTest extends TestCase { - /** @var Encryption */ - private $instance; - - /** @var \OCA\Encryption\KeyManager|\PHPUnit\Framework\MockObject\MockObject */ - private $keyManagerMock; - - /** @var \OCA\Encryption\Crypto\EncryptAll|\PHPUnit\Framework\MockObject\MockObject */ - private $encryptAllMock; - - /** @var \OCA\Encryption\Crypto\DecryptAll|\PHPUnit\Framework\MockObject\MockObject */ - private $decryptAllMock; - - /** @var \OCA\Encryption\Session|\PHPUnit\Framework\MockObject\MockObject */ - private $sessionMock; - - /** @var \OCA\Encryption\Crypto\Crypt|\PHPUnit\Framework\MockObject\MockObject */ - private $cryptMock; - - /** @var \OCA\Encryption\Util|\PHPUnit\Framework\MockObject\MockObject */ - private $utilMock; - - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $loggerMock; - /** @var \OCP\IL10N|\PHPUnit\Framework\MockObject\MockObject */ - private $l10nMock; + protected Encryption $instance; - /** @var \OCP\Files\Storage|\PHPUnit\Framework\MockObject\MockObject */ - private $storageMock; + protected KeyManager&MockObject $keyManagerMock; + protected EncryptAll&MockObject $encryptAllMock; + protected DecryptAll&MockObject $decryptAllMock; + protected Session&MockObject $sessionMock; + protected Crypt&MockObject $cryptMock; + protected Util&MockObject $utilMock; + protected LoggerInterface&MockObject $loggerMock; + protected IL10N&MockObject $l10nMock; + protected IStorage&MockObject $storageMock; protected function setUp(): void { parent::setUp(); - $this->storageMock = $this->getMockBuilder(Storage::class) + $this->storageMock = $this->getMockBuilder(IStorage::class) ->disableOriginalConstructor()->getMock(); $this->cryptMock = $this->getMockBuilder(Crypt::class) ->disableOriginalConstructor() @@ -121,7 +90,11 @@ class EncryptionTest extends TestCase { /** * test if public key from one of the recipients is missing */ - public function testEndUser1() { + public function testEndUser1(): void { + $this->sessionMock->expects($this->once()) + ->method('decryptAllModeActivated') + ->willReturn(false); + $this->instance->begin('/foo/bar', 'user1', 'r', [], ['users' => ['user1', 'user2', 'user3']]); $this->endTest(); } @@ -130,8 +103,12 @@ class EncryptionTest extends TestCase { * test if public key from owner is missing * */ - public function testEndUser2() { - $this->expectException(\OCA\Encryption\Exceptions\PublicKeyMissingException::class); + public function testEndUser2(): void { + $this->sessionMock->expects($this->once()) + ->method('decryptAllModeActivated') + ->willReturn(false); + + $this->expectException(PublicKeyMissingException::class); $this->instance->begin('/foo/bar', 'user2', 'r', [], ['users' => ['user1', 'user2', 'user3']]); $this->endTest(); @@ -175,16 +152,14 @@ class EncryptionTest extends TestCase { return $publicKeys; } - /** - * @dataProvider dataProviderForTestGetPathToRealFile - */ - public function testGetPathToRealFile($path, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataProviderForTestGetPathToRealFile')] + public function testGetPathToRealFile($path, $expected): void { $this->assertSame($expected, self::invokePrivate($this->instance, 'getPathToRealFile', [$path]) ); } - public function dataProviderForTestGetPathToRealFile() { + public static function dataProviderForTestGetPathToRealFile(): array { return [ ['/user/files/foo/bar.txt', '/user/files/foo/bar.txt'], ['/user/files/foo.txt', '/user/files/foo.txt'], @@ -193,10 +168,8 @@ class EncryptionTest extends TestCase { ]; } - /** - * @dataProvider dataTestBegin - */ - public function testBegin($mode, $header, $legacyCipher, $defaultCipher, $fileKey, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestBegin')] + public function testBegin($mode, $header, $legacyCipher, $defaultCipher, $fileKey, $expected): void { $this->sessionMock->expects($this->once()) ->method('decryptAllModeActivated') ->willReturn(false); @@ -237,7 +210,7 @@ class EncryptionTest extends TestCase { } } - public function dataTestBegin() { + public static function dataTestBegin(): array { return [ ['w', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'defaultCipher'], ['r', ['cipher' => 'myCipher'], 'legacyCipher', 'defaultCipher', 'fileKey', 'myCipher'], @@ -250,37 +223,18 @@ class EncryptionTest extends TestCase { /** * test begin() if decryptAll mode was activated */ - public function testBeginDecryptAll() { + public function testBeginDecryptAll(): void { $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('multiKeyDecryptLegacy') - ->with('encryptedFileKey', $recoveryShareKey, $decryptAllKey) + ->method('getFileKey') + ->with($path, 'user', null, true) ->willReturn($fileKey); - $this->keyManagerMock->expects($this->never())->method('getFileKey'); - $this->instance->begin($path, 'user', 'r', [], []); $this->assertSame($fileKey, @@ -293,7 +247,11 @@ class EncryptionTest extends TestCase { * in this case we can initialize the encryption without a username/password * and continue */ - public function testBeginInitMasterKey() { + public function testBeginInitMasterKey(): void { + $this->sessionMock->expects($this->once()) + ->method('decryptAllModeActivated') + ->willReturn(false); + $this->sessionMock->expects($this->once())->method('isReady')->willReturn(false); $this->utilMock->expects($this->once())->method('isMasterKeyEnabled') ->willReturn(true); @@ -303,12 +261,12 @@ class EncryptionTest extends TestCase { } /** - * @dataProvider dataTestUpdate * * @param string $fileKey * @param boolean $expected */ - public function testUpdate($fileKey, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestUpdate')] + public function testUpdate($fileKey, $expected): void { $this->keyManagerMock->expects($this->once()) ->method('getFileKey')->willReturn($fileKey); @@ -329,24 +287,24 @@ class EncryptionTest extends TestCase { ); } - public function dataTestUpdate() { + public static function dataTestUpdate(): array { return [ ['', false], ['fileKey', true] ]; } - public function testUpdateNoUsers() { + public function testUpdateNoUsers(): void { $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) { + ->willReturnCallback(function ($path, $version, $view): void { $this->assertSame('path', $path); $this->assertSame(2, $version); - $this->assertTrue($view instanceof \OC\Files\View); + $this->assertTrue($view instanceof View); }); $this->instance->update('path', 'user1', []); } @@ -355,13 +313,13 @@ class EncryptionTest extends TestCase { * Test case if the public key is missing. Nextcloud should still encrypt * the file for the remaining users */ - public function testUpdateMissingPublicKey() { + public function testUpdateMissingPublicKey(): void { $this->keyManagerMock->expects($this->once()) ->method('getFileKey')->willReturn('fileKey'); $this->keyManagerMock->expects($this->any()) ->method('getPublicKey')->willReturnCallback( - function ($user) { + function ($user): void { throw new PublicKeyMissingException($user); } ); @@ -392,10 +350,9 @@ class EncryptionTest extends TestCase { /** * 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) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestShouldEncrypt')] + public function testShouldEncrypt($path, $shouldEncryptHomeStorage, $isHomeStorage, $expected): void { $this->utilMock->expects($this->once())->method('shouldEncryptHomeStorage') ->willReturn($shouldEncryptHomeStorage); @@ -411,7 +368,7 @@ class EncryptionTest extends TestCase { ); } - public function dataTestShouldEncrypt() { + public static function dataTestShouldEncrypt(): array { return [ ['/user1/files/foo.txt', true, true, true], ['/user1/files_versions/foo.txt', true, true, true], @@ -428,14 +385,14 @@ class EncryptionTest extends TestCase { } - public function testDecrypt() { - $this->expectException(\OC\Encryption\Exceptions\DecryptionFailedException::class); + public function testDecrypt(): void { + $this->expectException(DecryptionFailedException::class); $this->expectExceptionMessage('Cannot decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.'); $this->instance->decrypt('abc'); } - public function testPrepareDecryptAll() { + public function testPrepareDecryptAll(): void { /** @var \Symfony\Component\Console\Input\InputInterface $input */ $input = $this->createMock(InputInterface::class); /** @var \Symfony\Component\Console\Output\OutputInterface $output */ diff --git a/apps/encryption/tests/EncryptedStorageTest.php b/apps/encryption/tests/EncryptedStorageTest.php index 3219707d48b..59f419a7f7a 100644 --- a/apps/encryption/tests/EncryptedStorageTest.php +++ b/apps/encryption/tests/EncryptedStorageTest.php @@ -2,23 +2,8 @@ declare(strict_types=1); /** - * @copyright Copyright (c) 2023 Robin Appelman <robin@icewind.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * 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 - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\encryption\tests; @@ -28,6 +13,7 @@ use OC\Files\Storage\Wrapper\Encryption; use OC\Files\View; use OCP\Files\Mount\IMountManager; use OCP\Files\Storage\IDisableEncryptionStorage; +use OCP\Server; use Test\TestCase; use Test\Traits\EncryptionTrait; use Test\Traits\MountProviderTrait; @@ -45,24 +31,24 @@ class EncryptedStorageTest extends TestCase { use EncryptionTrait; use UserTrait; - public function testMoveFromEncrypted() { - $this->createUser("test1", "test2"); - $this->setupForUser("test1", 'test2'); + public function testMoveFromEncrypted(): void { + $this->createUser('test1', 'test2'); + $this->setupForUser('test1', 'test2'); $unwrapped = new Temporary(); - $this->registerMount("test1", new TemporaryNoEncrypted(), "/test1/files/unenc"); - $this->registerMount("test1", $unwrapped, "/test1/files/enc"); + $this->registerMount('test1', new TemporaryNoEncrypted(), '/test1/files/unenc'); + $this->registerMount('test1', $unwrapped, '/test1/files/enc'); - $this->loginWithEncryption("test1"); + $this->loginWithEncryption('test1'); - $view = new View("/test1/files"); + $view = new View('/test1/files'); /** @var IMountManager $mountManager */ - $mountManager = \OC::$server->get(IMountManager::class); + $mountManager = Server::get(IMountManager::class); - $encryptedMount = $mountManager->find("/test1/files/enc"); - $unencryptedMount = $mountManager->find("/test1/files/unenc"); + $encryptedMount = $mountManager->find('/test1/files/enc'); + $unencryptedMount = $mountManager->find('/test1/files/unenc'); $encryptedStorage = $encryptedMount->getStorage(); $unencryptedStorage = $unencryptedMount->getStorage(); $encryptedCache = $encryptedStorage->getCache(); @@ -71,15 +57,15 @@ class EncryptedStorageTest extends TestCase { $this->assertTrue($encryptedStorage->instanceOfStorage(Encryption::class)); $this->assertFalse($unencryptedStorage->instanceOfStorage(Encryption::class)); - $encryptedStorage->file_put_contents("foo.txt", "bar"); - $this->assertEquals("bar", $encryptedStorage->file_get_contents("foo.txt")); - $this->assertStringStartsWith("HBEGIN:oc_encryption_module:", $unwrapped->file_get_contents("foo.txt")); + $encryptedStorage->file_put_contents('foo.txt', 'bar'); + $this->assertEquals('bar', $encryptedStorage->file_get_contents('foo.txt')); + $this->assertStringStartsWith('HBEGIN:oc_encryption_module:', $unwrapped->file_get_contents('foo.txt')); - $this->assertTrue($encryptedCache->get("foo.txt")->isEncrypted()); + $this->assertTrue($encryptedCache->get('foo.txt')->isEncrypted()); - $view->rename("enc/foo.txt", "unenc/foo.txt"); + $view->rename('enc/foo.txt', 'unenc/foo.txt'); - $this->assertEquals("bar", $unencryptedStorage->file_get_contents("foo.txt")); - $this->assertFalse($unencryptedCache->get("foo.txt")->isEncrypted()); + $this->assertEquals('bar', $unencryptedStorage->file_get_contents('foo.txt')); + $this->assertFalse($unencryptedCache->get('foo.txt')->isEncrypted()); } } diff --git a/apps/encryption/tests/HookManagerTest.php b/apps/encryption/tests/HookManagerTest.php deleted file mode 100644 index 13102c87168..00000000000 --- a/apps/encryption/tests/HookManagerTest.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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 OCA\Encryption\Hooks\Contracts\IHook; -use OCP\IConfig; -use Test\TestCase; - -class HookManagerTest extends TestCase { - - /** - * @var HookManager - */ - private static $instance; - - - public function testRegisterHookWithArray() { - self::$instance->registerHook([ - $this->getMockBuilder(IHook::class)->disableOriginalConstructor()->getMock(), - $this->getMockBuilder(IHook::class)->disableOriginalConstructor()->getMock(), - $this->createMock(IConfig::class) - ]); - - $hookInstances = self::invokePrivate(self::$instance, 'hookInstances'); - // Make sure our type checking works - $this->assertCount(2, $hookInstances); - } - - - - public static function setUpBeforeClass(): void { - parent::setUpBeforeClass(); - // have to make instance static to preserve data between tests - self::$instance = new HookManager(); - } - - - public function testRegisterHooksWithInstance() { - $mock = $this->getMockBuilder(IHook::class)->disableOriginalConstructor()->getMock(); - /** @var \OCA\Encryption\Hooks\Contracts\IHook $mock */ - self::$instance->registerHook($mock); - - $hookInstances = self::invokePrivate(self::$instance, 'hookInstances'); - $this->assertCount(3, $hookInstances); - } -} diff --git a/apps/encryption/tests/Hooks/UserHooksTest.php b/apps/encryption/tests/Hooks/UserHooksTest.php deleted file mode 100644 index 7faa6699e91..00000000000 --- a/apps/encryption/tests/Hooks/UserHooksTest.php +++ /dev/null @@ -1,390 +0,0 @@ -<?php -/** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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\Hooks; - -use OCA\Encryption\Crypto\Crypt; -use OCA\Encryption\Hooks\UserHooks; -use OCA\Encryption\KeyManager; -use OCA\Encryption\Recovery; -use OCA\Encryption\Session; -use OCA\Encryption\Users\Setup; -use OCA\Encryption\Util; -use OCP\IUser; -use OCP\IUserManager; -use OCP\IUserSession; -use PHPUnit\Framework\MockObject\MockObject; -use Psr\Log\LoggerInterface; -use Test\TestCase; - -/** - * Class UserHooksTest - * - * @group DB - * @package OCA\Encryption\Tests\Hooks - */ -class UserHooksTest extends TestCase { - /** - * @var \PHPUnit\Framework\MockObject\MockObject - */ - private $utilMock; - /** - * @var \PHPUnit\Framework\MockObject\MockObject - */ - private $recoveryMock; - /** - * @var \PHPUnit\Framework\MockObject\MockObject - */ - private $sessionMock; - /** - * @var \PHPUnit\Framework\MockObject\MockObject - */ - private $keyManagerMock; - /** - * @var \PHPUnit\Framework\MockObject\MockObject - */ - private $userManagerMock; - - /** - * @var \PHPUnit\Framework\MockObject\MockObject - */ - private $userSetupMock; - /** - * @var \PHPUnit\Framework\MockObject\MockObject - */ - private $userSessionMock; - /** - * @var MockObject|IUser - */ - private $user; - /** - * @var \PHPUnit\Framework\MockObject\MockObject - */ - private $cryptMock; - /** - * @var \PHPUnit\Framework\MockObject\MockObject - */ - private $loggerMock; - /** - * @var UserHooks - */ - private $instance; - - private $params = ['uid' => 'testUser', 'password' => 'password']; - - public function testLogin() { - $this->userSetupMock->expects($this->once()) - ->method('setupUser') - ->willReturnOnConsecutiveCalls(true, false); - - $this->keyManagerMock->expects($this->once()) - ->method('init') - ->with('testUser', 'password'); - - $this->assertNull($this->instance->login($this->params)); - } - - public function testLogout() { - $this->sessionMock->expects($this->once()) - ->method('clear'); - $this->instance->logout(); - $this->addToAssertionCount(1); - } - - public function testPostCreateUser() { - $this->userSetupMock->expects($this->once()) - ->method('setupUser'); - - $this->instance->postCreateUser($this->params); - $this->addToAssertionCount(1); - } - - public function testPostDeleteUser() { - $this->keyManagerMock->expects($this->once()) - ->method('deletePublicKey') - ->with('testUser'); - - $this->instance->postDeleteUser($this->params); - $this->addToAssertionCount(1); - } - - public function testPrePasswordReset() { - $params = ['uid' => 'user1']; - $expected = ['user1' => true]; - $this->instance->prePasswordReset($params); - $passwordResetUsers = $this->invokePrivate($this->instance, 'passwordResetUsers'); - - $this->assertSame($expected, $passwordResetUsers); - } - - public function testPostPasswordReset() { - $params = ['uid' => 'user1', 'password' => 'password']; - $this->invokePrivate($this->instance, 'passwordResetUsers', [['user1' => true]]); - $this->keyManagerMock->expects($this->once())->method('backupUserKeys') - ->with('passwordReset', 'user1'); - $this->keyManagerMock->expects($this->once())->method('deleteUserKeys') - ->with('user1'); - $this->userSetupMock->expects($this->once())->method('setupUser') - ->with('user1', 'password'); - - $this->instance->postPasswordReset($params); - $passwordResetUsers = $this->invokePrivate($this->instance, 'passwordResetUsers'); - $this->assertEmpty($passwordResetUsers); - } - - /** - * @dataProvider dataTestPreSetPassphrase - */ - public function testPreSetPassphrase($canChange) { - /** @var UserHooks | \PHPUnit\Framework\MockObject\MockObject $instance */ - $instance = $this->getMockBuilder(UserHooks::class) - ->setConstructorArgs( - [ - $this->keyManagerMock, - $this->userManagerMock, - $this->loggerMock, - $this->userSetupMock, - $this->userSessionMock, - $this->utilMock, - $this->sessionMock, - $this->cryptMock, - $this->recoveryMock - ] - ) - ->setMethods(['setPassphrase']) - ->getMock(); - - $userMock = $this->createMock(IUser::class); - - $this->userManagerMock->expects($this->once()) - ->method('get') - ->with($this->params['uid']) - ->willReturn($userMock); - $userMock->expects($this->once()) - ->method('canChangePassword') - ->willReturn($canChange); - - if ($canChange) { - // in this case the password will be changed in the post hook - $instance->expects($this->never())->method('setPassphrase'); - } else { - // if user can't change the password we update the encryption - // key password already in the pre hook - $instance->expects($this->once()) - ->method('setPassphrase') - ->with($this->params); - } - - $instance->preSetPassphrase($this->params); - } - - public function dataTestPreSetPassphrase() { - return [ - [true], - [false] - ]; - } - - public function XtestSetPassphrase() { - $this->sessionMock->expects($this->once()) - ->method('getPrivateKey') - ->willReturn(true); - - $this->cryptMock->expects($this->exactly(4)) - ->method('encryptPrivateKey') - ->willReturn(true); - - $this->cryptMock->expects($this->any()) - ->method('generateHeader') - ->willReturn(Crypt::HEADER_START . ':Cipher:test:' . Crypt::HEADER_END); - - $this->keyManagerMock->expects($this->exactly(4)) - ->method('setPrivateKey') - ->willReturnCallback(function ($user, $key) { - $header = substr($key, 0, strlen(Crypt::HEADER_START)); - $this->assertSame( - Crypt::HEADER_START, - $header, 'every encrypted file should start with a header'); - }); - - $this->assertNull($this->instance->setPassphrase($this->params)); - $this->params['recoveryPassword'] = 'password'; - - $this->recoveryMock->expects($this->exactly(3)) - ->method('isRecoveryEnabledForUser') - ->with('testUser1') - ->willReturnOnConsecutiveCalls(true, false); - - - $this->instance = $this->getMockBuilder(UserHooks::class) - ->setConstructorArgs( - [ - $this->keyManagerMock, - $this->userManagerMock, - $this->loggerMock, - $this->userSetupMock, - $this->userSessionMock, - $this->utilMock, - $this->sessionMock, - $this->cryptMock, - $this->recoveryMock - ] - )->setMethods(['initMountPoints'])->getMock(); - - $this->instance->expects($this->exactly(3))->method('initMountPoints'); - - $this->params['uid'] = 'testUser1'; - - // Test first if statement - $this->assertNull($this->instance->setPassphrase($this->params)); - - // Test Second if conditional - $this->keyManagerMock->expects($this->exactly(2)) - ->method('userHasKeys') - ->with('testUser1') - ->willReturn(true); - - $this->assertNull($this->instance->setPassphrase($this->params)); - - // Test third and final if condition - $this->utilMock->expects($this->once()) - ->method('userHasFiles') - ->with('testUser1') - ->willReturn(false); - - $this->cryptMock->expects($this->once()) - ->method('createKeyPair'); - - $this->keyManagerMock->expects($this->once()) - ->method('setPrivateKey'); - - $this->recoveryMock->expects($this->once()) - ->method('recoverUsersFiles') - ->with('password', 'testUser1'); - - $this->assertNull($this->instance->setPassphrase($this->params)); - } - - public function testSetPassphraseResetUserMode() { - $params = ['uid' => 'user1', 'password' => 'password']; - $this->invokePrivate($this->instance, 'passwordResetUsers', [[$params['uid'] => true]]); - $this->sessionMock->expects($this->never())->method('getPrivateKey'); - $this->keyManagerMock->expects($this->never())->method('setPrivateKey'); - $this->assertTrue($this->instance->setPassphrase($params)); - $this->invokePrivate($this->instance, 'passwordResetUsers', [[]]); - } - - public function XtestSetPasswordNoUser() { - $userSessionMock = $this->getMockBuilder(IUserSession::class) - ->disableOriginalConstructor() - ->getMock(); - - $userSessionMock->expects($this->any())->method('getUser')->willReturn(null); - - $this->recoveryMock->expects($this->once()) - ->method('isRecoveryEnabledForUser') - ->with('testUser') - ->willReturn(false); - - $userHooks = $this->getMockBuilder(UserHooks::class) - ->setConstructorArgs( - [ - $this->keyManagerMock, - $this->userManagerMock, - $this->loggerMock, - $this->userSetupMock, - $userSessionMock, - $this->utilMock, - $this->sessionMock, - $this->cryptMock, - $this->recoveryMock - ] - )->setMethods(['initMountPoints'])->getMock(); - - /** @var \OCA\Encryption\Hooks\UserHooks $userHooks */ - $this->assertNull($userHooks->setPassphrase($this->params)); - } - - protected function setUp(): void { - parent::setUp(); - $this->loggerMock = $this->createMock(LoggerInterface::class); - $this->keyManagerMock = $this->getMockBuilder(KeyManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userManagerMock = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userSetupMock = $this->getMockBuilder(Setup::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->user = $this->createMock(IUser::class); - $this->user->expects($this->any()) - ->method('getUID') - ->willReturn('testUser'); - - $this->userSessionMock = $this->createMock(IUserSession::class); - $this->userSessionMock->expects($this->any()) - ->method('getUser') - ->willReturn($this->user); - - $utilMock = $this->getMockBuilder(Util::class) - ->disableOriginalConstructor() - ->getMock(); - - $sessionMock = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->cryptMock = $this->getMockBuilder(Crypt::class) - ->disableOriginalConstructor() - ->getMock(); - $recoveryMock = $this->getMockBuilder(Recovery::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->sessionMock = $sessionMock; - $this->recoveryMock = $recoveryMock; - $this->utilMock = $utilMock; - $this->utilMock->expects($this->any())->method('isMasterKeyEnabled')->willReturn(false); - - $this->instance = $this->getMockBuilder(UserHooks::class) - ->setConstructorArgs( - [ - $this->keyManagerMock, - $this->userManagerMock, - $this->loggerMock, - $this->userSetupMock, - $this->userSessionMock, - $this->utilMock, - $this->sessionMock, - $this->cryptMock, - $this->recoveryMock - ] - )->setMethods(['setupFS'])->getMock(); - } -} diff --git a/apps/encryption/tests/KeyManagerTest.php b/apps/encryption/tests/KeyManagerTest.php index d51d4dde528..3fe76fc4f59 100644 --- a/apps/encryption/tests/KeyManagerTest.php +++ b/apps/encryption/tests/KeyManagerTest.php @@ -1,45 +1,26 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Vincent Petry <vincent@nextcloud.com> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests; use OC\Files\FileInfo; use OC\Files\View; use OCA\Encryption\Crypto\Crypt; +use OCA\Encryption\Crypto\Encryption; +use OCA\Encryption\Exceptions\PrivateKeyMissingException; +use OCA\Encryption\Exceptions\PublicKeyMissingException; use OCA\Encryption\KeyManager; use OCA\Encryption\Session; use OCA\Encryption\Util; use OCP\Encryption\Keys\IStorage; use OCP\Files\Cache\ICache; -use OCP\Files\Storage; +use OCP\Files\Storage\IStorage as FilesIStorage; use OCP\IConfig; use OCP\IUserSession; use OCP\Lock\ILockingProvider; @@ -49,41 +30,19 @@ use Psr\Log\LoggerInterface; use Test\TestCase; class KeyManagerTest extends TestCase { - /** - * @var KeyManager - */ - private $instance; - /** - * @var string - */ - private $userId; - - /** @var string */ - private $systemKeyId; - - /** @var \OCP\Encryption\Keys\IStorage|\PHPUnit\Framework\MockObject\MockObject */ - private $keyStorageMock; - /** @var \OCA\Encryption\Crypto\Crypt|\PHPUnit\Framework\MockObject\MockObject */ - private $cryptMock; + protected KeyManager $instance; - /** @var \OCP\IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userMock; - - /** @var \OCA\Encryption\Session|\PHPUnit\Framework\MockObject\MockObject */ - private $sessionMock; - - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $logMock; - - /** @var \OCA\Encryption\Util|\PHPUnit\Framework\MockObject\MockObject */ - private $utilMock; - - /** @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $configMock; - - /** @var ILockingProvider|MockObject */ - private $lockingProviderMock; + protected string $userId; + protected string $systemKeyId; + protected IStorage&MockObject $keyStorageMock; + protected Crypt&MockObject $cryptMock; + protected IUserSession&MockObject $userMock; + protected Session&MockObject $sessionMock; + protected LoggerInterface&MockObject $logMock; + protected Util&MockObject $utilMock; + protected IConfig&MockObject $configMock; + protected ILockingProvider&MockObject $lockingProviderMock; protected function setUp(): void { parent::setUp(); @@ -119,7 +78,7 @@ class KeyManagerTest extends TestCase { ); } - public function testDeleteShareKey() { + public function testDeleteShareKey(): void { $this->keyStorageMock->expects($this->any()) ->method('deleteFileKey') ->with($this->equalTo('/path'), $this->equalTo('keyId.shareKey')) @@ -130,7 +89,7 @@ class KeyManagerTest extends TestCase { ); } - public function testGetPrivateKey() { + public function testGetPrivateKey(): void { $this->keyStorageMock->expects($this->any()) ->method('getUserKey') ->with($this->equalTo($this->userId), $this->equalTo('privateKey')) @@ -142,7 +101,7 @@ class KeyManagerTest extends TestCase { ); } - public function testGetPublicKey() { + public function testGetPublicKey(): void { $this->keyStorageMock->expects($this->any()) ->method('getUserKey') ->with($this->equalTo($this->userId), $this->equalTo('publicKey')) @@ -154,7 +113,7 @@ class KeyManagerTest extends TestCase { ); } - public function testRecoveryKeyExists() { + public function testRecoveryKeyExists(): void { $this->keyStorageMock->expects($this->any()) ->method('getSystemUserKey') ->with($this->equalTo($this->systemKeyId . '.publicKey')) @@ -164,7 +123,7 @@ class KeyManagerTest extends TestCase { $this->assertTrue($this->instance->recoveryKeyExists()); } - public function testCheckRecoveryKeyPassword() { + public function testCheckRecoveryKeyPassword(): void { $this->keyStorageMock->expects($this->any()) ->method('getSystemUserKey') ->with($this->equalTo($this->systemKeyId . '.privateKey')) @@ -177,7 +136,7 @@ class KeyManagerTest extends TestCase { $this->assertTrue($this->instance->checkRecoveryPassword('pass')); } - public function testSetPublicKey() { + public function testSetPublicKey(): void { $this->keyStorageMock->expects($this->any()) ->method('setUserKey') ->with( @@ -192,7 +151,7 @@ class KeyManagerTest extends TestCase { ); } - public function testSetPrivateKey() { + public function testSetPrivateKey(): void { $this->keyStorageMock->expects($this->any()) ->method('setUserKey') ->with( @@ -207,10 +166,8 @@ class KeyManagerTest extends TestCase { ); } - /** - * @dataProvider dataTestUserHasKeys - */ - public function testUserHasKeys($key, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestUserHasKeys')] + public function testUserHasKeys($key, $expected): void { $this->keyStorageMock->expects($this->exactly(2)) ->method('getUserKey') ->with($this->equalTo($this->userId), $this->anything()) @@ -222,7 +179,7 @@ class KeyManagerTest extends TestCase { ); } - public function dataTestUserHasKeys() { + public static function dataTestUserHasKeys(): array { return [ ['key', true], ['', false] @@ -230,8 +187,8 @@ class KeyManagerTest extends TestCase { } - public function testUserHasKeysMissingPrivateKey() { - $this->expectException(\OCA\Encryption\Exceptions\PrivateKeyMissingException::class); + public function testUserHasKeysMissingPrivateKey(): void { + $this->expectException(PrivateKeyMissingException::class); $this->keyStorageMock->expects($this->exactly(2)) ->method('getUserKey') @@ -246,8 +203,8 @@ class KeyManagerTest extends TestCase { } - public function testUserHasKeysMissingPublicKey() { - $this->expectException(\OCA\Encryption\Exceptions\PublicKeyMissingException::class); + public function testUserHasKeysMissingPublicKey(): void { + $this->expectException(PublicKeyMissingException::class); $this->keyStorageMock->expects($this->exactly(2)) ->method('getUserKey') @@ -262,12 +219,11 @@ class KeyManagerTest extends TestCase { } /** - * @dataProvider dataTestInit - * * @param bool $useMasterKey */ - public function testInit($useMasterKey) { - /** @var \OCA\Encryption\KeyManager|\PHPUnit\Framework\MockObject\MockObject $instance */ + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestInit')] + public function testInit($useMasterKey): void { + /** @var KeyManager&MockObject $instance */ $instance = $this->getMockBuilder(KeyManager::class) ->setConstructorArgs( [ @@ -280,17 +236,18 @@ class KeyManagerTest extends TestCase { $this->utilMock, $this->lockingProviderMock ] - )->setMethods(['getMasterKeyId', 'getMasterKeyPassword', 'getSystemPrivateKey', 'getPrivateKey']) + )->onlyMethods(['getMasterKeyId', 'getMasterKeyPassword', 'getSystemPrivateKey', 'getPrivateKey']) ->getMock(); $this->utilMock->expects($this->once())->method('isMasterKeyEnabled') ->willReturn($useMasterKey); - $this->sessionMock->expects($this->exactly(2))->method('setStatus') - ->withConsecutive( - [Session::INIT_EXECUTED], - [Session::INIT_SUCCESSFUL], - ); + $sessionSetStatusCalls = []; + $this->sessionMock->expects($this->exactly(2)) + ->method('setStatus') + ->willReturnCallback(function (string $status) use (&$sessionSetStatusCalls): void { + $sessionSetStatusCalls[] = $status; + }); $instance->expects($this->any())->method('getMasterKeyId')->willReturn('masterKeyId'); $instance->expects($this->any())->method('getMasterKeyPassword')->willReturn('masterKeyPassword'); @@ -311,9 +268,13 @@ class KeyManagerTest extends TestCase { ->with('key'); $this->assertTrue($instance->init($this->userId, 'pass')); + self::assertEquals([ + Session::INIT_EXECUTED, + Session::INIT_SUCCESSFUL, + ], $sessionSetStatusCalls); } - public function dataTestInit() { + public static function dataTestInit(): array { return [ [true], [false] @@ -321,7 +282,7 @@ class KeyManagerTest extends TestCase { } - public function testSetRecoveryKey() { + public function testSetRecoveryKey(): void { $this->keyStorageMock->expects($this->exactly(2)) ->method('setSystemUserKey') ->willReturn(true); @@ -337,7 +298,7 @@ class KeyManagerTest extends TestCase { ); } - public function testSetSystemPrivateKey() { + public function testSetSystemPrivateKey(): void { $this->keyStorageMock->expects($this->exactly(1)) ->method('setSystemUserKey') ->with($this->equalTo('keyId.privateKey'), $this->equalTo('key')) @@ -349,7 +310,7 @@ class KeyManagerTest extends TestCase { ); } - public function testGetSystemPrivateKey() { + public function testGetSystemPrivateKey(): void { $this->keyStorageMock->expects($this->exactly(1)) ->method('getSystemUserKey') ->with($this->equalTo('keyId.privateKey')) @@ -361,7 +322,7 @@ class KeyManagerTest extends TestCase { ); } - public function testGetEncryptedFileKey() { + public function testGetEncryptedFileKey(): void { $this->keyStorageMock->expects($this->once()) ->method('getFileKey') ->with('/', 'fileKey') @@ -370,7 +331,7 @@ class KeyManagerTest extends TestCase { $this->assertTrue($this->instance->getEncryptedFileKey('/')); } - public function dataTestGetFileKey() { + public static function dataTestGetFileKey(): array { return [ ['user1', false, 'privateKey', 'legacyKey', 'multiKeyDecryptResult'], ['user1', false, 'privateKey', '', 'multiKeyDecryptResult'], @@ -392,14 +353,14 @@ class KeyManagerTest extends TestCase { } /** - * @dataProvider dataTestGetFileKey * * @param $uid * @param $isMasterKeyEnabled * @param $privateKey * @param $expected */ - public function testGetFileKey($uid, $isMasterKeyEnabled, $privateKey, $encryptedFileKey, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestGetFileKey')] + public function testGetFileKey($uid, $isMasterKeyEnabled, $privateKey, $encryptedFileKey, $expected): void { $path = '/foo.txt'; if ($isMasterKeyEnabled) { @@ -416,14 +377,10 @@ class KeyManagerTest extends TestCase { $this->keyStorageMock->expects($this->exactly(2)) ->method('getFileKey') - ->withConsecutive( - [$path, 'fileKey', 'OC_DEFAULT_MODULE'], - [$path, $expectedUid . '.shareKey', 'OC_DEFAULT_MODULE'], - ) - ->willReturnOnConsecutiveCalls( - $encryptedFileKey, - 'fileKey', - ); + ->willReturnMap([ + [$path, 'fileKey', 'OC_DEFAULT_MODULE', $encryptedFileKey], + [$path, $expectedUid . '.shareKey', 'OC_DEFAULT_MODULE', 'fileKey'], + ]); $this->utilMock->expects($this->any())->method('isMasterKeyEnabled') ->willReturn($isMasterKeyEnabled); @@ -470,7 +427,7 @@ class KeyManagerTest extends TestCase { ); } - public function testDeletePrivateKey() { + public function testDeletePrivateKey(): void { $this->keyStorageMock->expects($this->once()) ->method('deleteUserKey') ->with('user1', 'privateKey') @@ -481,7 +438,7 @@ class KeyManagerTest extends TestCase { [$this->userId])); } - public function testDeleteAllFileKeys() { + public function testDeleteAllFileKeys(): void { $this->keyStorageMock->expects($this->once()) ->method('deleteAllFileKeys') ->willReturn(true); @@ -492,14 +449,14 @@ class KeyManagerTest extends TestCase { /** * 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) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestAddSystemKeys')] + public function testAddSystemKeys($accessList, $publicKeys, $uid, $expectedKeys): void { $publicShareKeyId = 'publicShareKey'; $recoveryKeyId = 'recoveryKey'; @@ -536,7 +493,7 @@ class KeyManagerTest extends TestCase { * * @return array */ - public function dataTestAddSystemKeys() { + public static function dataTestAddSystemKeys(): array { return [ [['public' => true],[], 'user1', ['publicShareKey', 'recoveryKey']], [['public' => false], [], 'user1', ['recoveryKey']], @@ -545,13 +502,13 @@ class KeyManagerTest extends TestCase { ]; } - public function testGetMasterKeyId() { + public function testGetMasterKeyId(): void { $this->assertSame('systemKeyId', $this->instance->getMasterKeyId()); } - public function testGetPublicMasterKey() { + public function testGetPublicMasterKey(): void { $this->keyStorageMock->expects($this->once())->method('getSystemUserKey') - ->with('systemKeyId.publicKey', \OCA\Encryption\Crypto\Encryption::ID) + ->with('systemKeyId.publicKey', Encryption::ID) ->willReturn(true); $this->assertTrue( @@ -559,7 +516,7 @@ class KeyManagerTest extends TestCase { ); } - public function testGetMasterKeyPassword() { + public function testGetMasterKeyPassword(): void { $this->configMock->expects($this->once())->method('getSystemValue')->with('secret') ->willReturn('password'); @@ -569,7 +526,7 @@ class KeyManagerTest extends TestCase { } - public function testGetMasterKeyPasswordException() { + public function testGetMasterKeyPasswordException(): void { $this->expectException(\Exception::class); $this->configMock->expects($this->once())->method('getSystemValue')->with('secret') @@ -579,12 +536,11 @@ class KeyManagerTest extends TestCase { } /** - * @dataProvider dataTestValidateMasterKey - * * @param $masterKey */ - public function testValidateMasterKey($masterKey) { - /** @var \OCA\Encryption\KeyManager | \PHPUnit\Framework\MockObject\MockObject $instance */ + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestValidateMasterKey')] + public function testValidateMasterKey($masterKey): void { + /** @var KeyManager&MockObject $instance */ $instance = $this->getMockBuilder(KeyManager::class) ->setConstructorArgs( [ @@ -597,7 +553,7 @@ class KeyManagerTest extends TestCase { $this->utilMock, $this->lockingProviderMock ] - )->setMethods(['getPublicMasterKey', 'setSystemPrivateKey', 'getMasterKeyPassword']) + )->onlyMethods(['getPublicMasterKey', 'setSystemPrivateKey', 'getMasterKeyPassword']) ->getMock(); $this->utilMock->expects($this->once())->method('isMasterKeyEnabled') @@ -613,7 +569,7 @@ class KeyManagerTest extends TestCase { $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); + ->with('systemKeyId.publicKey', 'public', Encryption::ID); $this->cryptMock->expects($this->once())->method('encryptPrivateKey') ->with('private', 'masterKeyPassword', 'systemKeyId') ->willReturn('EncryptedKey'); @@ -631,21 +587,20 @@ class KeyManagerTest extends TestCase { $instance->validateMasterKey(); } - public function testValidateMasterKeyLocked() { - /** @var \OCA\Encryption\KeyManager | \PHPUnit_Framework_MockObject_MockObject $instance */ + public function testValidateMasterKeyLocked(): void { + /** @var KeyManager&MockObject $instance */ $instance = $this->getMockBuilder(KeyManager::class) - ->setConstructorArgs( - [ - $this->keyStorageMock, - $this->cryptMock, - $this->configMock, - $this->userMock, - $this->sessionMock, - $this->logMock, - $this->utilMock, - $this->lockingProviderMock - ] - )->setMethods(['getPublicMasterKey', 'getPrivateMasterKey', 'setSystemPrivateKey', 'getMasterKeyPassword']) + ->setConstructorArgs([ + $this->keyStorageMock, + $this->cryptMock, + $this->configMock, + $this->userMock, + $this->sessionMock, + $this->logMock, + $this->utilMock, + $this->lockingProviderMock + ]) + ->onlyMethods(['getPublicMasterKey', 'getPrivateMasterKey', 'setSystemPrivateKey', 'getMasterKeyPassword']) ->getMock(); $this->utilMock->expects($this->once())->method('isMasterKeyEnabled') @@ -667,14 +622,14 @@ class KeyManagerTest extends TestCase { $instance->validateMasterKey(); } - public function dataTestValidateMasterKey() { + public static function dataTestValidateMasterKey(): array { return [ ['masterKey'], [''] ]; } - public function testGetVersionWithoutFileInfo() { + public function testGetVersionWithoutFileInfo(): void { $view = $this->getMockBuilder(View::class) ->disableOriginalConstructor()->getMock(); $view->expects($this->once()) @@ -682,11 +637,11 @@ class KeyManagerTest extends TestCase { ->with('/admin/files/myfile.txt') ->willReturn(false); - /** @var \OC\Files\View $view */ + /** @var View $view */ $this->assertSame(0, $this->instance->getVersion('/admin/files/myfile.txt', $view)); } - public function testGetVersionWithFileInfo() { + public function testGetVersionWithFileInfo(): void { $view = $this->getMockBuilder(View::class) ->disableOriginalConstructor()->getMock(); $fileInfo = $this->getMockBuilder(FileInfo::class) @@ -699,11 +654,11 @@ class KeyManagerTest extends TestCase { ->with('/admin/files/myfile.txt') ->willReturn($fileInfo); - /** @var \OC\Files\View $view */ + /** @var View $view */ $this->assertSame(1337, $this->instance->getVersion('/admin/files/myfile.txt', $view)); } - public function testSetVersionWithFileInfo() { + public function testSetVersionWithFileInfo(): void { $view = $this->getMockBuilder(View::class) ->disableOriginalConstructor()->getMock(); $cache = $this->getMockBuilder(ICache::class) @@ -711,7 +666,7 @@ class KeyManagerTest extends TestCase { $cache->expects($this->once()) ->method('update') ->with(123, ['encrypted' => 5, 'encryptedVersion' => 5]); - $storage = $this->getMockBuilder(Storage::class) + $storage = $this->getMockBuilder(FilesIStorage::class) ->disableOriginalConstructor()->getMock(); $storage->expects($this->once()) ->method('getCache') @@ -729,11 +684,11 @@ class KeyManagerTest extends TestCase { ->with('/admin/files/myfile.txt') ->willReturn($fileInfo); - /** @var \OC\Files\View $view */ + /** @var View $view */ $this->instance->setVersion('/admin/files/myfile.txt', 5, $view); } - public function testSetVersionWithoutFileInfo() { + public function testSetVersionWithoutFileInfo(): void { $view = $this->getMockBuilder(View::class) ->disableOriginalConstructor()->getMock(); $view->expects($this->once()) @@ -741,11 +696,11 @@ class KeyManagerTest extends TestCase { ->with('/admin/files/myfile.txt') ->willReturn(false); - /** @var \OC\Files\View $view */ + /** @var View $view */ $this->instance->setVersion('/admin/files/myfile.txt', 5, $view); } - public function testBackupUserKeys() { + public function testBackupUserKeys(): void { $this->keyStorageMock->expects($this->once())->method('backupUserKeys') ->with('OC_DEFAULT_MODULE', 'test', 'user1'); $this->instance->backupUserKeys('test', 'user1'); diff --git a/apps/encryption/tests/Listeners/UserEventsListenersTest.php b/apps/encryption/tests/Listeners/UserEventsListenersTest.php new file mode 100644 index 00000000000..cb31523f105 --- /dev/null +++ b/apps/encryption/tests/Listeners/UserEventsListenersTest.php @@ -0,0 +1,258 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +namespace OCA\Encryption\Tests\Listeners; + +use OC\Core\Events\BeforePasswordResetEvent; +use OC\Core\Events\PasswordResetEvent; +use OC\Files\SetupManager; +use OCA\Encryption\KeyManager; +use OCA\Encryption\Listeners\UserEventsListener; +use OCA\Encryption\Services\PassphraseService; +use OCA\Encryption\Session; +use OCA\Encryption\Users\Setup; +use OCA\Encryption\Util; +use OCP\IUser; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\User\Events\BeforePasswordUpdatedEvent; +use OCP\User\Events\PasswordUpdatedEvent; +use OCP\User\Events\UserCreatedEvent; +use OCP\User\Events\UserDeletedEvent; +use OCP\User\Events\UserLoggedInEvent; +use OCP\User\Events\UserLoggedOutEvent; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; + +/** + * @group DB + */ +class UserEventsListenersTest extends TestCase { + + protected Util&MockObject $util; + protected Setup&MockObject $userSetup; + protected Session&MockObject $session; + protected KeyManager&MockObject $keyManager; + protected IUserManager&MockObject $userManager; + protected IUserSession&MockObject $userSession; + protected SetupManager&MockObject $setupManager; + protected PassphraseService&MockObject $passphraseService; + + protected UserEventsListener $instance; + + public function setUp(): void { + parent::setUp(); + + $this->util = $this->createMock(Util::class); + $this->userSetup = $this->createMock(Setup::class); + $this->session = $this->createMock(Session::class); + $this->keyManager = $this->createMock(KeyManager::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->setupManager = $this->createMock(SetupManager::class); + $this->passphraseService = $this->createMock(PassphraseService::class); + + $this->instance = new UserEventsListener( + $this->util, + $this->userSetup, + $this->session, + $this->keyManager, + $this->userManager, + $this->userSession, + $this->setupManager, + $this->passphraseService, + ); + } + + public function testLogin(): void { + $this->userSetup->expects(self::once()) + ->method('setupUser') + ->willReturn(true); + + $this->keyManager->expects(self::once()) + ->method('init') + ->with('testUser', 'password'); + + $this->util->method('isMasterKeyEnabled')->willReturn(false); + + $user = $this->createMock(IUser::class); + $user->expects(self::any()) + ->method('getUID') + ->willReturn('testUser'); + $event = $this->createMock(UserLoggedInEvent::class); + $event->expects(self::atLeastOnce()) + ->method('getUser') + ->willReturn($user); + $event->expects(self::atLeastOnce()) + ->method('getPassword') + ->willReturn('password'); + + $this->instance->handle($event); + } + + public function testLoginMasterKey(): void { + $this->util->method('isMasterKeyEnabled')->willReturn(true); + + $this->userSetup->expects(self::never()) + ->method('setupUser'); + + $this->keyManager->expects(self::once()) + ->method('init') + ->with('testUser', 'password'); + + $user = $this->createMock(IUser::class); + $user->expects(self::any()) + ->method('getUID') + ->willReturn('testUser'); + + $event = $this->createMock(UserLoggedInEvent::class); + $event->expects(self::atLeastOnce()) + ->method('getUser') + ->willReturn($user); + $event->expects(self::atLeastOnce()) + ->method('getPassword') + ->willReturn('password'); + + $this->instance->handle($event); + } + + public function testLogout(): void { + $this->session->expects(self::once()) + ->method('clear'); + + $event = $this->createMock(UserLoggedOutEvent::class); + $this->instance->handle($event); + } + + public function testUserCreated(): void { + $this->userSetup->expects(self::once()) + ->method('setupUser') + ->with('testUser', 'password'); + + $event = $this->createMock(UserCreatedEvent::class); + $event->expects(self::atLeastOnce()) + ->method('getUid') + ->willReturn('testUser'); + $event->expects(self::atLeastOnce()) + ->method('getPassword') + ->willReturn('password'); + + $this->instance->handle($event); + } + + public function testUserDeleted(): void { + $this->keyManager->expects(self::once()) + ->method('deletePublicKey') + ->with('testUser'); + + $event = $this->createMock(UserDeletedEvent::class); + $event->expects(self::atLeastOnce()) + ->method('getUid') + ->willReturn('testUser'); + $this->instance->handle($event); + } + + public function testBeforePasswordUpdated(): void { + $this->passphraseService->expects(self::never()) + ->method('setPassphraseForUser'); + + $user = $this->createMock(IUser::class); + $user->expects(self::atLeastOnce()) + ->method('canChangePassword') + ->willReturn(true); + + $event = $this->createMock(BeforePasswordUpdatedEvent::class); + $event->expects(self::atLeastOnce()) + ->method('getUser') + ->willReturn($user); + $event->expects(self::atLeastOnce()) + ->method('getPassword') + ->willReturn('password'); + $this->instance->handle($event); + } + + public function testBeforePasswordUpdated_CannotChangePassword(): void { + $this->passphraseService->expects(self::once()) + ->method('setPassphraseForUser') + ->with('testUser', 'password'); + + $user = $this->createMock(IUser::class); + $user->expects(self::atLeastOnce()) + ->method('getUID') + ->willReturn('testUser'); + $user->expects(self::atLeastOnce()) + ->method('canChangePassword') + ->willReturn(false); + + $event = $this->createMock(BeforePasswordUpdatedEvent::class); + $event->expects(self::atLeastOnce()) + ->method('getUser') + ->willReturn($user); + $event->expects(self::atLeastOnce()) + ->method('getPassword') + ->willReturn('password'); + $this->instance->handle($event); + } + + public function testPasswordUpdated(): void { + $this->passphraseService->expects(self::once()) + ->method('setPassphraseForUser') + ->with('testUser', 'password'); + + $event = $this->createMock(PasswordUpdatedEvent::class); + $event->expects(self::atLeastOnce()) + ->method('getUid') + ->willReturn('testUser'); + $event->expects(self::atLeastOnce()) + ->method('getPassword') + ->willReturn('password'); + + $this->instance->handle($event); + } + + public function testBeforePasswordReset(): void { + $this->passphraseService->expects(self::once()) + ->method('setProcessingReset') + ->with('testUser'); + + $event = $this->createMock(BeforePasswordResetEvent::class); + $event->expects(self::atLeastOnce()) + ->method('getUid') + ->willReturn('testUser'); + $this->instance->handle($event); + } + + public function testPasswordReset(): void { + // backup required + $this->keyManager->expects(self::once()) + ->method('backupUserKeys') + ->with('passwordReset', 'testUser'); + // delete old keys + $this->keyManager->expects(self::once()) + ->method('deleteUserKeys') + ->with('testUser'); + // create new keys + $this->userSetup->expects(self::once()) + ->method('setupUser') + ->with('testUser', 'password'); + // reset ends + $this->passphraseService->expects(self::once()) + ->method('setProcessingReset') + ->with('testUser', false); + + $event = $this->createMock(PasswordResetEvent::class); + $event->expects(self::atLeastOnce()) + ->method('getUid') + ->willReturn('testUser'); + $event->expects(self::atLeastOnce()) + ->method('getPassword') + ->willReturn('password'); + $this->instance->handle($event); + } + +} diff --git a/apps/encryption/tests/PassphraseServiceTest.php b/apps/encryption/tests/PassphraseServiceTest.php new file mode 100644 index 00000000000..c2dc9d8173c --- /dev/null +++ b/apps/encryption/tests/PassphraseServiceTest.php @@ -0,0 +1,196 @@ +<?php + +declare(strict_types=1); + +/** + * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later + */ +namespace OCA\Encryption\Tests; + +use OCA\Encryption\Crypto\Crypt; +use OCA\Encryption\KeyManager; +use OCA\Encryption\Recovery; +use OCA\Encryption\Services\PassphraseService; +use OCA\Encryption\Session; +use OCA\Encryption\Util; +use OCP\IUser; +use OCP\IUserManager; +use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +/** + * @group DB + */ +class PassphraseServiceTest extends TestCase { + + protected Util&MockObject $util; + protected Crypt&MockObject $crypt; + protected Session&MockObject $session; + protected Recovery&MockObject $recovery; + protected KeyManager&MockObject $keyManager; + protected IUserManager&MockObject $userManager; + protected IUserSession&MockObject $userSession; + + protected PassphraseService $instance; + + public function setUp(): void { + parent::setUp(); + + $this->util = $this->createMock(Util::class); + $this->crypt = $this->createMock(Crypt::class); + $this->session = $this->createMock(Session::class); + $this->recovery = $this->createMock(Recovery::class); + $this->keyManager = $this->createMock(KeyManager::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->userSession = $this->createMock(IUserSession::class); + + $this->instance = new PassphraseService( + $this->util, + $this->crypt, + $this->session, + $this->recovery, + $this->keyManager, + $this->createMock(LoggerInterface::class), + $this->userManager, + $this->userSession, + ); + } + + public function testSetProcessingReset(): void { + $this->instance->setProcessingReset('userId'); + $this->assertEquals(['userId' => true], $this->invokePrivate($this->instance, 'passwordResetUsers')); + } + + public function testUnsetProcessingReset(): void { + $this->instance->setProcessingReset('userId'); + $this->assertEquals(['userId' => true], $this->invokePrivate($this->instance, 'passwordResetUsers')); + $this->instance->setProcessingReset('userId', false); + $this->assertEquals([], $this->invokePrivate($this->instance, 'passwordResetUsers')); + } + + /** + * Check that the passphrase setting skips if a reset is processed + */ + public function testSetPassphraseResetUserMode(): void { + $this->session->expects(self::never()) + ->method('getPrivateKey'); + $this->keyManager->expects(self::never()) + ->method('setPrivateKey'); + + $this->instance->setProcessingReset('userId'); + $this->assertTrue($this->instance->setPassphraseForUser('userId', 'password')); + } + + public function testSetPassphrase_currentUser() { + $instance = $this->getMockBuilder(PassphraseService::class) + ->onlyMethods(['initMountPoints']) + ->setConstructorArgs([ + $this->util, + $this->crypt, + $this->session, + $this->recovery, + $this->keyManager, + $this->createMock(LoggerInterface::class), + $this->userManager, + $this->userSession, + ]) + ->getMock(); + + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn('testUser'); + $this->userSession->expects(self::atLeastOnce()) + ->method('getUser') + ->willReturn($user); + $this->userManager->expects(self::atLeastOnce()) + ->method('get') + ->with('testUser') + ->willReturn($user); + $this->session->expects(self::any()) + ->method('getPrivateKey') + ->willReturn('private-key'); + $this->crypt->expects(self::any()) + ->method('encryptPrivateKey') + ->with('private-key') + ->willReturn('encrypted-key'); + $this->crypt->expects(self::any()) + ->method('generateHeader') + ->willReturn('crypt-header: '); + + $this->keyManager->expects(self::atLeastOnce()) + ->method('setPrivateKey') + ->with('testUser', 'crypt-header: encrypted-key'); + + $this->assertTrue($instance->setPassphraseForUser('testUser', 'password')); + } + + public function testSetPassphrase_currentUserFails() { + $instance = $this->getMockBuilder(PassphraseService::class) + ->onlyMethods(['initMountPoints']) + ->setConstructorArgs([ + $this->util, + $this->crypt, + $this->session, + $this->recovery, + $this->keyManager, + $this->createMock(LoggerInterface::class), + $this->userManager, + $this->userSession, + ]) + ->getMock(); + + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn('testUser'); + $this->userManager->expects(self::atLeastOnce()) + ->method('get') + ->with('testUser') + ->willReturn($user); + $this->userSession->expects(self::atLeastOnce()) + ->method('getUser') + ->willReturn($user); + $this->session->expects(self::any()) + ->method('getPrivateKey') + ->willReturn('private-key'); + $this->crypt->expects(self::any()) + ->method('encryptPrivateKey') + ->with('private-key') + ->willReturn(false); + + $this->keyManager->expects(self::never()) + ->method('setPrivateKey'); + + $this->assertFalse($instance->setPassphraseForUser('testUser', 'password')); + } + + public function testSetPassphrase_currentUserNotExists() { + $instance = $this->getMockBuilder(PassphraseService::class) + ->onlyMethods(['initMountPoints']) + ->setConstructorArgs([ + $this->util, + $this->crypt, + $this->session, + $this->recovery, + $this->keyManager, + $this->createMock(LoggerInterface::class), + $this->userManager, + $this->userSession, + ]) + ->getMock(); + + $user = $this->createMock(IUser::class); + $user->method('getUID')->willReturn('testUser'); + $this->userManager->expects(self::atLeastOnce()) + ->method('get') + ->with('testUser') + ->willReturn(null); + $this->userSession->expects(self::never()) + ->method('getUser'); + $this->keyManager->expects(self::never()) + ->method('setPrivateKey'); + + $this->assertFalse($instance->setPassphraseForUser('testUser', 'password')); + } + +} diff --git a/apps/encryption/tests/RecoveryTest.php b/apps/encryption/tests/RecoveryTest.php index af053515f8c..0627724a856 100644 --- a/apps/encryption/tests/RecoveryTest.php +++ b/apps/encryption/tests/RecoveryTest.php @@ -1,29 +1,11 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests; @@ -41,15 +23,15 @@ use Test\TestCase; class RecoveryTest extends TestCase { private static $tempStorage = []; /** - * @var \OCP\Encryption\IFile|\PHPUnit\Framework\MockObject\MockObject + * @var IFile|\PHPUnit\Framework\MockObject\MockObject */ private $fileMock; /** - * @var \OC\Files\View|\PHPUnit\Framework\MockObject\MockObject + * @var View|\PHPUnit\Framework\MockObject\MockObject */ private $viewMock; /** - * @var \OCP\IUserSession|\PHPUnit\Framework\MockObject\MockObject + * @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ private $userSessionMock; /** @@ -57,15 +39,15 @@ class RecoveryTest extends TestCase { */ private $user; /** - * @var \OCA\Encryption\KeyManager|\PHPUnit\Framework\MockObject\MockObject + * @var KeyManager|\PHPUnit\Framework\MockObject\MockObject */ private $keyManagerMock; /** - * @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject + * @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ private $configMock; /** - * @var \OCA\Encryption\Crypto\Crypt|\PHPUnit\Framework\MockObject\MockObject + * @var Crypt|\PHPUnit\Framework\MockObject\MockObject */ private $cryptMock; /** @@ -73,7 +55,7 @@ class RecoveryTest extends TestCase { */ private $instance; - public function testEnableAdminRecoverySuccessful() { + public function testEnableAdminRecoverySuccessful(): void { $this->keyManagerMock->expects($this->exactly(2)) ->method('recoveryKeyExists') ->willReturnOnConsecutiveCalls(false, true); @@ -100,7 +82,7 @@ class RecoveryTest extends TestCase { $this->assertTrue($this->instance->enableAdminRecovery('password')); } - public function testEnableAdminRecoveryCouldNotCheckPassword() { + public function testEnableAdminRecoveryCouldNotCheckPassword(): void { $this->keyManagerMock->expects($this->exactly(2)) ->method('recoveryKeyExists') ->willReturnOnConsecutiveCalls(false, true); @@ -127,7 +109,7 @@ class RecoveryTest extends TestCase { $this->assertFalse($this->instance->enableAdminRecovery('password')); } - public function testEnableAdminRecoveryCouldNotCreateKey() { + public function testEnableAdminRecoveryCouldNotCreateKey(): void { $this->keyManagerMock->expects($this->once()) ->method('recoveryKeyExists') ->willReturn(false); @@ -139,7 +121,7 @@ class RecoveryTest extends TestCase { $this->assertFalse($this->instance->enableAdminRecovery('password')); } - public function testChangeRecoveryKeyPasswordSuccessful() { + public function testChangeRecoveryKeyPasswordSuccessful(): void { $this->assertFalse($this->instance->changeRecoveryKeyPassword('password', 'passwordOld')); @@ -157,7 +139,7 @@ class RecoveryTest extends TestCase { 'passwordOld')); } - public function testChangeRecoveryKeyPasswordCouldNotDecryptPrivateRecoveryKey() { + public function testChangeRecoveryKeyPasswordCouldNotDecryptPrivateRecoveryKey(): void { $this->assertFalse($this->instance->changeRecoveryKeyPassword('password', 'passwordOld')); $this->keyManagerMock->expects($this->once()) @@ -170,7 +152,7 @@ class RecoveryTest extends TestCase { $this->assertFalse($this->instance->changeRecoveryKeyPassword('password', 'passwordOld')); } - public function testDisableAdminRecovery() { + public function testDisableAdminRecovery(): void { $this->keyManagerMock->expects($this->exactly(2)) ->method('checkRecoveryPassword') ->willReturnOnConsecutiveCalls(true, false); @@ -182,7 +164,7 @@ class RecoveryTest extends TestCase { $this->assertFalse($this->instance->disableAdminRecovery('password')); } - public function testIsRecoveryEnabledForUser() { + public function testIsRecoveryEnabledForUser(): void { $this->configMock->expects($this->exactly(2)) ->method('getUserValue') ->willReturnOnConsecutiveCalls('1', '0'); @@ -191,13 +173,13 @@ class RecoveryTest extends TestCase { $this->assertFalse($this->instance->isRecoveryEnabledForUser('admin')); } - public function testIsRecoveryKeyEnabled() { + public function testIsRecoveryKeyEnabled(): void { $this->assertFalse($this->instance->isRecoveryKeyEnabled()); self::$tempStorage['recoveryAdminEnabled'] = '1'; $this->assertTrue($this->instance->isRecoveryKeyEnabled()); } - public function testSetRecoveryFolderForUser() { + public function testSetRecoveryFolderForUser(): void { $this->viewMock->expects($this->exactly(2)) ->method('getDirectoryContent') ->willReturn([]); @@ -205,7 +187,7 @@ class RecoveryTest extends TestCase { $this->assertTrue($this->instance->setRecoveryForUser('1')); } - public function testRecoverUserFiles() { + public function testRecoverUserFiles(): void { $this->viewMock->expects($this->once()) ->method('getDirectoryContent') ->willReturn([]); @@ -217,7 +199,7 @@ class RecoveryTest extends TestCase { $this->addToAssertionCount(1); } - public function testRecoverFile() { + public function testRecoverFile(): void { $this->keyManagerMock->expects($this->once()) ->method('getEncryptedFileKey') ->willReturn(true); diff --git a/apps/encryption/tests/SessionTest.php b/apps/encryption/tests/SessionTest.php index 91c83b80fa9..986502749c8 100644 --- a/apps/encryption/tests/SessionTest.php +++ b/apps/encryption/tests/SessionTest.php @@ -1,47 +1,28 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests; +use OCA\Encryption\Exceptions\PrivateKeyMissingException; use OCA\Encryption\Session; use OCP\ISession; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class SessionTest extends TestCase { private static $tempStorage = []; - /** - * @var Session - */ - private $instance; - /** @var \OCP\ISession|\PHPUnit\Framework\MockObject\MockObject */ - private $sessionMock; + protected Session $instance; + protected ISession&MockObject $sessionMock; - public function testThatGetPrivateKeyThrowsExceptionWhenNotSet() { - $this->expectException(\OCA\Encryption\Exceptions\PrivateKeyMissingException::class); + public function testThatGetPrivateKeyThrowsExceptionWhenNotSet(): void { + $this->expectException(PrivateKeyMissingException::class); $this->expectExceptionMessage('Private Key missing for user: please try to log-out and log-in again'); $this->instance->getPrivateKey(); @@ -50,7 +31,7 @@ class SessionTest extends TestCase { /** * @depends testThatGetPrivateKeyThrowsExceptionWhenNotSet */ - public function testSetAndGetPrivateKey() { + public function testSetAndGetPrivateKey(): void { $this->instance->setPrivateKey('dummyPrivateKey'); $this->assertEquals('dummyPrivateKey', $this->instance->getPrivateKey()); } @@ -58,7 +39,7 @@ class SessionTest extends TestCase { /** * @depends testSetAndGetPrivateKey */ - public function testIsPrivateKeySet() { + public function testIsPrivateKeySet(): void { $this->instance->setPrivateKey('dummyPrivateKey'); $this->assertTrue($this->instance->isPrivateKeySet()); @@ -69,21 +50,21 @@ class SessionTest extends TestCase { self::$tempStorage['privateKey'] = 'dummyPrivateKey'; } - public function testDecryptAllModeActivated() { + public function testDecryptAllModeActivated(): void { $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() { + public function testDecryptAllModeDeactivated(): void { $this->assertFalse($this->instance->decryptAllModeActivated()); } /** * @expectExceptionMessage 'Please activate decrypt all mode first' */ - public function testGetDecryptAllUidException() { + public function testGetDecryptAllUidException(): void { $this->expectException(\Exception::class); $this->instance->getDecryptAllUid(); @@ -92,7 +73,7 @@ class SessionTest extends TestCase { /** * @expectExceptionMessage 'No uid found while in decrypt all mode' */ - public function testGetDecryptAllUidException2() { + public function testGetDecryptAllUidException2(): void { $this->expectException(\Exception::class); $this->instance->prepareDecryptAll(null, 'key'); @@ -102,8 +83,8 @@ class SessionTest extends TestCase { /** * @expectExceptionMessage 'Please activate decrypt all mode first' */ - public function testGetDecryptAllKeyException() { - $this->expectException(\OCA\Encryption\Exceptions\PrivateKeyMissingException::class); + public function testGetDecryptAllKeyException(): void { + $this->expectException(PrivateKeyMissingException::class); $this->instance->getDecryptAllKey(); } @@ -111,15 +92,15 @@ class SessionTest extends TestCase { /** * @expectExceptionMessage 'No key found while in decrypt all mode' */ - public function testGetDecryptAllKeyException2() { - $this->expectException(\OCA\Encryption\Exceptions\PrivateKeyMissingException::class); + public function testGetDecryptAllKeyException2(): void { + $this->expectException(PrivateKeyMissingException::class); $this->instance->prepareDecryptAll('user', null); $this->instance->getDecryptAllKey(); } - public function testSetAndGetStatusWillSetAndReturn() { + public function testSetAndGetStatusWillSetAndReturn(): void { // Check if get status will return 0 if it has not been set before $this->assertEquals(0, $this->instance->getStatus()); @@ -134,16 +115,17 @@ class SessionTest extends TestCase { } /** - * @dataProvider dataTestIsReady * * @param int $status * @param bool $expected */ - public function testIsReady($status, $expected) { - /** @var Session | \PHPUnit\Framework\MockObject\MockObject $instance */ + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsReady')] + public function testIsReady($status, $expected): void { + /** @var Session&MockObject $instance */ $instance = $this->getMockBuilder(Session::class) ->setConstructorArgs([$this->sessionMock]) - ->setMethods(['getStatus'])->getMock(); + ->onlyMethods(['getStatus']) + ->getMock(); $instance->expects($this->once())->method('getStatus') ->willReturn($status); @@ -151,7 +133,7 @@ class SessionTest extends TestCase { $this->assertSame($expected, $instance->isReady()); } - public function dataTestIsReady() { + public static function dataTestIsReady(): array { return [ [Session::INIT_SUCCESSFUL, true], [Session::INIT_EXECUTED, false], @@ -186,7 +168,7 @@ class SessionTest extends TestCase { } - public function testClearWillRemoveValues() { + public function testClearWillRemoveValues(): void { $this->instance->setPrivateKey('privateKey'); $this->instance->setStatus('initStatus'); $this->instance->prepareDecryptAll('user', 'key'); @@ -202,15 +184,15 @@ class SessionTest extends TestCase { $this->sessionMock->expects($this->any()) ->method('set') - ->willReturnCallback([$this, "setValueTester"]); + ->willReturnCallback([$this, 'setValueTester']); $this->sessionMock->expects($this->any()) ->method('get') - ->willReturnCallback([$this, "getValueTester"]); + ->willReturnCallback([$this, 'getValueTester']); $this->sessionMock->expects($this->any()) ->method('remove') - ->willReturnCallback([$this, "removeValueTester"]); + ->willReturnCallback([$this, 'removeValueTester']); $this->instance = new Session($this->sessionMock); diff --git a/apps/encryption/tests/Settings/AdminTest.php b/apps/encryption/tests/Settings/AdminTest.php index d675b3030a8..8355cdf6729 100644 --- a/apps/encryption/tests/Settings/AdminTest.php +++ b/apps/encryption/tests/Settings/AdminTest.php @@ -1,27 +1,10 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016 Lukas Reschke <lukas@statuscode.ch> - * - * @author Julius Härtl <jus@bitgrid.net> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @license GNU AGPL version 3 or any later version - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * 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 - * along with this program. If not, see <http://www.gnu.org/licenses/>. - * + * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors + * SPDX-License-Identifier: AGPL-3.0-or-later */ namespace OCA\Encryption\Tests\Settings; @@ -32,24 +15,20 @@ use OCP\IL10N; use OCP\ISession; use OCP\IUserManager; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; class AdminTest extends TestCase { - /** @var Admin */ - private $admin; - /** @var IL10N */ - private $l; - /** @var LoggerInterface */ - private $logger; - /** @var IUserSession */ - private $userSession; - /** @var IConfig */ - private $config; - /** @var IUserManager */ - private $userManager; - /** @var ISession */ - private $session; + + protected Admin $admin; + + protected IL10N&MockObject $l; + protected LoggerInterface&MockObject $logger; + protected IUserSession&MockObject $userSession; + protected IConfig&MockObject $config; + protected IUserManager&MockObject $userManager; + protected ISession&MockObject $session; protected function setUp(): void { parent::setUp(); @@ -71,10 +50,10 @@ class AdminTest extends TestCase { ); } - public function testGetForm() { + public function testGetForm(): void { $this->config ->method('getAppValue') - ->will($this->returnCallback(function ($app, $key, $default) { + ->willReturnCallback(function ($app, $key, $default) { if ($app === 'encryption' && $key === 'recoveryAdminEnabled' && $default === '0') { return '1'; } @@ -82,7 +61,7 @@ class AdminTest extends TestCase { return '1'; } return $default; - })); + }); $params = [ 'recoveryEnabled' => '1', 'initStatus' => '0', @@ -93,11 +72,11 @@ class AdminTest extends TestCase { $this->assertEquals($expected, $this->admin->getForm()); } - public function testGetSection() { + public function testGetSection(): void { $this->assertSame('security', $this->admin->getSection()); } - public function testGetPriority() { + public function testGetPriority(): void { $this->assertSame(11, $this->admin->getPriority()); } } diff --git a/apps/encryption/tests/Users/SetupTest.php b/apps/encryption/tests/Users/SetupTest.php index 00888ba8c60..6b2b8b4cad5 100644 --- a/apps/encryption/tests/Users/SetupTest.php +++ b/apps/encryption/tests/Users/SetupTest.php @@ -1,48 +1,26 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Björn Schießle <bjoern@schiessle.org> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests\Users; use OCA\Encryption\Crypto\Crypt; use OCA\Encryption\KeyManager; use OCA\Encryption\Users\Setup; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class SetupTest extends TestCase { - /** - * @var \OCA\Encryption\KeyManager|\PHPUnit\Framework\MockObject\MockObject - */ - private $keyManagerMock; - /** - * @var \OCA\Encryption\Crypto\Crypt|\PHPUnit\Framework\MockObject\MockObject - */ - private $cryptMock; - /** - * @var Setup - */ - private $instance; + + protected Setup $instance; + + protected KeyManager&MockObject $keyManagerMock; + protected Crypt&MockObject $cryptMock; protected function setUp(): void { parent::setUp(); @@ -60,7 +38,7 @@ class SetupTest extends TestCase { } - public function testSetupSystem() { + public function testSetupSystem(): void { $this->keyManagerMock->expects($this->once())->method('validateShareKey'); $this->keyManagerMock->expects($this->once())->method('validateMasterKey'); @@ -68,12 +46,12 @@ class SetupTest extends TestCase { } /** - * @dataProvider dataTestSetupUser * * @param bool $hasKeys * @param bool $expected */ - public function testSetupUser($hasKeys, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestSetupUser')] + public function testSetupUser($hasKeys, $expected): void { $this->keyManagerMock->expects($this->once())->method('userHasKeys') ->with('uid')->willReturn($hasKeys); @@ -90,7 +68,7 @@ class SetupTest extends TestCase { ); } - public function dataTestSetupUser() { + public static function dataTestSetupUser(): array { return [ [true, true], [false, true] diff --git a/apps/encryption/tests/UtilTest.php b/apps/encryption/tests/UtilTest.php index 3c3a8ba371a..41860a44ffb 100644 --- a/apps/encryption/tests/UtilTest.php +++ b/apps/encryption/tests/UtilTest.php @@ -1,29 +1,11 @@ <?php + +declare(strict_types=1); + /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Björn Schießle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Clark Tomlinson <fallen013@gmail.com> - * @author Joas Schilling <coding@schilljs.com> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * - * @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/> - * + * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Encryption\Tests; @@ -31,7 +13,7 @@ use OC\Files\View; use OCA\Encryption\Crypto\Crypt; use OCA\Encryption\Util; use OCP\Files\Mount\IMountPoint; -use OCP\Files\Storage; +use OCP\Files\Storage\IStorage; use OCP\IConfig; use OCP\IUser; use OCP\IUserManager; @@ -40,29 +22,21 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class UtilTest extends TestCase { - private static $tempStorage = []; - - /** @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject */ - private $configMock; - - /** @var \OC\Files\View|\PHPUnit\Framework\MockObject\MockObject */ - private $filesMock; - - /** @var \OCP\IUserManager|\PHPUnit\Framework\MockObject\MockObject */ - private $userManagerMock; - /** @var \OCP\Files\Mount\IMountPoint|\PHPUnit\Framework\MockObject\MockObject */ - private $mountMock; + protected Util $instance; + protected static $tempStorage = []; - /** @var Util */ - private $instance; + protected IConfig&MockObject $configMock; + protected View&MockObject $filesMock; + protected IUserManager&MockObject $userManagerMock; + protected IMountPoint&MockObject $mountMock; - public function testSetRecoveryForUser() { + public function testSetRecoveryForUser(): void { $this->instance->setRecoveryForUser('1'); $this->assertArrayHasKey('recoveryEnabled', self::$tempStorage); } - public function testIsRecoveryEnabledForUser() { + public function testIsRecoveryEnabledForUser(): void { $this->assertTrue($this->instance->isRecoveryEnabledForUser('admin')); // Assert recovery will return default value if not set @@ -70,7 +44,7 @@ class UtilTest extends TestCase { $this->assertEquals(0, $this->instance->isRecoveryEnabledForUser('admin')); } - public function testUserHasFiles() { + public function testUserHasFiles(): void { $this->filesMock->expects($this->once()) ->method('file_exists') ->willReturn(true); @@ -84,7 +58,7 @@ class UtilTest extends TestCase { $this->filesMock = $this->createMock(View::class); $this->userManagerMock = $this->createMock(IUserManager::class); - /** @var \OCA\Encryption\Crypto\Crypt $cryptMock */ + /** @var Crypt $cryptMock */ $cryptMock = $this->getMockBuilder(Crypt::class) ->disableOriginalConstructor() ->getMock(); @@ -141,12 +115,12 @@ class UtilTest extends TestCase { } /** - * @dataProvider dataTestIsMasterKeyEnabled * * @param string $value * @param bool $expect */ - public function testIsMasterKeyEnabled($value, $expect) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestIsMasterKeyEnabled')] + public function testIsMasterKeyEnabled($value, $expect): void { $this->configMock->expects($this->once())->method('getAppValue') ->with('encryption', 'useMasterKey', '1')->willReturn($value); $this->assertSame($expect, @@ -154,7 +128,7 @@ class UtilTest extends TestCase { ); } - public function dataTestIsMasterKeyEnabled() { + public static function dataTestIsMasterKeyEnabled(): array { return [ ['0', false], ['1', true] @@ -162,11 +136,11 @@ class UtilTest extends TestCase { } /** - * @dataProvider dataTestShouldEncryptHomeStorage * @param string $returnValue return value from getAppValue() * @param bool $expected */ - public function testShouldEncryptHomeStorage($returnValue, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestShouldEncryptHomeStorage')] + public function testShouldEncryptHomeStorage($returnValue, $expected): void { $this->configMock->expects($this->once())->method('getAppValue') ->with('encryption', 'encryptHomeStorage', '1') ->willReturn($returnValue); @@ -175,7 +149,7 @@ class UtilTest extends TestCase { $this->instance->shouldEncryptHomeStorage()); } - public function dataTestShouldEncryptHomeStorage() { + public static function dataTestShouldEncryptHomeStorage(): array { return [ ['1', true], ['0', false] @@ -183,25 +157,25 @@ class UtilTest extends TestCase { } /** - * @dataProvider dataTestSetEncryptHomeStorage * @param $value * @param $expected */ - public function testSetEncryptHomeStorage($value, $expected) { + #[\PHPUnit\Framework\Attributes\DataProvider('dataTestSetEncryptHomeStorage')] + public function testSetEncryptHomeStorage($value, $expected): void { $this->configMock->expects($this->once())->method('setAppValue') ->with('encryption', 'encryptHomeStorage', $expected); $this->instance->setEncryptHomeStorage($value); } - public function dataTestSetEncryptHomeStorage() { + public static function dataTestSetEncryptHomeStorage(): array { return [ [true, '1'], [false, '0'] ]; } - public function testGetStorage() { - $return = $this->getMockBuilder(Storage::class) + public function testGetStorage(): void { + $return = $this->getMockBuilder(IStorage::class) ->disableOriginalConstructor() ->getMock(); |