diff --git a/.env b/.env index a09c1da12d..12b71fab58 100644 --- a/.env +++ b/.env @@ -175,6 +175,7 @@ _APP_MIGRATIONS_FIREBASE_CLIENT_SECRET= _APP_PROJECT_REGIONS=default _APP_GEO_SECRET=your-secret-key _APP_GEO_ENDPOINT=http://appwrite-geo/v1 +_APP_PWNED_PASSWORDS_ENDPOINT=http://localhost/v1/mock/tests/general/pwned-passwords _APP_VCS_GITHUB_APP_ID= _APP_VCS_GITHUB_APP_NAME= _APP_VCS_GITHUB_CLIENT_ID= diff --git a/app/config/errors.php b/app/config/errors.php index b8669b0890..438edfa9df 100644 --- a/app/config/errors.php +++ b/app/config/errors.php @@ -271,6 +271,11 @@ return [ 'description' => 'The password you are trying to use contains references to your name, email, phone or userID. For your security, please choose a different password and try again.', 'code' => 400, ], + Exception::USER_PASSWORD_PWNED => [ + 'name' => Exception::USER_PASSWORD_PWNED, + 'description' => 'The password you are trying to use has been exposed in a known data breach. For your security, please choose a different password and try again.', + 'code' => 400, + ], Exception::USER_SESSION_NOT_FOUND => [ 'name' => Exception::USER_SESSION_NOT_FOUND, 'description' => 'The current user session could not be found.', diff --git a/app/config/variables.php b/app/config/variables.php index 4421d51ba0..1245758fca 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_ENDPOINT', + 'description' => 'Endpoint of the Have I Been Pwned range API used by the password pwned project policy. Only the first five characters of a password SHA-1 hash are sent to this endpoint. Defaults to the public Have I Been Pwned service.', + 'introduction' => 'TBD', + 'default' => 'https://api.pwnedpasswords.com/range', + 'required' => false, + 'question' => '', + 'filter' => '' ] ], ], diff --git a/app/controllers/api/account.php b/app/controllers/api/account.php index 4bad06ca4e..2c66365cb2 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; @@ -361,6 +362,13 @@ Http::post('/v1/account') } } + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + if (!$pwnedValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); $passwordHistory = $project->getAttribute('auths', [])['passwordHistory'] ?? 0; @@ -3483,6 +3491,13 @@ Http::patch('/v1/account/password') } } + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + if (!$pwnedValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); $user @@ -4137,6 +4152,13 @@ Http::put('/v1/account/recovery') $history = array_slice($history, (count($history) - $historyLimit), $historyLimit); } + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + if (!$pwnedValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]); $sessions = $profile->getAttribute('sessions', []); diff --git a/app/controllers/mock.php b/app/controllers/mock.php index 9d91cccde4..6470b4eafa 100644 --- a/app/controllers/mock.php +++ b/app/controllers/mock.php @@ -501,3 +501,35 @@ Http::shutdown() $response->dynamic(new Document(['result' => \implode(',', $methods) . ':' . $route->getPath() . ':passed']), Response::MODEL_MOCK); }); + +Http::get('/v1/mock/tests/general/pwned-passwords/:prefix') + ->desc('Pwned Passwords range') + ->groups(['mock']) + ->label('scope', 'public') + ->label('docs', false) + ->label('mock', true) + ->param('prefix', '', new Text(5, 5), 'First five characters of the SHA-1 password hash.') + ->inject('response') + ->action(function (string $prefix, Response $response) { + // Mirrors the Have I Been Pwned range API: every leaked hash sharing the + // requested prefix comes back as `SUFFIX:COUNT`, one per line. + $leaked = [ + 'Password123!' => 12345, + 'Summer2024!' => 678, + 'letmein1234' => 9, + ]; + + $prefix = \strtoupper($prefix); + $lines = []; + foreach ($leaked as $password => $count) { + $hash = \strtoupper(\sha1($password)); + if (\str_starts_with($hash, $prefix)) { + $lines[] = \substr($hash, 5) . ':' . $count; + } + } + + // Padded entries carry a count of 0 and must never be treated as a breach + $lines[] = \str_repeat('0', 35) . ':0'; + + $response->text(\implode("\r\n", $lines)); + }); diff --git a/app/init/models.php b/app/init/models.php index 9dcfc5ef07..296b496ede 100644 --- a/app/init/models.php +++ b/app/init/models.php @@ -181,6 +181,7 @@ use Appwrite\Utopia\Response\Model\PolicyMFAFactors; use Appwrite\Utopia\Response\Model\PolicyPasswordDictionary; use Appwrite\Utopia\Response\Model\PolicyPasswordHistory; use Appwrite\Utopia\Response\Model\PolicyPasswordPersonalData; +use Appwrite\Utopia\Response\Model\PolicyPasswordPwned; use Appwrite\Utopia\Response\Model\PolicyPasswordStrength; use Appwrite\Utopia\Response\Model\PolicySessionAlert; use Appwrite\Utopia\Response\Model\PolicySessionDuration; @@ -473,6 +474,7 @@ Response::setModel(new PolicyPasswordDictionary()); Response::setModel(new PolicyPasswordHistory()); Response::setModel(new PolicyPasswordStrength()); Response::setModel(new PolicyPasswordPersonalData()); +Response::setModel(new PolicyPasswordPwned()); Response::setModel(new PolicySessionAlert()); Response::setModel(new PolicySessionDuration()); Response::setModel(new PolicySessionInvalidation()); diff --git a/docker-compose.yml b/docker-compose.yml index 333bcd9e61..8c9f5446f8 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_ENDPOINT - _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..656ec9283b --- /dev/null +++ b/src/Appwrite/Auth/Validator/PasswordPwned.php @@ -0,0 +1,129 @@ +endpoint = \rtrim($endpoint ?: self::ENDPOINT, '/'); + $this->client = $client ?? (new Client()) + ->setConnectTimeout(self::CONNECT_TIMEOUT) + ->setTimeout(self::REQUEST_TIMEOUT) + ->setAllowRedirects(false) + ->setUserAgent('Appwrite'); + } + + /** + * Get Description. + * + * Returns validator description + * + * @return string + */ + public function getDescription(): string + { + return 'Password must not have been exposed in a known data breach.'; + } + + /** + * Is valid. + * + * @param mixed $value + * + * @return bool + */ + public function isValid($value): bool + { + if (!parent::isValid($value)) { + return false; + } + + if ($this->allowEmpty && \strlen($value) === 0) { + return true; + } + + $hash = \strtoupper(\sha1($value)); + $prefix = \substr($hash, 0, self::PREFIX_LENGTH); + $suffix = \substr($hash, self::PREFIX_LENGTH); + + try { + $response = $this->client + ->addHeader('Add-Padding', 'true') + ->fetch($this->endpoint . '/' . $prefix); + } catch (\Throwable) { + return true; + } + + if ($response->getStatusCode() !== 200) { + return true; + } + + // Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches + foreach (\explode("\n", $response->text()) as $line) { + $line = \trim($line); + if ($line === '') { + continue; + } + + $separator = \strpos($line, ':'); + if ($separator === false) { + continue; + } + + $candidate = \strtoupper(\substr($line, 0, $separator)); + $count = (int) \substr($line, $separator + 1); + + if ($candidate === $suffix && $count > 0) { + return false; + } + } + + return true; + } + + /** + * Is array + * + * Function will return true if object is array. + * + * @return bool + */ + public function isArray(): bool + { + return false; + } + + /** + * Get Type + * + * Returns validator type. + * + * @return string + */ + public function getType(): string + { + return self::TYPE_STRING; + } +} diff --git a/src/Appwrite/Extend/Exception.php b/src/Appwrite/Extend/Exception.php index b9af9cecb4..cb58ced5db 100644 --- a/src/Appwrite/Extend/Exception.php +++ b/src/Appwrite/Extend/Exception.php @@ -83,6 +83,7 @@ class Exception extends \Exception public const string USER_NOT_FOUND = 'user_not_found'; public const string USER_PASSWORD_RECENTLY_USED = 'password_recently_used'; public const string USER_PASSWORD_PERSONAL_DATA = 'password_personal_data'; + public const string USER_PASSWORD_PWNED = 'password_pwned'; public const string USER_EMAIL_ALREADY_EXISTS = 'user_email_already_exists'; public const string USER_EMAIL_DISPOSABLE = 'user_email_disposable'; public const string USER_EMAIL_FREE = 'user_email_free'; diff --git a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php index 94e246a7ee..6d2b5c2037 100644 --- a/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Organization/Http/Projects/Create.php @@ -91,6 +91,7 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, + 'passwordPwned' => false, 'disposableEmails' => false, 'canonicalEmails' => false, 'freeEmails' => false, 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..fa943764b0 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,13 @@ class Get extends Action ]), Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA, ], + 'password-pwned' => [ + new Document([ + '$id' => 'password-pwned', + 'enabled' => $auths['passwordPwned'] ?? false, + ]), + Response::MODEL_POLICY_PASSWORD_PWNED, + ], 'session-alert' => [ new Document([ '$id' => 'session-alert', 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..79a02f5423 --- /dev/null +++ b/src/Appwrite/Platform/Modules/Project/Http/Project/Policies/PasswordPwned/Update.php @@ -0,0 +1,85 @@ +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 if you want password change to block passwords exposed in known data breaches, or false to allow them. When changing this policy, existing passwords remain valid.') + ->inject('response') + ->inject('dbForPlatform') + ->inject('project') + ->inject('authorization') + ->inject('queueForEvents') + ->callback($this->action(...)); + } + + public function action( + bool $enabled, + Response $response, + Database $dbForPlatform, + Document $project, + Authorization $authorization, + Event $queueForEvents, + ): void { + $auths = $project->getAttribute('auths', []); + $auths['passwordPwned'] = $enabled; + + $updates = new Document([ + 'auths' => $auths, + ]); + + $project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), $updates)); + $authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId())); + + $queueForEvents + ->setParam('projectId', $project->getId()) + ->setParam('policy', 'password-pwned'); + + $response->dynamic($project, Response::MODEL_PROJECT); + } +} 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..83693cff33 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,10 @@ class XList extends Action '$id' => 'password-personal-data', 'enabled' => $auths['personalDataCheck'] ?? false, ]), + new Document([ + '$id' => 'password-pwned', + 'enabled' => $auths['passwordPwned'] ?? false, + ]), new Document([ '$id' => 'session-alert', 'enabled' => $auths['sessionAlerts'] ?? false, 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..1606990885 100644 --- a/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php +++ b/src/Appwrite/Platform/Modules/Projects/Http/Projects/Create.php @@ -88,6 +88,7 @@ class Create extends Action 'passwordDictionary' => false, 'duration' => TOKEN_EXPIRATION_LOGIN_LONG, 'personalDataCheck' => false, + 'passwordPwned' => false, 'disposableEmails' => false, 'canonicalEmails' => false, 'freeEmails' => false, diff --git a/src/Appwrite/Platform/Modules/Users/Base.php b/src/Appwrite/Platform/Modules/Users/Base.php index 232d4fd52d..a251925e55 100644 --- a/src/Appwrite/Platform/Modules/Users/Base.php +++ b/src/Appwrite/Platform/Modules/Users/Base.php @@ -2,6 +2,7 @@ namespace Appwrite\Platform\Modules\Users; +use Appwrite\Auth\Validator\PasswordPwned; use Appwrite\Auth\Validator\PersonalData; use Appwrite\Extend\Exception; use Appwrite\Hooks\Hooks; @@ -18,6 +19,7 @@ use Utopia\Database\Helpers\Permission; use Utopia\Database\Helpers\Role; use Utopia\Database\Query; use Utopia\Emails\Email; +use Utopia\System\System; class Base extends Action { @@ -147,6 +149,13 @@ class Base extends Action ]); if (!$isHashed && !empty($password)) { + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT')); + if (!$pwnedValidator->isValid($plaintextPassword)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + $hooks->trigger('passwordValidator', [$dbForProject, $project, $plaintextPassword, &$user, true]); } 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..52647cd924 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; @@ -22,6 +23,7 @@ use Utopia\Database\DateTime; use Utopia\Database\Document; use Utopia\Database\Validator\UID; use Utopia\Platform\Scope\HTTP; +use Utopia\System\System; use Utopia\Validator; use Utopia\Validator\AllOf; @@ -84,6 +86,13 @@ class Update extends Action } } + if ($project->getAttribute('auths', [])['passwordPwned'] ?? false) { + $pwnedValidator = new PasswordPwned(System::getEnv('_APP_PWNED_PASSWORDS_ENDPOINT'), allowEmpty: true); + if (!$pwnedValidator->isValid($password)) { + throw new Exception(Exception::USER_PASSWORD_PWNED); + } + } + if (\strlen($password) === 0) { $user ->setAttribute('password', '') diff --git a/src/Appwrite/Utopia/Response.php b/src/Appwrite/Utopia/Response.php index 140314d326..6a9f667d6b 100644 --- a/src/Appwrite/Utopia/Response.php +++ b/src/Appwrite/Utopia/Response.php @@ -264,6 +264,7 @@ class Response extends SwooleResponse public const MODEL_POLICY_PASSWORD_HISTORY = 'policyPasswordHistory'; public const MODEL_POLICY_PASSWORD_STRENGTH = 'policyPasswordStrength'; public const MODEL_POLICY_PASSWORD_PERSONAL_DATA = 'policyPasswordPersonalData'; + public const MODEL_POLICY_PASSWORD_PWNED = 'policyPasswordPwned'; public const MODEL_POLICY_SESSION_ALERT = 'policySessionAlert'; public const MODEL_POLICY_SESSION_DURATION = 'policySessionDuration'; public const MODEL_POLICY_SESSION_INVALIDATION = 'policySessionInvalidation'; 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..f20511bb0b --- /dev/null +++ b/src/Appwrite/Utopia/Response/Model/PolicyPasswordPwned.php @@ -0,0 +1,34 @@ + 'password-pwned', + ]; + + public function __construct() + { + parent::__construct(); + + $this->addRule('enabled', [ + 'type' => self::TYPE_BOOLEAN, + 'description' => 'Whether password pwned policy is enabled.', + 'default' => false, + 'example' => true, + ]); + } + + public function getName(): string + { + return 'Policy Password Pwned'; + } + + public function getType(): string + { + return Response::MODEL_POLICY_PASSWORD_PWNED; + } +} diff --git a/tests/e2e/Services/Project/PoliciesBase.php b/tests/e2e/Services/Project/PoliciesBase.php index 43cbe1a53e..7382d65763 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'], 'session-alert' => ['enabled'], 'session-duration' => ['duration'], 'session-invalidation' => ['enabled'], @@ -635,6 +636,70 @@ trait PoliciesBase $this->assertSame(401, $response['headers']['status-code']); } + // ========================================================================= + // Password Pwned Policy + // ========================================================================= + + public function testUpdatePasswordPwnedPolicyEnable(): void + { + $response = $this->updatePasswordPwnedPolicy(true); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(200, $policy['headers']['status-code']); + $this->assertSame(true, $policy['body']['enabled']); + + // Cleanup + $this->updatePasswordPwnedPolicy(false); + } + + public function testUpdatePasswordPwnedPolicyDisable(): void + { + $this->updatePasswordPwnedPolicy(true); + + $response = $this->updatePasswordPwnedPolicy(false); + + $this->assertSame(200, $response['headers']['status-code']); + + $policy = $this->getPolicy('password-pwned'); + $this->assertSame(200, $policy['headers']['status-code']); + $this->assertSame(false, $policy['body']['enabled']); + } + + public function testUpdatePasswordPwnedPolicyDisabledByDefault(): void + { + $policy = $this->getPolicy('password-pwned'); + + $this->assertSame(200, $policy['headers']['status-code']); + $this->assertSame('password-pwned', $policy['body']['$id']); + $this->assertSame(false, $policy['body']['enabled']); + } + + public function testUpdatePasswordPwnedPolicyInvalidType(): void + { + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), [ + 'enabled' => 'not-a-boolean', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + } + + public function testUpdatePasswordPwnedPolicyMissingParam(): void + { + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), []); + + $this->assertSame(400, $response['headers']['status-code']); + } + + public function testUpdatePasswordPwnedPolicyWithoutAuth(): void + { + $response = $this->updatePasswordPwnedPolicy(true, false); + + $this->assertSame(401, $response['headers']['status-code']); + } + // ========================================================================= // Session Alert Policy // ========================================================================= @@ -1329,6 +1394,13 @@ trait PoliciesBase ]); } + protected function updatePasswordPwnedPolicy(bool $enabled, bool $authenticated = true): mixed + { + return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders($authenticated), [ + 'enabled' => $enabled, + ]); + } + protected function updateSessionAlertPolicy(bool $enabled, bool $authenticated = true): mixed { return $this->client->call(Client::METHOD_PATCH, '/project/policies/session-alert', $this->buildHeaders($authenticated), [ diff --git a/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php new file mode 100644 index 0000000000..5b0c62d6e7 --- /dev/null +++ b/tests/e2e/Services/Project/PoliciesPasswordPwnedIntegrationTest.php @@ -0,0 +1,311 @@ +updatePolicy(false); + + /** + * Test for SUCCESS + */ + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_off_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Pwned Off User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + $this->assertNotEmpty($user['body']['$id']); + + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $user['body']['$id'] . '/password', $this->serverHeaders(), [ + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + } + + public function testCreateUserWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_on_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Pwned On User', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_clean_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Clean User', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + + // Importing an already hashed password never exposes the plaintext, so the policy cannot apply + $response = $this->client->call(Client::METHOD_POST, '/users/sha', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_hashed_' . \uniqid() . '@localhost.test', + 'password' => \sha1(self::PWNED_PASSWORD), + 'passwordVersion' => 'sha1', + 'name' => 'Hashed User', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + + $this->updatePolicy(false); + } + + public function testUpdateUserPasswordWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + $user = $this->client->call(Client::METHOD_POST, '/users', $this->serverHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_update_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Update User', + ]); + + $this->assertSame(201, $user['headers']['status-code']); + $userId = $user['body']['$id']; + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $this->serverHeaders(), [ + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $this->serverHeaders(), [ + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + // Clearing the password is not a password to check + $response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $this->serverHeaders(), [ + 'password' => '', + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $this->updatePolicy(false); + } + + public function testCreateAccountWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_account_' . \uniqid() . '@localhost.test', + 'password' => self::PWNED_PASSWORD, + 'name' => 'Pwned Account', + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => 'pwned_account_clean_' . \uniqid() . '@localhost.test', + 'password' => $this->cleanPassword(), + 'name' => 'Clean Account', + ]); + + $this->assertSame(201, $response['headers']['status-code']); + $this->assertNotEmpty($response['body']['$id']); + + $this->updatePolicy(false); + } + + public function testUpdateAccountPasswordWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + $email = 'pwned_session_' . \uniqid() . '@localhost.test'; + $password = $this->cleanPassword(); + + $account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => $password, + 'name' => 'Session Account', + ]); + + $this->assertSame(201, $account['headers']['status-code']); + + $session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', $this->clientHeaders(), [ + 'email' => $email, + 'password' => $password, + ]); + + $this->assertSame(201, $session['headers']['status-code']); + + $headers = \array_merge($this->clientHeaders(), [ + 'cookie' => 'a_session_' . $this->getProject()['$id'] . '=' . $session['cookies']['a_session_' . $this->getProject()['$id']], + ]); + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => self::PWNED_PASSWORD, + 'oldPassword' => $password, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_PATCH, '/account/password', $headers, [ + 'password' => $this->cleanPassword(), + 'oldPassword' => $password, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $this->updatePolicy(false); + } + + public function testUpdateAccountRecoveryWithPolicyEnabled(): void + { + $this->updatePolicy(true); + + $email = 'pwned_recovery_' . \uniqid() . '@localhost.test'; + + $account = $this->client->call(Client::METHOD_POST, '/account', $this->clientHeaders(), [ + 'userId' => ID::unique(), + 'email' => $email, + 'password' => $this->cleanPassword(), + 'name' => 'Recovery Account', + ]); + + $this->assertSame(201, $account['headers']['status-code']); + $userId = $account['body']['$id']; + + $recovery = $this->client->call(Client::METHOD_POST, '/account/recovery', $this->clientHeaders(), [ + 'email' => $email, + 'url' => 'http://localhost/recovery', + ]); + + $this->assertSame(201, $recovery['headers']['status-code']); + + $lastEmail = $this->getLastEmailByAddress($email, function ($email) { + $this->assertStringContainsString('Password Reset', (string) $email['subject']); + }); + $secret = $this->extractQueryParamsFromEmailLink($lastEmail['html'])['secret']; + + /** + * Test for FAILURE + */ + $response = $this->client->call(Client::METHOD_PUT, '/account/recovery', $this->clientHeaders(), [ + 'userId' => $userId, + 'secret' => $secret, + 'password' => self::PWNED_PASSWORD, + ]); + + $this->assertSame(400, $response['headers']['status-code']); + $this->assertSame('password_pwned', $response['body']['type']); + + /** + * Test for SUCCESS + */ + $response = $this->client->call(Client::METHOD_PUT, '/account/recovery', $this->clientHeaders(), [ + 'userId' => $userId, + 'secret' => $secret, + 'password' => $this->cleanPassword(), + ]); + + $this->assertSame(200, $response['headers']['status-code']); + + $this->updatePolicy(false); + } + + private function updatePolicy(bool $enabled): void + { + $response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->serverHeaders(), [ + 'enabled' => $enabled, + ]); + + $this->assertSame(200, $response['headers']['status-code']); + } + + /** + * @return array + */ + 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/PasswordPwnedTest.php b/tests/unit/Auth/Validator/PasswordPwnedTest.php new file mode 100644 index 0000000000..ae74d6b461 --- /dev/null +++ b/tests/unit/Auth/Validator/PasswordPwnedTest.php @@ -0,0 +1,156 @@ +range([self::LEAKED => 42])); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertFalse($validator->isValid(self::LEAKED)); + } + + public function testCleanPasswordIsAccepted(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 42])); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertTrue($validator->isValid('never-leaked-' . \uniqid())); + } + + public function testPaddedEntryWithZeroCountIsNotABreach(): void + { + $adapter = new RangeAdapter(body: $this->range([self::LEAKED => 0])); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertTrue($validator->isValid(self::LEAKED)); + } + + public function testSuffixComparisonIgnoresCase(): void + { + $adapter = new RangeAdapter(body: \strtolower($this->range([self::LEAKED => 3]))); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertFalse($validator->isValid(self::LEAKED)); + } + + public function testOnlyHashPrefixLeavesTheServer(): void + { + $adapter = new RangeAdapter(body: ''); + $validator = new PasswordPwned('https://breaches.test/range/', new Client($adapter)); + + $validator->isValid(self::LEAKED); + + $hash = \strtoupper(\sha1(self::LEAKED)); + $this->assertCount(1, $adapter->requests); + $this->assertSame('https://breaches.test/range/' . \substr($hash, 0, 5), $adapter->requests[0]['url']); + $this->assertSame('GET', $adapter->requests[0]['method']); + $this->assertSame('true', $adapter->requests[0]['headers']['add-padding'] ?? null); + } + + public function testUnreachableServiceSkipsTheCheck(): void + { + $adapter = new RangeAdapter(failure: new \RuntimeException('connection refused')); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertTrue($validator->isValid(self::LEAKED)); + } + + public function testUnexpectedStatusSkipsTheCheck(): void + { + $adapter = new RangeAdapter(statusCode: 503, body: $this->range([self::LEAKED => 42])); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertTrue($validator->isValid(self::LEAKED)); + } + + public function testBasePasswordRulesStillApply(): void + { + $adapter = new RangeAdapter(body: ''); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter)); + + $this->assertFalse($validator->isValid('short')); + $this->assertFalse($validator->isValid(\str_repeat('p', 257))); + $this->assertFalse($validator->isValid('')); + $this->assertCount(0, $adapter->requests); + } + + public function testAllowEmptySkipsTheLookup(): void + { + $adapter = new RangeAdapter(body: ''); + $validator = new PasswordPwned('https://breaches.test/range', new Client($adapter), allowEmpty: true); + + $this->assertTrue($validator->isValid('')); + $this->assertCount(0, $adapter->requests); + } + + public function testEmptyEndpointFallsBackToDefault(): void + { + $adapter = new RangeAdapter(body: ''); + $validator = new PasswordPwned('', new Client($adapter)); + + $validator->isValid(self::LEAKED); + + $this->assertStringStartsWith(PasswordPwned::ENDPOINT . '/', $adapter->requests[0]['url']); + } + + /** + * Builds a range response body the way the Have I Been Pwned API does: + * one `SUFFIX:COUNT` line per leaked hash, CRLF separated, plus padding. + * + * @param array $leaked password => breach count + */ + private function range(array $leaked): string + { + $lines = []; + foreach ($leaked as $password => $count) { + $lines[] = \substr(\strtoupper(\sha1((string) $password)), 5) . ':' . $count; + } + $lines[] = \str_repeat('0', 35) . ':0'; + + return \implode("\r\n", $lines); + } +} + +final class RangeAdapter implements Adapter +{ + /** @var array}> */ + public array $requests = []; + + public function __construct( + private int $statusCode = 200, + private string $body = '', + private ?\Throwable $failure = null, + ) { + } + + public function send( + string $url, + string $method, + mixed $body, + array $headers, + RequestOptions $options, + ?callable $chunkCallback = null + ): Response { + $this->requests[] = ['url' => $url, 'method' => $method, 'headers' => $headers]; + + if ($this->failure !== null) { + throw $this->failure; + } + + return new Response($this->statusCode, $this->body, []); + } +}