Skip to content

fix: bound imported hash costs, fix empty password update, require ephemeral key purpose - #14825

Merged
ChiragAgg5k merged 9 commits into
mainfrom
fix/users-hash-limits
Oct 23, 2026
Merged

ChiragAgg5k merged 9 commits into
mainfrom
fix/users-hash-limits

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

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 main and then on this branch.

Problem After this PR
1 Any JWT signed with the platform secret that names the project works as an ephemeral API key, including the image token sent to every push notification recipient Keys must carry purpose: "key"; anything else is 401 user_unauthorized
2 Imported bcrypt, Argon2, PHPass and scrypt hashes can declare any cost, and every sign-in pays it Costs above a ceiling are refused at import with 400 general_argument_invalid
3 PATCH /v1/users/:userId/password with "" clears the password, then falls through and stores a hash of the empty string Clearing returns right away and the password stays empty

1. 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::decode only checked the signature and the projectId, so it could not tell a key apart from any of those.

 Before
 ──────
   POST /v1/messaging/messages/push  (image attached)
        │
        ▼
   image URL …/push?jwt=<{bucketId, fileId, projectId}>   ──►  sent to every recipient
                                    │
                                    ▼
   x-appwrite-key: ephemeral_<jwt>
        │
        ▼
   Key::decode ── signature ok? ✔ ── projectId matches? ✔ ──►  accepted as an API key


 After
 ─────
   Key::decode ── signature ok? ✔ ── purpose == "key"? ✘ ──►  401 user_unauthorized
                                                       ✔ ──►  projectId check … as before

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::decode refuses ephemeral_ and legacy dynamic_ JWTs without it.

A push notification image token used as an API key: 200 on main, 401 on this PR

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.

 POST /v1/users/bcrypt  { password: "$2y$31$…" }
                                    ▲
                                    └── cost lives in the hash: 2^31 rounds

 Before:  stored as-is ──► every POST /v1/account/sessions/email runs 2^cost rounds
                           cost 17 ≈ 7 s per sign-in, cost 31 ≈ 32 hours

 After:   Hash\Bcrypt validator ── format ok? ── 4 ≤ cost ≤ 15? ──► 201
                                         ✘              ✘       ──► 400 general_argument_invalid

Importing a cost-17 bcrypt hash: accepted with a 7.5 s sign-in on main, refused on this PR

New validators Appwrite\Auth\Validator\Hash\{Bcrypt,Argon2,PHPass} (they extend Password and 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:

Algorithm Allowed Common real-world values
bcrypt cost 4 to 15 10 to 12 (PHP, Laravel, Rails, Django); the existing fixtures use 15. Each step doubles the work, and the format allows 31
Argon2 m ≤ 262144 KiB (256 MiB), t ≤ 10, p ≤ 16; versions 16 and 19 PHP default m=64 MiB, t=4, p=1. RFC 9106 option 2: 64 MiB, t=3, p=4. libsodium "moderate": 256 MiB
PHPass portable ($P$/$H$) iteration log2 7 to 16 WordPress 13, phpBB 11; the format allows 30
PHPass bcrypt ($2*$) bcrypt ceiling —
scrypt N 2 to 65536, r 1 to 16, p 1 to 4, length 16 to 128 (memory 128·N·r ≤ 128 MiB) N=16384, r=8, p=1 (Firebase, Django, OpenSSL); the fixture uses N=16384, r=13, p=2

Other crypt() formats on the PHPass endpoint, such as $6$rounds= or extended DES, are refused because PHPass::verify would pass them straight to crypt(). The scrypt passwordMemory example was 65536, which never fit r, and is now 14.

3. Clearing a password stores a hash of ""

 PATCH /v1/users/:userId/password  { password: "" }

 Before:  clear password ──► (no return) ──► hash("") ──► save
                                                          └─► password is a real hash again

 After:   clear password ──► invalidate sessions ──► purge cache ──► return
                                                                    └─► password stays ""

Clearing a password: main stores an Argon2 hash of the empty string, this PR leaves it empty

Deploy note

Ephemeral keys minted before this deploy have no purpose claim, 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 that Key::decode reads (edge decodes its own router keys with a separate secret).

Tests

  • Unit (tests/unit/Auth/KeyTest.php): refuses JWTs without the purpose claim, with a different purpose, account-shaped JWTs and dynamic_ keys.
  • E2E (tests/e2e/Services/Users/UsersBase.php):
    • testCreateUserHashLimits imports 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 with general_argument_invalid.
    • testUpdateUserPasswordEmpty checks that clearing a password leaves it empty with the hash algorithm unchanged.
  • The Sites e2e keys minted by hand now carry the claim.
  • The screenshots above come from a local dev stack (docker compose up), running the same requests on main (5f3fc62) and on this branch (4db40a4).

Related: appwrite-labs/cloud#6666

ChiragAgg5k and others added 2 commits October 22, 2026 16:02
…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]>
@luxor-code-review

luxor-code-review Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Review complete. 🟠 1 high · 🟡 2 medium

💬 Inline comments (2)

  • 🟡 Purpose-claim check rejects pre-upgrade ephemeral JWTs — Key.php:175
  • 🟡 Hash import cost caps reject previously valid imports — Create.php:59
📍 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 · unchanged line

// 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 purgeCachedDocument('users', ...) or User::invalidateAuthentication(...) (src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php:111), which the non-empty path always executes at lines 150-155. Previously an empty password fell through the shared path, so both ran. Concrete impact: after an operator clears a user's password, the cached user document can keep serving the old hash so the removed password still authenticates until cache expiry, and existing sessions survive a password-clear operation.


This PR hardens two surfaces: ephemeral/dynamic API-key JWTs and user password-hash imports. Every JWT issuer that produces keys consumed by Key::decode() now embeds a purpose claim, and decode rejects key-type payloads without it, blocking token confusion with account JWTs signed by the same _APP_OPENSSL_KEY_V1 secret. Import endpoints (/users/bcrypt, /users/argon2, /users/phpass, /users/scrypt) switch from the generic Password validator to purpose-built hash validators with cost ceilings, preventing CPU/memory exhaustion from hostile hash parameters. The empty-password branch of Users/Password/Update becomes an explicit early return.

Files Change
src/Appwrite/Auth/Key.php, app/controllers/general.php Add PURPOSE claim and enforce it when decoding key-type JWTs
Ephemeral key endpoints, Executions/Create.php, Workers/Functions.php, Workers/Screenshots.php, Deployment/Deployments.php, Workers/Migrations.php Embed the purpose claim at every key-JWT issuance site
src/Appwrite/Auth/Validator/Hash/*, Users/{Argon2,Bcrypt,PHPass,Scrypt}/Create.php, Users/Password/Update.php New cost-capped hash validators wired into the import endpoints; empty-password early return
tests/unit/Auth/**, tests/e2e/** Unit coverage for the hash validators and Key::decode; e2e fixtures for hash limits and ephemeral keys

Reviewed commit: 627c3c8

@ChiragAgg5k ChiragAgg5k self-assigned this Oct 22, 2026
@ghost

ghost commented Oct 22, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

This 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.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 5
File Change
src/Appwrite/Auth/Validator/Hash/{Argon2,Bcrypt,PHPass}.php and src/Appwrite/Platform/Modules/Users/Http/Users/{Argon2,Bcrypt,PHPass}/Create.php Validate imported hash formats and cap their declared costs at the corresponding user import endpoints.
src/Appwrite/Platform/Modules/Users/Http/Users/Scrypt/Create.php Bound scrypt parameters and translate invalid parameter combinations into argument errors.
src/Appwrite/Platform/Modules/Users/Http/Users/Password/Update.php Finish the empty-password branch after clearing the password, invalidating sessions, and preparing the response.
src/Appwrite/Auth/Key.php and app/controllers/general.php, src/Appwrite/Deployment/Deployments.php, src/Appwrite/Platform/Modules/{Functions,Organization,Project}/, src/Appwrite/Platform/Workers/{Functions,Migrations}.php Require and add the purpose claim for ephemeral and dynamic API keys across their minting paths.
tests/e2e/Services/{Sites,Users}/ and tests/unit/Auth/KeyTest.php Update manually minted test keys and cover hash limits, empty-password updates, and JWT purpose validation.

Reviewed 4db40a4 · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

@luxor-code-review luxor-code-review Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread src/Appwrite/Auth/Key.php
Comment on lines +175 to +177
if (($payload[self::PURPOSE_CLAIM] ?? '') !== self::PURPOSE) {
throw new Exception(Exception::USER_UNAUTHORIZED);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +59 to +62
->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')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/users-hash-limits (after).

Metric Before After Change
🚀 Requests/sec 212.15 216.52 ⚪ +2.1%
⏱️ Latency P50 80.7 ms 78.99 ms ⚪ -2.1%
⏱️ Latency P95 188.74 ms 191.28 ms ⚪ +1.3%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 78.99 191.28 13,680 216.52 +2.54
Account 156.62 302.9 720 12.11 -1.88
TablesDB 76.11 143.96 7,440 120.44 +4.91
Storage 71.65 165.82 3,600 59.36 -30.92
Functions 117.93 234.01 1,920 32.26 +8.82

Top API waits (after)

API request Max wait (ms)
account.name.update 434.07
functions.create 433.04
account.prefs.update 404.23
tablesdb.rows.list 374.8
tablesdb.rows.create 374.34

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@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]>
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

…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.
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

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.
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · See the inline comments. Summary

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.
@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Tier A · Looks good to merge. Summary

@ChiragAgg5k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@ghost ghost left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Tier S · Looks good to merge. Summary

@ChiragAgg5k
ChiragAgg5k merged commit d5ccf14 into main Oct 23, 2026
77 checks passed
@ChiragAgg5k
ChiragAgg5k deleted the fix/users-hash-limits branch October 23, 2026 14:24
ChiragAgg5k added a commit that referenced this pull request Oct 24, 2026
…pty, and require ephemeral key purpose (backport #14825)

(cherry picked from commit d5ccf14)
Tapraj-Pathak pushed a commit to Tapraj-Pathak/appwrite that referenced this pull request Oct 24, 2026
fix: bound imported hash costs, fix empty password update, require ephemeral key purpose
(cherry picked from commit d5ccf14)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant