diff --git a/.env b/.env index 86d469ccfc..b5f5e1abde 100644 --- a/.env +++ b/.env @@ -176,6 +176,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_DSN=mock://localhost _APP_VCS_GITHUB_APP_ID= _APP_VCS_GITHUB_APP_NAME= _APP_VCS_GITHUB_CLIENT_ID= diff --git a/app/config/collections/common.php b/app/config/collections/common.php index 67f0f41fae..593b58c86c 100644 --- a/app/config/collections/common.php +++ b/app/config/collections/common.php @@ -397,6 +397,17 @@ return [ 'array' => false, 'filters' => [], ], + [ + '$id' => ID::custom('passwordPwned'), + 'type' => Database::VAR_BOOLEAN, + 'format' => '', + 'size' => 0, + 'signed' => true, + 'required' => false, + 'default' => null, + 'array' => false, + 'filters' => [], + ], [ '$id' => ID::custom('emailIsCorporate'), 'type' => Database::VAR_BOOLEAN, @@ -488,6 +499,13 @@ return [ 'lengths' => [], 'orders' => [Database::ORDER_ASC], ], + [ + '$id' => ID::custom('_key_passwordPwned'), + 'type' => Database::INDEX_KEY, + 'attributes' => ['passwordPwned'], + 'lengths' => [], + 'orders' => [Database::ORDER_ASC], + ], [ '$id' => ID::custom('_key_search'), 'type' => Database::INDEX_FULLTEXT, diff --git a/app/config/errors.php b/app/config/errors.php index b8cf874faa..961974e780 100644 --- a/app/config/errors.php +++ b/app/config/errors.php @@ -69,6 +69,11 @@ return [ 'description' => 'Phone provider is not configured. Please check the _APP_SMS_PROVIDER environment variable of your Appwrite server.', 'code' => 503, ], + Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE => [ + 'name' => Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, + 'description' => 'The breached password service could not be reached, so the password could not be verified. Please try again later.', + 'code' => 503, + ], Exception::GENERAL_ARGUMENT_INVALID => [ 'name' => Exception::GENERAL_ARGUMENT_INVALID, 'description' => 'The request contains one or more invalid arguments. Please refer to the endpoint documentation.', @@ -271,6 +276,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.', diff --git a/app/config/variables.php b/app/config/variables.php index 2299dcfe5c..fc69b5ce7e 100644 --- a/app/config/variables.php +++ b/app/config/variables.php @@ -483,6 +483,15 @@ return [ 'required' => false, 'question' => '', 'filter' => 'token' + ], + [ + 'name' => '_APP_PWNED_PASSWORDS_DSN', + 'description' => "DSN of the service the password pwned project policy asks whether a password has been breached. The scheme picks the adapter. Nothing is asked until you set it: the default, `none://localhost`, reports every password as safe, so the policy protects nothing until this points at a service.\n\nOptions:\n- None: `none://localhost` — the default. Reports every password as safe without asking anyone, for a server that must not or cannot reach a breach service\n- Have I Been Pwned: `hibp://localhost` — the public range API, which only ever receives the first five characters of the password SHA-1 hash. No other detail is read from the DSN\n- [Appwrite Pwned](https://github.com/appwrite-labs/pwned): `appwrite://SECRET@appwrite-pwned/v1/detection` — a service you run yourself, which answers from its own copy of the Have I Been Pwned corpus, so nothing about the password leaves your network. It receives the whole password, authenticated with `SECRET` as a Bearer token, which must match the service's `APPWRITE_PWNED_SECRET`, so only point it at a service on your own network or behind TLS. The path defaults to `v1/detection` and the connection is plain HTTP unless you add `?tls=true`\n- Testing: `mock://localhost` — reports a fixed list of passwords as breached without leaving the process. Refused on a production server, since it would report every real password as safe", + 'introduction' => 'TBD', + 'default' => 'none://localhost', + 'required' => false, + 'question' => '', + 'filter' => '' ] ], ], diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index fc0fa2ef5e..3246146e21 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -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; @@ -314,7 +315,8 @@ Http::post('/v1/account') ->inject('authorization') ->inject('hooks') ->inject('plan') - ->action(function (string $userId, string $email, string $password, ?string $name, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Authorization $authorization, Hooks $hooks, array $plan) { + ->inject('pwnedPasswords') + ->action(function (string $userId, string $email, string $password, ?string $name, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Authorization $authorization, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords) { $name ??= ''; $email = \strtolower($email); if ('console' === $project->getId()) { @@ -359,6 +361,14 @@ Http::post('/v1/account') } } + // null when the policy did not look, false when it looked and found nothing + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; + if ($passwordPwned) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); $passwordHistory = $project->getAttribute('auths', [])['passwordHistory'] ?? 0; @@ -435,6 +445,7 @@ Http::post('/v1/account') 'emailIsCorporate' => $emailMetadata['emailIsCorporate'], 'emailIsDisposable' => $emailMetadata['emailIsDisposable'], 'emailIsFree' => $emailMetadata['emailIsFree'], + 'passwordPwned' => $passwordPwned, ]); $user->removeAttribute('$sequence'); @@ -978,7 +989,8 @@ Http::post('/v1/account/sessions/email') ->inject('domainVerification') ->inject('cookieDomain') ->inject('authorization') - ->action(function (string $email, string $password, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Geo $geo, Event $queueForEvents, Bus $bus, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) { + ->inject('pwnedPasswords') + ->action(function (string $email, string $password, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Geo $geo, Event $queueForEvents, Bus $bus, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, bool $domainVerification, ?string $cookieDomain, Authorization $authorization, PasswordPwned $pwnedPasswords) { $email = \strtolower($email); $protocol = $request->getProtocol(); @@ -1037,6 +1049,24 @@ Http::post('/v1/account/sessions/email') $authorization->addRole(Role::user($user->getId())->toString()); + $pwnedPolicy = $project->getAttribute('auths', [])['passwordPwned'] ?? []; + + if (($pwnedPolicy['enabled'] ?? true) && ($pwnedPolicy['sessions'] ?? false)) { + // The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in + $passwordPwned = !$pwnedPasswords->isValid($password); + + if ($passwordPwned !== $user->getAttribute('passwordPwned')) { + $user->setAttribute('passwordPwned', $passwordPwned); + $dbForProject->updateDocument('users', $user->getId(), new Document([ + 'passwordPwned' => $passwordPwned, + ])); + } + + if ($passwordPwned && ($pwnedPolicy['users'] ?? false)) { + throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); + } + } + // Re-hash if not using recommended algo if ($user->getAttribute('hash') !== $proofForPassword->getHash()->getName()) { $proofForPasswordUpdated = new ProofsPassword(); @@ -3447,7 +3477,8 @@ Http::patch('/v1/account/password') ->inject('store') ->inject('proofForPassword') ->inject('proofForToken') - ->action(function (string $password, string $oldPassword, Response $response, User $user, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken) { + ->inject('pwnedPasswords') + ->action(function (string $password, string $oldPassword, Response $response, User $user, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, PasswordPwned $pwnedPasswords) { $userProofForPassword = ProofsPassword::createHash($user->getAttribute('hash'), $user->getAttribute('hashOptions')); // Check old password only if its an existing user. if (!empty($user->getAttribute('passwordUpdate')) && !$userProofForPassword->verify($oldPassword, $user->getAttribute('password'))) { // Double check user password @@ -3476,11 +3507,20 @@ Http::patch('/v1/account/password') } } + // null when the policy did not look, false when it looked and found nothing + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; + if ($passwordPwned) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $history) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('passwordUpdate', DateTime::now()) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()); @@ -3539,7 +3579,9 @@ Http::patch('/v1/account/email') ->inject('plan') ->inject('proofForPassword') ->inject('authorization') - ->action(function (string $email, string $password, ?\DateTime $requestTimestamp, Response $response, User $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, array $plan, ProofsPassword $proofForPassword, Authorization $authorization) { + ->inject('passwordsDictionary') + ->inject('pwnedPasswords') + ->action(function (string $email, string $password, ?\DateTime $requestTimestamp, Response $response, User $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, array $plan, ProofsPassword $proofForPassword, Authorization $authorization, array $passwordsDictionary, PasswordPwned $pwnedPasswords) { // passwordUpdate will be empty if the user has never set a password $passwordUpdate = $user->getAttribute('passwordUpdate'); @@ -3552,6 +3594,34 @@ Http::patch('/v1/account/email') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } + $passwordPwned = null; + if (empty($passwordUpdate)) { + // First password for an anonymous account: apply the same policies as account creation + $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); + if (!$strength->isValid($password)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $strength->getDescription()); + } + + $dictionary = new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false); + if (!$dictionary->isValid($password)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $dictionary->getDescription()); + } + + if ($project->getAttribute('auths', [])['personalDataCheck'] ?? false) { + $personalDataValidator = new PersonalData($user->getId(), $email, $user->getAttribute('name'), $user->getAttribute('phone')); + if (!$personalDataValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PERSONAL_DATA); + } + } + + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; + if ($passwordPwned) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]); $oldEmail = $user->getAttribute('email'); @@ -3617,8 +3687,12 @@ Http::patch('/v1/account/email') ; if (empty($passwordUpdate)) { + $newPassword = $proofForPassword->hash($password); + $historyLimit = $project->getAttribute('auths', [])['passwordHistory'] ?? 0; $user - ->setAttribute('password', $proofForPassword->hash($password)) + ->setAttribute('password', $newPassword) + ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -3681,7 +3755,9 @@ Http::patch('/v1/account/phone') ->inject('hooks') ->inject('proofForPassword') ->inject('authorization') - ->action(function (string $phone, string $password, Response $response, Document $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, ProofsPassword $proofForPassword, Authorization $authorization) { + ->inject('passwordsDictionary') + ->inject('pwnedPasswords') + ->action(function (string $phone, string $password, Response $response, Document $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, ProofsPassword $proofForPassword, Authorization $authorization, array $passwordsDictionary, PasswordPwned $pwnedPasswords) { // passwordUpdate will be empty if the user has never set a password $passwordUpdate = $user->getAttribute('passwordUpdate'); @@ -3694,6 +3770,34 @@ Http::patch('/v1/account/phone') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } + $passwordPwned = null; + if (empty($passwordUpdate)) { + // First password for an anonymous account: apply the same policies as account creation + $strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []); + if (!$strength->isValid($password)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $strength->getDescription()); + } + + $dictionary = new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false); + if (!$dictionary->isValid($password)) { + throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $dictionary->getDescription()); + } + + if ($project->getAttribute('auths', [])['personalDataCheck'] ?? false) { + $personalDataValidator = new PersonalData($user->getId(), $user->getAttribute('email'), $user->getAttribute('name'), $phone); + if (!$personalDataValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PERSONAL_DATA); + } + } + + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; + if ($passwordPwned) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]); $target = $authorization->skip(fn () => $dbForProject->findOne('targets', [ @@ -3712,8 +3816,12 @@ Http::patch('/v1/account/phone') ; if (empty($passwordUpdate)) { + $newPassword = $proofForPassword->hash($password); + $historyLimit = $project->getAttribute('auths', [])['passwordHistory'] ?? 0; $user - ->setAttribute('password', $proofForPassword->hash($password)) + ->setAttribute('password', $newPassword) + ->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : []) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -4098,7 +4206,8 @@ Http::put('/v1/account/recovery') ->inject('proofForPassword') ->inject('proofForToken') ->inject('authorization') - ->action(function (string $userId, string $secret, string $password, Response $response, User $user, Database $dbForProject, Document $project, Event $queueForEvents, Hooks $hooks, ProofsPassword $proofForPassword, ProofsToken $proofForToken, Authorization $authorization) { + ->inject('pwnedPasswords') + ->action(function (string $userId, string $secret, string $password, Response $response, User $user, Database $dbForProject, Document $project, Event $queueForEvents, Hooks $hooks, ProofsPassword $proofForPassword, ProofsToken $proofForToken, Authorization $authorization, PasswordPwned $pwnedPasswords) { /** @var Appwrite\Utopia\Database\Documents\User $profile */ $profile = $dbForProject->getDocument('users', $userId); @@ -4130,6 +4239,14 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } + // null when the policy did not look, false when it looked and found nothing + $passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? !$pwnedPasswords->isValid($password) + : null; + if ($passwordPwned) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); $sessions = $profile->getAttribute('sessions', []); @@ -4138,6 +4255,7 @@ Http::put('/v1/account/recovery') [ 'password' => $newPassword, 'passwordHistory' => $history, + 'passwordPwned' => $passwordPwned, 'passwordUpdate' => DateTime::now(), 'hash' => $proofForPassword->getHash()->getName(), 'hashOptions' => $proofForPassword->getHash()->getOptions(), diff --git a/app/init/models.php b/app/init/models.php index 3089e056cc..2eb36ce964 100644 --- a/app/init/models.php +++ b/app/init/models.php @@ -180,6 +180,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; @@ -470,6 +471,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()); diff --git a/app/init/resources/request.php b/app/init/resources/request.php index 9954f67260..10d8c8e29e 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -3,6 +3,10 @@ use Ahc\Jwt\JWT; use Ahc\Jwt\JWTException; use Appwrite\Auth\Key; +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\Auth\Validator\PasswordPwned\None as PasswordPwnedNone; use Appwrite\Database\Factory as DatabaseFactory; use Appwrite\Databases\TransactionState; use Appwrite\Deployment\Deployments; @@ -49,6 +53,7 @@ use Utopia\Database\Query; use Utopia\Database\Validator\Authorization; use Utopia\DI\Container; use Utopia\Domains\Domain; +use Utopia\DSN\DSN; use Utopia\Http\Http; use Utopia\Locale\Locale; use Utopia\Lock\Distributed as DistributedLock; @@ -663,6 +668,23 @@ return function (Container $context): void { return; }, ['user', 'store', 'proofForToken']); + $context->set('pwnedPasswords', function (Cache $cache) { + // Nothing is asked until an operator points this at a service + $dsn = new DSN(System::getEnv('_APP_PWNED_PASSWORDS_DSN', 'none://localhost')); + + return match ($dsn->getScheme()) { + 'hibp' => new PasswordPwnedHIBP($cache), + 'appwrite' => new PasswordPwnedAppwrite($dsn, $cache), + // Reports every password as safe by choice, for servers that cannot reach a breach service + 'none' => new PasswordPwnedNone(), + // 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 validator cannot be used in production.') + : new PasswordPwnedMock(), + default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown _APP_PWNED_PASSWORDS_DSN scheme: ' . $dsn->getScheme()), + }; + }, ['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) { if ($project->isEmpty() || $project->getId() === 'console') { return $dbForPlatform; diff --git a/docker-compose.yml b/docker-compose.yml index 83077ddc03..8862de0a9a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -254,6 +254,7 @@ services: - _APP_MIGRATION_HOST - _APP_GEO_SECRET - _APP_GEO_ENDPOINT + - _APP_PWNED_PASSWORDS_DSN - _APP_LIMIT_DATABASE_BATCH - _APP_DOCUMENTSDB - _APP_VECTORSDB diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php new file mode 100644 index 0000000000..fe6158a29b --- /dev/null +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -0,0 +1,119 @@ +allowEmpty && \strlen($value) === 0) { + return true; + } + + return !$this->isPwned($value); + } + + /** + * 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; + } + + /** + * Whether the password appears in a known data breach. + * + * A password is never silently accepted when the lookup did not happen, so + * an unreachable service raises `GENERAL_PWNED_PASSWORDS_UNAVAILABLE`. + * + * @throws Exception when the breach service cannot be reached or answers with nonsense + */ + abstract protected function isPwned(string $password): bool; + + /** + * Remembers what a breach service said, so the same question is not asked twice. + * + * Subclasses choose the key, because what is worth remembering differs: a + * whole range of hashes for one, a single answer for another. Nothing is + * stored when the lookup throws, so an outage is retried rather than + * remembered. + * + * @param callable(): array $resolve + * @return array + */ + protected function remember(string $key, callable $resolve): array + { + // A miss reads back as false, so an answer is always wrapped in an array + $cached = $this->cache?->load($key, static::CACHE_TTL); + + if (\is_array($cached)) { + return $cached; + } + + $answer = $resolve(); + + $this->cache?->save($key, $answer); + + return $answer; + } +} diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php new file mode 100644 index 0000000000..d9a758a0d1 --- /dev/null +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Appwrite.php @@ -0,0 +1,86 @@ +cache = $cache; + $scheme = $dsn->getParam('tls') === 'true' ? 'https' : 'http'; + $port = $dsn->getPort() !== null ? ':' . $dsn->getPort() : ''; + $path = $dsn->getPath(); + + $this->endpoint = $scheme . '://' . $dsn->getHost() . $port . '/' . ($path === '' || $path === null ? self::PATH : $path); + $this->secret = $dsn->getUser() ?? ''; + $this->client = $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); + } + + protected function isPwned(string $password): bool + { + // Keyed with the secret the service shares, so the cache never holds a crackable password hash + $key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . \hash_hmac('sha256', $password, $this->secret); + + $answer = $this->remember($key, function () use ($password) { + try { + $response = $this->client + ->addHeader('content-type', Client::CONTENT_TYPE_APPLICATION_JSON) + ->addHeader('authorization', 'Bearer ' . $this->secret) + ->fetch($this->endpoint, Client::METHOD_POST, [ + 'password' => $password, + ]); + } catch (\Throwable) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } + + // Anything else is the service's own error object: a rejected secret + // (401), a password it will not take (400) or a missing dataset (503) + if ($response->getStatusCode() !== 200) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } + + $body = \json_decode($response->text(), true); + + if (!\is_array($body) || !\is_bool($body['leaked'] ?? null)) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } + + return ['leaked' => $body['leaked']]; + }); + + return (bool) ($answer['leaked'] ?? false); + } +} diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php new file mode 100644 index 0000000000..603b18866b --- /dev/null +++ b/src/Appwrite/Auth/Validator/PasswordPwned/HIBP.php @@ -0,0 +1,93 @@ +cache = $cache; + $this->client = $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); + $this->endpoint = \rtrim($endpoint, '/'); + } + + protected 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 hash suffix => breach count + * @throws Exception when the service cannot be reached + */ + private function range(string $prefix): array + { + return $this->remember('pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix, function () use ($prefix) { + try { + $response = $this->client + ->addHeader('Add-Padding', 'true') + ->fetch($this->endpoint . '/' . $prefix); + } catch (\Throwable) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } + + if ($response->getStatusCode() !== 200) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_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; + } + } + + return $breaches; + }); + } +} diff --git a/src/Appwrite/Auth/Validator/PasswordPwned/Mock.php b/src/Appwrite/Auth/Validator/PasswordPwned/Mock.php new file mode 100644 index 0000000000..3be74fb19d --- /dev/null +++ b/src/Appwrite/Auth/Validator/PasswordPwned/Mock.php @@ -0,0 +1,31 @@ +createAttributeFromCollection($this->dbForProject, $id, 'passwordPwned'); + } catch (Throwable $th) { + Console::warning("Failed to create attribute \"passwordPwned\" in collection {$id}: {$th->getMessage()}"); + } + + try { + $this->createIndexFromCollection($this->dbForProject, $id, '_key_passwordPwned'); + } catch (Throwable $th) { + Console::warning("Failed to create index \"_key_passwordPwned\" from {$id}: {$th->getMessage()}"); + } + + $this->dbForProject->purgeCachedCollection($id); + break; + case 'identities': foreach (['photo', 'providerIdToken'] as $attribute) { try { diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php index 94e246a7ee..10d846791f 100644 --- a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php @@ -91,6 +91,11 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, + 'passwordPwned' => [ + 'enabled' => true, + 'sessions' => false, + 'users' => false, + ], 'disposableEmails' => false, 'canonicalEmails' => false, 'freeEmails' => false, diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php index a88237c360..9984257c66 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php @@ -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,16 @@ class Get extends Action ]), Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA, ], + 'password-pwned' => [ + new Document(\array_merge([ + 'enabled' => true, + 'sessions' => false, + 'users' => false, + ], $auths['passwordPwned'] ?? [], [ + '$id' => 'password-pwned', + ])), + Response::MODEL_POLICY_PASSWORD_PWNED, + ], 'session-alert' => [ new Document([ '$id' => 'session-alert', diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php new file mode 100644 index 0000000000..08b7e5fef8 --- /dev/null +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php @@ -0,0 +1,101 @@ +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: <<param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true to block passwords exposed in known data breaches, or false to allow them. Default is true. When changing this policy, existing passwords remain valid.', optional: true) + ->param('sessions', null, new Boolean(), 'Whether passwords are checked when a session is created. When enabled, signing in records whether the password appears in a known data breach. Default is false.', optional: true) + ->param('users', null, new Boolean(), 'Whether users signing in with a breached password are blocked until they reset it. Only applies when sessions are checked. Default is false, which allows the sign-in.', optional: true) + ->inject('response') + ->inject('dbForPlatform') + ->inject('project') + ->inject('authorization') + ->inject('queueForEvents') + ->callback($this->action(...)); + } + + public function action( + ?bool $enabled, + ?bool $sessions, + ?bool $users, + Response $response, + Database $dbForPlatform, + Document $project, + Authorization $authorization, + Event $queueForEvents, + ): void { + $auths = $project->getAttribute('auths', []); + $auths['passwordPwned'] = \array_merge([ + 'enabled' => true, + 'sessions' => false, + 'users' => false, + ], $auths['passwordPwned'] ?? []); + + if ($enabled !== null) { + $auths['passwordPwned']['enabled'] = $enabled; + } + if ($sessions !== null) { + $auths['passwordPwned']['sessions'] = $sessions; + } + if ($users !== null) { + $auths['passwordPwned']['users'] = $users; + } + + $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), new Document([ + 'auths' => $auths, + ]))); + $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); + + $queueForEvents + ->setParam('projectId', $project->getId()) + ->setParam('policy', 'password-pwned'); + + $response->dynamic($project, Response::MODEL_PROJECT); + } +} diff --git a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php index 0bcf3ffcbc..32bbaa2e7d 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php @@ -116,6 +116,13 @@ class XList extends Action '$id' => 'password-personal-data', 'enabled' => $auths['personalDataCheck'] ?? false, ]), + new Document(\array_merge([ + 'enabled' => true, + 'sessions' => false, + 'users' => false, + ], $auths['passwordPwned'] ?? [], [ + '$id' => 'password-pwned', + ])), new Document([ '$id' => 'session-alert', 'enabled' => $auths['sessionAlerts'] ?? false, diff --git a/src/Appwrite/Platform/Modules/Project/Services/Http.php b/src/Appwrite/Platform/Modules/Project/Services/Http.php index 0cdf4238ee..3e180afc84 100644 --- a/src/Appwrite/Platform/Modules/Project/Services/Http.php +++ b/src/Appwrite/Platform/Modules/Project/Services/Http.php @@ -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()); diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php index f65ca3eae9..f5a689adeb 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php @@ -88,6 +88,11 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, + 'passwordPwned' => [ + 'enabled' => true, + 'sessions' => false, + 'users' => false, + ], 'disposableEmails' => false, 'canonicalEmails' => false, 'freeEmails' => false, diff --git a/src/Appwrite/Platform/Modules/Users/Base.php b/src/Appwrite/Platform/Modules/Users/Base.php index 232d4fd52d..bd48b7b015 100644 --- a/src/Appwrite/Platform/Modules/Users/Base.php +++ b/src/Appwrite/Platform/Modules/Users/Base.php @@ -21,7 +21,7 @@ use Utopia\Emails\Email; class Base extends Action { - protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan): Document + protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan, ?bool $passwordPwned = null): Document { $name = $name ?? ''; $plaintextPassword = $password; @@ -144,6 +144,7 @@ class Base extends Action 'emailIsCorporate' => $emailMetadata['emailIsCorporate'], 'emailIsDisposable' => $emailMetadata['emailIsDisposable'], 'emailIsFree' => $emailMetadata['emailIsFree'], + 'passwordPwned' => $passwordPwned, ]); if (!$isHashed && !empty($password)) { diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php index 16bb0ece33..54dd362269 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php @@ -3,8 +3,10 @@ namespace Appwrite\Platform\Modules\Users\Http\Users; use Appwrite\Auth\Validator\PasswordDictionary; +use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Auth\Validator\PasswordStrength; use Appwrite\Auth\Validator\Phone; +use Appwrite\Extend\Exception; use Appwrite\Hooks\Hooks; use Appwrite\Platform\Action; use Appwrite\Platform\Modules\Users\Base; @@ -66,14 +68,22 @@ class Create extends Base ->inject('dbForProject') ->inject('hooks') ->inject('plan') + ->inject('pwnedPasswords') ->callback($this->action(...)); } - public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan): void + 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) || !($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? null + : !$pwnedPasswords->isValid($password); + if ($passwordPwned) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + $plaintext = new Plaintext(); - $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan); + $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan, $passwordPwned); $response ->setStatusCode(Response::STATUS_CODE_CREATED) diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php index 53651bb885..2efba854a0 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -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; @@ -66,10 +67,11 @@ class Update extends Action ->inject('dbForProject') ->inject('queueForEvents') ->inject('hooks') + ->inject('pwnedPasswords') ->callback($this->action(...)); } - public function action(string $userId, string $password, Response $response, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks): void + public function action(string $userId, string $password, Response $response, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks, PasswordPwned $pwnedPasswords): void { $user = $dbForProject->getDocument('users', $userId); @@ -84,6 +86,13 @@ class Update extends Action } } + $passwordPwned = \strlen($password) === 0 || !($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true) + ? null + : !$pwnedPasswords->isValid($password); + if ($passwordPwned) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + if (\strlen($password) === 0) { $user ->setAttribute('password', '') @@ -91,6 +100,7 @@ class Update extends Action $user = $dbForProject->updateDocument('users', $user->getId(), new Document([ 'password' => $user->getAttribute('password'), + 'passwordPwned' => null, 'passwordUpdate' => $user->getAttribute('passwordUpdate'), ])); $queueForEvents->setParam('userId', $user->getId()); @@ -121,6 +131,7 @@ class Update extends Action $user ->setAttribute('password', $newPassword) ->setAttribute('passwordHistory', $history) + ->setAttribute('passwordPwned', $passwordPwned) ->setAttribute('passwordUpdate', DateTime::now()) ->setAttribute('hash', $hasher->getName()) ->setAttribute('hashOptions', $hasher->getOptions()); @@ -128,6 +139,7 @@ class Update extends Action $user = $dbForProject->updateDocument('users', $user->getId(), new Document([ 'password' => $user->getAttribute('password'), 'passwordHistory' => $user->getAttribute('passwordHistory'), + 'passwordPwned' => $user->getAttribute('passwordPwned'), 'passwordUpdate' => $user->getAttribute('passwordUpdate'), 'hash' => $user->getAttribute('hash'), 'hashOptions' => $user->getAttribute('hashOptions'), diff --git a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php index e38cd6c397..e2e721c8c2 100644 --- a/src/Appwrite/Utopia/Database/Validator/Queries/Users.php +++ b/src/Appwrite/Utopia/Database/Validator/Queries/Users.php @@ -13,6 +13,7 @@ class Users extends Base 'registration', 'emailVerification', 'phoneVerification', + 'passwordPwned', 'labels', 'impersonator', 'accessedAt', diff --git a/src/Appwrite/Utopia/Response.php b/src/Appwrite/Utopia/Response.php index c1b7173bdd..60985c8145 100644 --- a/src/Appwrite/Utopia/Response.php +++ b/src/Appwrite/Utopia/Response.php @@ -262,6 +262,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'; diff --git a/src/Appwrite/Utopia/Response/Model/Account.php b/src/Appwrite/Utopia/Response/Model/Account.php index 769284d714..c716c24649 100644 --- a/src/Appwrite/Utopia/Response/Model/Account.php +++ b/src/Appwrite/Utopia/Response/Model/Account.php @@ -113,6 +113,13 @@ class Account extends Model 'default' => null, 'example' => true, ]) + ->addRule('passwordPwned', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.', + 'required' => false, + 'default' => null, + 'example' => false, + ]) ->addRule('phoneVerification', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Phone verification status.', diff --git a/src/Appwrite/Utopia/Response/Model/PolicyList.php b/src/Appwrite/Utopia/Response/Model/PolicyList.php index 894324a5d4..808e93c815 100644 --- a/src/Appwrite/Utopia/Response/Model/PolicyList.php +++ b/src/Appwrite/Utopia/Response/Model/PolicyList.php @@ -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, diff --git a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php new file mode 100644 index 0000000000..d1352e078e --- /dev/null +++ b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php @@ -0,0 +1,47 @@ + 'password-pwned', + ]; + + public function __construct() + { + parent::__construct(); + + $this + ->addRule('enabled', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether password pwned policy is enabled.', + 'default' => true, + 'example' => true, + ]) + ->addRule('sessions', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether passwords are checked when a session is created.', + 'default' => false, + 'example' => false, + ]) + ->addRule('users', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether users signing in with a breached password are blocked until they reset it. Only applies when sessions are checked.', + 'default' => false, + 'example' => false, + ]); + } + + public function getName(): string + { + return 'Policy Password Pwned'; + } + + public function getType(): string + { + return Response::MODEL_POLICY_PASSWORD_PWNED; + } +} diff --git a/src/Appwrite/Utopia/Response/Model/User.php b/src/Appwrite/Utopia/Response/Model/User.php index da1f7fe5fc..91d4ca7e54 100644 --- a/src/Appwrite/Utopia/Response/Model/User.php +++ b/src/Appwrite/Utopia/Response/Model/User.php @@ -143,6 +143,13 @@ class User extends Model 'default' => null, 'example' => true, ]) + ->addRule('passwordPwned', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.', + 'required' => false, + 'default' => null, + 'example' => false, + ]) ->addRule('phoneVerification', [ 'type' => self::TYPE_BOOLEAN, 'description' => 'Phone verification status.', diff --git a/tests/e2e/Services/Project/PoliciesBase.php b/tests/e2e/Services/Project/PoliciesBase.php index 43cbe1a53e..a50d8c707b 100644 --- a/tests/e2e/Services/Project/PoliciesBase.php +++ b/tests/e2e/Services/Project/PoliciesBase.php @@ -17,6 +17,7 @@ trait PoliciesBase 'password-history' => ['total'], 'password-strength' => ['min', 'uppercase', 'lowercase', 'number', 'symbols'], 'password-personal-data' => ['enabled'], + 'password-pwned' => ['enabled', 'sessions', 'users'], 'session-alert' => ['enabled'], 'session-duration' => ['duration'], 'session-invalidation' => ['enabled'], @@ -635,6 +636,122 @@ trait PoliciesBase $this->assertSame(401, $response['headers']['status-code']); } + // ========================================================================= + // Password Pwned Policy + // ========================================================================= + + public function testUpdatePasswordPwnedPolicyEnable(): void + { + $response = $this->updatePasswordPwnedPolicy(['enabled' => 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']); + $this->assertSame(false, $policy['body']['sessions']); + $this->assertSame(false, $policy['body']['users']); + + // Cleanup + $this->updatePasswordPwnedPolicy(['enabled' => false]); + } + + public function testUpdatePasswordPwnedPolicyDisable(): void + { + $this->updatePasswordPwnedPolicy(['enabled' => true]); + + $response = $this->updatePasswordPwnedPolicy(['enabled' => 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 testUpdatePasswordPwnedPolicyDefaults(): void + { + $this->resetPasswordPwnedPolicy(); + + $policy = $this->getPolicy('password-pwned'); + + $this->assertSame(200, $policy['headers']['status-code']); + $this->assertSame('password-pwned', $policy['body']['$id']); + $this->assertSame(true, $policy['body']['enabled']); + $this->assertSame(false, $policy['body']['sessions']); + $this->assertSame(false, $policy['body']['users']); + } + + public function testUpdatePasswordPwnedPolicySessions(): void + { + $response = $this->updatePasswordPwnedPolicy(['sessions' => true]); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(true, $policy['body']['sessions']); + + $response = $this->updatePasswordPwnedPolicy(['sessions' => false]); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(false, $policy['body']['sessions']); + } + + public function testUpdatePasswordPwnedPolicyOptionPreservesOtherOptions(): void + { + $response = $this->updatePasswordPwnedPolicy([ + 'sessions' => true, + 'users' => true, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $response = $this->updatePasswordPwnedPolicy(['enabled' => true]); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(true, $policy['body']['enabled']); + $this->assertSame(true, $policy['body']['sessions']); + $this->assertSame(true, $policy['body']['users']); + + // Cleanup + $this->resetPasswordPwnedPolicy(); + } + + public function testUpdatePasswordPwnedPolicyEmptyBody(): void + { + $this->resetPasswordPwnedPolicy(); + + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), []); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(true, $policy['body']['enabled']); + $this->assertSame(false, $policy['body']['sessions']); + $this->assertSame(false, $policy['body']['users']); + } + + public function testUpdatePasswordPwnedPolicyInvalidType(): void + { + foreach (['enabled', 'sessions', 'users'] as $option) { + $response = $this->updatePasswordPwnedPolicy([$option => 'not-a-boolean']); + + $this->assertSame(400, $response['headers']['status-code'], $option); + } + } + + public function testUpdatePasswordPwnedPolicyWithoutAuth(): void + { + $response = $this->updatePasswordPwnedPolicy(['enabled' => true], false); + + $this->assertSame(401, $response['headers']['status-code']); + } + // ========================================================================= // Session Alert Policy // ========================================================================= @@ -1329,6 +1446,23 @@ trait PoliciesBase ]); } + /** + * @param array $params + */ + protected function updatePasswordPwnedPolicy(array $params, bool $authenticated = true): mixed + { + return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders($authenticated), $params); + } + + protected function resetPasswordPwnedPolicy(): void + { + $this->updatePasswordPwnedPolicy([ + 'enabled' => true, + 'sessions' => false, + 'users' => false, + ]); + } + protected function updateSessionAlertPolicy(bool $enabled, bool $authenticated = true): mixed { return $this->client->call(Client::METHOD_PATCH, '/project/policies/session-alert', $this->buildHeaders($authenticated), [ diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php new file mode 100644 index 0000000000..05d001f109 --- /dev/null +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -0,0 +1,1036 @@ +getProject(fresh: true); + + $headers = [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $project['$id'], + 'x-appwrite-key' => $project['apiKey'], + ]; + + $response = $this->client->call(Client::METHOD_GET, '/project/policies/password-pwned', $headers); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertSame('password-pwned', $response['body']['$id']); + + // Breached passwords are rejected out of the box + $this->assertTrue($response['body']['enabled']); + + // Sign-in checks stay opt-in + $this->assertFalse($response['body']['sessions']); + $this->assertFalse($response['body']['users']); + + // A breached password is blocked without touching the policy + $response = $this->client->call(Client::METHOD_POST, '/users', $headers, [ + 'userId' => ID::unique(), + 'email' => 'pwned_default_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Default Policy User', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + } + + public function testCreateUserWithPolicyDisabled(): void + { + $this->updatePolicy(['enabled' => 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(['enabled' => 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(['enabled' => false]); + } + + public function testUpdateUserPasswordWithPolicyEnabled(): void + { + $this->updatePolicy(['enabled' => 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(['enabled' => false]); + } + + public function testCreateAccountWithPolicyEnabled(): void + { + $this->updatePolicy(['enabled' => 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(['enabled' => false]); + } + + public function testUpdateAccountPasswordWithPolicyEnabled(): void + { + $this->updatePolicy(['enabled' => 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(['enabled' => false]); + } + + public function testUpdateAccountRecoveryWithPolicyEnabled(): void + { + $this->updatePolicy(['enabled' => 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(['enabled' => false]); + } + + public function testSignInBlockedUntilReset(): void + { + $this->updatePolicy(['enabled' => false]); + + $email = 'pwned_signin_' . \uniqid() . '@localhost.test'; + + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Sign In User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + + /** + * Test for SUCCESS + */ + $this->updatePolicy(['enabled' => true, 'sessions' => true, 'users' => false]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + /** + * Test for FAILURE + */ + $this->updatePolicy(['users' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(412, $response['headers']['status-code']); + $this->assertSame('user_password_reset_required', $response['body']['type']); + + // A wrong password is still reported as such, not as a reset + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => 'wrong-' . self::PWNED_PASSWORD, + ]); + + $this->assertSame(401, $response['headers']['status-code']); + $this->assertSame('user_invalid_credentials', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $password = $this->cleanPassword(); + + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $user['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + $this->updatePolicy(['enabled' => false, 'sessions' => false, 'users' => false]); + } + + public function testSessionChecksAreOptional(): void + { + $this->updatePolicy(['enabled' => false]); + + $email = 'pwned_sessions_' . \uniqid() . '@localhost.test'; + + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Sessions User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + $this->assertNull($user['body']['passwordPwned']); + + /** + * Test for SUCCESS + */ + // Sign-in checks are off by default, so a forced reset has nothing to act on + $this->updatePolicy(['enabled' => true, 'sessions' => false, 'users' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + // Nothing was looked up, so nothing was recorded + $response = $this->client->call(Client::METHOD_GET, '/users/' . $user['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertNull($response['body']['passwordPwned']); + + // Checking sessions without forcing a reset records the breach and still allows the sign-in + $this->updatePolicy(['sessions' => true, 'users' => false]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $user['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertTrue($response['body']['passwordPwned']); + + /** + * Test for FAILURE + */ + $this->updatePolicy(['users' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(412, $response['headers']['status-code']); + $this->assertSame('user_password_reset_required', $response['body']['type']); + + $this->updatePolicy(['enabled' => false, 'sessions' => false, 'users' => false]); + } + + public function testUpdateAnonymousAccountEmail(): void + { + $this->updatePolicy(['enabled' => true]); + + $headers = $this->anonymousHeaders(); + $email = 'pwned_anonymous_' . \uniqid() . '@localhost.test'; + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + // Strength policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->serverHeaders(), ['min' => 12]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => 'Short1!x', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('general_argument_invalid', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->serverHeaders(), ['min' => 8]); + + // Dictionary policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-dictionary', $this->serverHeaders(), ['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => 'football', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('general_argument_invalid', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-dictionary', $this->serverHeaders(), ['enabled' => false]); + + // Personal data policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-personal-data', $this->serverHeaders(), ['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => \explode('@', $email)[0] . '-Pw!', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_personal_data', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-personal-data', $this->serverHeaders(), ['enabled' => false]); + + /** + * Test for SUCCESS + */ + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-history', $this->serverHeaders(), ['total' => 1]); + + $password = $this->cleanPassword(); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertSame($email, $response['body']['email']); + + // The first password entered the history, so it cannot be reused + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => $password, + 'oldPassword' => $password, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_recently_used', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-history', $this->serverHeaders(), ['total' => 0]); + $this->updatePolicy(['enabled' => false]); + } + + public function testUpdateAnonymousAccountPhone(): void + { + $this->updatePolicy(['enabled' => true]); + + $headers = $this->anonymousHeaders(); + $phone = '+15' . \random_int(100000000, 999999999); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => 'short', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('general_argument_invalid', $response['body']['type']); + + // Dictionary policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-dictionary', $this->serverHeaders(), ['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => 'football', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('general_argument_invalid', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-dictionary', $this->serverHeaders(), ['enabled' => false]); + + // Personal data policy + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-personal-data', $this->serverHeaders(), ['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => 'pw-' . \substr($phone, 1) . '!', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_personal_data', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-personal-data', $this->serverHeaders(), ['enabled' => false]); + + /** + * Test for SUCCESS + */ + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-history', $this->serverHeaders(), ['total' => 1]); + + $password = $this->cleanPassword(); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/phone', $headers, [ + 'phone' => $phone, + 'password' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertSame($phone, $response['body']['phone']); + + // The first password entered the history, so it cannot be reused + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => $password, + 'oldPassword' => $password, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_recently_used', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-history', $this->serverHeaders(), ['total' => 0]); + $this->updatePolicy(['enabled' => false]); + } + + public function testUpdateAccountEmailWithExistingPassword(): void + { + $this->updatePolicy(['enabled' => false]); + + $email = 'pwned_existing_' . \uniqid() . '@localhost.test'; + + $account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Existing Account', + ]); + + $this->assertSame(201, $account['headers']['status-code']); + + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $session['headers']['status-code']); + + $projectId = $this->getProject()['$id']; + $headers = \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId], + ]); + + // Policies tightened after the password was set only apply to new passwords + $this->updatePolicy(['enabled' => true]); + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->serverHeaders(), ['min' => 20]); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => 'pwned_existing_new_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $headers, [ + 'email' => 'pwned_existing_wrong_' . \uniqid() . '@localhost.test', + 'password' => 'wrong-' . self::PWNED_PASSWORD, + ]); + + $this->assertSame(401, $response['headers']['status-code']); + $this->assertSame('user_invalid_credentials', $response['body']['type']); + + $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->serverHeaders(), ['min' => 8]); + $this->updatePolicy(['enabled' => false]); + } + + public function testPasswordPwnedFlag(): void + { + // Policy off: nothing is known about the password + $this->updatePolicy(['enabled' => false]); + + $emailA = 'pwned_flag_a_' . \uniqid() . '@localhost.test'; + + $userA = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $emailA, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Flag User A', + ]); + + $this->assertSame(201, $userA['headers']['status-code']); + $this->assertArrayHasKey('passwordPwned', $userA['body']); + $this->assertNull($userA['body']['passwordPwned']); + + // Policy on, with sign-in checks: a clean password is recorded as clean + $this->updatePolicy(['enabled' => true, 'sessions' => true]); + + $userB = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_flag_b_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Flag User B', + ]); + + $this->assertSame(201, $userB['headers']['status-code']); + $this->assertFalse($userB['body']['passwordPwned']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $userB['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + // A hashed import never sees the plaintext, so nothing is known + $userC = $this->client->call(Client::METHOD_POST, '/users/sha', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_flag_c_' . \uniqid() . '@localhost.test', + 'password' => \sha1(self::PWNED_PASSWORD), + 'passwordVersion' => 'sha1', + 'name' => 'Flag User C', + ]); + + $this->assertSame(201, $userC['headers']['status-code']); + $this->assertNull($userC['body']['passwordPwned']); + + // Signing in records a breached password, on the users and the account API + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $emailA, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(201, $session['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $userA['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertArrayHasKey('passwordPwned', $response['body']); + $this->assertTrue($response['body']['passwordPwned']); + + $projectId = $this->getProject()['$id']; + $response = $this->client->call(Client::METHOD_GET, '/account', \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId], + ])); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertArrayHasKey('passwordPwned', $response['body']); + $this->assertTrue($response['body']['passwordPwned']); + + // A user that was never checked reports the flag as null on the users API + $response = $this->client->call(Client::METHOD_GET, '/users/' . $userC['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertArrayHasKey('passwordPwned', $response['body']); + $this->assertNull($response['body']['passwordPwned']); + + // Listing users returns the flag and can filter on it + $userAId = $userA['body']['$id']; + $userBId = $userB['body']['$id']; + $userCId = $userC['body']['$id']; + + $list = function (?string $filter) { + $queries = [ + Query::orderDesc('$createdAt')->toString(), + Query::limit(100)->toString(), + ]; + + if ($filter !== null) { + \array_unshift($queries, $filter); + } + + $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ + 'queries' => $queries, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $users = []; + foreach ($response['body']['users'] as $user) { + $users[$user['$id']] = $user; + } + + return $users; + }; + + // Every listed user carries the flag, whether or not it was ever checked + $listed = $list(null); + + $this->assertArrayHasKey('passwordPwned', $listed[$userAId]); + $this->assertTrue($listed[$userAId]['passwordPwned']); + $this->assertFalse($listed[$userBId]['passwordPwned']); + $this->assertNull($listed[$userCId]['passwordPwned']); + + // Breached passwords only + $listed = $list(Query::equal('passwordPwned', [true])->toString()); + + $this->assertArrayHasKey($userAId, $listed); + $this->assertArrayNotHasKey($userBId, $listed); + $this->assertArrayNotHasKey($userCId, $listed); + + foreach ($listed as $user) { + $this->assertTrue($user['passwordPwned']); + } + + // Clean passwords only + $listed = $list(Query::equal('passwordPwned', [false])->toString()); + + $this->assertArrayHasKey($userBId, $listed); + $this->assertArrayNotHasKey($userAId, $listed); + $this->assertArrayNotHasKey($userCId, $listed); + + foreach ($listed as $user) { + $this->assertFalse($user['passwordPwned']); + } + + // Never checked + $listed = $list(Query::isNull('passwordPwned')->toString()); + + $this->assertArrayHasKey($userCId, $listed); + $this->assertArrayNotHasKey($userAId, $listed); + $this->assertArrayNotHasKey($userBId, $listed); + + foreach ($listed as $user) { + $this->assertNull($user['passwordPwned']); + } + + // Checked at least once + $listed = $list(Query::isNotNull('passwordPwned')->toString()); + + $this->assertArrayHasKey($userAId, $listed); + $this->assertArrayHasKey($userBId, $listed); + $this->assertArrayNotHasKey($userCId, $listed); + + foreach ($listed as $user) { + $this->assertNotNull($user['passwordPwned']); + } + + // A clean password clears the flag + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userA['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + // Without the policy a new password is unknown again + $this->updatePolicy(['enabled' => false]); + + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userA['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertNull($response['body']['passwordPwned']); + + // Clearing the password clears the flag + $this->updatePolicy(['enabled' => true]); + + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userB['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => '', + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertNull($response['body']['passwordPwned']); + + $this->updatePolicy(['enabled' => false]); + } + + public function testPasswordPwnedFlagOnAccount(): void + { + $this->updatePolicy(['enabled' => true]); + + $email = 'pwned_flag_account_' . \uniqid() . '@localhost.test'; + $password = $this->cleanPassword(); + + /** + * Test for SUCCESS + */ + $account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => $password, + 'name' => 'Flag Account', + ]); + + $this->assertSame(201, $account['headers']['status-code']); + $this->assertFalse($account['body']['passwordPwned']); + + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(201, $session['headers']['status-code']); + + $projectId = $this->getProject()['$id']; + $headers = \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId], + ]); + + $response = $this->client->call(Client::METHOD_GET, '/account', $headers); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => $this->cleanPassword(), + 'oldPassword' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + // Recovery records the new password too + $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']; + + $response = $this->client->call(Client::METHOD_PUT, '/account/recovery', $this->clientHeaders(), [ + 'userId' => $account['body']['$id'], + 'secret' => $secret, + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $account['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + // Anonymous conversions record the first password + $response = $this->client->call(Client::METHOD_PATCH, '/account/email', $this->anonymousHeaders(), [ + 'email' => 'pwned_flag_anonymous_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertFalse($response['body']['passwordPwned']); + + /** + * Test for FAILURE + */ + // A forced reset still records the breach before blocking the sign-in + $this->updatePolicy(['enabled' => false]); + + $emailD = 'pwned_flag_d_' . \uniqid() . '@localhost.test'; + + $userD = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $emailD, + 'password' => self::PWNED_PASSWORD, + 'name' => 'Flag User D', + ]); + + $this->assertSame(201, $userD['headers']['status-code']); + $this->assertNull($userD['body']['passwordPwned']); + + $this->updatePolicy(['enabled' => true, 'sessions' => true, 'users' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $emailD, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(412, $response['headers']['status-code']); + $this->assertSame('user_password_reset_required', $response['body']['type']); + + $response = $this->client->call(Client::METHOD_GET, '/users/' . $userD['body']['$id'], $this->serverHeaders()); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertTrue($response['body']['passwordPwned']); + + // Filtering on an attribute outside the whitelist is rejected + $response = $this->client->call(Client::METHOD_GET, '/users', $this->serverHeaders(), [ + 'queries' => [Query::equal('passwordHistory', ['x'])->toString()], + ]); + + $this->assertSame(400, $response['headers']['status-code']); + + $this->updatePolicy(['enabled' => false, 'sessions' => false, 'users' => false]); + } + + /** + * Client headers carrying a fresh anonymous session. + * + * @return array + */ + private function anonymousHeaders(): array + { + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/anonymous', $this->clientHeaders()); + + $this->assertSame(201, $session['headers']['status-code']); + + $projectId = $this->getProject()['$id']; + + return \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $projectId . '=' . $session['cookies']['a_session_' . $projectId], + ]); + } + + /** + * @param array $params + */ + private function updatePolicy(array $params): void + { + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->serverHeaders(), $params); + + $this->assertSame(200, $response['headers']['status-code']); + } + + /** + * @return array + */ + private function serverHeaders(): array + { + return \array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $this->getProject()['$id'], + ], $this->getHeaders()); + } + + /** + * @return array + */ + 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!'; + } +} diff --git a/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php new file mode 100644 index 0000000000..0d9c1cd194 --- /dev/null +++ b/tests/unit/Auth/Validator/PasswordPwned/AppwriteTest.php @@ -0,0 +1,212 @@ +assertFalse($this->validator($fetch)->isValid(self::PASSWORD)); + } + + public function testCleanPasswordIsAccepted(): void + { + $fetch = new DetectionFetch(body: '{"leaked":false}'); + + $this->assertTrue($this->validator($fetch)->isValid(self::PASSWORD)); + } + + public function testThePasswordIsSentAsIsWithTheSharedSecretAsBearerToken(): void + { + $fetch = new DetectionFetch(body: '{"leaked":false}'); + + $this->validator($fetch)->isValid(self::PASSWORD); + + $this->assertCount(1, $fetch->requests); + $this->assertSame('POST', $fetch->requests[0]['method']); + + // The service hashes the password itself, so it travels in the clear + $this->assertSame(['password' => self::PASSWORD], \json_decode($fetch->requests[0]['body'], true)); + + $headers = \array_change_key_case($fetch->requests[0]['headers'], CASE_LOWER); + $this->assertSame('Bearer ' . self::SECRET, $headers['authorization'] ?? null); + $this->assertSame('application/json', $headers['content-type'] ?? null); + } + + public function testTheDsnDescribesWhereAndHowToConnect(): void + { + $cases = [ + 'appwrite://secret@pwned.test/v1/detection' => 'http://pwned.test/v1/detection', + // The path the service exposes is assumed when the DSN leaves it out + 'appwrite://secret@pwned.test' => 'http://pwned.test/v1/detection', + 'appwrite://secret@pwned.test:8088' => 'http://pwned.test:8088/v1/detection', + 'appwrite://secret@pwned.test/custom/path' => 'http://pwned.test/custom/path', + 'appwrite://secret@pwned.test?tls=true' => 'https://pwned.test/v1/detection', + ]; + + foreach ($cases as $dsn => $expected) { + $fetch = new DetectionFetch(body: '{"leaked":false}'); + + (new Appwrite(new DSN($dsn), null, new Client($fetch)))->isValid(self::PASSWORD); + + $this->assertSame($expected, $fetch->requests[0]['url'], $dsn); + } + } + + public function testUnreachableServiceIsReported(): void + { + $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()); + } + } + + /** + * The service answers every failure with its own error object; none of them may pass as a clean password. + */ + public function testServiceErrorsAreReported(): void + { + $errors = [ + 401 => '{"type":"general_unauthorized","message":"Missing or invalid Bearer token in the Authorization header.","code":401,"version":"0.2.0"}', + 400 => '{"type":"general_argument_invalid","message":"Invalid `password` param: Value must be a valid string and at least 1 chars and no longer than 256 chars","code":400,"version":"0.2.0"}', + 503 => '{"type":"dataset_unavailable","message":"The password dataset could not be read.","code":503,"version":"0.2.0"}', + 500 => '', + ]; + + foreach ($errors as $statusCode => $body) { + $fetch = new DetectionFetch(statusCode: $statusCode, body: $body); + + try { + $this->validator($fetch)->isValid(self::PASSWORD); + $this->fail('Expected a ' . $statusCode . ' to surface'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType(), (string) $statusCode); + } + } + } + + /** + * 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()); + } + } + } + + public function testAnswersAreCached(): void + { + $fetch = new DetectionFetch(body: '{"leaked":true}'); + $cache = new Cache(new Memory()); + + $this->assertFalse((new Appwrite(new DSN(self::DSN), $cache, new Client($fetch)))->isValid(self::PASSWORD)); + $this->assertFalse((new Appwrite(new DSN(self::DSN), $cache, new Client($fetch)))->isValid(self::PASSWORD)); + + $this->assertCount(1, $fetch->requests); + } + + public function testEachPasswordGetsItsOwnAnswer(): void + { + $fetch = new DetectionFetch(body: '{"leaked":true}'); + $cache = new Cache(new Memory()); + $validator = new Appwrite(new DSN(self::DSN), $cache, new Client($fetch)); + + $validator->isValid(self::PASSWORD); + $validator->isValid('a-completely-different-password'); + + $this->assertCount(2, $fetch->requests); + } + + public function testCacheIsScopedToEndpoint(): void + { + $fetch = new DetectionFetch(body: '{"leaked":true}'); + $cache = new Cache(new Memory()); + + (new Appwrite(new DSN('appwrite://secret@one.test'), $cache, new Client($fetch)))->isValid(self::PASSWORD); + (new Appwrite(new DSN('appwrite://secret@two.test'), $cache, new Client($fetch)))->isValid(self::PASSWORD); + + $this->assertCount(2, $fetch->requests); + } + + public function testFailedLookupIsNotCached(): void + { + $fetch = new DetectionFetch(failure: new \RuntimeException('connection refused')); + $validator = new Appwrite(new DSN(self::DSN), new Cache(new Memory()), new Client($fetch)); + + foreach ([1, 2] as $attempt) { + try { + $validator->isValid(self::PASSWORD); + } catch (Exception) { + // The lookup failed, which is the point; it must be retried rather than remembered + } + } + + $this->assertCount(2, $fetch->requests); + } + + private function validator(DetectionFetch $fetch): Appwrite + { + return new Appwrite(new DSN(self::DSN), null, new Client($fetch)); + } +} + +final class DetectionFetch implements Adapter +{ + /** @var array}> */ + 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, 'headers' => $headers]; + + if ($this->failure !== null) { + throw $this->failure; + } + + return new Response($this->statusCode, $this->body, []); + } +} diff --git a/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php b/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php new file mode 100644 index 0000000000..d14636122f --- /dev/null +++ b/tests/unit/Auth/Validator/PasswordPwned/HIBPTest.php @@ -0,0 +1,198 @@ +range([self::LEAKED => 42])); + + $this->assertFalse($this->validator($fetch)->isValid(self::LEAKED)); + } + + public function testCleanPasswordIsAccepted(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); + + $this->assertTrue($this->validator($fetch)->isValid('never-leaked-' . \uniqid())); + } + + public function testAnySingleBreachIsEnough(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 1])); + + $this->assertFalse($this->validator($fetch)->isValid(self::LEAKED)); + } + + public function testPaddedEntryWithZeroCountIsNotABreach(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 0])); + + $this->assertTrue($this->validator($fetch)->isValid(self::LEAKED)); + } + + public function testSuffixComparisonIgnoresCase(): void + { + $fetch = new RangeFetch(body: \strtolower($this->range([self::LEAKED => 3]))); + + $this->assertFalse($this->validator($fetch)->isValid(self::LEAKED)); + } + + public function testOnlyTheHashPrefixLeavesTheServer(): void + { + $fetch = new RangeFetch(body: ''); + + $this->validator($fetch)->isValid(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->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); + } + + public function testCacheIsScopedToEndpoint(): void + { + $fetch = new RangeFetch(body: $this->range([self::LEAKED => 42])); + $cache = new Cache(new Memory()); + + (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); + } + + public function testLookupsGoToTheConfiguredEndpoint(): void + { + $fetch = new RangeFetch(body: ''); + + (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]); + } + + public function testUnreachableServiceIsReported(): void + { + $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); + + try { + $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()); + } + } + + public function testUnexpectedStatusIsReported(): void + { + $fetch = new RangeFetch(statusCode: 503, body: ''); + + $this->expectException(Exception::class); + + $this->validator($fetch)->isValid(self::LEAKED); + } + + public function testFailedLookupIsNotCached(): void + { + $fetch = new RangeFetch(failure: new \RuntimeException('connection refused')); + $validator = new HIBP(new Cache(new Memory()), new Client($fetch), self::ENDPOINT); + + 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, $fetch->urls); + } + + private function validator(RangeFetch $fetch): HIBP + { + return new HIBP(null, new Client($fetch), self::ENDPOINT); + } + + /** + * 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 $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 URLs the validator 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, []); + } +} diff --git a/tests/unit/Auth/Validator/PasswordPwned/MockTest.php b/tests/unit/Auth/Validator/PasswordPwned/MockTest.php new file mode 100644 index 0000000000..efa712ce5e --- /dev/null +++ b/tests/unit/Auth/Validator/PasswordPwned/MockTest.php @@ -0,0 +1,38 @@ +assertFalse($validator->isValid($password), $password); + } + } + + public function testAnythingElseIsAccepted(): void + { + $validator = new Mock(); + + $this->assertTrue($validator->isValid('some-other-password')); + } + + public function testMatchingIsExact(): void + { + $validator = new Mock(); + $fixture = Mock::BREACHED[0]; + + // A password that merely resembles a fixture is not breached + $this->assertTrue($validator->isValid(\strtoupper($fixture))); + $this->assertTrue($validator->isValid($fixture . '!')); + $this->assertTrue($validator->isValid(\substr($fixture, 1))); + } +} diff --git a/tests/unit/Auth/Validator/PasswordPwned/NoneTest.php b/tests/unit/Auth/Validator/PasswordPwned/NoneTest.php new file mode 100644 index 0000000000..c6ebb3b872 --- /dev/null +++ b/tests/unit/Auth/Validator/PasswordPwned/NoneTest.php @@ -0,0 +1,36 @@ +assertTrue($validator->isValid($password), $password); + } + } + + public function testBasePasswordRulesStillApply(): void + { + $validator = new None(); + + $this->assertFalse($validator->isValid('short')); + $this->assertFalse($validator->isValid(\str_repeat('p', 257))); + $this->assertFalse($validator->isValid('')); + } + + public function testAllowEmptyAcceptsAnEmptyPassword(): void + { + $this->assertTrue((new None(allowEmpty: true))->isValid('')); + } +} diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php new file mode 100644 index 0000000000..b5e95ef59f --- /dev/null +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -0,0 +1,40 @@ +assertFalse($validator->isValid(self::BREACHED)); + $this->assertTrue($validator->isValid('a-password-nobody-leaked')); + } + + public function testBasePasswordRulesStillApply(): void + { + $validator = new Mock(); + + $this->assertFalse($validator->isValid('short')); + $this->assertFalse($validator->isValid(\str_repeat('p', 257))); + $this->assertFalse($validator->isValid('')); + } + + public function testAllowEmptyAcceptsAnEmptyPassword(): void + { + $this->assertTrue((new Mock(allowEmpty: true))->isValid('')); + $this->assertFalse((new Mock(allowEmpty: true))->isValid(self::BREACHED)); + } +}