feat(policies): add password pwned project policy

Adds a `password-pwned` project policy, disabled by default, that checks
new passwords against the Have I Been Pwned range API using k-anonymity.
Only the first five characters of the SHA-1 hash leave the server.

When enabled, breached passwords are rejected with `password_pwned` on
account create, account password update, account recovery update, users
create, and users password update. Hashed imports are unaffected. The
check fails open when the service is unreachable.

The endpoint is configurable via `_APP_PWNED_PASSWORDS_ENDPOINT`; the dev
and CI `.env` points it at a new mock range route so automated tests never
contact the real service.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Matej BačoandClaude Fable 5.1 committed 2026-09-15 12:53:27 +02:00
1 parent 16a8456190
commit 053e693cf3
23 files changed
+896

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_ENDPOINT=http://localhost/v1/mock/tests/general/pwned-passwords
_APP_VCS_GITHUB_APP_ID=
_APP_VCS_GITHUB_APP_NAME=
_APP_VCS_GITHUB_CLIENT_ID=
+5
View File
@@ -271,6 +271,11 @@ return [
'description' => 'The password you are trying to use contains references to your name, email, phone or userID. For your security, please choose a different password and try again.',
'code' => 400,
],
Exception::USER_PASSWORD_PWNED => [
'name' => Exception::USER_PASSWORD_PWNED,
'description' => 'The password you are trying to use has been exposed in a known data breach. For your security, please choose a different password and try again.',
'code' => 400,
],
Exception::USER_SESSION_NOT_FOUND => [
'name' => Exception::USER_SESSION_NOT_FOUND,
'description' => 'The current user session could not be found.',
+9
View File
@@ -483,6 +483,15 @@ return [
'required' => false,
'question' => '',
'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.',
'introduction' => 'TBD',
'default' => 'https://api.pwnedpasswords.com/range',
'required' => false,
'question' => '',
'filter' => ''
]
],
],
+22
View File
@@ -7,6 +7,7 @@ use Appwrite\Auth\Validator\EmailWhitelist;
use Appwrite\Auth\Validator\Password;
use Appwrite\Auth\Validator\PasswordDictionary;
use Appwrite\Auth\Validator\PasswordHistory;
use Appwrite\Auth\Validator\PasswordPwned;
use Appwrite\Auth\Validator\PasswordStrength;
use Appwrite\Auth\Validator\PersonalData;
use Appwrite\Auth\Validator\Phone;
@@ -361,6 +362,13 @@ Http::post('/v1/account')
}
}
if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) {
$pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'));
if (!$pwnedValidator->isValid($password)) {
throw new Exception(Exception::USER_PASSWORD_PWNED);
}
}
$hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]);
$passwordHistory = $project->getAttribute('auths', [])['passwordHistory'] ?? 0;
@@ -3483,6 +3491,13 @@ Http::patch('/v1/account/password')
}
}
if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) {
$pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'));
if (!$pwnedValidator->isValid($password)) {
throw new Exception(Exception::USER_PASSWORD_PWNED);
}
}
$hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]);
$user
@@ -4137,6 +4152,13 @@ Http::put('/v1/account/recovery')
$history = array_slice($history, (count($history) - $historyLimit), $historyLimit);
}
if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) {
$pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'));
if (!$pwnedValidator->isValid($password)) {
throw new Exception(Exception::USER_PASSWORD_PWNED);
}
}
$hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]);
$sessions = $profile->getAttribute('sessions', []);
+32
View File
@@ -501,3 +501,35 @@ Http::shutdown()
$response->dynamic(new Document(['result' => \implode(',', $methods) . ':' . $route->getPath() . ':passed']), Response::MODEL_MOCK);
});
Http::get('/v1/mock/tests/general/pwned-passwords/:prefix')
->desc('Pwned Passwords range')
->groups(['mock'])
->label('scope', 'public')
->label('docs', false)
->label('mock', true)
->param('prefix', '', new Text(5, 5), 'First five characters of the SHA-1 password hash.')
->inject('response')
->action(function (string $prefix, Response $response) {
// Mirrors the Have I Been Pwned range API: every leaked hash sharing the
// requested prefix comes back as `SUFFIX:COUNT`, one per line.
$leaked = [
'Password123!' => 12345,
'Summer2024!' => 678,
'letmein1234' => 9,
];
$prefix = \strtoupper($prefix);
$lines = [];
foreach ($leaked as $password => $count) {
$hash = \strtoupper(\sha1($password));
if (\str_starts_with($hash, $prefix)) {
$lines[] = \substr($hash, 5) . ':' . $count;
}
}
// Padded entries carry a count of 0 and must never be treated as a breach
$lines[] = \str_repeat('0', 35) . ':0';
$response->text(\implode("\r\n", $lines));
});
+2
View File
@@ -181,6 +181,7 @@ use Appwrite\Utopia\Response\Model\PolicyMFAFactors;
use Appwrite\Utopia\Response\Model\PolicyPasswordDictionary;
use Appwrite\Utopia\Response\Model\PolicyPasswordHistory;
use Appwrite\Utopia\Response\Model\PolicyPasswordPersonalData;
use Appwrite\Utopia\Response\Model\PolicyPasswordPwned;
use Appwrite\Utopia\Response\Model\PolicyPasswordStrength;
use Appwrite\Utopia\Response\Model\PolicySessionAlert;
use Appwrite\Utopia\Response\Model\PolicySessionDuration;
@@ -473,6 +474,7 @@ Response::setModel(new PolicyPasswordDictionary());
Response::setModel(new PolicyPasswordHistory());
Response::setModel(new PolicyPasswordStrength());
Response::setModel(new PolicyPasswordPersonalData());
Response::setModel(new PolicyPasswordPwned());
Response::setModel(new PolicySessionAlert());
Response::setModel(new PolicySessionDuration());
Response::setModel(new PolicySessionInvalidation());
+1
View File
@@ -254,6 +254,7 @@ services:
- _APP_MIGRATION_HOST
- _APP_GEO_SECRET
- _APP_GEO_ENDPOINT
- _APP_PWNED_PASSWORDS_ENDPOINT
- _APP_LIMIT_DATABASE_BATCH
- _APP_DOCUMENTSDB
- _APP_VECTORSDB
@@ -0,0 +1,129 @@
<?php
namespace Appwrite\Auth\Validator;
use Utopia\Fetch\Client;
/**
* Validates that a password has not been exposed in a known data breach.
*
* 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 candidate
* suffixes are compared locally. When the breach service cannot be reached the
* check is skipped, so an outage of the third party never blocks sign-ups or
* password changes.
*/
class PasswordPwned extends Password
{
public const ENDPOINT = 'https://api.pwnedpasswords.com/range';
private const PREFIX_LENGTH = 5;
private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds
private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds
protected string $endpoint;
protected Client $client;
public function __construct(?string $endpoint = null, ?Client $client = null, bool $allowEmpty = false)
{
parent::__construct($allowEmpty);
$this->endpoint = \rtrim($endpoint ?: self::ENDPOINT, '/');
$this->client = $client ?? (new Client())
->setConnectTimeout(self::CONNECT_TIMEOUT)
->setTimeout(self::REQUEST_TIMEOUT)
->setAllowRedirects(false)
->setUserAgent('Appwrite');
}
/**
* Get Description.
*
* Returns validator description
*
* @return string
*/
public function getDescription(): string
{
return 'Password must not have been exposed in a known data breach.';
}
/**
* Is valid.
*
* @param mixed $value
*
* @return bool
*/
public function isValid($value): bool
{
if (!parent::isValid($value)) {
return false;
}
if ($this->allowEmpty && \strlen($value) === 0) {
return true;
}
$hash = \strtoupper(\sha1($value));
$prefix = \substr($hash, 0, self::PREFIX_LENGTH);
$suffix = \substr($hash, self::PREFIX_LENGTH);
try {
$response = $this->client
->addHeader('Add-Padding', 'true')
->fetch($this->endpoint . '/' . $prefix);
} catch (\Throwable) {
return true;
}
if ($response->getStatusCode() !== 200) {
return true;
}
// Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches
foreach (\explode("\n", $response->text()) as $line) {
$line = \trim($line);
if ($line === '') {
continue;
}
$separator = \strpos($line, ':');
if ($separator === false) {
continue;
}
$candidate = \strtoupper(\substr($line, 0, $separator));
$count = (int) \substr($line, $separator + 1);
if ($candidate === $suffix && $count > 0) {
return false;
}
}
return true;
}
/**
* Is array
*
* Function will return true if object is array.
*
* @return bool
*/
public function isArray(): bool
{
return false;
}
/**
* Get Type
*
* Returns validator type.
*
* @return string
*/
public function getType(): string
{
return self::TYPE_STRING;
}
}
+1
View File
@@ -83,6 +83,7 @@ class Exception extends \Exception
public const string USER_NOT_FOUND = 'user_not_found';
public const string USER_PASSWORD_RECENTLY_USED = 'password_recently_used';
public const string USER_PASSWORD_PERSONAL_DATA = 'password_personal_data';
public const string USER_PASSWORD_PWNED = 'password_pwned';
public const string USER_EMAIL_ALREADY_EXISTS = 'user_email_already_exists';
public const string USER_EMAIL_DISPOSABLE = 'user_email_disposable';
public const string USER_EMAIL_FREE = 'user_email_free';
@@ -91,6 +91,7 @@ class Create extends Action
'passwordDictionary' => false,
'duration' => TOKEN_EXPIRATION_LOGIN_LONG,
'personalDataCheck' => false,
'passwordPwned' => false,
'disposableEmails' => false,
'canonicalEmails' => false,
'freeEmails' => false,
@@ -79,6 +79,7 @@ class Get extends Action
'password-history' => Response::MODEL_POLICY_PASSWORD_HISTORY,
'password-strength' => Response::MODEL_POLICY_PASSWORD_STRENGTH,
'password-personal-data' => Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA,
'password-pwned' => Response::MODEL_POLICY_PASSWORD_PWNED,
'session-alert' => Response::MODEL_POLICY_SESSION_ALERT,
'session-duration' => Response::MODEL_POLICY_SESSION_DURATION,
'session-invalidation' => Response::MODEL_POLICY_SESSION_INVALIDATION,
@@ -134,6 +135,13 @@ class Get extends Action
]),
Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA,
],
'password-pwned' => [
new Document([
'$id' => 'password-pwned',
'enabled' => $auths['passwordPwned'] ?? false,
]),
Response::MODEL_POLICY_PASSWORD_PWNED,
],
'session-alert' => [
new Document([
'$id' => 'session-alert',
@@ -0,0 +1,85 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordPwned;
use Appwrite\Event\Event;
use Appwrite\Platform\Action;
use Appwrite\SDK\AuthType;
use Appwrite\SDK\Method;
use Appwrite\SDK\Response as SDKResponse;
use Appwrite\Utopia\Response;
use Utopia\Database\Database;
use Utopia\Database\Document;
use Utopia\Database\Validator\Authorization;
use Utopia\Platform\Scope\HTTP;
use Utopia\Validator\Boolean;
class Update extends Action
{
use HTTP;
public static function getName()
{
return 'updateProjectPasswordPwnedPolicy';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_PATCH)
->setHttpPath('/v1/project/policies/password-pwned')
->desc('Update password pwned policy')
->groups(['api', 'project'])
->label('scope', ['policies.write', 'project.policies.write'])
->label('event', 'projects.[projectId].policies.[policy].update')
->label('audits.event', 'projects.[projectId].policies.[policy].update')
->label('audits.resource', 'project/{response.$id}')
->label('sdk', new Method(
namespace: 'project',
group: 'policies',
name: 'updatePasswordPwnedPolicy',
description: <<<EOT
Updating this policy allows you to control if new passwords are checked against the Have I Been Pwned breach database. When enabled, and user sets or changes their password, password must not have appeared in a known data breach. Only the first five characters of the password hash are ever shared with the service.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_PROJECT,
)
],
))
->param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true if you want password change to block passwords exposed in known data breaches, or false to allow them. When changing this policy, existing passwords remain valid.')
->inject('response')
->inject('dbForPlatform')
->inject('project')
->inject('authorization')
->inject('queueForEvents')
->callback($this->action(...));
}
public function action(
bool $enabled,
Response $response,
Database $dbForPlatform,
Document $project,
Authorization $authorization,
Event $queueForEvents,
): void {
$auths = $project->getAttribute('auths', []);
$auths['passwordPwned'] = $enabled;
$updates = new Document([
'auths' => $auths,
]);
$project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates));
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
$queueForEvents
->setParam('projectId', $project->getId())
->setParam('policy', 'password-pwned');
$response->dynamic($project, Response::MODEL_PROJECT);
}
}
@@ -116,6 +116,10 @@ class XList extends Action
'$id' => 'password-personal-data',
'enabled' => $auths['personalDataCheck'] ?? false,
]),
new Document([
'$id' => 'password-pwned',
'enabled' => $auths['passwordPwned'] ?? false,
]),
new Document([
'$id' => 'session-alert',
'enabled' => $auths['sessionAlerts'] ?? false,
@@ -91,6 +91,7 @@ use Appwrite\Platform\Modules\Project\Http\Project\Policies\MFAFactors\Update as
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordDictionary\Update as UpdatePasswordDictionaryPolicy;
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordHistory\Update as UpdatePasswordHistoryPolicy;
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordPersonalData\Update as UpdatePasswordPersonalDataPolicy;
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordPwned\Update as UpdatePasswordPwnedPolicy;
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordStrength\Update as UpdatePasswordStrengthPolicy;
use Appwrite\Platform\Modules\Project\Http\Project\Policies\SessionAlert\Update as UpdateSessionAlertPolicy;
use Appwrite\Platform\Modules\Project\Http\Project\Policies\SessionDuration\Update as UpdateSessionDurationPolicy;
@@ -184,6 +185,7 @@ class Http extends Service
$this->addAction(UpdatePasswordHistoryPolicy::getName(), new UpdatePasswordHistoryPolicy());
$this->addAction(UpdatePasswordStrengthPolicy::getName(), new UpdatePasswordStrengthPolicy());
$this->addAction(UpdatePasswordPersonalDataPolicy::getName(), new UpdatePasswordPersonalDataPolicy());
$this->addAction(UpdatePasswordPwnedPolicy::getName(), new UpdatePasswordPwnedPolicy());
$this->addAction(UpdateSessionAlertPolicy::getName(), new UpdateSessionAlertPolicy());
$this->addAction(UpdateSessionDurationPolicy::getName(), new UpdateSessionDurationPolicy());
$this->addAction(UpdateSessionInvalidationPolicy::getName(), new UpdateSessionInvalidationPolicy());
@@ -88,6 +88,7 @@ class Create extends Action
'passwordDictionary' => false,
'duration' => TOKEN_EXPIRATION_LOGIN_LONG,
'personalDataCheck' => false,
'passwordPwned' => false,
'disposableEmails' => false,
'canonicalEmails' => false,
'freeEmails' => false,
@@ -2,6 +2,7 @@
namespace Appwrite\Platform\Modules\Users;
use Appwrite\Auth\Validator\PasswordPwned;
use Appwrite\Auth\Validator\PersonalData;
use Appwrite\Extend\Exception;
use Appwrite\Hooks\Hooks;
@@ -18,6 +19,7 @@ use Utopia\Database\Helpers\Permission;
use Utopia\Database\Helpers\Role;
use Utopia\Database\Query;
use Utopia\Emails\Email;
use Utopia\System\System;
class Base extends Action
{
@@ -147,6 +149,13 @@ class Base extends Action
]);
if (!$isHashed && !empty($password)) {
if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) {
$pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'));
if (!$pwnedValidator->isValid($plaintextPassword)) {
throw new Exception(Exception::USER_PASSWORD_PWNED);
}
}
$hooks->trigger('passwordValidator', [$dbForProject, $project, $plaintextPassword, &$user, true]);
}
@@ -4,6 +4,7 @@ namespace Appwrite\Platform\Modules\Users\Http\Users\Password;
use Appwrite\Auth\Validator\PasswordDictionary;
use Appwrite\Auth\Validator\PasswordHistory;
use Appwrite\Auth\Validator\PasswordPwned;
use Appwrite\Auth\Validator\PasswordStrength;
use Appwrite\Auth\Validator\PersonalData;
use Appwrite\Event\Event;
@@ -22,6 +23,7 @@ use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Validator\UID;
use Utopia\Platform\Scope\HTTP;
use Utopia\System\System;
use Utopia\Validator;
use Utopia\Validator\AllOf;
@@ -84,6 +86,13 @@ class Update extends Action
}
}
if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) {
$pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'), allowEmpty: true);
if (!$pwnedValidator->isValid($password)) {
throw new Exception(Exception::USER_PASSWORD_PWNED);
}
}
if (\strlen($password) === 0) {
$user
->setAttribute('password', '')
+1
View File
@@ -264,6 +264,7 @@ class Response extends SwooleResponse
public const MODEL_POLICY_PASSWORD_HISTORY = 'policyPasswordHistory';
public const MODEL_POLICY_PASSWORD_STRENGTH = 'policyPasswordStrength';
public const MODEL_POLICY_PASSWORD_PERSONAL_DATA = 'policyPasswordPersonalData';
public const MODEL_POLICY_PASSWORD_PWNED = 'policyPasswordPwned';
public const MODEL_POLICY_SESSION_ALERT = 'policySessionAlert';
public const MODEL_POLICY_SESSION_DURATION = 'policySessionDuration';
public const MODEL_POLICY_SESSION_INVALIDATION = 'policySessionInvalidation';
@@ -34,6 +34,7 @@ class PolicyList extends Model
Response::MODEL_POLICY_PASSWORD_HISTORY,
Response::MODEL_POLICY_PASSWORD_STRENGTH,
Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA,
Response::MODEL_POLICY_PASSWORD_PWNED,
Response::MODEL_POLICY_SESSION_ALERT,
Response::MODEL_POLICY_SESSION_DURATION,
Response::MODEL_POLICY_SESSION_INVALIDATION,
@@ -0,0 +1,34 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Utopia\Response;
class PolicyPasswordPwned extends PolicyBase
{
public array $conditions = [
'$id' => 'password-pwned',
];
public function __construct()
{
parent::__construct();
$this->addRule('enabled', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether password pwned policy is enabled.',
'default' => false,
'example' => true,
]);
}
public function getName(): string
{
return 'Policy Password Pwned';
}
public function getType(): string
{
return Response::MODEL_POLICY_PASSWORD_PWNED;
}
}
@@ -17,6 +17,7 @@ trait PoliciesBase
'password-history' => ['total'],
'password-strength' => ['min', 'uppercase', 'lowercase', 'number', 'symbols'],
'password-personal-data' => ['enabled'],
'password-pwned' => ['enabled'],
'session-alert' => ['enabled'],
'session-duration' => ['duration'],
'session-invalidation' => ['enabled'],
@@ -635,6 +636,70 @@ trait PoliciesBase
$this->assertSame(401, $response['headers']['status-code']);
}
// =========================================================================
// Password Pwned Policy
// =========================================================================
public function testUpdatePasswordPwnedPolicyEnable(): void
{
$response = $this->updatePasswordPwnedPolicy(true);
$this->assertSame(200, $response['headers']['status-code']);
$this->assertNotEmpty($response['body']['$id']);
$policy = $this->getPolicy('password-pwned');
$this->assertSame(200, $policy['headers']['status-code']);
$this->assertSame(true, $policy['body']['enabled']);
// Cleanup
$this->updatePasswordPwnedPolicy(false);
}
public function testUpdatePasswordPwnedPolicyDisable(): void
{
$this->updatePasswordPwnedPolicy(true);
$response = $this->updatePasswordPwnedPolicy(false);
$this->assertSame(200, $response['headers']['status-code']);
$policy = $this->getPolicy('password-pwned');
$this->assertSame(200, $policy['headers']['status-code']);
$this->assertSame(false, $policy['body']['enabled']);
}
public function testUpdatePasswordPwnedPolicyDisabledByDefault(): void
{
$policy = $this->getPolicy('password-pwned');
$this->assertSame(200, $policy['headers']['status-code']);
$this->assertSame('password-pwned', $policy['body']['$id']);
$this->assertSame(false, $policy['body']['enabled']);
}
public function testUpdatePasswordPwnedPolicyInvalidType(): void
{
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), [
'enabled' => 'not-a-boolean',
]);
$this->assertSame(400, $response['headers']['status-code']);
}
public function testUpdatePasswordPwnedPolicyMissingParam(): void
{
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), []);
$this->assertSame(400, $response['headers']['status-code']);
}
public function testUpdatePasswordPwnedPolicyWithoutAuth(): void
{
$response = $this->updatePasswordPwnedPolicy(true, false);
$this->assertSame(401, $response['headers']['status-code']);
}
// =========================================================================
// Session Alert Policy
// =========================================================================
@@ -1329,6 +1394,13 @@ trait PoliciesBase
]);
}
protected function updatePasswordPwnedPolicy(bool $enabled, bool $authenticated = true): mixed
{
return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders($authenticated), [
'enabled' => $enabled,
]);
}
protected function updateSessionAlertPolicy(bool $enabled, bool $authenticated = true): mixed
{
return $this->client->call(Client::METHOD_PATCH, '/project/policies/session-alert', $this->buildHeaders($authenticated), [
@@ -0,0 +1,311 @@
<?php
declare(strict_types=1);
namespace Tests\E2E\Services\Project;
use Tests\E2E\Client;
use Tests\E2E\Scopes\ProjectCustom;
use Tests\E2E\Scopes\Scope;
use Tests\E2E\Scopes\SideServer;
use Utopia\Database\Helpers\ID;
/**
* The stack points `_APP_PWNED_PASSWORDS_ENDPOINT` at the mock range endpoint in
* `app/controllers/mock.php`, so no request ever reaches the real Have I Been Pwned service.
*/
final class PoliciesPasswordPwnedIntegrationTest extends Scope
{
use ProjectCustom;
use SideServer;
// Reported as breached by the mock range endpoint
private const PWNED_PASSWORD = 'Password123!';
public function testCreateUserWithPolicyDisabled(): void
{
$this->updatePolicy(false);
/**
* Test for SUCCESS
*/
$user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [
'userId' => ID::unique(),
'email' => 'pwned_off_' . \uniqid() . '@localhost.test',
'password' => self::PWNED_PASSWORD,
'name' => 'Pwned Off User',
]);
$this->assertSame(201, $user['headers']['status-code']);
$this->assertNotEmpty($user['body']['$id']);
$response = $this->client->call(Client::METHOD_PATCH, '/users/' . $user['body']['$id'] . '/password', $this->serverHeaders(), [
'password' => self::PWNED_PASSWORD,
]);
$this->assertSame(200, $response['headers']['status-code']);
}
public function testCreateUserWithPolicyEnabled(): void
{
$this->updatePolicy(true);
/**
* Test for FAILURE
*/
$response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [
'userId' => ID::unique(),
'email' => 'pwned_on_' . \uniqid() . '@localhost.test',
'password' => self::PWNED_PASSWORD,
'name' => 'Pwned On User',
]);
$this->assertSame(400, $response['headers']['status-code']);
$this->assertSame('password_pwned', $response['body']['type']);
/**
* Test for SUCCESS
*/
$response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [
'userId' => ID::unique(),
'email' => 'pwned_clean_' . \uniqid() . '@localhost.test',
'password' => $this->cleanPassword(),
'name' => 'Clean User',
]);
$this->assertSame(201, $response['headers']['status-code']);
$this->assertNotEmpty($response['body']['$id']);
// Importing an already hashed password never exposes the plaintext, so the policy cannot apply
$response = $this->client->call(Client::METHOD_POST, '/users/sha', $this->serverHeaders(), [
'userId' => ID::unique(),
'email' => 'pwned_hashed_' . \uniqid() . '@localhost.test',
'password' => \sha1(self::PWNED_PASSWORD),
'passwordVersion' => 'sha1',
'name' => 'Hashed User',
]);
$this->assertSame(201, $response['headers']['status-code']);
$this->assertNotEmpty($response['body']['$id']);
$this->updatePolicy(false);
}
public function testUpdateUserPasswordWithPolicyEnabled(): void
{
$this->updatePolicy(true);
$user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [
'userId' => ID::unique(),
'email' => 'pwned_update_' . \uniqid() . '@localhost.test',
'password' => $this->cleanPassword(),
'name' => 'Update User',
]);
$this->assertSame(201, $user['headers']['status-code']);
$userId = $user['body']['$id'];
/**
* Test for FAILURE
*/
$response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $this->serverHeaders(), [
'password' => self::PWNED_PASSWORD,
]);
$this->assertSame(400, $response['headers']['status-code']);
$this->assertSame('password_pwned', $response['body']['type']);
/**
* Test for SUCCESS
*/
$response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $this->serverHeaders(), [
'password' => $this->cleanPassword(),
]);
$this->assertSame(200, $response['headers']['status-code']);
// Clearing the password is not a password to check
$response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $this->serverHeaders(), [
'password' => '',
]);
$this->assertSame(200, $response['headers']['status-code']);
$this->updatePolicy(false);
}
public function testCreateAccountWithPolicyEnabled(): void
{
$this->updatePolicy(true);
/**
* Test for FAILURE
*/
$response = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [
'userId' => ID::unique(),
'email' => 'pwned_account_' . \uniqid() . '@localhost.test',
'password' => self::PWNED_PASSWORD,
'name' => 'Pwned Account',
]);
$this->assertSame(400, $response['headers']['status-code']);
$this->assertSame('password_pwned', $response['body']['type']);
/**
* Test for SUCCESS
*/
$response = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [
'userId' => ID::unique(),
'email' => 'pwned_account_clean_' . \uniqid() . '@localhost.test',
'password' => $this->cleanPassword(),
'name' => 'Clean Account',
]);
$this->assertSame(201, $response['headers']['status-code']);
$this->assertNotEmpty($response['body']['$id']);
$this->updatePolicy(false);
}
public function testUpdateAccountPasswordWithPolicyEnabled(): void
{
$this->updatePolicy(true);
$email = 'pwned_session_' . \uniqid() . '@localhost.test';
$password = $this->cleanPassword();
$account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [
'userId' => ID::unique(),
'email' => $email,
'password' => $password,
'name' => 'Session Account',
]);
$this->assertSame(201, $account['headers']['status-code']);
$session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [
'email' => $email,
'password' => $password,
]);
$this->assertSame(201, $session['headers']['status-code']);
$headers = \array_merge($this->clientHeaders(), [
'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session['cookies']['a_session_' . $this->getProject()['$id']],
]);
/**
* Test for FAILURE
*/
$response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [
'password' => self::PWNED_PASSWORD,
'oldPassword' => $password,
]);
$this->assertSame(400, $response['headers']['status-code']);
$this->assertSame('password_pwned', $response['body']['type']);
/**
* Test for SUCCESS
*/
$response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [
'password' => $this->cleanPassword(),
'oldPassword' => $password,
]);
$this->assertSame(200, $response['headers']['status-code']);
$this->updatePolicy(false);
}
public function testUpdateAccountRecoveryWithPolicyEnabled(): void
{
$this->updatePolicy(true);
$email = 'pwned_recovery_' . \uniqid() . '@localhost.test';
$account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [
'userId' => ID::unique(),
'email' => $email,
'password' => $this->cleanPassword(),
'name' => 'Recovery Account',
]);
$this->assertSame(201, $account['headers']['status-code']);
$userId = $account['body']['$id'];
$recovery = $this->client->call(Client::METHOD_POST, '/account/recovery', $this->clientHeaders(), [
'email' => $email,
'url' => 'http://localhost/recovery',
]);
$this->assertSame(201, $recovery['headers']['status-code']);
$lastEmail = $this->getLastEmailByAddress($email, function ($email) {
$this->assertStringContainsString('Password Reset', (string) $email['subject']);
});
$secret = $this->extractQueryParamsFromEmailLink($lastEmail['html'])['secret'];
/**
* Test for FAILURE
*/
$response = $this->client->call(Client::METHOD_PUT, '/account/recovery', $this->clientHeaders(), [
'userId' => $userId,
'secret' => $secret,
'password' => self::PWNED_PASSWORD,
]);
$this->assertSame(400, $response['headers']['status-code']);
$this->assertSame('password_pwned', $response['body']['type']);
/**
* Test for SUCCESS
*/
$response = $this->client->call(Client::METHOD_PUT, '/account/recovery', $this->clientHeaders(), [
'userId' => $userId,
'secret' => $secret,
'password' => $this->cleanPassword(),
]);
$this->assertSame(200, $response['headers']['status-code']);
$this->updatePolicy(false);
}
private function updatePolicy(bool $enabled): void
{
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->serverHeaders(), [
'enabled' => $enabled,
]);
$this->assertSame(200, $response['headers']['status-code']);
}
/**
* @return array<string, string>
*/
private function serverHeaders(): array
{
return \array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders());
}
/**
* @return array<string, string>
*/
private function clientHeaders(): array
{
return [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
];
}
private function cleanPassword(): string
{
return 'Clean-' . \uniqid() . '-Pw!';
}
}
@@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
namespace Tests\Unit\Auth\Validator;
use Appwrite\Auth\Validator\PasswordPwned;
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 PasswordPwnedTest extends TestCase
{
private const LEAKED = 'Password123!';
public function testLeakedPasswordIsRejected(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42]));
$validator = new PasswordPwned('https://breaches.test/range', new Client($adapter));
$this->assertFalse($validator->isValid(self::LEAKED));
}
public function testCleanPasswordIsAccepted(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42]));
$validator = new PasswordPwned('https://breaches.test/range', new Client($adapter));
$this->assertTrue($validator->isValid('never-leaked-' . \uniqid()));
}
public function testPaddedEntryWithZeroCountIsNotABreach(): void
{
$adapter = new RangeAdapter(body: $this->range([self::LEAKED => 0]));
$validator = new PasswordPwned('https://breaches.test/range', new Client($adapter));
$this->assertTrue($validator->isValid(self::LEAKED));
}
public function testSuffixComparisonIgnoresCase(): void
{
$adapter = new RangeAdapter(body: \strtolower($this->range([self::LEAKED => 3])));
$validator = new PasswordPwned('https://breaches.test/range', new Client($adapter));
$this->assertFalse($validator->isValid(self::LEAKED));
}
public function testOnlyHashPrefixLeavesTheServer(): void
{
$adapter = new RangeAdapter(body: '');
$validator = new PasswordPwned('https://breaches.test/range/', new Client($adapter));
$validator->isValid(self::LEAKED);
$hash = \strtoupper(\sha1(self::LEAKED));
$this->assertCount(1, $adapter->requests);
$this->assertSame('https://breaches.test/range/' . \substr($hash, 0, 5), $adapter->requests[0]['url']);
$this->assertSame('GET', $adapter->requests[0]['method']);
$this->assertSame('true', $adapter->requests[0]['headers']['add-padding'] ?? null);
}
public function testUnreachableServiceSkipsTheCheck(): void
{
$adapter = new RangeAdapter(failure: new \RuntimeException('connection refused'));
$validator = new PasswordPwned('https://breaches.test/range', new Client($adapter));
$this->assertTrue($validator->isValid(self::LEAKED));
}
public function testUnexpectedStatusSkipsTheCheck(): void
{
$adapter = new RangeAdapter(statusCode: 503, body: $this->range([self::LEAKED => 42]));
$validator = new PasswordPwned('https://breaches.test/range', new Client($adapter));
$this->assertTrue($validator->isValid(self::LEAKED));
}
public function testBasePasswordRulesStillApply(): void
{
$adapter = new RangeAdapter(body: '');
$validator = new PasswordPwned('https://breaches.test/range', new Client($adapter));
$this->assertFalse($validator->isValid('short'));
$this->assertFalse($validator->isValid(\str_repeat('p', 257)));
$this->assertFalse($validator->isValid(''));
$this->assertCount(0, $adapter->requests);
}
public function testAllowEmptySkipsTheLookup(): void
{
$adapter = new RangeAdapter(body: '');
$validator = new PasswordPwned('https://breaches.test/range', new Client($adapter), allowEmpty: true);
$this->assertTrue($validator->isValid(''));
$this->assertCount(0, $adapter->requests);
}
public function testEmptyEndpointFallsBackToDefault(): void
{
$adapter = new RangeAdapter(body: '');
$validator = new PasswordPwned('', new Client($adapter));
$validator->isValid(self::LEAKED);
$this->assertStringStartsWith(PasswordPwned::ENDPOINT . '/', $adapter->requests[0]['url']);
}
/**
* 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 RangeAdapter implements Adapter
{
/** @var array<int, array{url: string, method: string, headers: array<string, string>}> */
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, 'headers' => $headers];
if ($this->failure !== null) {
throw $this->failure;
}
return new Response($this->statusCode, $this->body, []);
}
}