Repository navigation
fix: bound imported hash costs, fix empty password update, require ephemeral key purpose - #14825
Conversation
…lthrough Imported bcrypt, Argon2 and PHPass hashes keep the cost encoded in the hash string, and scrypt imports store their parameters, so every sign-in pays whatever cost the import declared. Parse the imported hashes and cap their costs, and bound the scrypt parameters, so verification stays within what real deployments use. Clearing a password through the Users API fell through to hashing the empty string, which replaced the cleared password and invalidated the user's sessions. Co-Authored-By: Claude <[email protected]>
Ephemeral keys are HS256 JWTs signed with the same secret as other platform JWTs, and decoding only checked the signature and project, so any JWT minted with that secret for the project decoded as a key. Stamp every minted key with a purpose claim and refuse ephemeral and dynamic keys without it. Co-Authored-By: Claude <[email protected]>
|
Review complete. 🟠 1 high · 🟡 2 medium 💬 Inline comments (2)
📍 Findings outside the diff (1) — 🟠 1 high — defects on lines GitHub can't attach comments to🟠 High — Empty-password clear skips cache purge and session invalidation · Update.php:98–112 · // src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php
98 if (\strlen($password) === 0) {
99 $user
100 ->setAttribute('password', '')
101 ->setAttribute('passwordUpdate', DateTime::now());
102
103 $user = $dbForProject->updateDocument('users', $user->getId(), new Document([
104 'password' => $user->getAttribute('password'),
105 'passwordPwned' => null,
106 'passwordUpdate' => $user->getAttribute('passwordUpdate'),
107 ]));
108 $queueForEvents->setParam('userId', $user->getId());
109 $response->dynamic($user, Response::MODEL_USER);The new early return in the empty-password branch clears the password and responds without running This PR hardens two surfaces: ephemeral/dynamic API-key JWTs and user password-hash imports. Every JWT issuer that produces keys consumed by
Reviewed commit: 627c3c8 |
🟢 Tier S · Ready to mergeThis change adds bounded format validators for imported bcrypt, Argon2, and PHPass hashes, and caps scrypt parameters on user creation. It also fixes empty-password updates and requires a purpose claim on ephemeral and dynamic JWT keys, adding that claim to the key-minting paths and updating coverage.
📂 Walkthrough · 5
Reviewed |
There was a problem hiding this comment.
Adds a purpose: 'key' claim to ephemeral key JWTs and enforces it in Key::decode(), plus cost-capped hash validators for imported bcrypt/argon2/PHPass/scrypt hashes.
Key findings
- 🟠 Empty-password clear skips cache purge and session invalidation — Update.php:98
- 🟡 Purpose-claim check rejects pre-upgrade ephemeral JWTs — Key.php:175
- 🟡 Hash import cost caps reject previously valid imports — Create.php:59
| if (($payload[self::PURPOSE_CLAIM] ?? '') !== self::PURPOSE) { | ||
| throw new Exception(Exception::USER_UNAUTHORIZED); | ||
| } |
There was a problem hiding this comment.
🟡 compatibility · medium
Purpose-claim check rejects pre-upgrade ephemeral JWTs
Key::decode() now hard-rejects any ephemeral or legacy dynamic JWT lacking the purpose: 'key' claim (src/Appwrite/Auth/Key.php:175), while only the in-repo issuers were updated to add it — no migration can retrofit the claim onto keys already held by clients. During a rolling deploy, tokens minted by pre-upgrade pods (function-execution keys with timeout+60 TTL, build keys, migration keys with 86400s TTL at Workers/Migrations.php) fail with USER_UNAUTHORIZED mid-flight when decoded by a new pod, and user-held ephemeral keys stop working until they expire (max 24h). The strictness is security-motivated and correct; the residual risk is the mixed-version rollout window. The same rejection applies to the legacy dynamic type (src/Appwrite/Auth/Key.php:161), which the adjacent comment preserves "for backwards compatibility".
📋 Prompt for AI Agents
In src/Appwrite/Auth/Key.php around lines 175-177, the purpose-claim check intentionally rejects JWTs minted before this deploy (they carry no purpose claim), breaking in-flight executions/builds/migrations and user-held ephemeral keys during a rolling rollout. Keep the check, but ensure rollout is atomic, or add a temporary env-gated grace path (e.g. _APP_EPHEMERAL_KEY_GRACE cutoff timestamp) that accepts payloads MISSING the claim while still rejecting payloads whose purpose is present but not 'key' — accepting missing claims unconditionally would defeat the fix — with a comment to remove the grace path after one full rollout cycle. Also add a release-notes entry documenting that pre-upgrade ephemeral/dynamic tokens are rejected until expiry.
There was a problem hiding this comment.
Intentional, and called out in the PR body deploy note. A grace path that accepts JWTs without the claim would keep the gap open for its whole duration, because a JWT without the claim is exactly the case being closed. The affected tokens are short-lived (endpoint keys at most 1h, execution and build keys at their timeout). A migration that is running during the rollout can be retried. The dynamic type keeps its prefix for compatibility, but its JWTs now need the same claim. This will also go in the release notes.
| ->param('passwordCpu', 8, new Range(2, 65536), 'Optional CPU cost used to hash password. Maximum is 65536.', example: '8') | ||
| ->param('passwordMemory', 14, new Range(1, 16), 'Optional memory cost used to hash password. Maximum is 16.', example: '14') | ||
| ->param('passwordParallel', 1, new Range(1, 4), 'Optional parallelization cost used to hash password. Maximum is 4.', example: '1') | ||
| ->param('passwordLength', 64, new Range(16, 128), 'Optional hash length used to hash password. Must be between 16 and 128.', example: '64') |
There was a problem hiding this comment.
🟡 breaking-change · medium
Hash import cost caps reject previously valid imports
The import endpoints now enforce cost caps that previously accepted values: bcrypt cost above 15 (PHP bcrypt allows up to 31), Argon2 memory above 256 MiB / time above 10 / parallelism above 16, PHPass iterations above 2^16, and the scrypt Range bounds on passwordCpu/passwordMemory/passwordParallel/passwordLength (src/Appwrite/Platform/Modules/Users/Http/Users/Scrypt/Create.php:59; caps pinned by e2e testCreateUserHashLimits). Projects migrating users whose source system used higher parameters (e.g. bcrypt cost 16+, passwordMemory 65536 per the removed example) now receive 400 general_argument_invalid with no migration path. This is a deliberate resource cap, but it is an unannounced breaking change for the migration use case and should ship in release notes.
📋 Prompt for AI Agents
In docs/releases.md, add a breaking-changes entry for this release stating that the user hash-import endpoints now enforce cost caps — POST /v1/users/bcrypt (cost 4-15), /users/argon2 (memory <= 262144 KiB, time <= 10, parallelism <= 16), /users/phpass (iterations <= 2^16) and /users/scrypt (passwordCpu 2-65536, passwordMemory 1-16, passwordParallel 1-4, passwordLength 16-128) — and that previously accepted hashes above these caps now return 400 general_argument_invalid.
There was a problem hiding this comment.
Intentional cap; the PR body lists every ceiling and the real-world values behind it, and it will go in the release notes. docs/releases.md documents the release process rather than per-release changes, so I have not added an entry there. On the removed 65536 example: passwordMemory is scrypt r (the block size), and 65536 was never a meaningful value for it. Real-world r is 8 (Firebase, Django, OpenSSL defaults).
Returning early from the empty-password branch skipped the session invalidation and cache purge that every other password change runs, so clearing a password left existing sessions valid under the default policy. Co-Authored-By: Claude <[email protected]>
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
Security rulesNo new WARNING or ERROR findings from security rules. 6 existing findings tracked in
|
|
@hansi-codes review |
# Conflicts: # tests/unit/Auth/KeyTest.php
|
@hansi-codes review |
…ments The scrypt hasher requires a power-of-two CPU cost and throws for other values, which surfaced as a server error after validation passed. Report those as invalid arguments. Co-Authored-By: Claude <[email protected]>
|
@hansi-codes review |
…unit files testCreateUserHashLimits now imports the accepted boundary hashes (minimum and ceiling costs, every supported variant) and refuses the malformed and over-limit ones through the bcrypt, argon2 and phpass routes, so the three new validator unit files are dropped.
|
@hansi-codes review |
The validators checked structure and costs but not the encoded payload, so a bcrypt hash with a valid prefix and cost but a digest outside the bcrypt alphabet was stored, and crypt() then fails on every sign-in. Bcrypt and portable PHPass payloads must now use their crypt alphabets, and Argon2 salt and digest must be unpadded base64 of a decodable length.
|
@hansi-codes review |
The version field was only checked for a v= prefix, so v=garbage was stored and password_verify() could never match it. Argon2 defines versions 0x10 and 0x13, so only v=16 and v=19 are accepted.
|
@hansi-codes review |
|
@hansi-codes review |
fix: bound imported hash costs, fix empty password update, require ephemeral key purpose (cherry picked from commit d5ccf14)
What this fixes
Three separate holes in user import, password updates and ephemeral API keys. Each one is shown below with real requests against a local stack, first on
mainand then on this branch.purpose: "key"; anything else is401 user_unauthorized400 general_argument_invalidPATCH /v1/users/:userId/passwordwith""clears the password, then falls through and stores a hash of the empty string1. Ephemeral keys accept any platform JWT
Ephemeral keys are HS256 JWTs signed with
_APP_OPENSSL_KEY_V1. The same secret signs push image tokens, export download tokens, function and site tokens and more.Key::decodeonly checked the signature and theprojectId, so it could not tell a key apart from any of those.Every place that mints a key now sets the claim: the org and project ephemeral key endpoints, function executions (HTTP and worker), the router in
general.php, deployment runtime variables, site screenshots and migrations.Key::decoderefusesephemeral_and legacydynamic_JWTs without it.2. Imported hashes can declare any cost
bcrypt, Argon2 and PHPass keep their cost inside the hash string, and scrypt imports store their parameters next to the hash. Appwrite reuses that cost on every sign-in, so whoever imports the user picks how much CPU or memory each sign-in burns.
New validators
Appwrite\Auth\Validator\Hash\{Bcrypt,Argon2,PHPass}(they extendPasswordand use string functions only) check that the hash is in that algorithm's format. So one import endpoint can no longer be used to store another algorithm's hash. scrypt parameters are bounded on the import endpoint itself.Ceilings, picked from real-world maxima with headroom:
m≤ 262144 KiB (256 MiB),t≤ 10,p≤ 16; versions 16 and 19$P$/$H$)$2*$)Other
crypt()formats on the PHPass endpoint, such as$6$rounds=or extended DES, are refused becausePHPass::verifywould pass them straight tocrypt(). The scryptpasswordMemoryexample was65536, which never fit r, and is now14.3. Clearing a password stores a hash of
""Deploy note
Ephemeral keys minted before this deploy have no
purposeclaim, so they stop working once it is live. They are short-lived: the endpoint caps them at 1 hour, and function, site and build keys expire with the execution or build timeout. A migration running during the rollout may need a retry. I checked appwrite-labs/cloud and edge: neither mints keys thatKey::decodereads (edge decodes its own router keys with a separate secret).Tests
tests/unit/Auth/KeyTest.php): refuses JWTs without the purpose claim, with a different purpose, account-shaped JWTs anddynamic_keys.tests/e2e/Services/Users/UsersBase.php):testCreateUserHashLimitsimports through the bcrypt, Argon2 and PHPass routes at the minimum and ceiling costs. It checks that over-ceiling, malformed and cross-algorithm hashes, and over-limit scrypt parameters, are refused withgeneral_argument_invalid.testUpdateUserPasswordEmptychecks that clearing a password leaves it empty with the hash algorithm unchanged.docker compose up), running the same requests onmain(5f3fc62) and on this branch (4db40a4).Related: appwrite-labs/cloud#6666