mirror of
https://github.com/appwrite/appwrite.git
synced 2026-11-18 20:36:03 +00:00
Merge pull request #13702 from appwrite/feat/password-pwned-policy
feat(policies): add password pwned project policy
This commit is contained in:
37 files changed
+2476
-12
No files matched your search
@@ -176,6 +176,7 @@ _APP_MIGRATIONS_FIREBASE_CLIENT_SECRET=
|
||||
_APP_PROJECT_REGIONS=default
|
||||
_APP_GEO_SECRET=your-secret-key
|
||||
_APP_GEO_ENDPOINT=http://appwrite-geo/v1
|
||||
_APP_PWNED_PASSWORDS_DSN=mock://localhost
|
||||
_APP_VCS_GITHUB_APP_ID=
|
||||
_APP_VCS_GITHUB_APP_NAME=
|
||||
_APP_VCS_GITHUB_CLIENT_ID=
|
||||
|
||||
@@ -397,6 +397,17 @@ return [
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('passwordPwned'),
|
||||
'type' => Database::VAR_BOOLEAN,
|
||||
'format' => '',
|
||||
'size' => 0,
|
||||
'signed' => true,
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'array' => false,
|
||||
'filters' => [],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('emailIsCorporate'),
|
||||
'type' => Database::VAR_BOOLEAN,
|
||||
@@ -488,6 +499,13 @@ return [
|
||||
'lengths' => [],
|
||||
'orders' => [Database::ORDER_ASC],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_passwordPwned'),
|
||||
'type' => Database::INDEX_KEY,
|
||||
'attributes' => ['passwordPwned'],
|
||||
'lengths' => [],
|
||||
'orders' => [Database::ORDER_ASC],
|
||||
],
|
||||
[
|
||||
'$id' => ID::custom('_key_search'),
|
||||
'type' => Database::INDEX_FULLTEXT,
|
||||
|
||||
@@ -69,6 +69,11 @@ return [
|
||||
'description' => 'Phone provider is not configured. Please check the _APP_SMS_PROVIDER environment variable of your Appwrite server.',
|
||||
'code' => 503,
|
||||
],
|
||||
Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE => [
|
||||
'name' => Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE,
|
||||
'description' => 'The breached password service could not be reached, so the password could not be verified. Please try again later.',
|
||||
'code' => 503,
|
||||
],
|
||||
Exception::GENERAL_ARGUMENT_INVALID => [
|
||||
'name' => Exception::GENERAL_ARGUMENT_INVALID,
|
||||
'description' => 'The request contains one or more invalid arguments. Please refer to the endpoint documentation.',
|
||||
@@ -271,6 +276,11 @@ return [
|
||||
'description' => 'The password you are trying to use contains references to your name, email, phone or userID. For your security, please choose a different password and try again.',
|
||||
'code' => 400,
|
||||
],
|
||||
Exception::USER_PASSWORD_PWNED => [
|
||||
'name' => Exception::USER_PASSWORD_PWNED,
|
||||
'description' => 'The password you are trying to use has been exposed in a known data breach. For your security, please choose a different password and try again.',
|
||||
'code' => 400,
|
||||
],
|
||||
Exception::USER_SESSION_NOT_FOUND => [
|
||||
'name' => Exception::USER_SESSION_NOT_FOUND,
|
||||
'description' => 'The current user session could not be found.',
|
||||
|
||||
@@ -483,6 +483,15 @@ return [
|
||||
'required' => false,
|
||||
'question' => '',
|
||||
'filter' => 'token'
|
||||
],
|
||||
[
|
||||
'name' => '_APP_PWNED_PASSWORDS_DSN',
|
||||
'description' => "DSN of the service the password pwned project policy asks whether a password has been breached. The scheme picks the adapter. Nothing is asked until you set it: the default, `none://localhost`, reports every password as safe, so the policy protects nothing until this points at a service.\n\nOptions:\n- None: `none://localhost` — the default. Reports every password as safe without asking anyone, for a server that must not or cannot reach a breach service\n- Have I Been Pwned: `hibp://localhost` — the public range API, which only ever receives the first five characters of the password SHA-1 hash. No other detail is read from the DSN\n- [Appwrite Pwned](https://github.com/appwrite-labs/pwned): `appwrite://SECRET@appwrite-pwned/v1/detection` — a service you run yourself, which answers from its own copy of the Have I Been Pwned corpus, so nothing about the password leaves your network. It receives the whole password, authenticated with `SECRET` as a Bearer token, which must match the service's `APPWRITE_PWNED_SECRET`, so only point it at a service on your own network or behind TLS. The path defaults to `v1/detection` and the connection is plain HTTP unless you add `?tls=true`\n- Testing: `mock://localhost` — reports a fixed list of passwords as breached without leaving the process. Refused on a production server, since it would report every real password as safe",
|
||||
'introduction' => 'TBD',
|
||||
'default' => 'none://localhost',
|
||||
'required' => false,
|
||||
'question' => '',
|
||||
'filter' => ''
|
||||
]
|
||||
],
|
||||
],
|
||||
|
||||
@@ -7,6 +7,7 @@ use Appwrite\Auth\Validator\EmailWhitelist;
|
||||
use Appwrite\Auth\Validator\Password;
|
||||
use Appwrite\Auth\Validator\PasswordDictionary;
|
||||
use Appwrite\Auth\Validator\PasswordHistory;
|
||||
use Appwrite\Auth\Validator\PasswordPwned;
|
||||
use Appwrite\Auth\Validator\PasswordStrength;
|
||||
use Appwrite\Auth\Validator\PersonalData;
|
||||
use Appwrite\Auth\Validator\Phone;
|
||||
@@ -314,7 +315,8 @@ Http::post('/v1/account')
|
||||
->inject('authorization')
|
||||
->inject('hooks')
|
||||
->inject('plan')
|
||||
->action(function (string $userId, string $email, string $password, ?string $name, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Authorization $authorization, Hooks $hooks, array $plan) {
|
||||
->inject('pwnedPasswords')
|
||||
->action(function (string $userId, string $email, string $password, ?string $name, Request $request, Response $response, Document $user, Document $project, Database $dbForProject, Authorization $authorization, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords) {
|
||||
$name ??= '';
|
||||
$email = \strtolower($email);
|
||||
if ('console' === $project->getId()) {
|
||||
@@ -359,6 +361,14 @@ Http::post('/v1/account')
|
||||
}
|
||||
}
|
||||
|
||||
// null when the policy did not look, false when it looked and found nothing
|
||||
$passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true)
|
||||
? !$pwnedPasswords->isValid($password)
|
||||
: null;
|
||||
if ($passwordPwned) {
|
||||
throw new Exception(Exception::USER_PASSWORD_PWNED);
|
||||
}
|
||||
|
||||
$hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]);
|
||||
|
||||
$passwordHistory = $project->getAttribute('auths', [])['passwordHistory'] ?? 0;
|
||||
@@ -435,6 +445,7 @@ Http::post('/v1/account')
|
||||
'emailIsCorporate' => $emailMetadata['emailIsCorporate'],
|
||||
'emailIsDisposable' => $emailMetadata['emailIsDisposable'],
|
||||
'emailIsFree' => $emailMetadata['emailIsFree'],
|
||||
'passwordPwned' => $passwordPwned,
|
||||
]);
|
||||
|
||||
$user->removeAttribute('$sequence');
|
||||
@@ -978,7 +989,8 @@ Http::post('/v1/account/sessions/email')
|
||||
->inject('domainVerification')
|
||||
->inject('cookieDomain')
|
||||
->inject('authorization')
|
||||
->action(function (string $email, string $password, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Geo $geo, Event $queueForEvents, Bus $bus, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, bool $domainVerification, ?string $cookieDomain, Authorization $authorization) {
|
||||
->inject('pwnedPasswords')
|
||||
->action(function (string $email, string $password, Request $request, Response $response, User $user, Database $dbForProject, Document $project, array $platform, Locale $locale, Geo $geo, Event $queueForEvents, Bus $bus, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, bool $domainVerification, ?string $cookieDomain, Authorization $authorization, PasswordPwned $pwnedPasswords) {
|
||||
$email = \strtolower($email);
|
||||
$protocol = $request->getProtocol();
|
||||
|
||||
@@ -1037,6 +1049,24 @@ Http::post('/v1/account/sessions/email')
|
||||
|
||||
$authorization->addRole(Role::user($user->getId())->toString());
|
||||
|
||||
$pwnedPolicy = $project->getAttribute('auths', [])['passwordPwned'] ?? [];
|
||||
|
||||
if (($pwnedPolicy['enabled'] ?? true) && ($pwnedPolicy['sessions'] ?? false)) {
|
||||
// The outcome is recorded either way; only a forced reset needs an answer, so an outage never blocks a plain sign-in
|
||||
$passwordPwned = !$pwnedPasswords->isValid($password);
|
||||
|
||||
if ($passwordPwned !== $user->getAttribute('passwordPwned')) {
|
||||
$user->setAttribute('passwordPwned', $passwordPwned);
|
||||
$dbForProject->updateDocument('users', $user->getId(), new Document([
|
||||
'passwordPwned' => $passwordPwned,
|
||||
]));
|
||||
}
|
||||
|
||||
if ($passwordPwned && ($pwnedPolicy['users'] ?? false)) {
|
||||
throw new Exception(Exception::USER_PASSWORD_RESET_REQUIRED);
|
||||
}
|
||||
}
|
||||
|
||||
// Re-hash if not using recommended algo
|
||||
if ($user->getAttribute('hash') !== $proofForPassword->getHash()->getName()) {
|
||||
$proofForPasswordUpdated = new ProofsPassword();
|
||||
@@ -3447,7 +3477,8 @@ Http::patch('/v1/account/password')
|
||||
->inject('store')
|
||||
->inject('proofForPassword')
|
||||
->inject('proofForToken')
|
||||
->action(function (string $password, string $oldPassword, Response $response, User $user, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken) {
|
||||
->inject('pwnedPasswords')
|
||||
->action(function (string $password, string $oldPassword, Response $response, User $user, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks, Store $store, ProofsPassword $proofForPassword, ProofsToken $proofForToken, PasswordPwned $pwnedPasswords) {
|
||||
$userProofForPassword = ProofsPassword::createHash($user->getAttribute('hash'), $user->getAttribute('hashOptions'));
|
||||
// Check old password only if its an existing user.
|
||||
if (!empty($user->getAttribute('passwordUpdate')) && !$userProofForPassword->verify($oldPassword, $user->getAttribute('password'))) { // Double check user password
|
||||
@@ -3476,11 +3507,20 @@ Http::patch('/v1/account/password')
|
||||
}
|
||||
}
|
||||
|
||||
// null when the policy did not look, false when it looked and found nothing
|
||||
$passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true)
|
||||
? !$pwnedPasswords->isValid($password)
|
||||
: null;
|
||||
if ($passwordPwned) {
|
||||
throw new Exception(Exception::USER_PASSWORD_PWNED);
|
||||
}
|
||||
|
||||
$hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]);
|
||||
|
||||
$user
|
||||
->setAttribute('password', $newPassword)
|
||||
->setAttribute('passwordHistory', $history)
|
||||
->setAttribute('passwordPwned', $passwordPwned)
|
||||
->setAttribute('passwordUpdate', DateTime::now())
|
||||
->setAttribute('hash', $proofForPassword->getHash()->getName())
|
||||
->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions());
|
||||
@@ -3539,7 +3579,9 @@ Http::patch('/v1/account/email')
|
||||
->inject('plan')
|
||||
->inject('proofForPassword')
|
||||
->inject('authorization')
|
||||
->action(function (string $email, string $password, ?\DateTime $requestTimestamp, Response $response, User $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, array $plan, ProofsPassword $proofForPassword, Authorization $authorization) {
|
||||
->inject('passwordsDictionary')
|
||||
->inject('pwnedPasswords')
|
||||
->action(function (string $email, string $password, ?\DateTime $requestTimestamp, Response $response, User $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, array $plan, ProofsPassword $proofForPassword, Authorization $authorization, array $passwordsDictionary, PasswordPwned $pwnedPasswords) {
|
||||
// passwordUpdate will be empty if the user has never set a password
|
||||
$passwordUpdate = $user->getAttribute('passwordUpdate');
|
||||
|
||||
@@ -3552,6 +3594,34 @@ Http::patch('/v1/account/email')
|
||||
throw new Exception(Exception::USER_INVALID_CREDENTIALS);
|
||||
}
|
||||
|
||||
$passwordPwned = null;
|
||||
if (empty($passwordUpdate)) {
|
||||
// First password for an anonymous account: apply the same policies as account creation
|
||||
$strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []);
|
||||
if (!$strength->isValid($password)) {
|
||||
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $strength->getDescription());
|
||||
}
|
||||
|
||||
$dictionary = new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false);
|
||||
if (!$dictionary->isValid($password)) {
|
||||
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $dictionary->getDescription());
|
||||
}
|
||||
|
||||
if ($project->getAttribute('auths', [])['personalDataCheck'] ?? false) {
|
||||
$personalDataValidator = new PersonalData($user->getId(), $email, $user->getAttribute('name'), $user->getAttribute('phone'));
|
||||
if (!$personalDataValidator->isValid($password)) {
|
||||
throw new Exception(Exception::USER_PASSWORD_PERSONAL_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
$passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true)
|
||||
? !$pwnedPasswords->isValid($password)
|
||||
: null;
|
||||
if ($passwordPwned) {
|
||||
throw new Exception(Exception::USER_PASSWORD_PWNED);
|
||||
}
|
||||
}
|
||||
|
||||
$hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]);
|
||||
|
||||
$oldEmail = $user->getAttribute('email');
|
||||
@@ -3617,8 +3687,12 @@ Http::patch('/v1/account/email')
|
||||
;
|
||||
|
||||
if (empty($passwordUpdate)) {
|
||||
$newPassword = $proofForPassword->hash($password);
|
||||
$historyLimit = $project->getAttribute('auths', [])['passwordHistory'] ?? 0;
|
||||
$user
|
||||
->setAttribute('password', $proofForPassword->hash($password))
|
||||
->setAttribute('password', $newPassword)
|
||||
->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : [])
|
||||
->setAttribute('passwordPwned', $passwordPwned)
|
||||
->setAttribute('hash', $proofForPassword->getHash()->getName())
|
||||
->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions())
|
||||
->setAttribute('passwordUpdate', DateTime::now());
|
||||
@@ -3681,7 +3755,9 @@ Http::patch('/v1/account/phone')
|
||||
->inject('hooks')
|
||||
->inject('proofForPassword')
|
||||
->inject('authorization')
|
||||
->action(function (string $phone, string $password, Response $response, Document $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, ProofsPassword $proofForPassword, Authorization $authorization) {
|
||||
->inject('passwordsDictionary')
|
||||
->inject('pwnedPasswords')
|
||||
->action(function (string $phone, string $password, Response $response, Document $user, Database $dbForProject, Event $queueForEvents, Document $project, Hooks $hooks, ProofsPassword $proofForPassword, Authorization $authorization, array $passwordsDictionary, PasswordPwned $pwnedPasswords) {
|
||||
// passwordUpdate will be empty if the user has never set a password
|
||||
$passwordUpdate = $user->getAttribute('passwordUpdate');
|
||||
|
||||
@@ -3694,6 +3770,34 @@ Http::patch('/v1/account/phone')
|
||||
throw new Exception(Exception::USER_INVALID_CREDENTIALS);
|
||||
}
|
||||
|
||||
$passwordPwned = null;
|
||||
if (empty($passwordUpdate)) {
|
||||
// First password for an anonymous account: apply the same policies as account creation
|
||||
$strength = new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []);
|
||||
if (!$strength->isValid($password)) {
|
||||
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $strength->getDescription());
|
||||
}
|
||||
|
||||
$dictionary = new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false);
|
||||
if (!$dictionary->isValid($password)) {
|
||||
throw new Exception(Exception::GENERAL_ARGUMENT_INVALID, 'Invalid `password` param: ' . $dictionary->getDescription());
|
||||
}
|
||||
|
||||
if ($project->getAttribute('auths', [])['personalDataCheck'] ?? false) {
|
||||
$personalDataValidator = new PersonalData($user->getId(), $user->getAttribute('email'), $user->getAttribute('name'), $phone);
|
||||
if (!$personalDataValidator->isValid($password)) {
|
||||
throw new Exception(Exception::USER_PASSWORD_PERSONAL_DATA);
|
||||
}
|
||||
}
|
||||
|
||||
$passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true)
|
||||
? !$pwnedPasswords->isValid($password)
|
||||
: null;
|
||||
if ($passwordPwned) {
|
||||
throw new Exception(Exception::USER_PASSWORD_PWNED);
|
||||
}
|
||||
}
|
||||
|
||||
$hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, false]);
|
||||
|
||||
$target = $authorization->skip(fn () => $dbForProject->findOne('targets', [
|
||||
@@ -3712,8 +3816,12 @@ Http::patch('/v1/account/phone')
|
||||
;
|
||||
|
||||
if (empty($passwordUpdate)) {
|
||||
$newPassword = $proofForPassword->hash($password);
|
||||
$historyLimit = $project->getAttribute('auths', [])['passwordHistory'] ?? 0;
|
||||
$user
|
||||
->setAttribute('password', $proofForPassword->hash($password))
|
||||
->setAttribute('password', $newPassword)
|
||||
->setAttribute('passwordHistory', $historyLimit > 0 ? [$newPassword] : [])
|
||||
->setAttribute('passwordPwned', $passwordPwned)
|
||||
->setAttribute('hash', $proofForPassword->getHash()->getName())
|
||||
->setAttribute('hashOptions', $proofForPassword->getHash()->getOptions())
|
||||
->setAttribute('passwordUpdate', DateTime::now());
|
||||
@@ -4098,7 +4206,8 @@ Http::put('/v1/account/recovery')
|
||||
->inject('proofForPassword')
|
||||
->inject('proofForToken')
|
||||
->inject('authorization')
|
||||
->action(function (string $userId, string $secret, string $password, Response $response, User $user, Database $dbForProject, Document $project, Event $queueForEvents, Hooks $hooks, ProofsPassword $proofForPassword, ProofsToken $proofForToken, Authorization $authorization) {
|
||||
->inject('pwnedPasswords')
|
||||
->action(function (string $userId, string $secret, string $password, Response $response, User $user, Database $dbForProject, Document $project, Event $queueForEvents, Hooks $hooks, ProofsPassword $proofForPassword, ProofsToken $proofForToken, Authorization $authorization, PasswordPwned $pwnedPasswords) {
|
||||
/** @var Appwrite\Utopia\Database\Documents\User $profile */
|
||||
$profile = $dbForProject->getDocument('users', $userId);
|
||||
|
||||
@@ -4130,6 +4239,14 @@ Http::put('/v1/account/recovery')
|
||||
$history = array_slice($history, (count($history) - $historyLimit), $historyLimit);
|
||||
}
|
||||
|
||||
// null when the policy did not look, false when it looked and found nothing
|
||||
$passwordPwned = ($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true)
|
||||
? !$pwnedPasswords->isValid($password)
|
||||
: null;
|
||||
if ($passwordPwned) {
|
||||
throw new Exception(Exception::USER_PASSWORD_PWNED);
|
||||
}
|
||||
|
||||
$hooks->trigger('passwordValidator', [$dbForProject, $project, $password, &$user, true]);
|
||||
|
||||
$sessions = $profile->getAttribute('sessions', []);
|
||||
@@ -4138,6 +4255,7 @@ Http::put('/v1/account/recovery')
|
||||
[
|
||||
'password' => $newPassword,
|
||||
'passwordHistory' => $history,
|
||||
'passwordPwned' => $passwordPwned,
|
||||
'passwordUpdate' => DateTime::now(),
|
||||
'hash' => $proofForPassword->getHash()->getName(),
|
||||
'hashOptions' => $proofForPassword->getHash()->getOptions(),
|
||||
|
||||
@@ -180,6 +180,7 @@ use Appwrite\Utopia\Response\Model\PolicyMFAFactors;
|
||||
use Appwrite\Utopia\Response\Model\PolicyPasswordDictionary;
|
||||
use Appwrite\Utopia\Response\Model\PolicyPasswordHistory;
|
||||
use Appwrite\Utopia\Response\Model\PolicyPasswordPersonalData;
|
||||
use Appwrite\Utopia\Response\Model\PolicyPasswordPwned;
|
||||
use Appwrite\Utopia\Response\Model\PolicyPasswordStrength;
|
||||
use Appwrite\Utopia\Response\Model\PolicySessionAlert;
|
||||
use Appwrite\Utopia\Response\Model\PolicySessionDuration;
|
||||
@@ -470,6 +471,7 @@ Response::setModel(new PolicyPasswordDictionary());
|
||||
Response::setModel(new PolicyPasswordHistory());
|
||||
Response::setModel(new PolicyPasswordStrength());
|
||||
Response::setModel(new PolicyPasswordPersonalData());
|
||||
Response::setModel(new PolicyPasswordPwned());
|
||||
Response::setModel(new PolicySessionAlert());
|
||||
Response::setModel(new PolicySessionDuration());
|
||||
Response::setModel(new PolicySessionInvalidation());
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
use Ahc\Jwt\JWT;
|
||||
use Ahc\Jwt\JWTException;
|
||||
use Appwrite\Auth\Key;
|
||||
use Appwrite\Auth\Validator\PasswordPwned\Appwrite as PasswordPwnedAppwrite;
|
||||
use Appwrite\Auth\Validator\PasswordPwned\HIBP as PasswordPwnedHIBP;
|
||||
use Appwrite\Auth\Validator\PasswordPwned\Mock as PasswordPwnedMock;
|
||||
use Appwrite\Auth\Validator\PasswordPwned\None as PasswordPwnedNone;
|
||||
use Appwrite\Database\Factory as DatabaseFactory;
|
||||
use Appwrite\Databases\TransactionState;
|
||||
use Appwrite\Deployment\Deployments;
|
||||
@@ -49,6 +53,7 @@ use Utopia\Database\Query;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
use Utopia\DI\Container;
|
||||
use Utopia\Domains\Domain;
|
||||
use Utopia\DSN\DSN;
|
||||
use Utopia\Http\Http;
|
||||
use Utopia\Locale\Locale;
|
||||
use Utopia\Lock\Distributed as DistributedLock;
|
||||
@@ -663,6 +668,23 @@ return function (Container $context): void {
|
||||
return;
|
||||
}, ['user', 'store', 'proofForToken']);
|
||||
|
||||
$context->set('pwnedPasswords', function (Cache $cache) {
|
||||
// Nothing is asked until an operator points this at a service
|
||||
$dsn = new DSN(System::getEnv('_APP_PWNED_PASSWORDS_DSN', 'none://localhost'));
|
||||
|
||||
return match ($dsn->getScheme()) {
|
||||
'hibp' => new PasswordPwnedHIBP($cache),
|
||||
'appwrite' => new PasswordPwnedAppwrite($dsn, $cache),
|
||||
// Reports every password as safe by choice, for servers that cannot reach a breach service
|
||||
'none' => new PasswordPwnedNone(),
|
||||
// Reports almost every password as safe, so it must never be reachable on a real server
|
||||
'mock' => Http::isProduction()
|
||||
? throw new Exception(Exception::GENERAL_SERVER_ERROR, 'The mock breach validator cannot be used in production.')
|
||||
: new PasswordPwnedMock(),
|
||||
default => throw new Exception(Exception::GENERAL_SERVER_ERROR, 'Unknown _APP_PWNED_PASSWORDS_DSN scheme: ' . $dsn->getScheme()),
|
||||
};
|
||||
}, ['cache']);
|
||||
|
||||
$context->set('dbForProject', function (DatabaseFactory $databaseFactory, Database $dbForPlatform, Document $project, Response $response, Publisher $publisher, Event $queueForEvents, FunctionPublisher $publisherForFunctions, Webhook $queueForWebhooks, Realtime $queueForRealtime, UsageContext $usage, Request $request) {
|
||||
if ($project->isEmpty() || $project->getId() === 'console') {
|
||||
return $dbForPlatform;
|
||||
|
||||
@@ -254,6 +254,7 @@ services:
|
||||
- _APP_MIGRATION_HOST
|
||||
- _APP_GEO_SECRET
|
||||
- _APP_GEO_ENDPOINT
|
||||
- _APP_PWNED_PASSWORDS_DSN
|
||||
- _APP_LIMIT_DATABASE_BATCH
|
||||
- _APP_DOCUMENTSDB
|
||||
- _APP_VECTORSDB
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Auth\Validator;
|
||||
|
||||
use Appwrite\Extend\Exception;
|
||||
use Utopia\Cache\Cache;
|
||||
|
||||
/**
|
||||
* Validates that a password has not been exposed in a known data breach.
|
||||
*
|
||||
* Whether to ask at all is the caller's decision, read from the project's
|
||||
* `passwordPwned` policy, the same way the personal data and history checks
|
||||
* work. Subclasses differ in who answers the question and in what leaves the
|
||||
* server, so read the one you are configuring. `_APP_PWNED_PASSWORDS_DSN` picks
|
||||
* it, and the DSN scheme matches the subclass.
|
||||
*/
|
||||
abstract class PasswordPwned extends Password
|
||||
{
|
||||
/**
|
||||
* How long an answer from a breach service stays good for.
|
||||
*/
|
||||
protected const CACHE_TTL = 3600; // seconds
|
||||
|
||||
protected ?Cache $cache = null;
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @throws Exception when the breach service cannot be reached
|
||||
*/
|
||||
public function isValid($value): bool
|
||||
{
|
||||
if (!parent::isValid($value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->allowEmpty && \strlen($value) === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return !$this->isPwned($value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Is array
|
||||
*
|
||||
* Function will return true if object is array.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isArray(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Type
|
||||
*
|
||||
* Returns validator type.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getType(): string
|
||||
{
|
||||
return self::TYPE_STRING;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the password appears in a known data breach.
|
||||
*
|
||||
* A password is never silently accepted when the lookup did not happen, so
|
||||
* an unreachable service raises `GENERAL_PWNED_PASSWORDS_UNAVAILABLE`.
|
||||
*
|
||||
* @throws Exception when the breach service cannot be reached or answers with nonsense
|
||||
*/
|
||||
abstract protected function isPwned(string $password): bool;
|
||||
|
||||
/**
|
||||
* Remembers what a breach service said, so the same question is not asked twice.
|
||||
*
|
||||
* Subclasses choose the key, because what is worth remembering differs: a
|
||||
* whole range of hashes for one, a single answer for another. Nothing is
|
||||
* stored when the lookup throws, so an outage is retried rather than
|
||||
* remembered.
|
||||
*
|
||||
* @param callable(): array<mixed> $resolve
|
||||
* @return array<mixed>
|
||||
*/
|
||||
protected function remember(string $key, callable $resolve): array
|
||||
{
|
||||
// A miss reads back as false, so an answer is always wrapped in an array
|
||||
$cached = $this->cache?->load($key, static::CACHE_TTL);
|
||||
|
||||
if (\is_array($cached)) {
|
||||
return $cached;
|
||||
}
|
||||
|
||||
$answer = $resolve();
|
||||
|
||||
$this->cache?->save($key, $answer);
|
||||
|
||||
return $answer;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Auth\Validator\PasswordPwned;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordPwned;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\DSN\DSN;
|
||||
use Utopia\Fetch\Client;
|
||||
|
||||
/**
|
||||
* Asks an Appwrite Pwned service, https://github.com/appwrite-labs/pwned.
|
||||
*
|
||||
* The service answers from its own copy of the Have I Been Pwned corpus, for a
|
||||
* whole password rather than a hash prefix, so unlike `HIBP` this sends the
|
||||
* password itself. The request carries a secret the service shares as a
|
||||
* Bearer token, which is only safe on a network you control or behind TLS.
|
||||
* In exchange nothing about the password ever leaves that network.
|
||||
*
|
||||
* DSN: `appwrite://SECRET@HOST[:PORT][/PATH][?tls=true]`. The secret must match
|
||||
* the service's `APPWRITE_PWNED_SECRET`, the path defaults to `v1/detection`,
|
||||
* and the connection is plain HTTP unless `tls=true`.
|
||||
*/
|
||||
class Appwrite extends PasswordPwned
|
||||
{
|
||||
private const PATH = 'v1/detection';
|
||||
private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds
|
||||
private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds
|
||||
|
||||
protected string $endpoint;
|
||||
protected string $secret;
|
||||
protected Client $client;
|
||||
|
||||
public function __construct(DSN $dsn, ?Cache $cache = null, ?Client $client = null, bool $allowEmpty = false)
|
||||
{
|
||||
parent::__construct($allowEmpty);
|
||||
|
||||
$this->cache = $cache;
|
||||
$scheme = $dsn->getParam('tls') === 'true' ? 'https' : 'http';
|
||||
$port = $dsn->getPort() !== null ? ':' . $dsn->getPort() : '';
|
||||
$path = $dsn->getPath();
|
||||
|
||||
$this->endpoint = $scheme . '://' . $dsn->getHost() . $port . '/' . ($path === '' || $path === null ? self::PATH : $path);
|
||||
$this->secret = $dsn->getUser() ?? '';
|
||||
$this->client = $client ?? (new Client())
|
||||
->setConnectTimeout(self::CONNECT_TIMEOUT)
|
||||
->setTimeout(self::REQUEST_TIMEOUT)
|
||||
->setAllowRedirects(false)
|
||||
->setUserAgent('Appwrite');
|
||||
}
|
||||
|
||||
protected function isPwned(string $password): bool
|
||||
{
|
||||
// Keyed with the secret the service shares, so the cache never holds a crackable password hash
|
||||
$key = 'pwned-passwords:' . \md5($this->endpoint) . ':' . \hash_hmac('sha256', $password, $this->secret);
|
||||
|
||||
$answer = $this->remember($key, function () use ($password) {
|
||||
try {
|
||||
$response = $this->client
|
||||
->addHeader('content-type', Client::CONTENT_TYPE_APPLICATION_JSON)
|
||||
->addHeader('authorization', 'Bearer ' . $this->secret)
|
||||
->fetch($this->endpoint, Client::METHOD_POST, [
|
||||
'password' => $password,
|
||||
]);
|
||||
} catch (\Throwable) {
|
||||
throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE);
|
||||
}
|
||||
|
||||
// Anything else is the service's own error object: a rejected secret
|
||||
// (401), a password it will not take (400) or a missing dataset (503)
|
||||
if ($response->getStatusCode() !== 200) {
|
||||
throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE);
|
||||
}
|
||||
|
||||
$body = \json_decode($response->text(), true);
|
||||
|
||||
if (!\is_array($body) || !\is_bool($body['leaked'] ?? null)) {
|
||||
throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE);
|
||||
}
|
||||
|
||||
return ['leaked' => $body['leaked']];
|
||||
});
|
||||
|
||||
return (bool) ($answer['leaked'] ?? false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Auth\Validator\PasswordPwned;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordPwned;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\Fetch\Client;
|
||||
|
||||
/**
|
||||
* Asks the public Have I Been Pwned range API.
|
||||
*
|
||||
* Uses k-anonymity: only the first five characters of the password's SHA-1 hash
|
||||
* leave the server, and the candidate suffixes that come back are compared
|
||||
* locally. Range responses are cached per prefix, so a busy project does not
|
||||
* ask the service the same question twice.
|
||||
*
|
||||
* DSN: `hibp://localhost`, no details are read.
|
||||
*/
|
||||
class HIBP extends PasswordPwned
|
||||
{
|
||||
public const ENDPOINT = 'https://api.pwnedpasswords.com/range';
|
||||
|
||||
private const PREFIX_LENGTH = 5;
|
||||
private const CONNECT_TIMEOUT = 3 * 1000; // milliseconds
|
||||
private const REQUEST_TIMEOUT = 5 * 1000; // milliseconds
|
||||
|
||||
protected Client $client;
|
||||
protected string $endpoint;
|
||||
|
||||
public function __construct(?Cache $cache = null, ?Client $client = null, string $endpoint = self::ENDPOINT, bool $allowEmpty = false)
|
||||
{
|
||||
parent::__construct($allowEmpty);
|
||||
|
||||
$this->cache = $cache;
|
||||
$this->client = $client ?? (new Client())
|
||||
->setConnectTimeout(self::CONNECT_TIMEOUT)
|
||||
->setTimeout(self::REQUEST_TIMEOUT)
|
||||
->setAllowRedirects(false)
|
||||
->setUserAgent('Appwrite');
|
||||
$this->endpoint = \rtrim($endpoint, '/');
|
||||
}
|
||||
|
||||
protected function isPwned(string $password): bool
|
||||
{
|
||||
$hash = \strtoupper(\sha1($password));
|
||||
$prefix = \substr($hash, 0, self::PREFIX_LENGTH);
|
||||
$suffix = \substr($hash, self::PREFIX_LENGTH);
|
||||
|
||||
// Entries with no breaches are dropped, so any hit means the password is breached
|
||||
return isset($this->range($prefix)[$suffix]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Breach counts for every known hash sharing the prefix, from cache or the service.
|
||||
*
|
||||
* @return array<string, int> hash suffix => breach count
|
||||
* @throws Exception when the service cannot be reached
|
||||
*/
|
||||
private function range(string $prefix): array
|
||||
{
|
||||
return $this->remember('pwned-passwords:' . \md5($this->endpoint) . ':' . $prefix, function () use ($prefix) {
|
||||
try {
|
||||
$response = $this->client
|
||||
->addHeader('Add-Padding', 'true')
|
||||
->fetch($this->endpoint . '/' . $prefix);
|
||||
} catch (\Throwable) {
|
||||
throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE);
|
||||
}
|
||||
|
||||
if ($response->getStatusCode() !== 200) {
|
||||
throw new Exception(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE);
|
||||
}
|
||||
|
||||
// Each line is `HASH_SUFFIX:COUNT`; padded entries carry a count of 0 and are not breaches
|
||||
$breaches = [];
|
||||
foreach (\explode("\n", $response->text()) as $line) {
|
||||
$line = \trim($line);
|
||||
$separator = \strpos($line, ':');
|
||||
if ($line === '' || $separator === false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$count = (int) \substr($line, $separator + 1);
|
||||
if ($count > 0) {
|
||||
$breaches[\strtoupper(\substr($line, 0, $separator))] = $count;
|
||||
}
|
||||
}
|
||||
|
||||
return $breaches;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Auth\Validator\PasswordPwned;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordPwned;
|
||||
|
||||
/**
|
||||
* Reports a fixed set of passwords as breached, without leaving the process.
|
||||
*
|
||||
* Lets the test suite exercise the policy without depending on a breach
|
||||
* service. Selecting it on a production server is refused, because it would
|
||||
* quietly report every real password as safe.
|
||||
*
|
||||
* DSN: `mock://localhost`, no details are read.
|
||||
*/
|
||||
class Mock extends PasswordPwned
|
||||
{
|
||||
/**
|
||||
* The passwords this validator reports as breached.
|
||||
*/
|
||||
public const BREACHED = [
|
||||
'pwned-fixture-common',
|
||||
'pwned-fixture-uncommon',
|
||||
'pwned-fixture-rare',
|
||||
];
|
||||
|
||||
protected function isPwned(string $password): bool
|
||||
{
|
||||
return \in_array($password, self::BREACHED, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Auth\Validator\PasswordPwned;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordPwned;
|
||||
|
||||
/**
|
||||
* Reports every password as safe, without asking anyone.
|
||||
*
|
||||
* The default until an operator points `_APP_PWNED_PASSWORDS_DSN` at a
|
||||
* service, and the right choice for a server that must not, or cannot, reach
|
||||
* one, such as an air-gapped installation. Projects can still switch the
|
||||
* policy on, but it protects nothing until the server is pointed at a real
|
||||
* service, and every checked user reads as clean.
|
||||
*
|
||||
* DSN: `none://localhost`, no details are read.
|
||||
*/
|
||||
class None extends PasswordPwned
|
||||
{
|
||||
protected function isPwned(string $password): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
@@ -83,6 +84,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';
|
||||
|
||||
@@ -252,6 +252,22 @@ class V25 extends Migration
|
||||
}
|
||||
break;
|
||||
|
||||
case 'users':
|
||||
try {
|
||||
$this->createAttributeFromCollection($this->dbForProject, $id, 'passwordPwned');
|
||||
} catch (Throwable $th) {
|
||||
Console::warning("Failed to create attribute \"passwordPwned\" in collection {$id}: {$th->getMessage()}");
|
||||
}
|
||||
|
||||
try {
|
||||
$this->createIndexFromCollection($this->dbForProject, $id, '_key_passwordPwned');
|
||||
} catch (Throwable $th) {
|
||||
Console::warning("Failed to create index \"_key_passwordPwned\" from {$id}: {$th->getMessage()}");
|
||||
}
|
||||
|
||||
$this->dbForProject->purgeCachedCollection($id);
|
||||
break;
|
||||
|
||||
case 'identities':
|
||||
foreach (['photo', 'providerIdToken'] as $attribute) {
|
||||
try {
|
||||
|
||||
@@ -91,6 +91,11 @@ class Create extends Action
|
||||
'passwordDictionary' => false,
|
||||
'duration' => TOKEN_EXPIRATION_LOGIN_LONG,
|
||||
'personalDataCheck' => false,
|
||||
'passwordPwned' => [
|
||||
'enabled' => true,
|
||||
'sessions' => false,
|
||||
'users' => false,
|
||||
],
|
||||
'disposableEmails' => false,
|
||||
'canonicalEmails' => false,
|
||||
'freeEmails' => false,
|
||||
|
||||
@@ -79,6 +79,7 @@ class Get extends Action
|
||||
'password-history' => Response::MODEL_POLICY_PASSWORD_HISTORY,
|
||||
'password-strength' => Response::MODEL_POLICY_PASSWORD_STRENGTH,
|
||||
'password-personal-data' => Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA,
|
||||
'password-pwned' => Response::MODEL_POLICY_PASSWORD_PWNED,
|
||||
'session-alert' => Response::MODEL_POLICY_SESSION_ALERT,
|
||||
'session-duration' => Response::MODEL_POLICY_SESSION_DURATION,
|
||||
'session-invalidation' => Response::MODEL_POLICY_SESSION_INVALIDATION,
|
||||
@@ -134,6 +135,16 @@ class Get extends Action
|
||||
]),
|
||||
Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA,
|
||||
],
|
||||
'password-pwned' => [
|
||||
new Document(\array_merge([
|
||||
'enabled' => true,
|
||||
'sessions' => false,
|
||||
'users' => false,
|
||||
], $auths['passwordPwned'] ?? [], [
|
||||
'$id' => 'password-pwned',
|
||||
])),
|
||||
Response::MODEL_POLICY_PASSWORD_PWNED,
|
||||
],
|
||||
'session-alert' => [
|
||||
new Document([
|
||||
'$id' => 'session-alert',
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordPwned;
|
||||
|
||||
use Appwrite\Event\Event;
|
||||
use Appwrite\Platform\Action;
|
||||
use Appwrite\SDK\AuthType;
|
||||
use Appwrite\SDK\Method;
|
||||
use Appwrite\SDK\Response as SDKResponse;
|
||||
use Appwrite\Utopia\Response;
|
||||
use Utopia\Database\Database;
|
||||
use Utopia\Database\Document;
|
||||
use Utopia\Database\Validator\Authorization;
|
||||
use Utopia\Platform\Scope\HTTP;
|
||||
use Utopia\Validator\Boolean;
|
||||
|
||||
class Update extends Action
|
||||
{
|
||||
use HTTP;
|
||||
|
||||
public static function getName()
|
||||
{
|
||||
return 'updateProjectPasswordPwnedPolicy';
|
||||
}
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this
|
||||
->setHttpMethod(Action::HTTP_REQUEST_METHOD_PATCH)
|
||||
->setHttpPath('/v1/project/policies/password-pwned')
|
||||
->desc('Update password pwned policy')
|
||||
->groups(['api', 'project'])
|
||||
->label('scope', ['policies.write', 'project.policies.write'])
|
||||
->label('event', 'projects.[projectId].policies.[policy].update')
|
||||
->label('audits.event', 'projects.[projectId].policies.[policy].update')
|
||||
->label('audits.resource', 'project/{response.$id}')
|
||||
->label('sdk', new Method(
|
||||
namespace: 'project',
|
||||
group: 'policies',
|
||||
name: 'updatePasswordPwnedPolicy',
|
||||
description: <<<EOT
|
||||
Updating this policy allows you to control if passwords are checked against the Have I Been Pwned breach database. When enabled, a password that appears in any known breach cannot be set or changed. Enable `sessions` to check passwords on sign-in too. Only the first five characters of the password hash are ever shared with the service. Options left out keep their current value.
|
||||
EOT,
|
||||
auth: [AuthType::ADMIN, AuthType::KEY],
|
||||
responses: [
|
||||
new SDKResponse(
|
||||
code: Response::STATUS_CODE_OK,
|
||||
model: Response::MODEL_PROJECT,
|
||||
)
|
||||
],
|
||||
))
|
||||
->param('enabled', null, new Boolean(), 'Toggle password pwned policy. Set to true to block passwords exposed in known data breaches, or false to allow them. Default is true. When changing this policy, existing passwords remain valid.', optional: true)
|
||||
->param('sessions', null, new Boolean(), 'Whether passwords are checked when a session is created. When enabled, signing in records whether the password appears in a known data breach. Default is false.', optional: true)
|
||||
->param('users', null, new Boolean(), 'Whether users signing in with a breached password are blocked until they reset it. Only applies when sessions are checked. Default is false, which allows the sign-in.', optional: true)
|
||||
->inject('response')
|
||||
->inject('dbForPlatform')
|
||||
->inject('project')
|
||||
->inject('authorization')
|
||||
->inject('queueForEvents')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
public function action(
|
||||
?bool $enabled,
|
||||
?bool $sessions,
|
||||
?bool $users,
|
||||
Response $response,
|
||||
Database $dbForPlatform,
|
||||
Document $project,
|
||||
Authorization $authorization,
|
||||
Event $queueForEvents,
|
||||
): void {
|
||||
$auths = $project->getAttribute('auths', []);
|
||||
$auths['passwordPwned'] = \array_merge([
|
||||
'enabled' => true,
|
||||
'sessions' => false,
|
||||
'users' => false,
|
||||
], $auths['passwordPwned'] ?? []);
|
||||
|
||||
if ($enabled !== null) {
|
||||
$auths['passwordPwned']['enabled'] = $enabled;
|
||||
}
|
||||
if ($sessions !== null) {
|
||||
$auths['passwordPwned']['sessions'] = $sessions;
|
||||
}
|
||||
if ($users !== null) {
|
||||
$auths['passwordPwned']['users'] = $users;
|
||||
}
|
||||
|
||||
$project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), new Document([
|
||||
'auths' => $auths,
|
||||
])));
|
||||
$authorization->skip(fn () => $dbForPlatform->purgeCachedDocument('projects', $project->getId()));
|
||||
|
||||
$queueForEvents
|
||||
->setParam('projectId', $project->getId())
|
||||
->setParam('policy', 'password-pwned');
|
||||
|
||||
$response->dynamic($project, Response::MODEL_PROJECT);
|
||||
}
|
||||
}
|
||||
@@ -116,6 +116,13 @@ class XList extends Action
|
||||
'$id' => 'password-personal-data',
|
||||
'enabled' => $auths['personalDataCheck'] ?? false,
|
||||
]),
|
||||
new Document(\array_merge([
|
||||
'enabled' => true,
|
||||
'sessions' => false,
|
||||
'users' => false,
|
||||
], $auths['passwordPwned'] ?? [], [
|
||||
'$id' => 'password-pwned',
|
||||
])),
|
||||
new Document([
|
||||
'$id' => 'session-alert',
|
||||
'enabled' => $auths['sessionAlerts'] ?? false,
|
||||
|
||||
@@ -91,6 +91,7 @@ use Appwrite\Platform\Modules\Project\Http\Project\Policies\MFAFactors\Update as
|
||||
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordDictionary\Update as UpdatePasswordDictionaryPolicy;
|
||||
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordHistory\Update as UpdatePasswordHistoryPolicy;
|
||||
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordPersonalData\Update as UpdatePasswordPersonalDataPolicy;
|
||||
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordPwned\Update as UpdatePasswordPwnedPolicy;
|
||||
use Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordStrength\Update as UpdatePasswordStrengthPolicy;
|
||||
use Appwrite\Platform\Modules\Project\Http\Project\Policies\SessionAlert\Update as UpdateSessionAlertPolicy;
|
||||
use Appwrite\Platform\Modules\Project\Http\Project\Policies\SessionDuration\Update as UpdateSessionDurationPolicy;
|
||||
@@ -184,6 +185,7 @@ class Http extends Service
|
||||
$this->addAction(UpdatePasswordHistoryPolicy::getName(), new UpdatePasswordHistoryPolicy());
|
||||
$this->addAction(UpdatePasswordStrengthPolicy::getName(), new UpdatePasswordStrengthPolicy());
|
||||
$this->addAction(UpdatePasswordPersonalDataPolicy::getName(), new UpdatePasswordPersonalDataPolicy());
|
||||
$this->addAction(UpdatePasswordPwnedPolicy::getName(), new UpdatePasswordPwnedPolicy());
|
||||
$this->addAction(UpdateSessionAlertPolicy::getName(), new UpdateSessionAlertPolicy());
|
||||
$this->addAction(UpdateSessionDurationPolicy::getName(), new UpdateSessionDurationPolicy());
|
||||
$this->addAction(UpdateSessionInvalidationPolicy::getName(), new UpdateSessionInvalidationPolicy());
|
||||
|
||||
@@ -88,6 +88,11 @@ class Create extends Action
|
||||
'passwordDictionary' => false,
|
||||
'duration' => TOKEN_EXPIRATION_LOGIN_LONG,
|
||||
'personalDataCheck' => false,
|
||||
'passwordPwned' => [
|
||||
'enabled' => true,
|
||||
'sessions' => false,
|
||||
'users' => false,
|
||||
],
|
||||
'disposableEmails' => false,
|
||||
'canonicalEmails' => false,
|
||||
'freeEmails' => false,
|
||||
|
||||
@@ -21,7 +21,7 @@ use Utopia\Emails\Email;
|
||||
|
||||
class Base extends Action
|
||||
{
|
||||
protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan): Document
|
||||
protected function createUser(Hash $hash, string $userId, ?string $email, ?string $password, ?string $phone, ?string $name, Document $project, Database $dbForProject, Hooks $hooks, array $plan, ?bool $passwordPwned = null): Document
|
||||
{
|
||||
$name = $name ?? '';
|
||||
$plaintextPassword = $password;
|
||||
@@ -144,6 +144,7 @@ class Base extends Action
|
||||
'emailIsCorporate' => $emailMetadata['emailIsCorporate'],
|
||||
'emailIsDisposable' => $emailMetadata['emailIsDisposable'],
|
||||
'emailIsFree' => $emailMetadata['emailIsFree'],
|
||||
'passwordPwned' => $passwordPwned,
|
||||
]);
|
||||
|
||||
if (!$isHashed && !empty($password)) {
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
namespace Appwrite\Platform\Modules\Users\Http\Users;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordDictionary;
|
||||
use Appwrite\Auth\Validator\PasswordPwned;
|
||||
use Appwrite\Auth\Validator\PasswordStrength;
|
||||
use Appwrite\Auth\Validator\Phone;
|
||||
use Appwrite\Extend\Exception;
|
||||
use Appwrite\Hooks\Hooks;
|
||||
use Appwrite\Platform\Action;
|
||||
use Appwrite\Platform\Modules\Users\Base;
|
||||
@@ -66,14 +68,22 @@ class Create extends Base
|
||||
->inject('dbForProject')
|
||||
->inject('hooks')
|
||||
->inject('plan')
|
||||
->inject('pwnedPasswords')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan): void
|
||||
public function action(string $userId, ?string $email, ?string $phone, ?string $password, ?string $name, Response $response, Document $project, Database $dbForProject, Hooks $hooks, array $plan, PasswordPwned $pwnedPasswords): void
|
||||
{
|
||||
$passwordPwned = empty($password) || !($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true)
|
||||
? null
|
||||
: !$pwnedPasswords->isValid($password);
|
||||
if ($passwordPwned) {
|
||||
throw new Exception(Exception::USER_PASSWORD_PWNED);
|
||||
}
|
||||
|
||||
$plaintext = new Plaintext();
|
||||
|
||||
$user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan);
|
||||
$user = $this->createUser($plaintext, $userId, $email, $password, $phone, $name, $project, $dbForProject, $hooks, $plan, $passwordPwned);
|
||||
|
||||
$response
|
||||
->setStatusCode(Response::STATUS_CODE_CREATED)
|
||||
|
||||
@@ -4,6 +4,7 @@ namespace Appwrite\Platform\Modules\Users\Http\Users\Password;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordDictionary;
|
||||
use Appwrite\Auth\Validator\PasswordHistory;
|
||||
use Appwrite\Auth\Validator\PasswordPwned;
|
||||
use Appwrite\Auth\Validator\PasswordStrength;
|
||||
use Appwrite\Auth\Validator\PersonalData;
|
||||
use Appwrite\Event\Event;
|
||||
@@ -66,10 +67,11 @@ class Update extends Action
|
||||
->inject('dbForProject')
|
||||
->inject('queueForEvents')
|
||||
->inject('hooks')
|
||||
->inject('pwnedPasswords')
|
||||
->callback($this->action(...));
|
||||
}
|
||||
|
||||
public function action(string $userId, string $password, Response $response, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks): void
|
||||
public function action(string $userId, string $password, Response $response, Document $project, Database $dbForProject, Event $queueForEvents, Hooks $hooks, PasswordPwned $pwnedPasswords): void
|
||||
{
|
||||
$user = $dbForProject->getDocument('users', $userId);
|
||||
|
||||
@@ -84,6 +86,13 @@ class Update extends Action
|
||||
}
|
||||
}
|
||||
|
||||
$passwordPwned = \strlen($password) === 0 || !($project->getAttribute('auths', [])['passwordPwned']['enabled'] ?? true)
|
||||
? null
|
||||
: !$pwnedPasswords->isValid($password);
|
||||
if ($passwordPwned) {
|
||||
throw new Exception(Exception::USER_PASSWORD_PWNED);
|
||||
}
|
||||
|
||||
if (\strlen($password) === 0) {
|
||||
$user
|
||||
->setAttribute('password', '')
|
||||
@@ -91,6 +100,7 @@ class Update extends Action
|
||||
|
||||
$user = $dbForProject->updateDocument('users', $user->getId(), new Document([
|
||||
'password' => $user->getAttribute('password'),
|
||||
'passwordPwned' => null,
|
||||
'passwordUpdate' => $user->getAttribute('passwordUpdate'),
|
||||
]));
|
||||
$queueForEvents->setParam('userId', $user->getId());
|
||||
@@ -121,6 +131,7 @@ class Update extends Action
|
||||
$user
|
||||
->setAttribute('password', $newPassword)
|
||||
->setAttribute('passwordHistory', $history)
|
||||
->setAttribute('passwordPwned', $passwordPwned)
|
||||
->setAttribute('passwordUpdate', DateTime::now())
|
||||
->setAttribute('hash', $hasher->getName())
|
||||
->setAttribute('hashOptions', $hasher->getOptions());
|
||||
@@ -128,6 +139,7 @@ class Update extends Action
|
||||
$user = $dbForProject->updateDocument('users', $user->getId(), new Document([
|
||||
'password' => $user->getAttribute('password'),
|
||||
'passwordHistory' => $user->getAttribute('passwordHistory'),
|
||||
'passwordPwned' => $user->getAttribute('passwordPwned'),
|
||||
'passwordUpdate' => $user->getAttribute('passwordUpdate'),
|
||||
'hash' => $user->getAttribute('hash'),
|
||||
'hashOptions' => $user->getAttribute('hashOptions'),
|
||||
|
||||
@@ -13,6 +13,7 @@ class Users extends Base
|
||||
'registration',
|
||||
'emailVerification',
|
||||
'phoneVerification',
|
||||
'passwordPwned',
|
||||
'labels',
|
||||
'impersonator',
|
||||
'accessedAt',
|
||||
|
||||
@@ -262,6 +262,7 @@ class Response extends SwooleResponse
|
||||
public const MODEL_POLICY_PASSWORD_HISTORY = 'policyPasswordHistory';
|
||||
public const MODEL_POLICY_PASSWORD_STRENGTH = 'policyPasswordStrength';
|
||||
public const MODEL_POLICY_PASSWORD_PERSONAL_DATA = 'policyPasswordPersonalData';
|
||||
public const MODEL_POLICY_PASSWORD_PWNED = 'policyPasswordPwned';
|
||||
public const MODEL_POLICY_SESSION_ALERT = 'policySessionAlert';
|
||||
public const MODEL_POLICY_SESSION_DURATION = 'policySessionDuration';
|
||||
public const MODEL_POLICY_SESSION_INVALIDATION = 'policySessionInvalidation';
|
||||
|
||||
@@ -113,6 +113,13 @@ class Account extends Model
|
||||
'default' => null,
|
||||
'example' => true,
|
||||
])
|
||||
->addRule('passwordPwned', [
|
||||
'type' => self::TYPE_BOOLEAN,
|
||||
'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.',
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'example' => false,
|
||||
])
|
||||
->addRule('phoneVerification', [
|
||||
'type' => self::TYPE_BOOLEAN,
|
||||
'description' => 'Phone verification status.',
|
||||
|
||||
@@ -34,6 +34,7 @@ class PolicyList extends Model
|
||||
Response::MODEL_POLICY_PASSWORD_HISTORY,
|
||||
Response::MODEL_POLICY_PASSWORD_STRENGTH,
|
||||
Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA,
|
||||
Response::MODEL_POLICY_PASSWORD_PWNED,
|
||||
Response::MODEL_POLICY_SESSION_ALERT,
|
||||
Response::MODEL_POLICY_SESSION_DURATION,
|
||||
Response::MODEL_POLICY_SESSION_INVALIDATION,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace Appwrite\Utopia\Response\Model;
|
||||
|
||||
use Appwrite\Utopia\Response;
|
||||
|
||||
class PolicyPasswordPwned extends PolicyBase
|
||||
{
|
||||
public array $conditions = [
|
||||
'$id' => 'password-pwned',
|
||||
];
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
|
||||
$this
|
||||
->addRule('enabled', [
|
||||
'type' => self::TYPE_BOOLEAN,
|
||||
'description' => 'Whether password pwned policy is enabled.',
|
||||
'default' => true,
|
||||
'example' => true,
|
||||
])
|
||||
->addRule('sessions', [
|
||||
'type' => self::TYPE_BOOLEAN,
|
||||
'description' => 'Whether passwords are checked when a session is created.',
|
||||
'default' => false,
|
||||
'example' => false,
|
||||
])
|
||||
->addRule('users', [
|
||||
'type' => self::TYPE_BOOLEAN,
|
||||
'description' => 'Whether users signing in with a breached password are blocked until they reset it. Only applies when sessions are checked.',
|
||||
'default' => false,
|
||||
'example' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
public function getName(): string
|
||||
{
|
||||
return 'Policy Password Pwned';
|
||||
}
|
||||
|
||||
public function getType(): string
|
||||
{
|
||||
return Response::MODEL_POLICY_PASSWORD_PWNED;
|
||||
}
|
||||
}
|
||||
@@ -143,6 +143,13 @@ class User extends Model
|
||||
'default' => null,
|
||||
'example' => true,
|
||||
])
|
||||
->addRule('passwordPwned', [
|
||||
'type' => self::TYPE_BOOLEAN,
|
||||
'description' => 'Whether the password was found in a known data breach the last time it was checked. Null when the password has never been checked.',
|
||||
'required' => false,
|
||||
'default' => null,
|
||||
'example' => false,
|
||||
])
|
||||
->addRule('phoneVerification', [
|
||||
'type' => self::TYPE_BOOLEAN,
|
||||
'description' => 'Phone verification status.',
|
||||
|
||||
@@ -17,6 +17,7 @@ trait PoliciesBase
|
||||
'password-history' => ['total'],
|
||||
'password-strength' => ['min', 'uppercase', 'lowercase', 'number', 'symbols'],
|
||||
'password-personal-data' => ['enabled'],
|
||||
'password-pwned' => ['enabled', 'sessions', 'users'],
|
||||
'session-alert' => ['enabled'],
|
||||
'session-duration' => ['duration'],
|
||||
'session-invalidation' => ['enabled'],
|
||||
@@ -635,6 +636,122 @@ trait PoliciesBase
|
||||
$this->assertSame(401, $response['headers']['status-code']);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Password Pwned Policy
|
||||
// =========================================================================
|
||||
|
||||
public function testUpdatePasswordPwnedPolicyEnable(): void
|
||||
{
|
||||
$response = $this->updatePasswordPwnedPolicy(['enabled' => true]);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
$this->assertNotEmpty($response['body']['$id']);
|
||||
|
||||
$policy = $this->getPolicy('password-pwned');
|
||||
$this->assertSame(200, $policy['headers']['status-code']);
|
||||
$this->assertSame(true, $policy['body']['enabled']);
|
||||
$this->assertSame(false, $policy['body']['sessions']);
|
||||
$this->assertSame(false, $policy['body']['users']);
|
||||
|
||||
// Cleanup
|
||||
$this->updatePasswordPwnedPolicy(['enabled' => false]);
|
||||
}
|
||||
|
||||
public function testUpdatePasswordPwnedPolicyDisable(): void
|
||||
{
|
||||
$this->updatePasswordPwnedPolicy(['enabled' => true]);
|
||||
|
||||
$response = $this->updatePasswordPwnedPolicy(['enabled' => false]);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
|
||||
$policy = $this->getPolicy('password-pwned');
|
||||
$this->assertSame(200, $policy['headers']['status-code']);
|
||||
$this->assertSame(false, $policy['body']['enabled']);
|
||||
}
|
||||
|
||||
public function testUpdatePasswordPwnedPolicyDefaults(): void
|
||||
{
|
||||
$this->resetPasswordPwnedPolicy();
|
||||
|
||||
$policy = $this->getPolicy('password-pwned');
|
||||
|
||||
$this->assertSame(200, $policy['headers']['status-code']);
|
||||
$this->assertSame('password-pwned', $policy['body']['$id']);
|
||||
$this->assertSame(true, $policy['body']['enabled']);
|
||||
$this->assertSame(false, $policy['body']['sessions']);
|
||||
$this->assertSame(false, $policy['body']['users']);
|
||||
}
|
||||
|
||||
public function testUpdatePasswordPwnedPolicySessions(): void
|
||||
{
|
||||
$response = $this->updatePasswordPwnedPolicy(['sessions' => true]);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
|
||||
$policy = $this->getPolicy('password-pwned');
|
||||
$this->assertSame(true, $policy['body']['sessions']);
|
||||
|
||||
$response = $this->updatePasswordPwnedPolicy(['sessions' => false]);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
|
||||
$policy = $this->getPolicy('password-pwned');
|
||||
$this->assertSame(false, $policy['body']['sessions']);
|
||||
}
|
||||
|
||||
public function testUpdatePasswordPwnedPolicyOptionPreservesOtherOptions(): void
|
||||
{
|
||||
$response = $this->updatePasswordPwnedPolicy([
|
||||
'sessions' => true,
|
||||
'users' => true,
|
||||
]);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
|
||||
$response = $this->updatePasswordPwnedPolicy(['enabled' => true]);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
|
||||
$policy = $this->getPolicy('password-pwned');
|
||||
$this->assertSame(true, $policy['body']['enabled']);
|
||||
$this->assertSame(true, $policy['body']['sessions']);
|
||||
$this->assertSame(true, $policy['body']['users']);
|
||||
|
||||
// Cleanup
|
||||
$this->resetPasswordPwnedPolicy();
|
||||
}
|
||||
|
||||
public function testUpdatePasswordPwnedPolicyEmptyBody(): void
|
||||
{
|
||||
$this->resetPasswordPwnedPolicy();
|
||||
|
||||
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders(), []);
|
||||
|
||||
$this->assertSame(200, $response['headers']['status-code']);
|
||||
|
||||
$policy = $this->getPolicy('password-pwned');
|
||||
$this->assertSame(true, $policy['body']['enabled']);
|
||||
$this->assertSame(false, $policy['body']['sessions']);
|
||||
$this->assertSame(false, $policy['body']['users']);
|
||||
}
|
||||
|
||||
public function testUpdatePasswordPwnedPolicyInvalidType(): void
|
||||
{
|
||||
foreach (['enabled', 'sessions', 'users'] as $option) {
|
||||
$response = $this->updatePasswordPwnedPolicy([$option => 'not-a-boolean']);
|
||||
|
||||
$this->assertSame(400, $response['headers']['status-code'], $option);
|
||||
}
|
||||
}
|
||||
|
||||
public function testUpdatePasswordPwnedPolicyWithoutAuth(): void
|
||||
{
|
||||
$response = $this->updatePasswordPwnedPolicy(['enabled' => true], false);
|
||||
|
||||
$this->assertSame(401, $response['headers']['status-code']);
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Session Alert Policy
|
||||
// =========================================================================
|
||||
@@ -1329,6 +1446,23 @@ trait PoliciesBase
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, bool|int|string> $params
|
||||
*/
|
||||
protected function updatePasswordPwnedPolicy(array $params, bool $authenticated = true): mixed
|
||||
{
|
||||
return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-pwned', $this->buildHeaders($authenticated), $params);
|
||||
}
|
||||
|
||||
protected function resetPasswordPwnedPolicy(): void
|
||||
{
|
||||
$this->updatePasswordPwnedPolicy([
|
||||
'enabled' => true,
|
||||
'sessions' => false,
|
||||
'users' => false,
|
||||
]);
|
||||
}
|
||||
|
||||
protected function updateSessionAlertPolicy(bool $enabled, bool $authenticated = true): mixed
|
||||
{
|
||||
return $this->client->call(Client::METHOD_PATCH, '/project/policies/session-alert', $this->buildHeaders($authenticated), [
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,212 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Auth\Validator\PasswordPwned;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordPwned\Appwrite;
|
||||
use Appwrite\Extend\Exception;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Utopia\Cache\Adapter\Memory;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\DSN\DSN;
|
||||
use Utopia\Fetch\Adapter;
|
||||
use Utopia\Fetch\Client;
|
||||
use Utopia\Fetch\Options\Request as RequestOptions;
|
||||
use Utopia\Fetch\Response;
|
||||
|
||||
final class AppwriteTest extends TestCase
|
||||
{
|
||||
private const PASSWORD = 'Password123!';
|
||||
private const SECRET = 'shared-with-the-service';
|
||||
private const DSN = 'appwrite://' . self::SECRET . '@pwned.test/v1/detection';
|
||||
|
||||
public function testLeakedPasswordIsRejected(): void
|
||||
{
|
||||
$fetch = new DetectionFetch(body: '{"leaked":true}');
|
||||
|
||||
$this->assertFalse($this->validator($fetch)->isValid(self::PASSWORD));
|
||||
}
|
||||
|
||||
public function testCleanPasswordIsAccepted(): void
|
||||
{
|
||||
$fetch = new DetectionFetch(body: '{"leaked":false}');
|
||||
|
||||
$this->assertTrue($this->validator($fetch)->isValid(self::PASSWORD));
|
||||
}
|
||||
|
||||
public function testThePasswordIsSentAsIsWithTheSharedSecretAsBearerToken(): void
|
||||
{
|
||||
$fetch = new DetectionFetch(body: '{"leaked":false}');
|
||||
|
||||
$this->validator($fetch)->isValid(self::PASSWORD);
|
||||
|
||||
$this->assertCount(1, $fetch->requests);
|
||||
$this->assertSame('POST', $fetch->requests[0]['method']);
|
||||
|
||||
// The service hashes the password itself, so it travels in the clear
|
||||
$this->assertSame(['password' => self::PASSWORD], \json_decode($fetch->requests[0]['body'], true));
|
||||
|
||||
$headers = \array_change_key_case($fetch->requests[0]['headers'], CASE_LOWER);
|
||||
$this->assertSame('Bearer ' . self::SECRET, $headers['authorization'] ?? null);
|
||||
$this->assertSame('application/json', $headers['content-type'] ?? null);
|
||||
}
|
||||
|
||||
public function testTheDsnDescribesWhereAndHowToConnect(): void
|
||||
{
|
||||
$cases = [
|
||||
'appwrite://secret@pwned.test/v1/detection' => 'http://pwned.test/v1/detection',
|
||||
// The path the service exposes is assumed when the DSN leaves it out
|
||||
'appwrite://secret@pwned.test' => 'http://pwned.test/v1/detection',
|
||||
'appwrite://secret@pwned.test:8088' => 'http://pwned.test:8088/v1/detection',
|
||||
'appwrite://secret@pwned.test/custom/path' => 'http://pwned.test/custom/path',
|
||||
'appwrite://secret@pwned.test?tls=true' => 'https://pwned.test/v1/detection',
|
||||
];
|
||||
|
||||
foreach ($cases as $dsn => $expected) {
|
||||
$fetch = new DetectionFetch(body: '{"leaked":false}');
|
||||
|
||||
(new Appwrite(new DSN($dsn), null, new Client($fetch)))->isValid(self::PASSWORD);
|
||||
|
||||
$this->assertSame($expected, $fetch->requests[0]['url'], $dsn);
|
||||
}
|
||||
}
|
||||
|
||||
public function testUnreachableServiceIsReported(): void
|
||||
{
|
||||
$fetch = new DetectionFetch(failure: new \RuntimeException('connection refused'));
|
||||
|
||||
try {
|
||||
$this->validator($fetch)->isValid(self::PASSWORD);
|
||||
$this->fail('Expected the unreachable service to surface');
|
||||
} catch (Exception $e) {
|
||||
$this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The service answers every failure with its own error object; none of them may pass as a clean password.
|
||||
*/
|
||||
public function testServiceErrorsAreReported(): void
|
||||
{
|
||||
$errors = [
|
||||
401 => '{"type":"general_unauthorized","message":"Missing or invalid Bearer token in the Authorization header.","code":401,"version":"0.2.0"}',
|
||||
400 => '{"type":"general_argument_invalid","message":"Invalid `password` param: Value must be a valid string and at least 1 chars and no longer than 256 chars","code":400,"version":"0.2.0"}',
|
||||
503 => '{"type":"dataset_unavailable","message":"The password dataset could not be read.","code":503,"version":"0.2.0"}',
|
||||
500 => '',
|
||||
];
|
||||
|
||||
foreach ($errors as $statusCode => $body) {
|
||||
$fetch = new DetectionFetch(statusCode: $statusCode, body: $body);
|
||||
|
||||
try {
|
||||
$this->validator($fetch)->isValid(self::PASSWORD);
|
||||
$this->fail('Expected a ' . $statusCode . ' to surface');
|
||||
} catch (Exception $e) {
|
||||
$this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType(), (string) $statusCode);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An answer the validator cannot read must never pass as a clean password.
|
||||
*/
|
||||
public function testUnreadableAnswerIsReported(): void
|
||||
{
|
||||
foreach (['', 'not json', '{}', '{"leaked":"yes"}', '{"pwned":true}'] as $body) {
|
||||
$fetch = new DetectionFetch(body: $body);
|
||||
|
||||
try {
|
||||
$this->validator($fetch)->isValid(self::PASSWORD);
|
||||
$this->fail('Expected an unreadable answer to surface: ' . $body);
|
||||
} catch (Exception $e) {
|
||||
$this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function testAnswersAreCached(): void
|
||||
{
|
||||
$fetch = new DetectionFetch(body: '{"leaked":true}');
|
||||
$cache = new Cache(new Memory());
|
||||
|
||||
$this->assertFalse((new Appwrite(new DSN(self::DSN), $cache, new Client($fetch)))->isValid(self::PASSWORD));
|
||||
$this->assertFalse((new Appwrite(new DSN(self::DSN), $cache, new Client($fetch)))->isValid(self::PASSWORD));
|
||||
|
||||
$this->assertCount(1, $fetch->requests);
|
||||
}
|
||||
|
||||
public function testEachPasswordGetsItsOwnAnswer(): void
|
||||
{
|
||||
$fetch = new DetectionFetch(body: '{"leaked":true}');
|
||||
$cache = new Cache(new Memory());
|
||||
$validator = new Appwrite(new DSN(self::DSN), $cache, new Client($fetch));
|
||||
|
||||
$validator->isValid(self::PASSWORD);
|
||||
$validator->isValid('a-completely-different-password');
|
||||
|
||||
$this->assertCount(2, $fetch->requests);
|
||||
}
|
||||
|
||||
public function testCacheIsScopedToEndpoint(): void
|
||||
{
|
||||
$fetch = new DetectionFetch(body: '{"leaked":true}');
|
||||
$cache = new Cache(new Memory());
|
||||
|
||||
(new Appwrite(new DSN('appwrite://secret@one.test'), $cache, new Client($fetch)))->isValid(self::PASSWORD);
|
||||
(new Appwrite(new DSN('appwrite://secret@two.test'), $cache, new Client($fetch)))->isValid(self::PASSWORD);
|
||||
|
||||
$this->assertCount(2, $fetch->requests);
|
||||
}
|
||||
|
||||
public function testFailedLookupIsNotCached(): void
|
||||
{
|
||||
$fetch = new DetectionFetch(failure: new \RuntimeException('connection refused'));
|
||||
$validator = new Appwrite(new DSN(self::DSN), new Cache(new Memory()), new Client($fetch));
|
||||
|
||||
foreach ([1, 2] as $attempt) {
|
||||
try {
|
||||
$validator->isValid(self::PASSWORD);
|
||||
} catch (Exception) {
|
||||
// The lookup failed, which is the point; it must be retried rather than remembered
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertCount(2, $fetch->requests);
|
||||
}
|
||||
|
||||
private function validator(DetectionFetch $fetch): Appwrite
|
||||
{
|
||||
return new Appwrite(new DSN(self::DSN), null, new Client($fetch));
|
||||
}
|
||||
}
|
||||
|
||||
final class DetectionFetch implements Adapter
|
||||
{
|
||||
/** @var array<int, array{url: string, method: string, body: mixed, headers: array<string, string>}> */
|
||||
public array $requests = [];
|
||||
|
||||
public function __construct(
|
||||
private int $statusCode = 200,
|
||||
private string $body = '',
|
||||
private ?\Throwable $failure = null,
|
||||
) {
|
||||
}
|
||||
|
||||
public function send(
|
||||
string $url,
|
||||
string $method,
|
||||
mixed $body,
|
||||
array $headers,
|
||||
RequestOptions $options,
|
||||
?callable $chunkCallback = null
|
||||
): Response {
|
||||
$this->requests[] = ['url' => $url, 'method' => $method, 'body' => $body, 'headers' => $headers];
|
||||
|
||||
if ($this->failure !== null) {
|
||||
throw $this->failure;
|
||||
}
|
||||
|
||||
return new Response($this->statusCode, $this->body, []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Auth\Validator\PasswordPwned;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordPwned\HIBP;
|
||||
use Appwrite\Extend\Exception;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use Utopia\Cache\Adapter\Memory;
|
||||
use Utopia\Cache\Cache;
|
||||
use Utopia\Fetch\Adapter;
|
||||
use Utopia\Fetch\Client;
|
||||
use Utopia\Fetch\Options\Request as RequestOptions;
|
||||
use Utopia\Fetch\Response;
|
||||
|
||||
final class HIBPTest extends TestCase
|
||||
{
|
||||
private const LEAKED = 'Password123!';
|
||||
private const ENDPOINT = 'https://breaches.test/range';
|
||||
|
||||
public function testLeakedPasswordIsRejected(): void
|
||||
{
|
||||
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 42]));
|
||||
|
||||
$this->assertFalse($this->validator($fetch)->isValid(self::LEAKED));
|
||||
}
|
||||
|
||||
public function testCleanPasswordIsAccepted(): void
|
||||
{
|
||||
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 42]));
|
||||
|
||||
$this->assertTrue($this->validator($fetch)->isValid('never-leaked-' . \uniqid()));
|
||||
}
|
||||
|
||||
public function testAnySingleBreachIsEnough(): void
|
||||
{
|
||||
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 1]));
|
||||
|
||||
$this->assertFalse($this->validator($fetch)->isValid(self::LEAKED));
|
||||
}
|
||||
|
||||
public function testPaddedEntryWithZeroCountIsNotABreach(): void
|
||||
{
|
||||
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 0]));
|
||||
|
||||
$this->assertTrue($this->validator($fetch)->isValid(self::LEAKED));
|
||||
}
|
||||
|
||||
public function testSuffixComparisonIgnoresCase(): void
|
||||
{
|
||||
$fetch = new RangeFetch(body: \strtolower($this->range([self::LEAKED => 3])));
|
||||
|
||||
$this->assertFalse($this->validator($fetch)->isValid(self::LEAKED));
|
||||
}
|
||||
|
||||
public function testOnlyTheHashPrefixLeavesTheServer(): void
|
||||
{
|
||||
$fetch = new RangeFetch(body: '');
|
||||
|
||||
$this->validator($fetch)->isValid(self::LEAKED);
|
||||
|
||||
$this->assertCount(1, $fetch->urls);
|
||||
|
||||
$hash = \strtoupper(\sha1(self::LEAKED));
|
||||
$url = $fetch->urls[0];
|
||||
|
||||
// Neither the password nor anything that identifies it may reach the service
|
||||
$this->assertStringNotContainsStringIgnoringCase(self::LEAKED, $url);
|
||||
$this->assertStringNotContainsStringIgnoringCase($hash, $url);
|
||||
$this->assertStringNotContainsStringIgnoringCase(\substr($hash, 5), $url);
|
||||
|
||||
// Only the first five characters go out, so the service cannot tell which password was checked
|
||||
$this->assertStringEndsWith(\substr($hash, 0, 5), $url);
|
||||
}
|
||||
|
||||
public function testRangeIsCachedPerPrefix(): void
|
||||
{
|
||||
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 42]));
|
||||
$cache = new Cache(new Memory());
|
||||
|
||||
$this->assertFalse((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED));
|
||||
$this->assertFalse((new HIBP($cache, new Client($fetch), self::ENDPOINT))->isValid(self::LEAKED));
|
||||
|
||||
$this->assertCount(1, $fetch->urls);
|
||||
}
|
||||
|
||||
public function testCacheIsScopedToEndpoint(): void
|
||||
{
|
||||
$fetch = new RangeFetch(body: $this->range([self::LEAKED => 42]));
|
||||
$cache = new Cache(new Memory());
|
||||
|
||||
(new HIBP($cache, new Client($fetch), 'https://one.test/range'))->isValid(self::LEAKED);
|
||||
(new HIBP($cache, new Client($fetch), 'https://two.test/range'))->isValid(self::LEAKED);
|
||||
|
||||
$this->assertCount(2, $fetch->urls);
|
||||
}
|
||||
|
||||
public function testLookupsGoToTheConfiguredEndpoint(): void
|
||||
{
|
||||
$fetch = new RangeFetch(body: '');
|
||||
|
||||
(new HIBP(null, new Client($fetch), 'https://server.test/range'))->isValid(self::LEAKED);
|
||||
(new HIBP(null, new Client($fetch), 'https://other.test/range/'))->isValid(self::LEAKED);
|
||||
|
||||
$this->assertStringStartsWith('https://server.test/range/', $fetch->urls[0]);
|
||||
$this->assertStringStartsWith('https://other.test/range/', $fetch->urls[1]);
|
||||
}
|
||||
|
||||
public function testUnreachableServiceIsReported(): void
|
||||
{
|
||||
$fetch = new RangeFetch(failure: new \RuntimeException('connection refused'));
|
||||
|
||||
try {
|
||||
$this->validator($fetch)->isValid(self::LEAKED);
|
||||
$this->fail('Expected the unreachable service to surface');
|
||||
} catch (Exception $e) {
|
||||
$this->assertSame(Exception::GENERAL_PWNED_PASSWORDS_UNAVAILABLE, $e->getType());
|
||||
}
|
||||
}
|
||||
|
||||
public function testUnexpectedStatusIsReported(): void
|
||||
{
|
||||
$fetch = new RangeFetch(statusCode: 503, body: '');
|
||||
|
||||
$this->expectException(Exception::class);
|
||||
|
||||
$this->validator($fetch)->isValid(self::LEAKED);
|
||||
}
|
||||
|
||||
public function testFailedLookupIsNotCached(): void
|
||||
{
|
||||
$fetch = new RangeFetch(failure: new \RuntimeException('connection refused'));
|
||||
$validator = new HIBP(new Cache(new Memory()), new Client($fetch), self::ENDPOINT);
|
||||
|
||||
foreach ([1, 2] as $attempt) {
|
||||
try {
|
||||
$validator->isValid(self::LEAKED);
|
||||
} catch (Exception) {
|
||||
// The lookup failed, which is the point; it must be retried rather than remembered
|
||||
}
|
||||
}
|
||||
|
||||
$this->assertCount(2, $fetch->urls);
|
||||
}
|
||||
|
||||
private function validator(RangeFetch $fetch): HIBP
|
||||
{
|
||||
return new HIBP(null, new Client($fetch), self::ENDPOINT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a range response body the way the Have I Been Pwned API does:
|
||||
* one `SUFFIX:COUNT` line per leaked hash, CRLF separated, plus padding.
|
||||
*
|
||||
* @param array<string, int> $leaked password => breach count
|
||||
*/
|
||||
private function range(array $leaked): string
|
||||
{
|
||||
$lines = [];
|
||||
foreach ($leaked as $password => $count) {
|
||||
$lines[] = \substr(\strtoupper(\sha1((string) $password)), 5) . ':' . $count;
|
||||
}
|
||||
$lines[] = \str_repeat('0', 35) . ':0';
|
||||
|
||||
return \implode("\r\n", $lines);
|
||||
}
|
||||
}
|
||||
|
||||
final class RangeFetch implements Adapter
|
||||
{
|
||||
/** @var array<int, string> URLs the validator asked the breach service for */
|
||||
public array $urls = [];
|
||||
|
||||
public function __construct(
|
||||
private int $statusCode = 200,
|
||||
private string $body = '',
|
||||
private ?\Throwable $failure = null,
|
||||
) {
|
||||
}
|
||||
|
||||
public function send(
|
||||
string $url,
|
||||
string $method,
|
||||
mixed $body,
|
||||
array $headers,
|
||||
RequestOptions $options,
|
||||
?callable $chunkCallback = null
|
||||
): Response {
|
||||
$this->urls[] = $url;
|
||||
|
||||
if ($this->failure !== null) {
|
||||
throw $this->failure;
|
||||
}
|
||||
|
||||
return new Response($this->statusCode, $this->body, []);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Auth\Validator\PasswordPwned;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordPwned\Mock;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class MockTest extends TestCase
|
||||
{
|
||||
public function testFixturesAreReportedAsBreached(): void
|
||||
{
|
||||
$validator = new Mock();
|
||||
|
||||
foreach (Mock::BREACHED as $password) {
|
||||
$this->assertFalse($validator->isValid($password), $password);
|
||||
}
|
||||
}
|
||||
|
||||
public function testAnythingElseIsAccepted(): void
|
||||
{
|
||||
$validator = new Mock();
|
||||
|
||||
$this->assertTrue($validator->isValid('some-other-password'));
|
||||
}
|
||||
|
||||
public function testMatchingIsExact(): void
|
||||
{
|
||||
$validator = new Mock();
|
||||
$fixture = Mock::BREACHED[0];
|
||||
|
||||
// A password that merely resembles a fixture is not breached
|
||||
$this->assertTrue($validator->isValid(\strtoupper($fixture)));
|
||||
$this->assertTrue($validator->isValid($fixture . '!'));
|
||||
$this->assertTrue($validator->isValid(\substr($fixture, 1)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Auth\Validator\PasswordPwned;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordPwned\Mock;
|
||||
use Appwrite\Auth\Validator\PasswordPwned\None;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class NoneTest extends TestCase
|
||||
{
|
||||
public function testEveryPasswordIsAccepted(): void
|
||||
{
|
||||
$validator = new None();
|
||||
|
||||
// Even the ones every other validator would reject
|
||||
foreach ([...Mock::BREACHED, 'password', '123456789', 'qwertyuiop'] as $password) {
|
||||
$this->assertTrue($validator->isValid($password), $password);
|
||||
}
|
||||
}
|
||||
|
||||
public function testBasePasswordRulesStillApply(): void
|
||||
{
|
||||
$validator = new None();
|
||||
|
||||
$this->assertFalse($validator->isValid('short'));
|
||||
$this->assertFalse($validator->isValid(\str_repeat('p', 257)));
|
||||
$this->assertFalse($validator->isValid(''));
|
||||
}
|
||||
|
||||
public function testAllowEmptyAcceptsAnEmptyPassword(): void
|
||||
{
|
||||
$this->assertTrue((new None(allowEmpty: true))->isValid(''));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Tests\Unit\Auth\Validator;
|
||||
|
||||
use Appwrite\Auth\Validator\PasswordPwned\Mock;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* The behaviour every breach validator shares, exercised through the one
|
||||
* subclass that needs no service behind it.
|
||||
*/
|
||||
final class PasswordPwnedTest extends TestCase
|
||||
{
|
||||
private const BREACHED = Mock::BREACHED[0];
|
||||
|
||||
public function testBreachedPasswordIsInvalid(): void
|
||||
{
|
||||
$validator = new Mock();
|
||||
|
||||
$this->assertFalse($validator->isValid(self::BREACHED));
|
||||
$this->assertTrue($validator->isValid('a-password-nobody-leaked'));
|
||||
}
|
||||
|
||||
public function testBasePasswordRulesStillApply(): void
|
||||
{
|
||||
$validator = new Mock();
|
||||
|
||||
$this->assertFalse($validator->isValid('short'));
|
||||
$this->assertFalse($validator->isValid(\str_repeat('p', 257)));
|
||||
$this->assertFalse($validator->isValid(''));
|
||||
}
|
||||
|
||||
public function testAllowEmptyAcceptsAnEmptyPassword(): void
|
||||
{
|
||||
$this->assertTrue((new Mock(allowEmpty: true))->isValid(''));
|
||||
$this->assertFalse((new Mock(allowEmpty: true))->isValid(self::BREACHED));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user