feat(auth): make the pwned lookup adapter driven

The breach lookup moves out of the validator and behind an adapter, so a
server can choose who answers the question.

- `hibp` keeps the current behaviour: the public Have I Been Pwned range
  API with k-anonymity, sending only the first five characters of the
  SHA-1 hash and caching ranges per prefix.
- `appwrite` talks to an Appwrite Pwned service
  (https://github.com/appwrite-labs/pwned), which answers for a whole
  password. The password travels inside a short-lived JWT signed with
  `_APP_OPENSSL_KEY_V1`, so it is only appropriate for a service on your
  own network, and in exchange the service caches and can front a
  detector of its own choosing.

`_APP_PWNED_PASSWORDS_ADAPTER` picks the adapter and defaults to `hibp`.
`_APP_PWNED_PASSWORDS_ENDPOINT` now defaults to empty and falls back to
whichever address the chosen adapter ships with. An unknown adapter name
fails loudly at request time rather than quietly falling back.

`PasswordPwned` keeps the policy decisions and delegates the lookup, so
its unit test no longer needs an HTTP double. Each adapter has its own
test next to it.

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:33:18 +02:00
1 parent 4f2e203327
commit 84f3c39d73
11 files changed
+640 -290

No files matched your search

+1
View File
@@ -175,6 +175,7 @@ _APP_MIGRATIONS_FIREBASE_CLIENT_SECRET=
_APP_PROJECT_REGIONS=default
_APP_GEO_SECRET=your-secret-key
_APP_GEO_ENDPOINT=http://appwrite-geo/v1
_APP_PWNED_PASSWORDS_ADAPTER=hibp
_APP_PWNED_PASSWORDS_ENDPOINT=http://localhost/v1/mock/tests/general/pwned-passwords
_APP_VCS_GITHUB_APP_ID=
_APP_VCS_GITHUB_APP_NAME=
+12 -3
View File
@@ -485,10 +485,19 @@ return [
'filter' => 'token'
],
[
'name' => '_APP_PWNED_PASSWORDS_ENDPOINT',
'description' => 'Endpoint of the Have I Been Pwned range API used by the password pwned project policy. Only the first five characters of a password SHA-1 hash are sent to this endpoint. Defaults to the public Have I Been Pwned service.',
'name' => '_APP_PWNED_PASSWORDS_ADAPTER',
'description' => 'Service the password pwned project policy asks whether a password has been breached. `hibp` calls the Have I Been Pwned range API and only ever sends the first five characters of the password SHA-1 hash. `appwrite` calls an [Appwrite Pwned](https://github.com/appwrite-labs/pwned) service you run yourself, which caches answers and can front a detector of your choice, but receives the whole password inside a JWT signed with `_APP_OPENSSL_KEY_V1`, so only point it at a service on your own network.',
'introduction' => 'TBD',
'default' => 'https://api.pwnedpasswords.com/range',
'default' => 'hibp',
'required' => false,
'question' => '',
'filter' => ''
],
[
'name' => '_APP_PWNED_PASSWORDS_ENDPOINT',
'description' => 'Address the adapter chosen in `_APP_PWNED_PASSWORDS_ADAPTER` calls. Leave empty to use that adapter\'s default, which is `https://api.pwnedpasswords.com/range` for `hibp` and `http://appwrite-pwned/v1/detection` for `appwrite`.',
'introduction' => 'TBD',
'default' => '',
'required' => false,
'question' => '',
'filter' => ''
+12 -1
View File
@@ -3,6 +3,8 @@
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\Validator\PasswordPwned;
use Appwrite\Database\Factory as DatabaseFactory;
use Appwrite\Databases\TransactionState;
@@ -675,7 +677,16 @@ return function (Container $context): void {
}, ['user', 'store', 'proofForToken']);
$context->set('pwnedPasswords', function (Document $project, Cache $cache) {
return new PasswordPwned($project->getAttribute('auths', [])['passwordPwned'] ?? [], $cache, System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'));
$endpoint = System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT', '');
$name = \strtolower(System::getEnv('_APP_PWNED_PASSWORDS_ADAPTER', 'hibp'));
$adapter = match ($name) {
'hibp' => new PwnedHIBP($endpoint, $cache),
'appwrite' => new PwnedAppwrite($endpoint, System::getEnv('_APP_OPENSSL_KEY_V1', '')),
default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown _APP_PWNED_PASSWORDS_ADAPTER: ' . $name),
};
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) {
+1
View File
@@ -254,6 +254,7 @@ services:
- _APP_MIGRATION_HOST
- _APP_GEO_SECRET
- _APP_GEO_ENDPOINT
- _APP_PWNED_PASSWORDS_ADAPTER
- _APP_PWNED_PASSWORDS_ENDPOINT
- _APP_LIMIT_DATABASE_BATCH
- _APP_DOCUMENTSDB
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace Appwrite\Auth;
use Appwrite\Extend\Exception;
use Utopia\Fetch\Client;
/**
* Looks a password up in a database of known data breaches.
*
* Adapters differ in what leaves the server and where it goes, so read the
* concrete class before choosing one. Pick the adapter with
* `_APP_PWNED_PASSWORDS_ADAPTER` and the address with
* `_APP_PWNED_PASSWORDS_ENDPOINT`.
*/
abstract class Pwned
{
protected const CONNECT_TIMEOUT = 3 * 1000; // milliseconds
protected const REQUEST_TIMEOUT = 5 * 1000; // milliseconds
protected string $endpoint;
protected Client $client;
public function __construct(string $endpoint, ?Client $client = null)
{
$this->endpoint = \rtrim($endpoint, '/');
$this->client = $client ?? (new Client())
->setConnectTimeout(self::CONNECT_TIMEOUT)
->setTimeout(self::REQUEST_TIMEOUT)
->setAllowRedirects(false)
->setUserAgent('Appwrite');
}
/**
* Adapter name, as accepted by `_APP_PWNED_PASSWORDS_ADAPTER`.
*/
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 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);
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace Appwrite\Auth\Pwned;
use Ahc\Jwt\JWT;
use Appwrite\Auth\Pwned;
use Utopia\Fetch\Client;
/**
* Talks to 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
* signed with a secret shared with the service, which is only safe on a network
* you control. In exchange the service caches answers and can front Have I Been
* Pwned or another detector without the server knowing which.
*/
class Appwrite extends Pwned
{
public const ENDPOINT = 'http://appwrite-pwned/v1/detection';
// The service decodes with the same window
private const TOKEN_EXPIRY = 900; // seconds
private const TOKEN_LEEWAY = 10; // seconds
protected string $secret;
public function __construct(string $endpoint = '', string $secret = '', ?Client $client = null)
{
parent::__construct($endpoint ?: self::ENDPOINT, $client);
$this->secret = $secret;
}
public function getName(): string
{
return 'appwrite';
}
public function isPwned(string $password): bool
{
$jwt = new JWT($this->secret, 'HS256', self::TOKEN_EXPIRY, self::TOKEN_LEEWAY);
try {
$response = $this->client
->addHeader('content-type', Client::CONTENT_TYPE_APPLICATION_JSON)
->fetch($this->endpoint, Client::METHOD_POST, [
'password' => $jwt->encode(['password' => $password]),
]);
} catch (\Throwable) {
$this->unavailable();
}
if ($response->getStatusCode() !== 200) {
$this->unavailable();
}
$body = \json_decode($response->text(), true);
if (!\is_array($body) || !\is_bool($body['leaked'] ?? null)) {
$this->unavailable();
}
return $body['leaked'];
}
}
+95
View File
@@ -0,0 +1,95 @@
<?php
namespace Appwrite\Auth\Pwned;
use Appwrite\Auth\Pwned;
use Utopia\Cache\Cache;
use Utopia\Fetch\Client;
/**
* Talks to 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
* locally. Range responses are cached per prefix, so a busy project does not
* ask the service the same question twice.
*/
class HIBP extends Pwned
{
public const ENDPOINT = 'https://api.pwnedpasswords.com/range';
public const CACHE_TTL = 3600; // seconds
private const PREFIX_LENGTH = 5;
protected ?Cache $cache;
public function __construct(string $endpoint = '', ?Cache $cache = null, ?Client $client = null)
{
parent::__construct($endpoint ?: self::ENDPOINT, $client);
$this->cache = $cache;
}
public function getName(): string
{
return 'hibp';
}
public function isPwned(string $password): bool
{
$hash = \strtoupper(\sha1($password));
$prefix = \substr($hash, 0, self::PREFIX_LENGTH);
$suffix = \substr($hash, self::PREFIX_LENGTH);
// Entries with no breaches are dropped, so any hit means the password is breached
return isset($this->range($prefix)[$suffix]);
}
/**
* Breach counts for every known hash sharing the prefix, from cache or the service.
*
* @return array<string, int> hash suffix => breach count
*/
private function range(string $prefix): array
{
$key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix;
if ($this->cache !== null) {
$cached = $this->cache->load($key, self::CACHE_TTL);
if (\is_array($cached)) {
return $cached;
}
}
try {
$response = $this->client
->addHeader('Add-Padding', 'true')
->fetch($this->endpoint . '/' . $prefix);
} catch (\Throwable) {
$this->unavailable();
}
if ($response->getStatusCode() !== 200) {
$this->unavailable();
}
// Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches
$breaches = [];
foreach (\explode("\n", $response->text()) as $line) {
$line = \trim($line);
$separator = \strpos($line, ':');
if ($line === '' || $separator === false) {
continue;
}
$count = (int) \substr($line, $separator + 1);
if ($count > 0) {
$breaches[\strtoupper(\substr($line, 0, $separator))] = $count;
}
}
$this->cache?->save($key, $breaches);
return $breaches;
}
}
+9 -88
View File
@@ -2,53 +2,33 @@
namespace Appwrite\Auth\Validator;
use Appwrite\Auth\Pwned;
use Appwrite\Extend\Exception;
use Utopia\Cache\Cache;
use Utopia\Fetch\Client;
/**
* Validates that a password has not been exposed in a known data breach.
* Validates a password against the project's `password-pwned` policy.
*
* Configured from the project's `password-pwned` policy. Uses the Have I Been
* Pwned range API with k-anonymity: only the first five characters of the
* SHA-1 hash leave the server, and the returned suffixes are compared locally.
* Range responses are cached per prefix so repeated checks do not hit the
* service again.
* The lookup itself belongs to the configured adapter, see `Appwrite\Auth\Pwned`.
* This class only decides whether the policy asks for one.
*/
class PasswordPwned extends Password
{
public const ENDPOINT = 'https://api.pwnedpasswords.com/range';
public const CACHE_TTL = 3600; // seconds
private const PREFIX_LENGTH = 5;
private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds
private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds
protected bool $enabled;
protected string $endpoint;
protected bool $sessions;
protected bool $users;
protected ?Cache $cache;
protected Client $client;
protected Pwned $adapter;
/**
* @param array<string, mixed> $policy the project's `passwordPwned` auth settings
* @param ?string $endpoint the breach API this server is configured to use
*/
public function __construct(array $policy = [], ?Cache $cache = null, ?string $endpoint = null, ?Client $client = null, bool $allowEmpty = false)
public function __construct(Pwned $adapter, 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);
$this->endpoint = \rtrim($endpoint ?: self::ENDPOINT, '/');
$this->cache = $cache;
$this->client = $client ?? (new Client())
->setConnectTimeout(self::CONNECT_TIMEOUT)
->setTimeout(self::REQUEST_TIMEOUT)
->setAllowRedirects(false)
->setUserAgent('Appwrite');
}
/**
@@ -102,18 +82,7 @@ class PasswordPwned extends Password
return null;
}
$hash = \strtoupper(\sha1($password));
$prefix = \substr($hash, 0, self::PREFIX_LENGTH);
$suffix = \substr($hash, self::PREFIX_LENGTH);
$breaches = $this->range($prefix);
if ($breaches === null) {
throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE);
}
// Entries with no breaches are dropped, so any hit means the password is breached
return isset($breaches[$suffix]);
return $this->adapter->isPwned($password);
}
/**
@@ -122,7 +91,7 @@ class PasswordPwned extends Password
* @param mixed $value
*
* @return bool
* @throws Exception when the breach service is unreachable and the policy fails closed
* @throws Exception when the breach service cannot be reached
*/
public function isValid($value): bool
{
@@ -137,54 +106,6 @@ class PasswordPwned extends Password
return $this->check($value) !== true;
}
/**
* Breach counts for every known hash sharing the prefix, from cache or the service.
*
* @return ?array<string, int> hash suffix => breach count, null when the service could not be reached
*/
private function range(string $prefix): ?array
{
$key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix;
if ($this->cache !== null) {
$cached = $this->cache->load($key, self::CACHE_TTL);
if (\is_array($cached)) {
return $cached;
}
}
try {
$response = $this->client
->addHeader('Add-Padding', 'true')
->fetch($this->endpoint . '/' . $prefix);
} catch (\Throwable) {
return null;
}
if ($response->getStatusCode() !== 200) {
return null;
}
// Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches
$breaches = [];
foreach (\explode("\n", $response->text()) as $line) {
$line = \trim($line);
$separator = \strpos($line, ':');
if ($line === '' || $separator === false) {
continue;
}
$count = (int) \substr($line, $separator + 1);
if ($count > 0) {
$breaches[\strtoupper(\substr($line, 0, $separator))] = $count;
}
}
$this->cache?->save($key, $breaches);
return $breaches;
}
/**
* Is array
*
+150
View File
@@ -0,0 +1,150 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Auth\Pwned;
use Ahc\Jwt\JWT;
use Appwrite\Auth\Pwned\Appwrite;
use Appwrite\Extend\Exception;
use PHPUnit\Framework\TestCase;
use Utopia\Fetch\Adapter;
use Utopia\Fetch\Client;
use Utopia\Fetch\Options\Request as RequestOptions;
use Utopia\Fetch\Response;
final class AppwriteTest extends TestCase
{
private const PASSWORD = 'Password123!';
private const ENDPOINT = 'https://pwned.test/v1/detection';
private const SECRET = 'shared-with-the-service';
public function testLeakedPasswordIsReported(): void
{
$fetch = new DetectionFetch(body: '{"leaked":true}');
$this->assertTrue($this->adapter($fetch)->isPwned(self::PASSWORD));
}
public function testCleanPasswordIsNotReported(): void
{
$fetch = new DetectionFetch(body: '{"leaked":false}');
$this->assertFalse($this->adapter($fetch)->isPwned(self::PASSWORD));
}
public function testThePasswordTravelsInAJwtTheServiceCanOpen(): void
{
$fetch = new DetectionFetch(body: '{"leaked":false}');
$this->adapter($fetch)->isPwned(self::PASSWORD);
$this->assertCount(1, $fetch->requests);
$this->assertSame('POST', $fetch->requests[0]['method']);
$this->assertSame(self::ENDPOINT, $fetch->requests[0]['url']);
$sent = \json_decode($fetch->requests[0]['body'], true);
$this->assertIsArray($sent);
$this->assertArrayHasKey('password', $sent);
// The service decodes with the shared secret, so it must round-trip
$decoded = (new JWT(self::SECRET, 'HS256', 900, 10))->decode($sent['password']);
$this->assertSame(self::PASSWORD, $decoded['password']);
}
public function testATokenSignedWithAnotherSecretIsNotAccepted(): void
{
$fetch = new DetectionFetch(body: '{"leaked":false}');
$this->adapter($fetch)->isPwned(self::PASSWORD);
$sent = \json_decode($fetch->requests[0]['body'], true);
$this->expectException(\Throwable::class);
(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());
}
}
}
private function adapter(DetectionFetch $fetch): Appwrite
{
return new Appwrite(self::ENDPOINT, self::SECRET, new Client($fetch));
}
}
final class DetectionFetch implements Adapter
{
/** @var array<int, array{url: string, method: string, body: mixed}> */
public array $requests = [];
public function __construct(
private int $statusCode = 200,
private string $body = '',
private ?\Throwable $failure = null,
) {
}
public function send(
string $url,
string $method,
mixed $body,
array $headers,
RequestOptions $options,
?callable $chunkCallback = null
): Response {
$this->requests[] = ['url' => $url, 'method' => $method, 'body' => $body];
if ($this->failure !== null) {
throw $this->failure;
}
return new Response($this->statusCode, $this->body, []);
}
}
+198
View File
@@ -0,0 +1,198 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Auth\Pwned;
use Appwrite\Auth\Pwned\HIBP;
use Appwrite\Extend\Exception;
use PHPUnit\Framework\TestCase;
use Utopia\Cache\Adapter\Memory;
use Utopia\Cache\Cache;
use Utopia\Fetch\Adapter;
use Utopia\Fetch\Client;
use Utopia\Fetch\Options\Request as RequestOptions;
use Utopia\Fetch\Response;
final class HIBPTest extends TestCase
{
private const LEAKED = 'Password123!';
private const ENDPOINT = 'https://breaches.test/range';
public function testLeakedPasswordIsReported(): void
{
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 42]));
$this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED));
}
public function testCleanPasswordIsNotReported(): void
{
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 42]));
$this->assertFalse($this->adapter($fetch)->isPwned('never-leaked-' . \uniqid()));
}
public function testAnySingleBreachCounts(): void
{
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 1]));
$this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED));
}
public function testPaddedEntryWithZeroCountIsNotABreach(): void
{
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 0]));
$this->assertFalse($this->adapter($fetch)->isPwned(self::LEAKED));
}
public function testSuffixComparisonIgnoresCase(): void
{
$fetch = new RangeFetch(body: \strtolower($this->range([self::LEAKED => 3])));
$this->assertTrue($this->adapter($fetch)->isPwned(self::LEAKED));
}
public function testOnlyTheHashPrefixLeavesTheServer(): void
{
$fetch = new RangeFetch(body: '');
$this->adapter($fetch)->isPwned(self::LEAKED);
$this->assertCount(1, $fetch->urls);
$hash = \strtoupper(\sha1(self::LEAKED));
$url = $fetch->urls[0];
// Neither the password nor anything that identifies it may reach the service
$this->assertStringNotContainsStringIgnoringCase(self::LEAKED, $url);
$this->assertStringNotContainsStringIgnoringCase($hash, $url);
$this->assertStringNotContainsStringIgnoringCase(\substr($hash, 5), $url);
// Only the first five characters go out, so the service cannot tell which password was checked
$this->assertStringEndsWith(\substr($hash, 0, 5), $url);
}
public function testRangeIsCachedPerPrefix(): void
{
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 42]));
$cache = new Cache(new Memory());
$this->assertTrue((new HIBP(self::ENDPOINT, $cache, new Client($fetch)))->isPwned(self::LEAKED));
$this->assertTrue((new HIBP(self::ENDPOINT, $cache, new Client($fetch)))->isPwned(self::LEAKED));
$this->assertCount(1, $fetch->urls);
}
public function testCacheIsScopedToEndpoint(): void
{
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 42]));
$cache = new Cache(new Memory());
(new HIBP('https://one.test/range', $cache, new Client($fetch)))->isPwned(self::LEAKED);
(new HIBP('https://two.test/range', $cache, new Client($fetch)))->isPwned(self::LEAKED);
$this->assertCount(2, $fetch->urls);
}
public function testLookupsGoToTheConfiguredEndpoint(): void
{
$fetch = new RangeFetch(body: '');
(new HIBP('https://server.test/range', null, new Client($fetch)))->isPwned(self::LEAKED);
(new HIBP('https://other.test/range/', null, new Client($fetch)))->isPwned(self::LEAKED);
$this->assertStringStartsWith('https://server.test/range/', $fetch->urls[0]);
$this->assertStringStartsWith('https://other.test/range/', $fetch->urls[1]);
}
public function testUnreachableServiceIsReported(): void
{
$fetch = new RangeFetch(failure: new \RuntimeException('connection refused'));
try {
$this->adapter($fetch)->isPwned(self::LEAKED);
$this->fail('Expected the unreachable service to surface');
} catch (Exception $e) {
$this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType());
}
}
public function testUnexpectedStatusIsReported(): void
{
$fetch = new RangeFetch(statusCode: 503, body: '');
$this->expectException(Exception::class);
$this->adapter($fetch)->isPwned(self::LEAKED);
}
public function testFailedLookupIsNotCached(): void
{
$fetch = new RangeFetch(failure: new \RuntimeException('connection refused'));
$adapter = new HIBP(self::ENDPOINT, new Cache(new Memory()), new Client($fetch));
foreach ([1, 2] as $attempt) {
try {
$adapter->isPwned(self::LEAKED);
} catch (Exception) {
// The lookup failed, which is the point; it must be retried rather than remembered
}
}
$this->assertCount(2, $fetch->urls);
}
private function adapter(RangeFetch $fetch): HIBP
{
return new HIBP(self::ENDPOINT, null, new Client($fetch));
}
/**
* Builds a range response body the way the Have I Been Pwned API does:
* one `SUFFIX:COUNT` line per leaked hash, CRLF separated, plus padding.
*
* @param array<string, int> $leaked password => breach count
*/
private function range(array $leaked): string
{
$lines = [];
foreach ($leaked as $password => $count) {
$lines[] = \substr(\strtoupper(\sha1((string) $password)), 5) . ':' . $count;
}
$lines[] = \str_repeat('0', 35) . ':0';
return \implode("\r\n", $lines);
}
}
final class RangeFetch implements Adapter
{
/** @var array<int, string> URLs the adapter asked the breach service for */
public array $urls = [];
public function __construct(
private int $statusCode = 200,
private string $body = '',
private ?\Throwable $failure = null,
) {
}
public function send(
string $url,
string $method,
mixed $body,
array $headers,
RequestOptions $options,
?callable $chunkCallback = null
): Response {
$this->urls[] = $url;
if ($this->failure !== null) {
throw $this->failure;
}
return new Response($this->statusCode, $this->body, []);
}
}
+41 -198
View File
@@ -4,24 +4,18 @@ declare(strict_types=1);
namespace Tests\Unit\Auth\Validator;
use Appwrite\Auth\Pwned;
use Appwrite\Auth\Validator\PasswordPwned;
use Appwrite\Extend\Exception;
use PHPUnit\Framework\TestCase;
use Utopia\Cache\Adapter\Memory;
use Utopia\Cache\Cache;
use Utopia\Fetch\Adapter;
use Utopia\Fetch\Client;
use Utopia\Fetch\Options\Request as RequestOptions;
use Utopia\Fetch\Response;
final class PasswordPwnedTest extends TestCase
{
private const LEAKED = 'Password123!';
private const ENDPOINT = 'https://breaches.test/range';
private const PASSWORD = 'Password123!';
public function testEnabledByDefaultWithoutSessionChecks(): void
{
$validator = new PasswordPwned();
$validator = new PasswordPwned(new FakePwned());
$this->assertTrue($validator->isEnabled());
$this->assertFalse($validator->checksSessions());
@@ -30,7 +24,7 @@ final class PasswordPwnedTest extends TestCase
public function testPolicyFlags(): void
{
$validator = new PasswordPwned(['enabled' => true, 'sessions' => true, 'users' => true]);
$validator = new PasswordPwned(new FakePwned(), ['enabled' => true, 'sessions' => true, 'users' => true]);
$this->assertTrue($validator->isEnabled());
$this->assertTrue($validator->checksSessions());
@@ -39,237 +33,86 @@ final class PasswordPwnedTest extends TestCase
public function testSessionChecksNeedAnEnabledPolicy(): void
{
$validator = new PasswordPwned(['enabled' => false, 'sessions' => true, 'users' => true]);
$validator = new PasswordPwned(new FakePwned(), ['enabled' => false, 'sessions' => true, 'users' => true]);
$this->assertFalse($validator->checksSessions());
}
public function testDisabledPolicyNeverChecks(): void
public function testDisabledPolicyNeverAsksTheAdapter(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42]));
$validator = new PasswordPwned(['enabled' => false], null, self::ENDPOINT, new Client($adapter));
$adapter = new FakePwned(pwned: true);
$validator = new PasswordPwned($adapter, ['enabled' => false]);
$this->assertNull($validator->check(self::LEAKED));
$this->assertTrue($validator->isValid(self::LEAKED));
$this->assertCount(0, $adapter->requests);
$this->assertNull($validator->check(self::PASSWORD));
$this->assertTrue($validator->isValid(self::PASSWORD));
$this->assertSame(0, $adapter->calls);
}
public function testCheckReportsBreachState(): void
public function testCheckReportsWhatTheAdapterFound(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42]));
$validator = $this->validator([], $adapter);
$this->assertTrue($validator->check(self::LEAKED));
$this->assertFalse($validator->check('never-leaked-' . \uniqid()));
$this->assertTrue((new PasswordPwned(new FakePwned(pwned: true)))->check(self::PASSWORD));
$this->assertFalse((new PasswordPwned(new FakePwned(pwned: false)))->check(self::PASSWORD));
}
public function testLeakedPasswordIsRejected(): void
public function testBreachedPasswordIsInvalid(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42]));
$validator = $this->validator([], $adapter);
$this->assertFalse($validator->isValid(self::LEAKED));
$this->assertFalse((new PasswordPwned(new FakePwned(pwned: true)))->isValid(self::PASSWORD));
$this->assertTrue((new PasswordPwned(new FakePwned(pwned: false)))->isValid(self::PASSWORD));
}
public function testCleanPasswordIsAccepted(): void
public function testAdapterFailureSurfaces(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42]));
$validator = $this->validator([], $adapter);
$this->assertTrue($validator->isValid('never-leaked-' . \uniqid()));
}
public function testPaddedEntryWithZeroCountIsNotABreach(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 0]));
$validator = $this->validator([], $adapter);
$this->assertTrue($validator->isValid(self::LEAKED));
}
public function testSuffixComparisonIgnoresCase(): void
{
$adapter = new RangeAdapter(body: \strtolower($this->range([self::LEAKED => 3])));
$validator = $this->validator([], $adapter);
$this->assertFalse($validator->isValid(self::LEAKED));
}
public function testAnySingleBreachIsEnough(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 1]));
$this->assertFalse($this->validator([], $adapter)->isValid(self::LEAKED));
}
public function testOnlyTheHashPrefixLeavesTheServer(): void
{
$adapter = new RangeAdapter(body: '');
$validator = $this->validator([], $adapter);
$validator->isValid(self::LEAKED);
$this->assertCount(1, $adapter->requests);
$hash = \strtoupper(\sha1(self::LEAKED));
$url = $adapter->requests[0];
// Neither the password nor anything that identifies it may reach the service
$this->assertStringNotContainsStringIgnoringCase(self::LEAKED, $url);
$this->assertStringNotContainsStringIgnoringCase($hash, $url);
$this->assertStringNotContainsStringIgnoringCase(\substr($hash, 5), $url);
// Only the first five characters of the hash go out, so the service cannot tell which password was checked
$this->assertStringEndsWith(\substr($hash, 0, 5), $url);
}
public function testRangeIsCachedPerPrefix(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42]));
$cache = new Cache(new Memory());
$first = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter));
$second = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter));
$this->assertFalse($first->isValid(self::LEAKED));
$this->assertFalse($second->isValid(self::LEAKED));
$this->assertCount(1, $adapter->requests);
}
public function testCacheIsScopedToEndpoint(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42]));
$cache = new Cache(new Memory());
(new PasswordPwned(['enabled' => true], $cache, 'https://one.test/range', new Client($adapter)))->isValid(self::LEAKED);
(new PasswordPwned(['enabled' => true], $cache, 'https://two.test/range', new Client($adapter)))->isValid(self::LEAKED);
$this->assertCount(2, $adapter->requests);
}
public function testUnreachableServiceIsReported(): void
{
$adapter = new RangeAdapter(failure: new \RuntimeException('connection refused'));
$validator = $this->validator([], $adapter);
try {
$validator->isValid(self::LEAKED);
$this->fail('Expected the unreachable service to surface');
} catch (Exception $e) {
$this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType());
}
}
public function testUnexpectedStatusIsReported(): void
{
$adapter = new RangeAdapter(statusCode: 503, body: '');
$validator = $this->validator([], $adapter);
$adapter = new FakePwned(failure: new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE));
$validator = new PasswordPwned($adapter);
$this->expectException(Exception::class);
$validator->isValid(self::LEAKED);
}
public function testFailedLookupIsNotCached(): void
{
$adapter = new RangeAdapter(failure: new \RuntimeException('connection refused'));
$cache = new Cache(new Memory());
$validator = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter));
foreach ([1, 2] as $attempt) {
try {
$validator->isValid(self::LEAKED);
} catch (Exception) {
// The lookup failed, which is the point; it must be retried rather than remembered
}
}
$this->assertCount(2, $adapter->requests);
$validator->isValid(self::PASSWORD);
}
public function testBasePasswordRulesStillApply(): void
{
$adapter = new RangeAdapter(body: '');
$validator = $this->validator([], $adapter);
$adapter = new FakePwned(pwned: false);
$validator = new PasswordPwned($adapter);
$this->assertFalse($validator->isValid('short'));
$this->assertFalse($validator->isValid(\str_repeat('p', 257)));
$this->assertFalse($validator->isValid(''));
$this->assertCount(0, $adapter->requests);
$this->assertSame(0, $adapter->calls);
}
public function testAllowEmptySkipsTheLookup(): void
{
$adapter = new RangeAdapter(body: '');
$validator = new PasswordPwned(['enabled' => true], null, self::ENDPOINT, new Client($adapter), allowEmpty: true);
$adapter = new FakePwned(pwned: true);
$validator = new PasswordPwned($adapter, [], allowEmpty: true);
$this->assertTrue($validator->isValid(''));
$this->assertCount(0, $adapter->requests);
}
public function testLookupsGoToTheConfiguredEndpoint(): void
{
$adapter = new RangeAdapter(body: '');
(new PasswordPwned(['enabled' => true], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED);
(new PasswordPwned(['enabled' => true], null, 'https://other.test/range/', new Client($adapter)))->isValid(self::LEAKED);
$this->assertStringStartsWith('https://server.test/range/', $adapter->requests[0]);
$this->assertStringStartsWith('https://other.test/range/', $adapter->requests[1]);
}
/**
* @param array<string, mixed> $policy
*/
private function validator(array $policy, RangeAdapter $adapter): PasswordPwned
{
return new PasswordPwned(\array_merge(['enabled' => true], $policy), null, self::ENDPOINT, new Client($adapter));
}
/**
* Builds a range response body the way the Have I Been Pwned API does:
* one `SUFFIX:COUNT` line per leaked hash, CRLF separated, plus padding.
*
* @param array<string, int> $leaked password => breach count
*/
private function range(array $leaked): string
{
$lines = [];
foreach ($leaked as $password => $count) {
$lines[] = \substr(\strtoupper(\sha1((string) $password)), 5) . ':' . $count;
}
$lines[] = \str_repeat('0', 35) . ':0';
return \implode("\r\n", $lines);
$this->assertSame(0, $adapter->calls);
}
}
final class RangeAdapter implements Adapter
final class FakePwned extends Pwned
{
/** @var array<int, string> URLs the validator asked the breach service for */
public array $requests = [];
public int $calls = 0;
public function __construct(
private int $statusCode = 200,
private string $body = '',
private ?\Throwable $failure = null,
) {
public function __construct(private bool $pwned = false, private ?\Throwable $failure = null)
{
parent::__construct('https://breaches.test');
}
public function send(
string $url,
string $method,
mixed $body,
array $headers,
RequestOptions $options,
?callable $chunkCallback = null
): Response {
$this->requests[] = $url;
public function getName(): string
{
return 'fake';
}
public function isPwned(string $password): bool
{
$this->calls++;
if ($this->failure !== null) {
throw $this->failure;
}
return new Response($this->statusCode, $this->body, []);
return $this->pwned;
}
}