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) <noreply@anthropic.com>
This commit is contained in:
Matej BačoandClaude Opus 5 committed 2026-09-15 15:48:47 +02:00
1 parent 21d36f8425
commit eb94af3654
15 files changed
+257 -319

No files matched your search

+10 -7
View File
@@ -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);
}
+10 -11
View File
@@ -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) {
-53
View File
@@ -1,53 +0,0 @@
<?php
namespace Appwrite\Auth;
use Appwrite\Extend\Exception;
use Utopia\Fetch\Client;
/**
* Looks a password up in a database of known data breaches.
*
* The adapter and its details both come from `_APP_PWNED_PASSWORDS_DSN`, whose
* scheme picks the adapter. Adapters differ in what leaves the server and where
* it goes, so read the concrete class before choosing one.
*/
abstract class Pwned
{
private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds
private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds
/**
* Adapter name, matching the DSN scheme that selects it.
*/
abstract public function getName(): string;
/**
* Whether the password appears in a known data breach.
*
* @throws Exception when the breach service cannot be reached or answers with nonsense
*/
abstract public 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);
}
}
+46 -24
View File
@@ -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<string, mixed> $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);
}
}
@@ -1,14 +1,14 @@
<?php
namespace Appwrite\Auth\Pwned;
namespace Appwrite\Auth\Validator\PasswordPwned;
use Ahc\Jwt\JWT;
use Appwrite\Auth\Pwned;
use Appwrite\Auth\Validator\PasswordPwned;
use Utopia\DSN\DSN;
use Utopia\Fetch\Client;
/**
* Talks to an Appwrite Pwned service, https://github.com/appwrite-labs/pwned.
* Asks an Appwrite Pwned service, https://github.com/appwrite-labs/pwned.
*
* The service answers for a whole password rather than a hash prefix, so unlike
* `HIBP` this sends the password itself. It travels inside a short-lived JWT
@@ -20,7 +20,7 @@ use Utopia\Fetch\Client;
* the service's `APPWRITE_PWNED_JWT_SECRET`, the path defaults to
* `v1/detection`, and the connection is plain HTTP unless `tls=true`.
*/
class Appwrite extends Pwned
class Appwrite extends PasswordPwned
{
private const PATH = 'v1/detection';
@@ -32,8 +32,13 @@ class Appwrite extends Pwned
protected string $secret;
protected Client $client;
public function __construct(DSN $dsn, ?Client $client = null)
/**
* @param array<string, mixed> $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);
@@ -1,13 +1,13 @@
<?php
namespace Appwrite\Auth\Pwned;
namespace Appwrite\Auth\Validator\PasswordPwned;
use Appwrite\Auth\Pwned;
use Appwrite\Auth\Validator\PasswordPwned;
use Utopia\Cache\Cache;
use Utopia\Fetch\Client;
/**
* Talks to the public Have I Been Pwned range API.
* Asks the public Have I Been Pwned range API.
*
* Uses k-anonymity: only the first five characters of the password's SHA-1 hash
* leave the server, and the candidate suffixes that come back are compared
@@ -16,7 +16,7 @@ use Utopia\Fetch\Client;
*
* DSN: `hibp://localhost`, no details are read.
*/
class HIBP extends Pwned
class HIBP extends PasswordPwned
{
public const ENDPOINT = 'https://api.pwnedpasswords.com/range';
public const CACHE_TTL = 3600; // seconds
@@ -27,19 +27,19 @@ class HIBP extends Pwned
protected Client $client;
protected string $endpoint;
public function __construct(?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT)
/**
* @param array<string, mixed> $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);
@@ -1,8 +1,8 @@
<?php
namespace Appwrite\Auth\Pwned;
namespace Appwrite\Auth\Validator\PasswordPwned;
use Appwrite\Auth\Pwned;
use Appwrite\Auth\Validator\PasswordPwned;
/**
* Reports a fixed set of passwords as breached, without leaving the process.
@@ -13,10 +13,10 @@ use Appwrite\Auth\Pwned;
*
* DSN: `mock://localhost`, no details are read.
*/
class Mock extends Pwned
class Mock extends PasswordPwned
{
/**
* The passwords this adapter reports as breached.
* The passwords this validator reports as breached.
*/
public const BREACHED = [
'pwned-fixture-common',
@@ -24,12 +24,7 @@ class Mock extends Pwned
'pwned-fixture-rare',
];
public function getName(): string
{
return 'mock';
}
public function isPwned(string $password): bool
protected function isPwned(string $password): bool
{
return \in_array($password, self::BREACHED, true);
}
@@ -74,7 +74,9 @@ class Create extends Base
public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords): void
{
$passwordPwned = empty($password) ? null : $pwnedPasswords->check($password);
$passwordPwned = empty($password) || !$pwnedPasswords->isEnabled()
? null
: !$pwnedPasswords->isValid($password);
if ($passwordPwned) {
throw new Exception(Exception::USER_PASSWORD_PWNED);
}
@@ -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);
}
@@ -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
-39
View File
@@ -1,39 +0,0 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Auth\Pwned;
use Appwrite\Auth\Pwned\Mock;
use PHPUnit\Framework\TestCase;
final class MockTest extends TestCase
{
public function testFixturesAreReportedAsBreached(): void
{
$adapter = new Mock();
foreach (Mock::BREACHED as $password) {
$this->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)));
}
}
@@ -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));
}
}
@@ -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<int, string> URLs the adapter asked the breach service for */
/** @var array<int, string> URLs the validator asked the breach service for */
public array $urls = [];
public function __construct(
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Auth\Validator\PasswordPwned;
use Appwrite\Auth\Validator\PasswordPwned\Mock;
use PHPUnit\Framework\TestCase;
final class MockTest extends TestCase
{
public function testFixturesAreReportedAsBreached(): void
{
$validator = new Mock();
foreach (Mock::BREACHED as $password) {
$this->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)));
}
}
+20 -66
View File
@@ -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));
}
}