Merge pull request #11825 from appwrite/feat-project-password-policy

Add project password policy settings
This commit is contained in:
Torsten Dittmann authored and GitHub committed 2026-06-03 15:49:31 +04:00
commit ff6711283b
17 files changed
+782 -12

No files matched your search

+6 -4
View File
@@ -7,6 +7,7 @@ use Appwrite\Auth\Phrase;
use Appwrite\Auth\Validator\Password;
use Appwrite\Auth\Validator\PasswordDictionary;
use Appwrite\Auth\Validator\PasswordHistory;
use Appwrite\Auth\Validator\PasswordStrength;
use Appwrite\Auth\Validator\PersonalData;
use Appwrite\Auth\Validator\Phone;
use Appwrite\Bus\Events\SessionCreated;
@@ -71,6 +72,7 @@ use Utopia\Platform\Enum;
use Utopia\Storage\Validator\FileName;
use Utopia\System\System;
use Utopia\Validator;
use Utopia\Validator\AllOf;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Assoc;
use Utopia\Validator\Boolean;
@@ -255,7 +257,7 @@ Http::post('/v1/account')
->label('abuse-limit', 10)
->param('userId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForProject'])
->param('email', '', new EmailValidator(), 'User email.')
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordDictionary($passwordsDictionary, $project->getAttribute('auths', [])['passwordDictionary'] ?? false), 'New user password. Must be between 8 and 256 chars.', false, ['project', 'passwordsDictionary'])
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING), 'New user password. Must be between 8 and 256 chars.', false, ['project', 'passwordsDictionary'])
->param('name', '', new Text(128), 'User name. Max length: 128 chars.', true)
->inject('request')
->inject('response')
@@ -3271,8 +3273,8 @@ Http::patch('/v1/account/password')
contentType: ContentType::JSON
))
->label('abuse-limit', 10)
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordDictionary($passwordsDictionary, $project->getAttribute('auths', [])['passwordDictionary'] ?? false), 'New user password. Must be at least 8 chars.', false, ['project', 'passwordsDictionary'])
->param('oldPassword', '', new Password(), 'Current user password. Must be at least 8 chars.', true)
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING), 'New user password. Must be at least 8 chars.', false, ['project', 'passwordsDictionary'])
->param('oldPassword', '', new Text(256, 0), 'Current user password. Max length: 256 chars.', true)
->inject('response')
->inject('user')
->inject('project')
@@ -3888,7 +3890,7 @@ Http::put('/v1/account/recovery')
->label('abuse-key', 'url:{url},userId:{param-userId}')
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('secret', '', new Text(256), 'Valid reset token.')
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordDictionary($passwordsDictionary, $project->getAttribute('auths', [])['passwordDictionary'] ?? false), 'New user password. Must be between 8 and 256 chars.', false, ['project', 'passwordsDictionary'])
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING), 'New user password. Must be between 8 and 256 chars.', false, ['project', 'passwordsDictionary'])
->inject('response')
->inject('user')
->inject('dbForProject')
+5 -2
View File
@@ -6,6 +6,7 @@ use Appwrite\Auth\MFA\Type\TOTP;
use Appwrite\Auth\Validator\Password;
use Appwrite\Auth\Validator\PasswordDictionary;
use Appwrite\Auth\Validator\PasswordHistory;
use Appwrite\Auth\Validator\PasswordStrength;
use Appwrite\Auth\Validator\PersonalData;
use Appwrite\Auth\Validator\Phone;
use Appwrite\Deletes\Identities as DeleteIdentities;
@@ -65,6 +66,8 @@ use Utopia\Http\Http;
use Utopia\Locale\Locale;
use Utopia\Platform\Enum;
use Utopia\System\System;
use Utopia\Validator;
use Utopia\Validator\AllOf;
use Utopia\Validator\ArrayList;
use Utopia\Validator\Assoc;
use Utopia\Validator\Boolean;
@@ -280,7 +283,7 @@ Http::post('/v1/users')
->param('userId', '', fn (Database $dbForProject) => new CustomId(false, $dbForProject->getAdapter()->getMaxUIDLength()), 'User ID. Choose a custom ID or generate a random ID with `ID.unique()`. Valid chars are a-z, A-Z, 0-9, period, hyphen, and underscore. Can\'t start with a special char. Max length is 36 chars.', false, ['dbForProject'])
->param('email', null, new Nullable(new EmailValidator()), 'User email.', true)
->param('phone', null, new Nullable(new Phone()), 'Phone number. Format this number with a leading \'+\' and a country code, e.g., +16175551212.', true)
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordDictionary($passwordsDictionary, $project->getAttribute('auths', [])['passwordDictionary'] ?? false), 'Plain text user password. Must be at least 8 chars.', true, ['project', 'passwordsDictionary'])
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? []), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false)], Validator::TYPE_STRING), 'Plain text user password. Must be at least 8 chars.', true, ['project', 'passwordsDictionary'])
->param('name', '', new Text(128), 'User name. Max length: 128 chars.', true)
->inject('response')
->inject('project')
@@ -1431,7 +1434,7 @@ Http::patch('/v1/users/:userId/password')
]
))
->param('userId', '', fn (Database $dbForProject) => new UID($dbForProject->getAdapter()->getMaxUIDLength()), 'User ID.', false, ['dbForProject'])
->param('password', '', fn ($project, $passwordsDictionary) => new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false, allowEmpty: true), 'New user password. Must be at least 8 chars.', false, ['project', 'passwordsDictionary'])
->param('password', '', fn ($project, $passwordsDictionary) => new AllOf([new PasswordStrength($project->getAttribute('auths', [])['passwordStrength'] ?? [], allowEmpty: true), new PasswordDictionary($passwordsDictionary, enabled: $project->getAttribute('auths', [])['passwordDictionary'] ?? false, allowEmpty: true)], Validator::TYPE_STRING), 'New user password. Must be at least 8 chars.', false, ['project', 'passwordsDictionary'])
->inject('response')
->inject('project')
->inject('dbForProject')
+2
View File
@@ -168,6 +168,7 @@ use Appwrite\Utopia\Response\Model\PolicyMembershipPrivacy;
use Appwrite\Utopia\Response\Model\PolicyPasswordDictionary;
use Appwrite\Utopia\Response\Model\PolicyPasswordHistory;
use Appwrite\Utopia\Response\Model\PolicyPasswordPersonalData;
use Appwrite\Utopia\Response\Model\PolicyPasswordStrength;
use Appwrite\Utopia\Response\Model\PolicySessionAlert;
use Appwrite\Utopia\Response\Model\PolicySessionDuration;
use Appwrite\Utopia\Response\Model\PolicySessionInvalidation;
@@ -460,6 +461,7 @@ Response::setModel(new OAuth2Microsoft());
Response::setModel(new OAuth2ProviderList());
Response::setModel(new PolicyPasswordDictionary());
Response::setModel(new PolicyPasswordHistory());
Response::setModel(new PolicyPasswordStrength());
Response::setModel(new PolicyPasswordPersonalData());
Response::setModel(new PolicySessionAlert());
Response::setModel(new PolicySessionDuration());
@@ -0,0 +1,89 @@
<?php
namespace Appwrite\Auth\Validator;
/**
* PasswordStrength.
*
* Validates password complexity rules.
*/
class PasswordStrength extends Password
{
protected int $min;
protected bool $uppercase;
protected bool $lowercase;
protected bool $number;
protected bool $symbols;
public function __construct(array $policy = [], bool $allowEmpty = false)
{
parent::__construct($allowEmpty);
$this->min = $policy['min'] ?? 8;
$this->uppercase = $policy['uppercase'] ?? false;
$this->lowercase = $policy['lowercase'] ?? false;
$this->number = $policy['number'] ?? false;
$this->symbols = $policy['symbols'] ?? false;
}
public function getDescription(): string
{
$requirements = [
'between ' . $this->min . ' and 256 characters long',
];
if ($this->uppercase) {
$requirements[] = 'include an uppercase letter';
}
if ($this->lowercase) {
$requirements[] = 'include a lowercase letter';
}
if ($this->number) {
$requirements[] = 'include a number';
}
if ($this->symbols) {
$requirements[] = 'include a symbol';
}
return 'Password must be ' . \implode(', ', $requirements) . '.';
}
/**
* @param mixed $value
*/
public function isValid($value): bool
{
if (!parent::isValid($value)) {
return false;
}
if ($this->allowEmpty && \strlen($value) === 0) {
return true;
}
if (\strlen($value) < $this->min) {
return false;
}
if ($this->uppercase && !\preg_match('/[A-Z]/', $value)) {
return false;
}
if ($this->lowercase && !\preg_match('/[a-z]/', $value)) {
return false;
}
if ($this->number && !\preg_match('/\d/', $value)) {
return false;
}
if ($this->symbols && !\preg_match('/[^\p{L}\p{N}\s]/u', $value)) {
return false;
}
return true;
}
}
@@ -77,6 +77,7 @@ class Get extends Action
return [
'password-dictionary' => Response::MODEL_POLICY_PASSWORD_DICTIONARY,
'password-history' => Response::MODEL_POLICY_PASSWORD_HISTORY,
'password-strength' => Response::MODEL_POLICY_PASSWORD_STRENGTH,
'password-personal-data' => Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA,
'session-alert' => Response::MODEL_POLICY_SESSION_ALERT,
'session-duration' => Response::MODEL_POLICY_SESSION_DURATION,
@@ -109,6 +110,18 @@ class Get extends Action
]),
Response::MODEL_POLICY_PASSWORD_HISTORY,
],
'password-strength' => [
new Document(\array_merge([
'min' => 8,
'uppercase' => false,
'lowercase' => false,
'number' => false,
'symbols' => false,
], $auths['passwordStrength'] ?? [], [
'$id' => 'password-strength',
])),
Response::MODEL_POLICY_PASSWORD_STRENGTH,
],
'password-personal-data' => [
new Document([
'$id' => 'password-personal-data',
@@ -0,0 +1,115 @@
<?php
namespace Appwrite\Platform\Modules\Project\Http\Project\Policies\PasswordStrength;
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;
use Utopia\Validator\Range;
class Update extends Action
{
use HTTP;
public static function getName()
{
return 'updateProjectPasswordStrengthPolicy';
}
public function __construct()
{
$this
->setHttpMethod(Action::HTTP_REQUEST_METHOD_PATCH)
->setHttpPath('/v1/project/policies/password-strength')
->desc('Update password strength 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: 'updatePasswordStrengthPolicy',
description: <<<'EOT'
Update the password strength requirements for users in the project.
EOT,
auth: [AuthType::ADMIN, AuthType::KEY],
responses: [
new SDKResponse(
code: Response::STATUS_CODE_OK,
model: Response::MODEL_POLICY_PASSWORD_STRENGTH,
),
],
))
->param('min', null, new Range(8, 256), 'Minimum password length. Value must be between 8 and 256. Default is 8.', optional: true)
->param('uppercase', null, new Boolean(), 'Whether passwords must include at least one uppercase letter.', optional: true)
->param('lowercase', null, new Boolean(), 'Whether passwords must include at least one lowercase letter.', optional: true)
->param('number', null, new Boolean(), 'Whether passwords must include at least one number.', optional: true)
->param('symbols', null, new Boolean(), 'Whether passwords must include at least one symbol.', optional: true)
->inject('response')
->inject('dbForPlatform')
->inject('project')
->inject('authorization')
->inject('queueForEvents')
->callback($this->action(...));
}
public function action(
?int $min,
?bool $uppercase,
?bool $lowercase,
?bool $number,
?bool $symbols,
Response $response,
Database $dbForPlatform,
Document $project,
Authorization $authorization,
Event $queueForEvents,
): void {
$auths = $project->getAttribute('auths', []);
$auths['passwordStrength'] = \array_merge([
'min' => 8,
'uppercase' => false,
'lowercase' => false,
'number' => false,
'symbols' => false,
], $auths['passwordStrength'] ?? []);
if ($min !== null) {
$auths['passwordStrength']['min'] = $min;
}
if ($uppercase !== null) {
$auths['passwordStrength']['uppercase'] = $uppercase;
}
if ($lowercase !== null) {
$auths['passwordStrength']['lowercase'] = $lowercase;
}
if ($number !== null) {
$auths['passwordStrength']['number'] = $number;
}
if ($symbols !== null) {
$auths['passwordStrength']['symbols'] = $symbols;
}
$project = $authorization->skip(fn () => $dbForPlatform->updateDocument('projects', $project->getId(), new Document([
'auths' => $auths,
])));
$queueForEvents
->setParam('projectId', $project->getId())
->setParam('policy', 'password-strength');
$response->dynamic(new Document(\array_merge($auths['passwordStrength'], [
'$id' => 'password-strength',
])), Response::MODEL_POLICY_PASSWORD_STRENGTH);
}
}
@@ -103,6 +103,15 @@ class XList extends Action
'$id' => 'password-history',
'total' => $auths['passwordHistory'] ?? 0,
]),
new Document(\array_merge([
'min' => 8,
'uppercase' => false,
'lowercase' => false,
'number' => false,
'symbols' => false,
], $auths['passwordStrength'] ?? [], [
'$id' => 'password-strength',
])),
new Document([
'$id' => 'password-personal-data',
'enabled' => $auths['personalDataCheck'] ?? false,
@@ -80,6 +80,7 @@ use Appwrite\Platform\Modules\Project\Http\Project\Policies\MembershipPrivacy\Up
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\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;
use Appwrite\Platform\Modules\Project\Http\Project\Policies\SessionInvalidation\Update as UpdateSessionInvalidationPolicy;
@@ -168,6 +169,7 @@ class Http extends Service
$this->addAction(UpdateMembershipPrivacyPolicy::getName(), new UpdateMembershipPrivacyPolicy());
$this->addAction(UpdatePasswordDictionaryPolicy::getName(), new UpdatePasswordDictionaryPolicy());
$this->addAction(UpdatePasswordHistoryPolicy::getName(), new UpdatePasswordHistoryPolicy());
$this->addAction(UpdatePasswordStrengthPolicy::getName(), new UpdatePasswordStrengthPolicy());
$this->addAction(UpdatePasswordPersonalDataPolicy::getName(), new UpdatePasswordPersonalDataPolicy());
$this->addAction(UpdateSessionAlertPolicy::getName(), new UpdateSessionAlertPolicy());
$this->addAction(UpdateSessionDurationPolicy::getName(), new UpdateSessionDurationPolicy());
@@ -83,6 +83,13 @@ class Create extends Action
$auths = [
'limit' => 0,
'maxSessions' => 0,
'passwordStrength' => [
'min' => 8,
'uppercase' => false,
'lowercase' => false,
'number' => false,
'symbols' => false,
],
'passwordHistory' => 0,
'passwordDictionary' => false,
'duration' => TOKEN_EXPIRATION_LOGIN_LONG,
+1
View File
@@ -267,6 +267,7 @@ class Response extends SwooleResponse
public const MODEL_POLICY_LIST = 'policyList';
public const MODEL_POLICY_PASSWORD_DICTIONARY = 'policyPasswordDictionary';
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_SESSION_ALERT = 'policySessionAlert';
public const MODEL_POLICY_SESSION_DURATION = 'policySessionDuration';
@@ -14,7 +14,7 @@ class PolicyList extends Model
'type' => self::TYPE_INTEGER,
'description' => 'Total number of policies in the given project.',
'default' => 0,
'example' => 9,
'example' => 10,
])
->addRule('policies', [
'type' => $this->getPolicyModels(),
@@ -32,6 +32,7 @@ class PolicyList extends Model
return [
Response::MODEL_POLICY_PASSWORD_DICTIONARY,
Response::MODEL_POLICY_PASSWORD_HISTORY,
Response::MODEL_POLICY_PASSWORD_STRENGTH,
Response::MODEL_POLICY_PASSWORD_PERSONAL_DATA,
Response::MODEL_POLICY_SESSION_ALERT,
Response::MODEL_POLICY_SESSION_DURATION,
@@ -0,0 +1,59 @@
<?php
namespace Appwrite\Utopia\Response\Model;
use Appwrite\Utopia\Response;
class PolicyPasswordStrength extends PolicyBase
{
public array $conditions = [
'$id' => 'password-strength',
];
public function __construct()
{
parent::__construct();
$this
->addRule('min', [
'type' => self::TYPE_INTEGER,
'description' => 'Minimum password length required for user passwords.',
'default' => 8,
'example' => 12,
])
->addRule('uppercase', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether passwords must include at least one uppercase letter.',
'default' => false,
'example' => true,
])
->addRule('lowercase', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether passwords must include at least one lowercase letter.',
'default' => false,
'example' => true,
])
->addRule('number', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether passwords must include at least one number.',
'default' => false,
'example' => true,
])
->addRule('symbols', [
'type' => self::TYPE_BOOLEAN,
'description' => 'Whether passwords must include at least one symbol.',
'default' => false,
'example' => true,
]);
}
public function getName(): string
{
return 'Policy Password Strength';
}
public function getType(): string
{
return Response::MODEL_POLICY_PASSWORD_STRENGTH;
}
}
+160 -5
View File
@@ -15,6 +15,7 @@ trait PoliciesBase
return [
'password-dictionary' => ['enabled'],
'password-history' => ['total'],
'password-strength' => ['min', 'uppercase', 'lowercase', 'number', 'symbols'],
'password-personal-data' => ['enabled'],
'session-alert' => ['enabled'],
'session-duration' => ['duration'],
@@ -66,6 +67,13 @@ trait PoliciesBase
{
$this->updatePasswordDictionaryPolicy(true);
$this->updatePasswordHistoryPolicy(5);
$this->updatePasswordStrengthPolicy([
'min' => 12,
'uppercase' => true,
'lowercase' => true,
'number' => true,
'symbols' => true,
]);
$this->updateSessionDurationPolicy(3600);
$this->updateMembershipPrivacyPolicy([
'userId' => true,
@@ -77,6 +85,7 @@ trait PoliciesBase
$passwordDictionary = $this->getPolicy('password-dictionary');
$passwordHistory = $this->getPolicy('password-history');
$passwordStrength = $this->getPolicy('password-strength');
$sessionDuration = $this->getPolicy('session-duration');
$membershipPrivacy = $this->getPolicy('membership-privacy');
@@ -86,6 +95,13 @@ trait PoliciesBase
$this->assertSame(200, $passwordHistory['headers']['status-code']);
$this->assertSame(5, $passwordHistory['body']['total']);
$this->assertSame(200, $passwordStrength['headers']['status-code']);
$this->assertSame(12, $passwordStrength['body']['min']);
$this->assertSame(true, $passwordStrength['body']['uppercase']);
$this->assertSame(true, $passwordStrength['body']['lowercase']);
$this->assertSame(true, $passwordStrength['body']['number']);
$this->assertSame(true, $passwordStrength['body']['symbols']);
$this->assertSame(200, $sessionDuration['headers']['status-code']);
$this->assertSame(3600, $sessionDuration['body']['duration']);
@@ -99,6 +115,7 @@ trait PoliciesBase
// Cleanup
$this->updatePasswordDictionaryPolicy(false);
$this->updatePasswordHistoryPolicy(null);
$this->resetPasswordStrengthPolicy();
$this->updateSessionDurationPolicy(31536000);
$this->updateMembershipPrivacyPolicy([
'userId' => false,
@@ -180,6 +197,13 @@ trait PoliciesBase
{
$this->updatePasswordDictionaryPolicy(true);
$this->updatePasswordHistoryPolicy(5);
$this->updatePasswordStrengthPolicy([
'min' => 12,
'uppercase' => true,
'lowercase' => true,
'number' => true,
'symbols' => true,
]);
$this->updateSessionDurationPolicy(3600);
$this->updateMembershipPrivacyPolicy([
'userId' => true,
@@ -200,6 +224,11 @@ trait PoliciesBase
$this->assertSame(true, $byId['password-dictionary']['enabled']);
$this->assertSame(5, $byId['password-history']['total']);
$this->assertSame(12, $byId['password-strength']['min']);
$this->assertSame(true, $byId['password-strength']['uppercase']);
$this->assertSame(true, $byId['password-strength']['lowercase']);
$this->assertSame(true, $byId['password-strength']['number']);
$this->assertSame(true, $byId['password-strength']['symbols']);
$this->assertSame(3600, $byId['session-duration']['duration']);
$this->assertSame(true, $byId['membership-privacy']['userId']);
$this->assertSame(true, $byId['membership-privacy']['userEmail']);
@@ -210,6 +239,7 @@ trait PoliciesBase
// Cleanup
$this->updatePasswordDictionaryPolicy(false);
$this->updatePasswordHistoryPolicy(null);
$this->resetPasswordStrengthPolicy();
$this->updateSessionDurationPolicy(31536000);
$this->updateMembershipPrivacyPolicy([
'userId' => false,
@@ -435,6 +465,112 @@ trait PoliciesBase
$this->assertSame(401, $response['headers']['status-code']);
}
// =========================================================================
// Password Strength
// =========================================================================
public function testUpdatePasswordStrengthPolicy(): void
{
$response = $this->updatePasswordStrengthPolicy([
'min' => 12,
'uppercase' => true,
'lowercase' => true,
'number' => true,
'symbols' => true,
]);
$this->assertSame(200, $response['headers']['status-code']);
$this->assertSame('password-strength', $response['body']['$id']);
$this->assertSame(12, $response['body']['min']);
$this->assertSame(true, $response['body']['uppercase']);
$this->assertSame(true, $response['body']['lowercase']);
$this->assertSame(true, $response['body']['number']);
$this->assertSame(true, $response['body']['symbols']);
$policy = $this->getPolicy('password-strength');
$this->assertSame(200, $policy['headers']['status-code']);
$this->assertSame(12, $policy['body']['min']);
$this->assertSame(true, $policy['body']['uppercase']);
$this->assertSame(true, $policy['body']['lowercase']);
$this->assertSame(true, $policy['body']['number']);
$this->assertSame(true, $policy['body']['symbols']);
// Cleanup
$this->resetPasswordStrengthPolicy();
}
public function testUpdatePasswordStrengthPolicyOptionPreservesOtherOptions(): void
{
$response = $this->updatePasswordStrengthPolicy([
'min' => 12,
'uppercase' => true,
'lowercase' => true,
'number' => true,
'symbols' => true,
]);
$this->assertSame(200, $response['headers']['status-code']);
$response = $this->updatePasswordStrengthPolicy([
'lowercase' => false,
]);
$this->assertSame(200, $response['headers']['status-code']);
$this->assertSame(12, $response['body']['min']);
$this->assertSame(true, $response['body']['uppercase']);
$this->assertSame(false, $response['body']['lowercase']);
$this->assertSame(true, $response['body']['number']);
$this->assertSame(true, $response['body']['symbols']);
// Cleanup
$this->resetPasswordStrengthPolicy();
}
public function testUpdatePasswordStrengthPolicyMin(): void
{
$response = $this->updatePasswordStrengthPolicy([
'min' => 8,
]);
$this->assertSame(200, $response['headers']['status-code']);
$this->assertSame(8, $response['body']['min']);
// Cleanup
$this->resetPasswordStrengthPolicy();
}
public function testUpdatePasswordStrengthPolicyBelowMin(): void
{
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->buildHeaders(), [
'min' => 7,
]);
$this->assertSame(400, $response['headers']['status-code']);
}
public function testUpdatePasswordStrengthPolicyEmptyBody(): void
{
$this->resetPasswordStrengthPolicy();
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->buildHeaders(), []);
$this->assertSame(200, $response['headers']['status-code']);
$this->assertSame(8, $response['body']['min']);
$this->assertSame(false, $response['body']['uppercase']);
$this->assertSame(false, $response['body']['lowercase']);
$this->assertSame(false, $response['body']['number']);
$this->assertSame(false, $response['body']['symbols']);
}
public function testUpdatePasswordStrengthPolicyWithoutAuth(): void
{
$response = $this->updatePasswordStrengthPolicy([
'min' => 12,
], false);
$this->assertSame(401, $response['headers']['status-code']);
}
// =========================================================================
// Password Personal Data Policy
// =========================================================================
@@ -987,7 +1123,7 @@ trait PoliciesBase
if ($otherParam === $param) {
continue;
}
$this->assertSame(true, $response['body'][$otherAttribute], $otherAttribute . ' should be untouched while only ' . $param . ' was updated');
$this->assertSame(true, $response['body'][$otherAttribute], $otherAttribute.' should be untouched while only '.$param.' was updated');
}
// Restore the field before the next iteration
@@ -1102,10 +1238,10 @@ trait PoliciesBase
protected function getProjectDocument(): array
{
return $this->client->call(Client::METHOD_GET, '/projects/' . $this->getProject()['$id'], [
return $this->client->call(Client::METHOD_GET, '/projects/'.$this->getProject()['$id'], [
'content-type' => 'application/json',
'x-appwrite-project' => 'console',
'cookie' => 'a_session_console=' . $this->getRoot()['session'],
'cookie' => 'a_session_console='.$this->getRoot()['session'],
'x-appwrite-response-format' => '1.9.4',
]);
}
@@ -1127,7 +1263,7 @@ trait PoliciesBase
protected function getPolicy(string $policyId, bool $authenticated = true): mixed
{
return $this->client->call(Client::METHOD_GET, '/project/policies/' . $policyId, $this->buildHeaders($authenticated));
return $this->client->call(Client::METHOD_GET, '/project/policies/'.$policyId, $this->buildHeaders($authenticated));
}
protected function updatePasswordDictionaryPolicy(bool $enabled, bool $authenticated = true): mixed
@@ -1144,6 +1280,25 @@ trait PoliciesBase
]);
}
/**
* @param array<string, bool|int> $params
*/
protected function updatePasswordStrengthPolicy(array $params, bool $authenticated = true): mixed
{
return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $this->buildHeaders($authenticated), $params);
}
protected function resetPasswordStrengthPolicy(): void
{
$this->updatePasswordStrengthPolicy([
'min' => 8,
'uppercase' => false,
'lowercase' => false,
'number' => false,
'symbols' => false,
]);
}
protected function updatePasswordPersonalDataPolicy(bool $enabled, bool $authenticated = true): mixed
{
return $this->client->call(Client::METHOD_PATCH, '/project/policies/password-personal-data', $this->buildHeaders($authenticated), [
@@ -1187,7 +1342,7 @@ trait PoliciesBase
}
/**
* @param array<string, bool> $params
* @param array<string, bool> $params
*/
protected function updateMembershipPrivacyPolicy(array $params, bool $authenticated = true): mixed
{
@@ -0,0 +1,77 @@
<?php
namespace Tests\E2E\Services\Project;
use Tests\E2E\Client;
use Tests\E2E\Scopes\ProjectCustom;
use Tests\E2E\Scopes\Scope;
use Tests\E2E\Scopes\SideServer;
use Utopia\Database\Helpers\ID;
class PoliciesPasswordStrengthIntegrationTest extends Scope
{
use ProjectCustom;
use SideServer;
public function testPasswordStrengthIntegration(): void
{
$projectId = $this->getProject()['$id'];
$apiKey = $this->getProject()['apiKey'];
$serverHeaders = [
'content-type' => 'application/json',
'x-appwrite-project' => $projectId,
'x-appwrite-key' => $apiKey,
'x-appwrite-response-format' => '1.9.4',
];
$signupHeaders = [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $projectId,
];
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $serverHeaders, [
'min' => 12,
'uppercase' => true,
'lowercase' => true,
'number' => true,
'symbols' => true,
]);
$this->assertSame(200, $response['headers']['status-code']);
$this->assertSame(12, $response['body']['min']);
$this->assertTrue($response['body']['uppercase']);
$this->assertTrue($response['body']['lowercase']);
$this->assertTrue($response['body']['number']);
$this->assertTrue($response['body']['symbols']);
$weak = $this->client->call(Client::METHOD_POST, '/account', $signupHeaders, [
'userId' => ID::unique(),
'email' => 'strength_weak_' . uniqid() . '@localhost.test',
'password' => 'password123!',
'name' => 'Weak Password User',
]);
$this->assertSame(400, $weak['headers']['status-code']);
$valid = $this->client->call(Client::METHOD_POST, '/account', $signupHeaders, [
'userId' => ID::unique(),
'email' => 'strength_valid_' . uniqid() . '@localhost.test',
'password' => 'Password123!',
'name' => 'Valid Password User',
]);
$this->assertSame(201, $valid['headers']['status-code']);
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', $serverHeaders, [
'min' => 8,
'uppercase' => false,
'lowercase' => false,
'number' => false,
'symbols' => false,
]);
$this->assertSame(200, $response['headers']['status-code']);
}
}
@@ -122,6 +122,11 @@ class ProjectConsoleClientTest extends Scope
$this->assertArrayNotHasKey('authLimit', $response['body']);
$this->assertArrayNotHasKey('authSessionsLimit', $response['body']);
$this->assertArrayNotHasKey('authPasswordHistory', $response['body']);
$this->assertArrayNotHasKey('authPasswordStrengthMin', $response['body']);
$this->assertArrayNotHasKey('authPasswordStrengthRequireUppercase', $response['body']);
$this->assertArrayNotHasKey('authPasswordStrengthRequireLowercase', $response['body']);
$this->assertArrayNotHasKey('authPasswordStrengthRequireNumber', $response['body']);
$this->assertArrayNotHasKey('authPasswordStrengthRequireSpecialChar', $response['body']);
$this->assertArrayNotHasKey('authPasswordDictionary', $response['body']);
$this->assertArrayNotHasKey('authPersonalDataCheck', $response['body']);
$this->assertArrayNotHasKey('authDisposableEmails', $response['body']);
@@ -2906,6 +2906,177 @@ class ProjectsConsoleClientTest extends Scope
$this->assertEquals(0, $response['body']['authPasswordHistory']);
}
public function testUpdateProjectAuthPasswordStrength(): void
{
$data = $this->setupProjectData();
$id = $data['projectId'];
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $id,
'x-appwrite-mode' => 'admin',
], $this->getHeaders()), [
'min' => 7,
]);
$this->assertEquals(400, $response['headers']['status-code']);
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $id,
'x-appwrite-mode' => 'admin',
], $this->getHeaders()), [
'min' => 12,
]);
$this->assertEquals(200, $response['headers']['status-code']);
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $id,
'x-appwrite-mode' => 'admin',
], $this->getHeaders()), [
'uppercase' => true,
'lowercase' => true,
'number' => true,
'symbols' => true,
]);
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertEquals(12, $response['body']['min']);
$this->assertEquals(true, $response['body']['uppercase']);
$this->assertEquals(true, $response['body']['lowercase']);
$this->assertEquals(true, $response['body']['number']);
$this->assertEquals(true, $response['body']['symbols']);
$weakPassword = 'password123!';
$validPassword = 'Password123!';
$email = uniqid() . 'user@localhost.test';
$response = $this->client->call(Client::METHOD_POST, '/account', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $id,
]), [
'userId' => ID::unique(),
'email' => uniqid() . 'weak-account@localhost.test',
'password' => $weakPassword,
'name' => 'Weak Account',
]);
$this->assertEquals(400, $response['headers']['status-code']);
$response = $this->client->call(Client::METHOD_POST, '/users', array_merge($this->getHeaders(), [
'content-type' => 'application/json',
'x-appwrite-project' => $id,
'x-appwrite-mode' => 'admin',
]), [
'userId' => ID::unique(),
'email' => uniqid() . 'weak-user@localhost.test',
'password' => $weakPassword,
'name' => 'Weak User',
]);
$this->assertEquals(400, $response['headers']['status-code']);
$response = $this->client->call(Client::METHOD_POST, '/account', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $id,
]), [
'userId' => ID::unique(),
'email' => $email,
'password' => $validPassword,
'name' => 'Password Strength User',
]);
$this->assertEquals(201, $response['headers']['status-code']);
$userId = $response['body']['$id'];
$session = $this->client->call(Client::METHOD_POST, '/account/sessions/email', [
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $id,
], [
'email' => $email,
'password' => $validPassword,
]);
$this->assertEquals(201, $session['headers']['status-code']);
$session = $session['cookies']['a_session_' . $id];
$response = $this->client->call(Client::METHOD_PATCH, '/account/password', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $id,
'cookie' => 'a_session_' . $id . '=' . $session,
]), [
'oldPassword' => $validPassword,
'password' => $weakPassword,
]);
$this->assertEquals(400, $response['headers']['status-code']);
$response = $this->client->call(Client::METHOD_POST, '/account/recovery', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $id,
]), [
'email' => $email,
'url' => 'http://localhost/recovery',
]);
$this->assertEquals(201, $response['headers']['status-code']);
$lastEmail = $this->getLastEmailByAddress($email, function ($email) {
$this->assertStringContainsString('Password Reset', $email['subject']);
});
$tokens = $this->extractQueryParamsFromEmailLink($lastEmail['html']);
$response = $this->client->call(Client::METHOD_PUT, '/account/recovery', array_merge([
'origin' => 'http://localhost',
'content-type' => 'application/json',
'x-appwrite-project' => $id,
]), [
'userId' => $userId,
'secret' => $tokens['secret'],
'password' => $weakPassword,
]);
$this->assertEquals(400, $response['headers']['status-code']);
$headers = array_merge($this->getHeaders(), [
'x-appwrite-mode' => 'admin',
'content-type' => 'application/json',
'x-appwrite-project' => $id,
]);
$response = $this->client->call(Client::METHOD_PATCH, '/users/' . $userId . '/password', $headers, [
'password' => $weakPassword,
]);
$this->assertEquals(400, $response['headers']['status-code']);
$response = $this->client->call(Client::METHOD_PATCH, '/project/policies/password-strength', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $id,
'x-appwrite-mode' => 'admin',
], $this->getHeaders()), [
'min' => 8,
'uppercase' => false,
'lowercase' => false,
'number' => false,
'symbols' => false,
]);
$this->assertEquals(200, $response['headers']['status-code']);
$this->assertEquals(8, $response['body']['min']);
$this->assertEquals(false, $response['body']['uppercase']);
$this->assertEquals(false, $response['body']['lowercase']);
$this->assertEquals(false, $response['body']['number']);
$this->assertEquals(false, $response['body']['symbols']);
}
#[Group('smtpAndTemplates')]
#[Group('projectsCRUD')]
public function testUpdateMockNumbers(): void
@@ -0,0 +1,59 @@
<?php
namespace Tests\Unit\Auth\Validator;
use Appwrite\Auth\Validator\PasswordStrength;
use PHPUnit\Framework\TestCase;
class PasswordStrengthTest extends TestCase
{
public function testDefaultPolicy(): void
{
$validator = new PasswordStrength();
$this->assertFalse($validator->isValid('1234567'));
$this->assertTrue($validator->isValid('password'));
}
public function testConfiguredPolicy(): void
{
$validator = new PasswordStrength([
'min' => 12,
'uppercase' => true,
'lowercase' => true,
'number' => true,
'symbols' => true,
]);
$this->assertFalse($validator->isValid('Password1!'));
$this->assertFalse($validator->isValid('password123!'));
$this->assertFalse($validator->isValid('PASSWORD123!'));
$this->assertFalse($validator->isValid('PasswordOnly!'));
$this->assertFalse($validator->isValid('Password1234'));
$this->assertTrue($validator->isValid('Password123!'));
$this->assertTrue($validator->isValid('Password123€'));
}
public function testMinimumCanBeEight(): void
{
$validator = new PasswordStrength([
'min' => 8,
]);
$this->assertFalse($validator->isValid('1234567'));
$this->assertTrue($validator->isValid('12345678'));
}
public function testAllowEmpty(): void
{
$validator = new PasswordStrength([
'min' => 12,
'uppercase' => true,
'lowercase' => true,
'number' => true,
'symbols' => true,
], true);
$this->assertTrue($validator->isValid(''));
}
}