diff --git a/app/config/errors.php b/app/config/errors.php index 438edfa9df..70153f2e99 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.', diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 2c66365cb2..7ddc1c1d10 100644 --- a/app/controllers/api/account.php +++ b/app/controllers/api/account.php @@ -317,7 +317,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) { $email = \strtolower($email); if ('console' === $project->getId()) { @@ -362,11 +363,8 @@ Http::post('/v1/account') } } - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); - if (!$pwnedValidator->isValid($password)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); } $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); @@ -988,7 +986,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(); @@ -1008,6 +1007,10 @@ Http::post('/v1/account/sessions/email') $user->setAttributes($profile->getArrayCopy()); + if ($pwnedPasswords->isEnabled() && $pwnedPasswords->isForceReset() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED); + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]); $duration = $project->getAttribute('auths', [])['duration'] ?? TOKEN_EXPIRATION_LOGIN_LONG; @@ -3462,7 +3465,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 @@ -3491,11 +3495,8 @@ Http::patch('/v1/account/password') } } - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); - if (!$pwnedValidator->isValid($password)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); } $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); @@ -3561,7 +3562,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'); @@ -3574,6 +3577,30 @@ Http::patch('/v1/account/email') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } + 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); + } + } + + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]); $oldEmail = $user->getAttribute('email'); @@ -3639,8 +3666,11 @@ 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('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -3703,7 +3733,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'); @@ -3716,6 +3748,30 @@ Http::patch('/v1/account/phone') throw new Exception(Exception::USER_INVALID_CREDENTIALS); } + 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); + } + } + + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]); $target = $authorization->skip(fn () => $dbForProject->findOne('targets', [ @@ -3734,8 +3790,11 @@ 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('hash', $proofForPassword->getHash()->getName()) ->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions()) ->setAttribute('passwordUpdate', DateTime::now()); @@ -4120,7 +4179,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); @@ -4152,11 +4212,8 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); - if (!$pwnedValidator->isValid($password)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } + if ($pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); } $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); diff --git a/app/init/registers.php b/app/init/registers.php index 22d49647cb..3c7c39c697 100644 --- a/app/init/registers.php +++ b/app/init/registers.php @@ -35,6 +35,7 @@ if (!Http::isProduction()) { // Useful for existing tests involving webhooks PublicDomain::allow(['request-catcher-sms']); PublicDomain::allow(['request-catcher-webhook']); + PublicDomain::allow(['localhost']); // Lets the pwned passwords policy point at the mock range endpoint } $register->set('pools', function () { diff --git a/app/init/resources/request.php b/app/init/resources/request.php index 7f4d949e77..430f73cbff 100644 --- a/app/init/resources/request.php +++ b/app/init/resources/request.php @@ -3,6 +3,7 @@ use Ahc\Jwt\JWT; use Ahc\Jwt\JWTException; use Appwrite\Auth\Key; +use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Database\Factory as DatabaseFactory; use Appwrite\Databases\TransactionState; use Appwrite\Deployment\Deployments; @@ -673,6 +674,10 @@ return function (Container $context): void { return; }, ['user', 'store', 'proofForToken']); + $context->set('pwnedPasswords', function (Document $project, Cache $cache) { + return new PasswordPwned($project->getAttribute('auths', [])['passwordPwned'] ?? [], $cache, System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + }, ['project', 'cache']); + $context->set('dbForProject', function (DatabaseFactory $databaseFactory, Database $dbForPlatform, Document $project, Response $response, Publisher $publisher, Event $queueForEvents, FunctionPublisher $publisherForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime, UsageContext $usage, Request $request) { if ($project->isEmpty() || $project->getId() === 'console') { return $dbForPlatform; diff --git a/src/Appwrite/Auth/Validator/PasswordPwned.php b/src/Appwrite/Auth/Validator/PasswordPwned.php index 656ec9283b..8d1cbf4fa8 100644 --- a/src/Appwrite/Auth/Validator/PasswordPwned.php +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -2,32 +2,50 @@ namespace Appwrite\Auth\Validator; +use Appwrite\Extend\Exception; +use Utopia\Cache\Cache; use Utopia\Fetch\Client; /** * Validates that a password has not been exposed in a known data breach. * - * Uses the Have I Been Pwned range API with k-anonymity: only the first five - * characters of the SHA-1 hash leave the server, and the returned candidate - * suffixes are compared locally. When the breach service cannot be reached the - * check is skipped, so an outage of the third party never blocks sign-ups or - * password changes. + * Configured from the project's `password-pwned` policy. Uses the Have I Been + * Pwned range API with k-anonymity: only the first five characters of the + * SHA-1 hash leave the server, and the returned suffixes are compared locally. + * Range responses are cached per prefix so repeated checks do not hit the + * service again. */ class PasswordPwned extends Password { public const ENDPOINT = 'https://api.pwnedpasswords.com/range'; + public const CACHE_TTL = 3600; // seconds private const PREFIX_LENGTH = 5; private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds + protected bool $enabled; protected string $endpoint; + protected int $threshold; + protected bool $forceReset; + protected bool $failClosed; + protected ?Cache $cache; protected Client $client; - public function __construct(?string $endpoint = null, ?Client $client = null, bool $allowEmpty = false) + /** + * @param array $policy the project's `passwordPwned` auth settings + * @param ?string $endpoint server-wide endpoint, used when the policy sets none + */ + public function __construct(array $policy = [], ?Cache $cache = null, ?string $endpoint = null, ?Client $client = null, bool $allowEmpty = false) { parent::__construct($allowEmpty); - $this->endpoint = \rtrim($endpoint ?: self::ENDPOINT, '/'); + + $this->enabled = (bool) ($policy['enabled'] ?? false); + $this->endpoint = \rtrim(($policy['endpoint'] ?? '') ?: ($endpoint ?: self::ENDPOINT), '/'); + $this->threshold = \max(1, (int) ($policy['threshold'] ?? 1)); + $this->forceReset = (bool) ($policy['forceReset'] ?? false); + $this->failClosed = (bool) ($policy['failClosed'] ?? true); + $this->cache = $cache; $this->client = $client ?? (new Client()) ->setConnectTimeout(self::CONNECT_TIMEOUT) ->setTimeout(self::REQUEST_TIMEOUT) @@ -35,6 +53,22 @@ class PasswordPwned extends Password ->setUserAgent('Appwrite'); } + /** + * Whether the project enforces the policy at all. + */ + public function isEnabled(): bool + { + return $this->enabled; + } + + /** + * Whether a breached password blocks sign-in until it is reset. + */ + public function isForceReset(): bool + { + return $this->forceReset; + } + /** * Get Description. * @@ -53,6 +87,7 @@ class PasswordPwned extends Password * @param mixed $value * * @return bool + * @throws Exception when the breach service is unreachable and the policy fails closed */ public function isValid($value): bool { @@ -68,39 +103,65 @@ class PasswordPwned extends Password $prefix = \substr($hash, 0, self::PREFIX_LENGTH); $suffix = \substr($hash, self::PREFIX_LENGTH); + $breaches = $this->range($prefix); + + if ($breaches === null) { + if ($this->failClosed) { + throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE); + } + + return true; + } + + return ($breaches[$suffix] ?? 0) < $this->threshold; + } + + /** + * Breach counts for every known hash sharing the prefix, from cache or the service. + * + * @return ?array hash suffix => breach count, null when the service could not be reached + */ + private function range(string $prefix): ?array + { + $key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix; + + if ($this->cache !== null) { + $cached = $this->cache->load($key, self::CACHE_TTL); + if (\is_array($cached)) { + return $cached; + } + } + try { $response = $this->client ->addHeader('Add-Padding', 'true') ->fetch($this->endpoint . '/' . $prefix); } catch (\Throwable) { - return true; + return null; } if ($response->getStatusCode() !== 200) { - return true; + return null; } // Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches + $breaches = []; foreach (\explode("\n", $response->text()) as $line) { $line = \trim($line); - if ($line === '') { - continue; - } - $separator = \strpos($line, ':'); - if ($separator === false) { + if ($line === '' || $separator === false) { continue; } - $candidate = \strtoupper(\substr($line, 0, $separator)); $count = (int) \substr($line, $separator + 1); - - if ($candidate === $suffix && $count > 0) { - return false; + if ($count > 0) { + $breaches[\strtoupper(\substr($line, 0, $separator))] = $count; } } - return true; + $this->cache?->save($key, $breaches); + + return $breaches; } /** diff --git a/src/Appwrite/Extend/Exception.php b/src/Appwrite/Extend/Exception.php index cb58ced5db..d44d5803b3 100644 --- a/src/Appwrite/Extend/Exception.php +++ b/src/Appwrite/Extend/Exception.php @@ -48,6 +48,7 @@ class Exception extends \Exception public const string GENERAL_RESOURCE_LOCKED = 'general_resource_locked'; public const string GENERAL_SMTP_DISABLED = 'general_smtp_disabled'; public const string GENERAL_PHONE_DISABLED = 'general_phone_disabled'; + public const string GENERAL_PWNED_PASSWORDS_UNAVAILABLE = 'general_pwned_passwords_unavailable'; public const string GENERAL_ARGUMENT_INVALID = 'general_argument_invalid'; public const string GENERAL_COLUMN_QUERY_LIMIT_EXCEEDED = 'general_column_query_limit_exceeded'; public const string GENERAL_ATTRIBUTE_QUERY_LIMIT_EXCEEDED = 'general_attribute_query_limit_exceeded'; diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php index 6d2b5c2037..2361d6a31d 100644 --- a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php @@ -91,7 +91,13 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, - 'passwordPwned' => false, + 'passwordPwned' => [ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], '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 fa943764b0..98e2654925 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/Get.php @@ -136,10 +136,15 @@ class Get extends Action Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA, ], 'password-pwned' => [ - new Document([ + new Document(\array_merge([ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], $auths['passwordPwned'] ?? [], [ '$id' => 'password-pwned', - 'enabled' => $auths['passwordPwned'] ?? false, - ]), + ])), Response::MODEL_POLICY_PASSWORD_PWNED, ], '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 index 79a02f5423..9aef08278d 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php @@ -11,8 +11,14 @@ use Appwrite\Utopia\Response; use Utopia\Database\Database; use Utopia\Database\Document; use Utopia\Database\Validator\Authorization; +use Utopia\Domains\Validator\PublicDomain; use Utopia\Platform\Scope\HTTP; +use Utopia\Validator\AnyOf; use Utopia\Validator\Boolean; +use Utopia\Validator\Multiple; +use Utopia\Validator\Range; +use Utopia\Validator\URL; +use Utopia\Validator\WhiteList; class Update extends Action { @@ -39,7 +45,7 @@ class Update extends Action group: 'policies', name: 'updatePasswordPwnedPolicy', description: <<param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true if you want password change to block passwords exposed in known data breaches, or false to allow them. When changing this policy, existing passwords remain valid.') + ->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. When changing this policy, existing passwords remain valid.', optional: true) + ->param('endpoint', null, new AnyOf([new WhiteList([''], true), new Multiple([new URL(['http', 'https']), new PublicDomain()], Multiple::TYPE_STRING)], AnyOf::TYPE_STRING), 'Custom endpoint of a Have I Been Pwned compatible range API, for example a self-hosted mirror. Pass an empty string to use the server default.', optional: true) + ->param('threshold', null, new Range(1, PHP_INT_MAX), 'Minimum number of known breaches a password must appear in before it is rejected. Default is 1.', optional: true) + ->param('forceReset', null, new Boolean(), 'Whether signing in with a breached password is blocked until the password is reset. Default is false, which allows the sign-in.', optional: true) + ->param('failClosed', null, new Boolean(), 'Whether passwords are rejected when the breach service cannot be reached. Default is true. Set to false to skip the check instead.', optional: true) ->inject('response') ->inject('dbForPlatform') ->inject('project') @@ -59,7 +69,11 @@ class Update extends Action } public function action( - bool $enabled, + ?bool $enabled, + ?string $endpoint, + ?int $threshold, + ?bool $forceReset, + ?bool $failClosed, Response $response, Database $dbForPlatform, Document $project, @@ -67,13 +81,33 @@ class Update extends Action Event $queueForEvents, ): void { $auths = $project->getAttribute('auths', []); - $auths['passwordPwned'] = $enabled; + $auths['passwordPwned'] = \array_merge([ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], $auths['passwordPwned'] ?? []); - $updates = new Document([ + if ($enabled !== null) { + $auths['passwordPwned']['enabled'] = $enabled; + } + if ($endpoint !== null) { + $auths['passwordPwned']['endpoint'] = $endpoint; + } + if ($threshold !== null) { + $auths['passwordPwned']['threshold'] = $threshold; + } + if ($forceReset !== null) { + $auths['passwordPwned']['forceReset'] = $forceReset; + } + if ($failClosed !== null) { + $auths['passwordPwned']['failClosed'] = $failClosed; + } + + $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), new Document([ 'auths' => $auths, - ]); - - $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates)); + ]))); $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); $queueForEvents 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 83693cff33..8d5d85ec50 100644 --- a/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/XList.php @@ -116,10 +116,15 @@ class XList extends Action '$id' => 'password-personal-data', 'enabled' => $auths['personalDataCheck'] ?? false, ]), - new Document([ + new Document(\array_merge([ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], $auths['passwordPwned'] ?? [], [ '$id' => 'password-pwned', - 'enabled' => $auths['passwordPwned'] ?? false, - ]), + ])), new Document([ '$id' => 'session-alert', 'enabled' => $auths['sessionAlerts'] ?? false, diff --git a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php index 1606990885..9182796e9a 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php @@ -88,7 +88,13 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, - 'passwordPwned' => false, + 'passwordPwned' => [ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, + ], '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 a251925e55..232d4fd52d 100644 --- a/src/Appwrite/Platform/Modules/Users/Base.php +++ b/src/Appwrite/Platform/Modules/Users/Base.php @@ -2,7 +2,6 @@ namespace Appwrite\Platform\Modules\Users; -use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Auth\Validator\PersonalData; use Appwrite\Extend\Exception; use Appwrite\Hooks\Hooks; @@ -19,7 +18,6 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Query; use Utopia\Emails\Email; -use Utopia\System\System; class Base extends Action { @@ -149,13 +147,6 @@ class Base extends Action ]); if (!$isHashed && !empty($password)) { - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); - if (!$pwnedValidator->isValid($plaintextPassword)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } - } - $hooks->trigger('passwordValidator', [$dbForProject, $project, $plaintextPassword, &$user, true]); } diff --git a/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php b/src/Appwrite/Platform/Modules/Users/Http/Users/Create.php index 16bb0ece33..e81b3f1f71 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,11 +68,16 @@ 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 { + if (!empty($password) && $pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + $plaintext = new Plaintext(); $user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan); 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 52647cd924..05cbf45f28 100644 --- a/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php +++ b/src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php @@ -23,7 +23,6 @@ use Utopia\Database\DateTime; use Utopia\Database\Document; use Utopia\Database\Validator\UID; use Utopia\Platform\Scope\HTTP; -use Utopia\System\System; use Utopia\Validator; use Utopia\Validator\AllOf; @@ -68,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); @@ -86,11 +86,8 @@ class Update extends Action } } - if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { - $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'), allowEmpty: true); - if (!$pwnedValidator->isValid($password)) { - throw new Exception(Exception::USER_PASSWORD_PWNED); - } + if (\strlen($password) > 0 && $pwnedPasswords->isEnabled() && !$pwnedPasswords->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); } if (\strlen($password) === 0) { diff --git a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php index f20511bb0b..fb258a8ebb 100644 --- a/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php +++ b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php @@ -14,12 +14,37 @@ class PolicyPasswordPwned extends PolicyBase { parent::__construct(); - $this->addRule('enabled', [ - 'type' => self::TYPE_BOOLEAN, - 'description' => 'Whether password pwned policy is enabled.', - 'default' => false, - 'example' => true, - ]); + $this + ->addRule('enabled', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether password pwned policy is enabled.', + 'default' => false, + 'example' => true, + ]) + ->addRule('endpoint', [ + 'type' => self::TYPE_STRING, + 'description' => 'Custom endpoint of a Have I Been Pwned compatible range API. Empty when the server default is used.', + 'default' => '', + 'example' => 'https://api.pwnedpasswords.com/range', + ]) + ->addRule('threshold', [ + 'type' => self::TYPE_INTEGER, + 'description' => 'Minimum number of known breaches a password must appear in before it is rejected.', + 'default' => 1, + 'example' => 1, + ]) + ->addRule('forceReset', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether signing in with a breached password is blocked until the password is reset.', + 'default' => false, + 'example' => false, + ]) + ->addRule('failClosed', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether passwords are rejected when the breach service cannot be reached. When false, the check is skipped instead.', + 'default' => true, + 'example' => true, + ]); } public function getName(): string diff --git a/tests/e2e/Services/Project/PoliciesBase.php b/tests/e2e/Services/Project/PoliciesBase.php index 7382d65763..b06dd0b791 100644 --- a/tests/e2e/Services/Project/PoliciesBase.php +++ b/tests/e2e/Services/Project/PoliciesBase.php @@ -17,7 +17,7 @@ trait PoliciesBase 'password-history' => ['total'], 'password-strength' => ['min', 'uppercase', 'lowercase', 'number', 'symbols'], 'password-personal-data' => ['enabled'], - 'password-pwned' => ['enabled'], + 'password-pwned' => ['enabled', 'endpoint', 'threshold', 'forceReset', 'failClosed'], 'session-alert' => ['enabled'], 'session-duration' => ['duration'], 'session-invalidation' => ['enabled'], @@ -642,7 +642,7 @@ trait PoliciesBase public function testUpdatePasswordPwnedPolicyEnable(): void { - $response = $this->updatePasswordPwnedPolicy(true); + $response = $this->updatePasswordPwnedPolicy(['enabled' => true]); $this->assertSame(200, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); @@ -650,16 +650,20 @@ trait PoliciesBase $policy = $this->getPolicy('password-pwned'); $this->assertSame(200, $policy['headers']['status-code']); $this->assertSame(true, $policy['body']['enabled']); + $this->assertSame('', $policy['body']['endpoint']); + $this->assertSame(1, $policy['body']['threshold']); + $this->assertSame(false, $policy['body']['forceReset']); + $this->assertSame(true, $policy['body']['failClosed']); // Cleanup - $this->updatePasswordPwnedPolicy(false); + $this->updatePasswordPwnedPolicy(['enabled' => false]); } public function testUpdatePasswordPwnedPolicyDisable(): void { - $this->updatePasswordPwnedPolicy(true); + $this->updatePasswordPwnedPolicy(['enabled' => true]); - $response = $this->updatePasswordPwnedPolicy(false); + $response = $this->updatePasswordPwnedPolicy(['enabled' => false]); $this->assertSame(200, $response['headers']['status-code']); @@ -675,27 +679,86 @@ trait PoliciesBase $this->assertSame(200, $policy['headers']['status-code']); $this->assertSame('password-pwned', $policy['body']['$id']); $this->assertSame(false, $policy['body']['enabled']); + $this->assertSame('', $policy['body']['endpoint']); + $this->assertSame(1, $policy['body']['threshold']); + $this->assertSame(false, $policy['body']['forceReset']); + $this->assertSame(true, $policy['body']['failClosed']); + } + + public function testUpdatePasswordPwnedPolicyOptionPreservesOtherOptions(): void + { + $response = $this->updatePasswordPwnedPolicy([ + 'endpoint' => 'https://example.com/range', + 'threshold' => 5, + 'forceReset' => true, + 'failClosed' => false, + ]); + + $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('https://example.com/range', $policy['body']['endpoint']); + $this->assertSame(5, $policy['body']['threshold']); + $this->assertSame(true, $policy['body']['forceReset']); + $this->assertSame(false, $policy['body']['failClosed']); + + // 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(false, $policy['body']['enabled']); + $this->assertSame('', $policy['body']['endpoint']); + $this->assertSame(1, $policy['body']['threshold']); + $this->assertSame(false, $policy['body']['forceReset']); + $this->assertSame(true, $policy['body']['failClosed']); } public function testUpdatePasswordPwnedPolicyInvalidType(): void { - $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), [ - 'enabled' => 'not-a-boolean', - ]); + foreach (['enabled', 'forceReset', 'failClosed'] as $option) { + $response = $this->updatePasswordPwnedPolicy([$option => 'not-a-boolean']); + + $this->assertSame(400, $response['headers']['status-code'], $option); + } + + $response = $this->updatePasswordPwnedPolicy(['threshold' => 'not-a-number']); $this->assertSame(400, $response['headers']['status-code']); } - public function testUpdatePasswordPwnedPolicyMissingParam(): void + public function testUpdatePasswordPwnedPolicyInvalidThreshold(): void { - $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), []); + $response = $this->updatePasswordPwnedPolicy(['threshold' => 0]); $this->assertSame(400, $response['headers']['status-code']); } + public function testUpdatePasswordPwnedPolicyInvalidEndpoint(): void + { + foreach (['not-a-url', 'ftp://example.com/range', 'http://192.168.1.1/range'] as $endpoint) { + $response = $this->updatePasswordPwnedPolicy(['endpoint' => $endpoint]); + + $this->assertSame(400, $response['headers']['status-code'], $endpoint); + } + } + public function testUpdatePasswordPwnedPolicyWithoutAuth(): void { - $response = $this->updatePasswordPwnedPolicy(true, false); + $response = $this->updatePasswordPwnedPolicy(['enabled' => true], false); $this->assertSame(401, $response['headers']['status-code']); } @@ -1394,10 +1457,22 @@ trait PoliciesBase ]); } - protected function updatePasswordPwnedPolicy(bool $enabled, bool $authenticated = true): mixed + /** + * @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), [ - 'enabled' => $enabled, + return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders($authenticated), $params); + } + + protected function resetPasswordPwnedPolicy(): void + { + $this->updatePasswordPwnedPolicy([ + 'enabled' => false, + 'endpoint' => '', + 'threshold' => 1, + 'forceReset' => false, + 'failClosed' => true, ]); } diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php index 5b0c62d6e7..94eedc7852 100644 --- a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -19,12 +19,19 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope use ProjectCustom; use SideServer; - // Reported as breached by the mock range endpoint + // Reported as breached by the mock range endpoint, 12345 and 9 times respectively private const PWNED_PASSWORD = 'Password123!'; + private const RARELY_PWNED_PASSWORD = 'letmein1234'; + + // The mock range endpoint the stack already uses through _APP_PWNED_PASSWORDS_ENDPOINT + private const MOCK_ENDPOINT = 'http://localhost/v1/mock/tests/general/pwned-passwords'; + + // Nothing listens here, so lookups fail + private const DEAD_ENDPOINT = 'http://localhost:1/range'; public function testCreateUserWithPolicyDisabled(): void { - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); /** * Test for SUCCESS @@ -48,7 +55,7 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope public function testCreateUserWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); /** * Test for FAILURE @@ -88,12 +95,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } public function testUpdateUserPasswordWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ 'userId' => ID::unique(), @@ -131,12 +138,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(200, $response['headers']['status-code']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } public function testCreateAccountWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); /** * Test for FAILURE @@ -164,12 +171,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(201, $response['headers']['status-code']); $this->assertNotEmpty($response['body']['$id']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } public function testUpdateAccountPasswordWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); $email = 'pwned_session_' . \uniqid() . '@localhost.test'; $password = $this->cleanPassword(); @@ -215,12 +222,12 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(200, $response['headers']['status-code']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } public function testUpdateAccountRecoveryWithPolicyEnabled(): void { - $this->updatePolicy(true); + $this->updatePolicy(['enabled' => true]); $email = 'pwned_recovery_' . \uniqid() . '@localhost.test'; @@ -269,15 +276,478 @@ final class PoliciesPasswordPwnedIntegrationTest extends Scope $this->assertSame(200, $response['headers']['status-code']); - $this->updatePolicy(false); + $this->updatePolicy(['enabled' => false]); } - private function updatePolicy(bool $enabled): void + public function testThreshold(): void { - $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->serverHeaders(), [ - 'enabled' => $enabled, + $this->updatePolicy(['enabled' => true, 'threshold' => 10]); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_rare_' . \uniqid() . '@localhost.test', + 'password' => self::RARELY_PWNED_PASSWORD, + 'name' => 'Rarely Pwned User', ]); + $this->assertSame(201, $response['headers']['status-code']); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_often_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Often Pwned User', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + $this->updatePolicy(['enabled' => false, 'threshold' => 1]); + } + + public function testCustomEndpoint(): void + { + $this->updatePolicy(['enabled' => true, 'endpoint' => self::MOCK_ENDPOINT]); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_endpoint_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Endpoint 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_endpoint_clean_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Endpoint Clean User', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + // An empty endpoint falls back to the server configuration + $this->updatePolicy(['endpoint' => '']); + + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_fallback_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Fallback User', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + $this->updatePolicy(['enabled' => false]); + } + + public function testFailClosed(): void + { + $this->updatePolicy(['enabled' => true, 'endpoint' => self::DEAD_ENDPOINT, 'failClosed' => true]); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_outage_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Outage User', + ]); + + $this->assertSame(503, $response['headers']['status-code']); + $this->assertSame('general_pwned_passwords_unavailable', $response['body']['type']); + + $response = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_outage_account_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Outage Account', + ]); + + $this->assertSame(503, $response['headers']['status-code']); + $this->assertSame('general_pwned_passwords_unavailable', $response['body']['type']); + + // Forced reset needs the lookup, so sign-in fails closed as well + $this->updatePolicy(['enabled' => false]); + + $email = 'pwned_outage_signin_' . \uniqid() . '@localhost.test'; + $password = $this->cleanPassword(); + + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => $password, + 'name' => 'Outage Sign In User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + + $this->updatePolicy(['enabled' => true, 'forceReset' => true]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(503, $response['headers']['status-code']); + $this->assertSame('general_pwned_passwords_unavailable', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $this->updatePolicy(['failClosed' => false]); + + $response = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_outage_open_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Outage Open User', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + + $this->updatePolicy(['enabled' => false, 'endpoint' => '', 'forceReset' => false, 'failClosed' => true]); + } + + public function testForceResetOnSignIn(): 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, 'forceReset' => 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(['forceReset' => 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, 'forceReset' => 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]); + } + + /** + * 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']); } diff --git a/tests/unit/Auth/Validator/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php index ae74d6b461..a4b14707d9 100644 --- a/tests/unit/Auth/Validator/PasswordPwnedTest.php +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -5,7 +5,10 @@ declare(strict_types=1); namespace Tests\Unit\Auth\Validator; use Appwrite\Auth\Validator\PasswordPwned; +use Appwrite\Extend\Exception; use PHPUnit\Framework\TestCase; +use Utopia\Cache\Adapter\Memory; +use Utopia\Cache\Cache; use Utopia\Fetch\Adapter; use Utopia\Fetch\Client; use Utopia\Fetch\Options\Request as RequestOptions; @@ -14,11 +17,28 @@ use Utopia\Fetch\Response; final class PasswordPwnedTest extends TestCase { private const LEAKED = 'Password123!'; + private const ENDPOINT = 'https://breaches.test/range'; + + public function testDisabledByDefault(): void + { + $validator = new PasswordPwned(); + + $this->assertFalse($validator->isEnabled()); + $this->assertFalse($validator->isForceReset()); + } + + public function testPolicyFlags(): void + { + $validator = new PasswordPwned(['enabled' => true, 'forceReset' => true]); + + $this->assertTrue($validator->isEnabled()); + $this->assertTrue($validator->isForceReset()); + } public function testLeakedPasswordIsRejected(): void { $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertFalse($validator->isValid(self::LEAKED)); } @@ -26,7 +46,7 @@ final class PasswordPwnedTest extends TestCase public function testCleanPasswordIsAccepted(): void { $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertTrue($validator->isValid('never-leaked-' . \uniqid())); } @@ -34,7 +54,7 @@ final class PasswordPwnedTest extends TestCase public function testPaddedEntryWithZeroCountIsNotABreach(): void { $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 0])); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertTrue($validator->isValid(self::LEAKED)); } @@ -42,45 +62,104 @@ final class PasswordPwnedTest extends TestCase public function testSuffixComparisonIgnoresCase(): void { $adapter = new RangeAdapter(body: \strtolower($this->range([self::LEAKED => 3]))); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertFalse($validator->isValid(self::LEAKED)); } + public function testThresholdToleratesRareBreaches(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 9])); + + $this->assertTrue($this->validator(['threshold' => 10], $adapter)->isValid(self::LEAKED)); + $this->assertFalse($this->validator(['threshold' => 9], $adapter)->isValid(self::LEAKED)); + } + public function testOnlyHashPrefixLeavesTheServer(): void { $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned('https://breaches.test/range/', new Client($adapter)); + $validator = $this->validator([], $adapter); $validator->isValid(self::LEAKED); $hash = \strtoupper(\sha1(self::LEAKED)); $this->assertCount(1, $adapter->requests); - $this->assertSame('https://breaches.test/range/' . \substr($hash, 0, 5), $adapter->requests[0]['url']); + $this->assertSame(self::ENDPOINT . '/' . \substr($hash, 0, 5), $adapter->requests[0]['url']); $this->assertSame('GET', $adapter->requests[0]['method']); $this->assertSame('true', $adapter->requests[0]['headers']['add-padding'] ?? null); } - public function testUnreachableServiceSkipsTheCheck(): void + public function testRangeIsCachedPerPrefix(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); + $cache = new Cache(new Memory()); + + $first = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter)); + $second = new PasswordPwned(['enabled' => true], $cache, self::ENDPOINT, new Client($adapter)); + + $this->assertFalse($first->isValid(self::LEAKED)); + $this->assertFalse($second->isValid(self::LEAKED)); + $this->assertCount(1, $adapter->requests); + } + + public function testCacheIsScopedToEndpoint(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); + $cache = new Cache(new Memory()); + + (new PasswordPwned([], $cache, 'https://one.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned([], $cache, 'https://two.test/range', new Client($adapter)))->isValid(self::LEAKED); + + $this->assertCount(2, $adapter->requests); + } + + public function testUnreachableServiceFailsClosedByDefault(): void { $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); + + try { + $validator->isValid(self::LEAKED); + $this->fail('Expected the check to fail closed'); + } catch (Exception $e) { + $this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType()); + } + } + + public function testUnexpectedStatusFailsClosedByDefault(): void + { + $adapter = new RangeAdapter(statusCode: 503, body: ''); + $validator = $this->validator([], $adapter); + + $this->expectException(Exception::class); + + $validator->isValid(self::LEAKED); + } + + public function testUnreachableServiceSkipsTheCheckWhenFailingOpen(): void + { + $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); + $validator = $this->validator(['failClosed' => false], $adapter); $this->assertTrue($validator->isValid(self::LEAKED)); } - public function testUnexpectedStatusSkipsTheCheck(): void + public function testFailedLookupIsNotCached(): void { - $adapter = new RangeAdapter(statusCode: 503, body: $this->range([self::LEAKED => 42])); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); + $cache = new Cache(new Memory()); + $validator = new PasswordPwned(['failClosed' => false], $cache, self::ENDPOINT, new Client($adapter)); - $this->assertTrue($validator->isValid(self::LEAKED)); + $validator->isValid(self::LEAKED); + $validator->isValid(self::LEAKED); + + $this->assertCount(2, $adapter->requests); } public function testBasePasswordRulesStillApply(): void { $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + $validator = $this->validator([], $adapter); $this->assertFalse($validator->isValid('short')); $this->assertFalse($validator->isValid(\str_repeat('p', 257))); @@ -91,20 +170,32 @@ final class PasswordPwnedTest extends TestCase public function testAllowEmptySkipsTheLookup(): void { $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter), allowEmpty: true); + $validator = new PasswordPwned([], null, self::ENDPOINT, new Client($adapter), allowEmpty: true); $this->assertTrue($validator->isValid('')); $this->assertCount(0, $adapter->requests); } - public function testEmptyEndpointFallsBackToDefault(): void + public function testEndpointPrecedence(): void { $adapter = new RangeAdapter(body: ''); - $validator = new PasswordPwned('', new Client($adapter)); + $prefix = \substr(\strtoupper(\sha1(self::LEAKED)), 0, 5); - $validator->isValid(self::LEAKED); + (new PasswordPwned(['endpoint' => 'https://policy.test/range/'], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned(['endpoint' => ''], null, 'https://server.test/range', new Client($adapter)))->isValid(self::LEAKED); + (new PasswordPwned([], null, '', new Client($adapter)))->isValid(self::LEAKED); - $this->assertStringStartsWith(PasswordPwned::ENDPOINT . '/', $adapter->requests[0]['url']); + $this->assertSame('https://policy.test/range/' . $prefix, $adapter->requests[0]['url']); + $this->assertSame('https://server.test/range/' . $prefix, $adapter->requests[1]['url']); + $this->assertSame(PasswordPwned::ENDPOINT . '/' . $prefix, $adapter->requests[2]['url']); + } + + /** + * @param array $policy + */ + private function validator(array $policy, RangeAdapter $adapter): PasswordPwned + { + return new PasswordPwned($policy, null, self::ENDPOINT, new Client($adapter)); } /**