From eb94af3654753c268eed8c46041527454463e2c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20Ba=C4=8Do?= Date: Tue, 15 Sep 2026 15:48:47 +0200 Subject: [PATCH] refactor(auth): drop the adapter layer, let the validator be the validator Review feedback: `Appwrite\Auth\Pwned` was a second hierarchy wrapped by a validator whose `isValid()` nothing called, and every call site reached for `check()` instead. That is not how validators are used here. `PasswordPwned` is now abstract, with one subclass per service, the same shape as `OAuth2` and its providers. The request resource hands back the right subclass and call sites use `isValid()` like they already do for `PersonalData` and `PasswordHistory`. The tri-state for the `passwordPwned` user attribute did not need a method of its own after all. A call site knows whether the policy is enabled, so null comes from not asking rather than from a return value. Co-Authored-By: Claude Opus 5 (1M context) --- app/controllers/api/account.php | 17 ++- app/init/resources/request.php | 21 ++- src/Appwrite/Auth/Pwned.php | 53 -------- src/Appwrite/Auth/Validator/PasswordPwned.php | 70 ++++++---- .../PasswordPwned}/Appwrite.php | 22 +-- .../PasswordPwned}/HIBP.php | 22 +-- .../PasswordPwned}/Mock.php | 15 +-- .../Modules/Users/Http/Users/Create.php | 4 +- .../Users/Http/Users/Password/Update.php | 4 +- .../PoliciesPasswordPwnedIntegrationTest.php | 2 +- tests/unit/Auth/Pwned/MockTest.php | 39 ------ .../PasswordPwned}/AppwriteTest.php | 127 +++++++++--------- .../PasswordPwned}/HIBPTest.php | 56 ++++---- .../Auth/Validator/PasswordPwned/MockTest.php | 38 ++++++ .../unit/Auth/Validator/PasswordPwnedTest.php | 86 +++--------- 15 files changed, 257 insertions(+), 319 deletions(-) delete mode 100644 src/Appwrite/Auth/Pwned.php rename src/Appwrite/Auth/{Pwned => Validator/PasswordPwned}/Appwrite.php (83%) rename src/Appwrite/Auth/{Pwned => Validator/PasswordPwned}/HIBP.php (84%) rename src/Appwrite/Auth/{Pwned => Validator/PasswordPwned}/Mock.php (68%) delete mode 100644 tests/unit/Auth/Pwned/MockTest.php rename tests/unit/Auth/{Pwned => Validator/PasswordPwned}/AppwriteTest.php (77%) rename tests/unit/Auth/{Pwned => Validator/PasswordPwned}/HIBPTest.php (68%) create mode 100644 tests/unit/Auth/Validator/PasswordPwned/MockTest.php diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 9256ab59c7..e665d9cb43 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -363,7 +363,8 @@ Http::post('/v1/account') } } - $passwordPwned = $pwnedPasswords->check($password); + // null when the policy did not look, false when it looked and found nothing + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -1050,9 +1051,9 @@ Http::post('/v1/account/sessions/email') if ($pwnedPasswords->checksSessions()) { // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in - $passwordPwned = $pwnedPasswords->check($password); + $passwordPwned = !$pwnedPasswords->isValid($password); - if ($passwordPwned !== null && $passwordPwned !== $user->getAttribute('passwordPwned')) { + if ($passwordPwned !== $user->getAttribute('passwordPwned')) { $user->setAttribute('passwordPwned', $passwordPwned); $dbForProject->updateDocument('users', $user->getId(), new Document([ 'passwordPwned' => $passwordPwned, @@ -3509,7 +3510,8 @@ Http::patch('/v1/account/password') } } - $passwordPwned = $pwnedPasswords->check($password); + // null when the policy did not look, false when it looked and found nothing + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -3613,7 +3615,7 @@ Http::patch('/v1/account/email') } } - $passwordPwned = $pwnedPasswords->check($password); + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -3787,7 +3789,7 @@ Http::patch('/v1/account/phone') } } - $passwordPwned = $pwnedPasswords->check($password); + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } @@ -4234,7 +4236,8 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } - $passwordPwned = $pwnedPasswords->check($password); + // null when the policy did not look, false when it looked and found nothing + $passwordPwned = $pwnedPasswords->isEnabled() ? !$pwnedPasswords->isValid($password) : null; if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } diff --git a/app/init/resources/request.php b/app/init/resources/request.php index ce0a337fa9..ca3b559721 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -3,10 +3,9 @@ use Ahc\Jwt\JWT; use Ahc\Jwt\JWTException; use Appwrite\Auth\Key; -use Appwrite\Auth\Pwned\Appwrite as PwnedAppwrite; -use Appwrite\Auth\Pwned\HIBP as PwnedHIBP; -use Appwrite\Auth\Pwned\Mock as PwnedMock; -use Appwrite\Auth\Validator\PasswordPwned; +use Appwrite\Auth\Validator\PasswordPwned\Appwrite as PasswordPwnedAppwrite; +use Appwrite\Auth\Validator\PasswordPwned\HIBP as PasswordPwnedHIBP; +use Appwrite\Auth\Validator\PasswordPwned\Mock as PasswordPwnedMock; use Appwrite\Database\Factory as DatabaseFactory; use Appwrite\Databases\TransactionState; use Appwrite\Deployment\Deployments; @@ -681,17 +680,17 @@ return function (Container $context): void { $context->set('pwnedPasswords', function (Document $project, Cache $cache) { $dsn = new DSN(System::getEnv('_APP_PWNED_PASSWORDS_DSN', 'hibp://localhost')); - $adapter = match ($dsn->getScheme()) { - 'hibp' => new PwnedHIBP($cache), - 'appwrite' => new PwnedAppwrite($dsn), + $policy = $project->getAttribute('auths', [])['passwordPwned'] ?? []; + + return match ($dsn->getScheme()) { + 'hibp' => new PasswordPwnedHIBP($policy, $cache), + 'appwrite' => new PasswordPwnedAppwrite($policy, $dsn), // Reports almost every password as safe, so it must never be reachable on a real server 'mock' => Http::isProduction() - ? throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The mock breach adapter cannot be used in production.') - : new PwnedMock(), + ? throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The mock breach validator cannot be used in production.') + : new PasswordPwnedMock($policy), default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown _APP_PWNED_PASSWORDS_DSN scheme: ' . $dsn->getScheme()), }; - - return new PasswordPwned($adapter, $project->getAttribute('auths', [])['passwordPwned'] ?? []); }, ['project', 'cache']); $context->set('dbForProject', function (DatabaseFactory $databaseFactory, Database $dbForPlatform, Document $project, Response $response, Publisher $publisher, Event $queueForEvents, FunctionPublisher $publisherForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime, UsageContext $usage, Request $request) { diff --git a/src/Appwrite/Auth/Pwned.php b/src/Appwrite/Auth/Pwned.php deleted file mode 100644 index 25ae03bd2b..0000000000 --- a/src/Appwrite/Auth/Pwned.php +++ /dev/null @@ -1,53 +0,0 @@ -setConnectTimeout(self::CONNECT_TIMEOUT) - ->setTimeout(self::REQUEST_TIMEOUT) - ->setAllowRedirects(false) - ->setUserAgent('Appwrite'); - } - - /** - * A password is never silently accepted when the lookup did not happen. - * - * @throws Exception - */ - protected function unavailable(): never - { - throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); - } -} diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index 40b6fdae87..649d21948d 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -2,30 +2,32 @@ namespace Appwrite\Auth\Validator; -use Appwrite\Auth\Pwned; use Appwrite\Extend\Exception; +use Utopia\Fetch\Client; /** * Validates a password against the project's `password-pwned` policy. * - * The lookup itself belongs to the configured adapter, see `Appwrite\Auth\Pwned`. - * This class only decides whether the policy asks for one. + * Subclasses differ in who answers the question and in what leaves the server, + * so read the one you are configuring. `_APP_PWNED_PASSWORDS_DSN` picks it, and + * the DSN scheme matches the subclass. */ -class PasswordPwned extends Password +abstract class PasswordPwned extends Password { + private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds + private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds + protected bool $enabled; protected bool $sessions; protected bool $users; - protected Pwned $adapter; /** * @param array $policy the project's `passwordPwned` auth settings */ - public function __construct(Pwned $adapter, array $policy = [], bool $allowEmpty = false) + public function __construct(array $policy = [], bool $allowEmpty = false) { parent::__construct($allowEmpty); - $this->adapter = $adapter; $this->enabled = (bool) ($policy['enabled'] ?? true); $this->sessions = (bool) ($policy['sessions'] ?? false); $this->users = (bool) ($policy['users'] ?? false); @@ -69,25 +71,12 @@ class PasswordPwned extends Password return 'Password must not have been exposed in a known data breach.'; } - /** - * Whether the password appears in a known breach. - * - * Returns null only when the policy is disabled. - * - * @throws Exception when the breach service cannot be reached - */ - public function check(string $password): ?bool - { - if (!$this->enabled) { - return null; - } - - return $this->adapter->isPwned($password); - } - /** * Is valid. * + * A password the policy did not look at is valid, so callers that need to + * tell "clean" from "never checked" ask `isEnabled()` first. + * * @param mixed $value * * @return bool @@ -103,7 +92,11 @@ class PasswordPwned extends Password return true; } - return $this->check($value) !== true; + if (!$this->enabled) { + return true; + } + + return !$this->isPwned($value); } /** @@ -129,4 +122,33 @@ class PasswordPwned extends Password { return self::TYPE_STRING; } + + /** + * Whether the password appears in a known data breach. + * + * @throws Exception when the breach service cannot be reached or answers with nonsense + */ + abstract protected function isPwned(string $password): bool; + + /** + * A client with the timeouts a password check can afford to wait. + */ + protected function client(?Client $client = null): Client + { + return $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); + } + + /** + * A password is never silently accepted when the lookup did not happen. + * + * @throws Exception + */ + protected function unavailable(): never + { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } } diff --git a/src/Appwrite/Auth/Pwned/Appwrite.php b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php similarity index 83% rename from src/Appwrite/Auth/Pwned/Appwrite.php rename to src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php index 099f86711a..a2199a50d5 100644 --- a/src/Appwrite/Auth/Pwned/Appwrite.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php @@ -1,14 +1,14 @@ $policy + */ + public function __construct(array $policy, DSN $dsn, ?Client $client = null) { + parent::__construct($policy); + $scheme = $dsn->getParam('tls') === 'true' ? 'https' : 'http'; $port = $dsn->getPort() !== null ? ':' . $dsn->getPort() : ''; $path = $dsn->getPath(); @@ -43,12 +48,7 @@ class Appwrite extends Pwned $this->client = $this->client($client); } - public function getName(): string - { - return 'appwrite'; - } - - public function isPwned(string $password): bool + protected function isPwned(string $password): bool { $jwt = new JWT($this->secret, 'HS256', self::TOKEN_EXPIRY, self::TOKEN_LEEWAY); diff --git a/src/Appwrite/Auth/Pwned/HIBP.php b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php similarity index 84% rename from src/Appwrite/Auth/Pwned/HIBP.php rename to src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php index bbbf7ce8a3..086c5a5f6f 100644 --- a/src/Appwrite/Auth/Pwned/HIBP.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php @@ -1,13 +1,13 @@ $policy + */ + public function __construct(array $policy = [], ?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT) { + parent::__construct($policy); + $this->cache = $cache; $this->client = $this->client($client); $this->endpoint = \rtrim($endpoint, '/'); } - public function getName(): string - { - return 'hibp'; - } - - public function isPwned(string $password): bool + protected function isPwned(string $password): bool { $hash = \strtoupper(\sha1($password)); $prefix = \substr($hash, 0, self::PREFIX_LENGTH); diff --git a/src/Appwrite/Auth/Pwned/Mock.php b/src/Appwrite/Auth/Validator/PasswordPwned/Mock.php similarity index 68% rename from src/Appwrite/Auth/Pwned/Mock.php rename to src/Appwrite/Auth/Validator/PasswordPwned/Mock.php index d272ae9e0c..3be74fb19d 100644 --- a/src/Appwrite/Auth/Pwned/Mock.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Mock.php @@ -1,8 +1,8 @@ check($password); + $passwordPwned = empty($password) || !$pwnedPasswords->isEnabled() + ? null + : !$pwnedPasswords->isValid($password); if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php index aba1363d92..b39fdc6a82 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -86,7 +86,9 @@ class Update extends Action } } - $passwordPwned = \strlen($password) === 0 ? null : $pwnedPasswords->check($password); + $passwordPwned = \strlen($password) === 0 || !$pwnedPasswords->isEnabled() + ? null + : !$pwnedPasswords->isValid($password); if ($passwordPwned) { throw new Exception(Exception::USER_PASSWORD_PWNED); } diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index 7564df4e96..05d001f109 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -20,7 +20,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope use ProjectCustom; use SideServer; - // Reported as breached by the mock adapter, see Appwrite\Auth\Pwned\Mock + // Reported as breached by the mock adapter, see Appwrite\Auth\Validator\PasswordPwned\Mock private const PWNED_PASSWORD = 'pwned-fixture-common'; public function testDefaultsOnNewProject(): void diff --git a/tests/unit/Auth/Pwned/MockTest.php b/tests/unit/Auth/Pwned/MockTest.php deleted file mode 100644 index 932c7422b9..0000000000 --- a/tests/unit/Auth/Pwned/MockTest.php +++ /dev/null @@ -1,39 +0,0 @@ -assertTrue($adapter->isPwned($password), $password); - } - } - - public function testAnythingElseIsReportedAsSafe(): void - { - $adapter = new Mock(); - - $this->assertFalse($adapter->isPwned('some-other-password')); - $this->assertFalse($adapter->isPwned('')); - } - - public function testMatchingIsExact(): void - { - $adapter = new Mock(); - $fixture = Mock::BREACHED[0]; - - // A fixture that merely contains or resembles a breached one is not breached - $this->assertFalse($adapter->isPwned(\strtoupper($fixture))); - $this->assertFalse($adapter->isPwned($fixture . '!')); - $this->assertFalse($adapter->isPwned(\substr($fixture, 1))); - } -} diff --git a/tests/unit/Auth/Pwned/AppwriteTest.php b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php similarity index 77% rename from tests/unit/Auth/Pwned/AppwriteTest.php rename to tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php index 924c30dfcc..43ad793fd2 100644 --- a/tests/unit/Auth/Pwned/AppwriteTest.php +++ b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php @@ -2,10 +2,10 @@ declare(strict_types=1); -namespace Tests\Unit\Auth\Pwned; +namespace Tests\Unit\Auth\Validator\PasswordPwned; use Ahc\Jwt\JWT; -use Appwrite\Auth\Pwned\Appwrite; +use Appwrite\Auth\Validator\PasswordPwned\Appwrite; use Appwrite\Extend\Exception; use PHPUnit\Framework\TestCase; use Utopia\DSN\DSN; @@ -20,29 +20,36 @@ final class AppwriteTest extends TestCase private const SECRET = 'shared-with-the-service'; private const DSN = 'appwrite://' . self::SECRET . '@pwned.test/v1/detection'; - public function testLeakedPasswordIsReported(): void + public function testLeakedPasswordIsRejected(): void { $fetch = new DetectionFetch(body: '{"leaked":true}'); - $this->assertTrue($this->adapter($fetch)->isPwned(self::PASSWORD)); + $this->assertFalse($this->validator($fetch)->isValid(self::PASSWORD)); } - public function testCleanPasswordIsNotReported(): void + public function testCleanPasswordIsAccepted(): void { $fetch = new DetectionFetch(body: '{"leaked":false}'); - $this->assertFalse($this->adapter($fetch)->isPwned(self::PASSWORD)); + $this->assertTrue($this->validator($fetch)->isValid(self::PASSWORD)); + } + + public function testDisabledPolicyNeverAsksTheService(): void + { + $fetch = new DetectionFetch(body: '{"leaked":true}'); + + $this->assertTrue((new Appwrite(['enabled' => false], new DSN(self::DSN), new Client($fetch)))->isValid(self::PASSWORD)); + $this->assertCount(0, $fetch->requests); } public function testThePasswordTravelsInAJwtTheServiceCanOpen(): void { $fetch = new DetectionFetch(body: '{"leaked":false}'); - $this->adapter($fetch)->isPwned(self::PASSWORD); + $this->validator($fetch)->isValid(self::PASSWORD); $this->assertCount(1, $fetch->requests); $this->assertSame('POST', $fetch->requests[0]['method']); - $this->assertSame('http://pwned.test/v1/detection', $fetch->requests[0]['url']); $sent = \json_decode($fetch->requests[0]['body'], true); $this->assertIsArray($sent); @@ -57,7 +64,7 @@ final class AppwriteTest extends TestCase { $fetch = new DetectionFetch(body: '{"leaked":false}'); - $this->adapter($fetch)->isPwned(self::PASSWORD); + $this->validator($fetch)->isValid(self::PASSWORD); $sent = \json_decode($fetch->requests[0]['body'], true); @@ -66,54 +73,6 @@ final class AppwriteTest extends TestCase (new JWT('a-different-secret', 'HS256', 900, 10))->decode($sent['password']); } - public function testUnreachableServiceIsReported(): void - { - $fetch = new DetectionFetch(failure: new \RuntimeException('connection refused')); - - try { - $this->adapter($fetch)->isPwned(self::PASSWORD); - $this->fail('Expected the unreachable service to surface'); - } catch (Exception $e) { - $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); - } - } - - public function testRejectedTokenIsReported(): void - { - // The service answers 400 when it cannot decode the token - $fetch = new DetectionFetch(statusCode: 400, body: '{"message":"Failed to verify JWT."}'); - - $this->expectException(Exception::class); - - $this->adapter($fetch)->isPwned(self::PASSWORD); - } - - public function testDetectorFailureIsReported(): void - { - $fetch = new DetectionFetch(statusCode: 500, body: ''); - - $this->expectException(Exception::class); - - $this->adapter($fetch)->isPwned(self::PASSWORD); - } - - /** - * A body the adapter cannot read must never be taken as a clean password. - */ - public function testUnreadableAnswerIsReported(): void - { - foreach (['', 'not json', '{}', '{"leaked":"yes"}', '{"pwned":true}'] as $body) { - $fetch = new DetectionFetch(body: $body); - - try { - $this->adapter($fetch)->isPwned(self::PASSWORD); - $this->fail('Expected an unreadable answer to surface: ' . $body); - } catch (Exception $e) { - $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); - } - } - } - public function testTheDsnDescribesWhereAndHowToConnect(): void { $cases = [ @@ -128,15 +87,63 @@ final class AppwriteTest extends TestCase foreach ($cases as $dsn => $expected) { $fetch = new DetectionFetch(body: '{"leaked":false}'); - (new Appwrite(new DSN($dsn), new Client($fetch)))->isPwned(self::PASSWORD); + (new Appwrite([], new DSN($dsn), new Client($fetch)))->isValid(self::PASSWORD); $this->assertSame($expected, $fetch->requests[0]['url'], $dsn); } } - private function adapter(DetectionFetch $fetch): Appwrite + public function testUnreachableServiceIsReported(): void { - return new Appwrite(new DSN(self::DSN), new Client($fetch)); + $fetch = new DetectionFetch(failure: new \RuntimeException('connection refused')); + + try { + $this->validator($fetch)->isValid(self::PASSWORD); + $this->fail('Expected the unreachable service to surface'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); + } + } + + public function testRejectedTokenIsReported(): void + { + // The service answers 400 when it cannot decode the token + $fetch = new DetectionFetch(statusCode: 400, body: '{"message":"Failed to verify JWT."}'); + + $this->expectException(Exception::class); + + $this->validator($fetch)->isValid(self::PASSWORD); + } + + public function testDetectorFailureIsReported(): void + { + $fetch = new DetectionFetch(statusCode: 500, body: ''); + + $this->expectException(Exception::class); + + $this->validator($fetch)->isValid(self::PASSWORD); + } + + /** + * An answer the validator cannot read must never pass as a clean password. + */ + public function testUnreadableAnswerIsReported(): void + { + foreach (['', 'not json', '{}', '{"leaked":"yes"}', '{"pwned":true}'] as $body) { + $fetch = new DetectionFetch(body: $body); + + try { + $this->validator($fetch)->isValid(self::PASSWORD); + $this->fail('Expected an unreadable answer to surface: ' . $body); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); + } + } + } + + private function validator(DetectionFetch $fetch): Appwrite + { + return new Appwrite([], new DSN(self::DSN), new Client($fetch)); } } diff --git a/tests/unit/Auth/Pwned/HIBPTest.php b/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php similarity index 68% rename from tests/unit/Auth/Pwned/HIBPTest.php rename to tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php index 9c3a55ce3b..4b5e70ec52 100644 --- a/tests/unit/Auth/Pwned/HIBPTest.php +++ b/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php @@ -2,9 +2,9 @@ declare(strict_types=1); -namespace Tests\Unit\Auth\Pwned; +namespace Tests\Unit\Auth\Validator\PasswordPwned; -use Appwrite\Auth\Pwned\HIBP; +use Appwrite\Auth\Validator\PasswordPwned\HIBP; use Appwrite\Extend\Exception; use PHPUnit\Framework\TestCase; use Utopia\Cache\Adapter\Memory; @@ -19,46 +19,46 @@ final class HIBPTest extends TestCase private const LEAKED = 'Password123!'; private const ENDPOINT = 'https://breaches.test/range'; - public function testLeakedPasswordIsReported(): void + public function testLeakedPasswordIsRejected(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); - $this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED)); + $this->assertFalse($this->validator($fetch)->isValid(self::LEAKED)); } - public function testCleanPasswordIsNotReported(): void + public function testCleanPasswordIsAccepted(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); - $this->assertFalse($this->adapter($fetch)->isPwned('never-leaked-' . \uniqid())); + $this->assertTrue($this->validator($fetch)->isValid('never-leaked-' . \uniqid())); } - public function testAnySingleBreachCounts(): void + public function testAnySingleBreachIsEnough(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 1])); - $this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED)); + $this->assertFalse($this->validator($fetch)->isValid(self::LEAKED)); } public function testPaddedEntryWithZeroCountIsNotABreach(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 0])); - $this->assertFalse($this->adapter($fetch)->isPwned(self::LEAKED)); + $this->assertTrue($this->validator($fetch)->isValid(self::LEAKED)); } public function testSuffixComparisonIgnoresCase(): void { $fetch = new RangeFetch(body: \strtolower($this->range([self::LEAKED => 3]))); - $this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED)); + $this->assertFalse($this->validator($fetch)->isValid(self::LEAKED)); } public function testOnlyTheHashPrefixLeavesTheServer(): void { $fetch = new RangeFetch(body: ''); - $this->adapter($fetch)->isPwned(self::LEAKED); + $this->validator($fetch)->isValid(self::LEAKED); $this->assertCount(1, $fetch->urls); @@ -74,13 +74,21 @@ final class HIBPTest extends TestCase $this->assertStringEndsWith(\substr($hash, 0, 5), $url); } + public function testDisabledPolicyNeverAsksTheService(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); + + $this->assertTrue((new HIBP(['enabled' => false], null, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); + $this->assertCount(0, $fetch->urls); + } + public function testRangeIsCachedPerPrefix(): void { $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); $cache = new Cache(new Memory()); - $this->assertTrue((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isPwned(self::LEAKED)); - $this->assertTrue((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isPwned(self::LEAKED)); + $this->assertFalse((new HIBP([], $cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); + $this->assertFalse((new HIBP([], $cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED)); $this->assertCount(1, $fetch->urls); } @@ -90,8 +98,8 @@ final class HIBPTest extends TestCase $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); $cache = new Cache(new Memory()); - (new HIBP($cache, new Client($fetch), 'https://one.test/range'))->isPwned(self::LEAKED); - (new HIBP($cache, new Client($fetch), 'https://two.test/range'))->isPwned(self::LEAKED); + (new HIBP([], $cache, new Client($fetch), 'https://one.test/range'))->isValid(self::LEAKED); + (new HIBP([], $cache, new Client($fetch), 'https://two.test/range'))->isValid(self::LEAKED); $this->assertCount(2, $fetch->urls); } @@ -100,8 +108,8 @@ final class HIBPTest extends TestCase { $fetch = new RangeFetch(body: ''); - (new HIBP(null, new Client($fetch), 'https://server.test/range'))->isPwned(self::LEAKED); - (new HIBP(null, new Client($fetch), 'https://other.test/range/'))->isPwned(self::LEAKED); + (new HIBP([], null, new Client($fetch), 'https://server.test/range'))->isValid(self::LEAKED); + (new HIBP([], null, new Client($fetch), 'https://other.test/range/'))->isValid(self::LEAKED); $this->assertStringStartsWith('https://server.test/range/', $fetch->urls[0]); $this->assertStringStartsWith('https://other.test/range/', $fetch->urls[1]); @@ -112,7 +120,7 @@ final class HIBPTest extends TestCase $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); try { - $this->adapter($fetch)->isPwned(self::LEAKED); + $this->validator($fetch)->isValid(self::LEAKED); $this->fail('Expected the unreachable service to surface'); } catch (Exception $e) { $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); @@ -125,17 +133,17 @@ final class HIBPTest extends TestCase $this->expectException(Exception::class); - $this->adapter($fetch)->isPwned(self::LEAKED); + $this->validator($fetch)->isValid(self::LEAKED); } public function testFailedLookupIsNotCached(): void { $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); - $adapter = new HIBP(new Cache(new Memory()), new Client($fetch), self::ENDPOINT); + $validator = new HIBP([], new Cache(new Memory()), new Client($fetch), self::ENDPOINT); foreach ([1, 2] as $attempt) { try { - $adapter->isPwned(self::LEAKED); + $validator->isValid(self::LEAKED); } catch (Exception) { // The lookup failed, which is the point; it must be retried rather than remembered } @@ -144,9 +152,9 @@ final class HIBPTest extends TestCase $this->assertCount(2, $fetch->urls); } - private function adapter(RangeFetch $fetch): HIBP + private function validator(RangeFetch $fetch): HIBP { - return new HIBP(null, new Client($fetch), self::ENDPOINT); + return new HIBP([], null, new Client($fetch), self::ENDPOINT); } /** @@ -169,7 +177,7 @@ final class HIBPTest extends TestCase final class RangeFetch implements Adapter { - /** @var array URLs the adapter asked the breach service for */ + /** @var array URLs the validator asked the breach service for */ public array $urls = []; public function __construct( diff --git a/tests/unit/Auth/Validator/PasswordPwned/MockTest.php b/tests/unit/Auth/Validator/PasswordPwned/MockTest.php new file mode 100644 index 0000000000..efa712ce5e --- /dev/null +++ b/tests/unit/Auth/Validator/PasswordPwned/MockTest.php @@ -0,0 +1,38 @@ +assertFalse($validator->isValid($password), $password); + } + } + + public function testAnythingElseIsAccepted(): void + { + $validator = new Mock(); + + $this->assertTrue($validator->isValid('some-other-password')); + } + + public function testMatchingIsExact(): void + { + $validator = new Mock(); + $fixture = Mock::BREACHED[0]; + + // A password that merely resembles a fixture is not breached + $this->assertTrue($validator->isValid(\strtoupper($fixture))); + $this->assertTrue($validator->isValid($fixture . '!')); + $this->assertTrue($validator->isValid(\substr($fixture, 1))); + } +} diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index 79360c602a..5dfbdcc133 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -4,18 +4,20 @@ declare(strict_types=1); namespace Tests\Unit\Auth\Validator; -use Appwrite\Auth\Pwned; -use Appwrite\Auth\Validator\PasswordPwned; -use Appwrite\Extend\Exception; +use Appwrite\Auth\Validator\PasswordPwned\Mock; use PHPUnit\Framework\TestCase; +/** + * The policy decisions every breach validator shares, exercised through the one + * subclass that needs no service behind it. + */ final class PasswordPwnedTest extends TestCase { - private const PASSWORD = 'Password123!'; + private const BREACHED = Mock::BREACHED[0]; public function testEnabledByDefaultWithoutSessionChecks(): void { - $validator = new PasswordPwned(new FakePwned()); + $validator = new Mock(); $this->assertTrue($validator->isEnabled()); $this->assertFalse($validator->checksSessions()); @@ -24,7 +26,7 @@ final class PasswordPwnedTest extends TestCase public function testPolicyFlags(): void { - $validator = new PasswordPwned(new FakePwned(), ['enabled' => true, 'sessions' => true, 'users' => true]); + $validator = new Mock(['enabled' => true, 'sessions' => true, 'users' => true]); $this->assertTrue($validator->isEnabled()); $this->assertTrue($validator->checksSessions()); @@ -33,86 +35,38 @@ final class PasswordPwnedTest extends TestCase public function testSessionChecksNeedAnEnabledPolicy(): void { - $validator = new PasswordPwned(new FakePwned(), ['enabled' => false, 'sessions' => true, 'users' => true]); + $validator = new Mock(['enabled' => false, 'sessions' => true, 'users' => true]); $this->assertFalse($validator->checksSessions()); } - public function testDisabledPolicyNeverAsksTheAdapter(): void - { - $adapter = new FakePwned(pwned: true); - $validator = new PasswordPwned($adapter, ['enabled' => false]); - - $this->assertNull($validator->check(self::PASSWORD)); - $this->assertTrue($validator->isValid(self::PASSWORD)); - $this->assertSame(0, $adapter->calls); - } - - public function testCheckReportsWhatTheAdapterFound(): void - { - $this->assertTrue((new PasswordPwned(new FakePwned(pwned: true)))->check(self::PASSWORD)); - $this->assertFalse((new PasswordPwned(new FakePwned(pwned: false)))->check(self::PASSWORD)); - } - public function testBreachedPasswordIsInvalid(): void { - $this->assertFalse((new PasswordPwned(new FakePwned(pwned: true)))->isValid(self::PASSWORD)); - $this->assertTrue((new PasswordPwned(new FakePwned(pwned: false)))->isValid(self::PASSWORD)); + $validator = new Mock(); + + $this->assertFalse($validator->isValid(self::BREACHED)); + $this->assertTrue($validator->isValid('a-password-nobody-leaked')); } - public function testAdapterFailureSurfaces(): void + public function testDisabledPolicyAcceptsEverything(): void { - $adapter = new FakePwned(failure: new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE)); - $validator = new PasswordPwned($adapter); + $validator = new Mock(['enabled' => false]); - $this->expectException(Exception::class); - - $validator->isValid(self::PASSWORD); + $this->assertTrue($validator->isValid(self::BREACHED)); } public function testBasePasswordRulesStillApply(): void { - $adapter = new FakePwned(pwned: false); - $validator = new PasswordPwned($adapter); + $validator = new Mock(); $this->assertFalse($validator->isValid('short')); $this->assertFalse($validator->isValid(\str_repeat('p', 257))); $this->assertFalse($validator->isValid('')); - $this->assertSame(0, $adapter->calls); } - public function testAllowEmptySkipsTheLookup(): void + public function testAllowEmptyAcceptsAnEmptyPassword(): void { - $adapter = new FakePwned(pwned: true); - $validator = new PasswordPwned($adapter, [], allowEmpty: true); - - $this->assertTrue($validator->isValid('')); - $this->assertSame(0, $adapter->calls); - } -} - -final class FakePwned extends Pwned -{ - public int $calls = 0; - - public function __construct(private bool $pwned = false, private ?\Throwable $failure = null) - { - parent::__construct('https://breaches.test'); - } - - public function getName(): string - { - return 'fake'; - } - - public function isPwned(string $password): bool - { - $this->calls++; - - if ($this->failure !== null) { - throw $this->failure; - } - - return $this->pwned; + $this->assertTrue((new Mock([], allowEmpty: true))->isValid('')); + $this->assertFalse((new Mock([], allowEmpty: true))->isValid(self::BREACHED)); } }