Skip to content

fix(account): claim an email verification token under the user row lock [appwrite:appwrite:alert#4642] - #15278

Merged
ChiragAgg5k merged 1 commit into
mainfrom
fix/email-verification-under-user-lock
Nov 10, 2026
Merged

ChiragAgg5k merged 1 commit into
mainfrom
fix/email-verification-under-user-lock

Conversation

@claudear

@claudear claudear commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Closes code scanning alert #4642.

Problem

Both email verification confirmation handlers validated the submitted secret against an unlocked user snapshot and then wrote emailVerification => true outside any transaction, discarding the token delete's return value:

  • Verifications/Email/Update.php — read at :104 with authorization->skip(getDocument(...)) (no forUpdate, no transaction), tokenVerify() against that snapshot at :110, sparse flag write at :118, deleteDocument return value ignored at :128.
  • Verifications/Email/OTP/Update.php — the identical sequence.

Account/Email/Update.php is the writer they race. Inside withTransaction it locks the row with forUpdate, persists the new email with emailVerification false, and deletes every TOKEN_TYPE_VERIFICATION / TOKEN_TYPE_VERIFICATION_OTP token — precisely so a token sent to the old address cannot prove the new one. Because the confirmation side held no lock, that transaction committing between the confirmation's read and its write made Database::updateDocument() merge the sparse {'emailVerification': true} onto the row's current email, marking the new, unproven address verified.

A verified flag on an address the account holder does not own defeats every feature that trusts it: the users/verified permission role, and the account-claim guard — Account/Base.php:203, Sessions/IdToken/Create.php:437 and Sessions/OAuth2/Redirect/Get.php:449 only call User::revokeCredentials() when emailVerification is false, so the real owner later signing in with a verified OAuth/ID-token identity lands in the pre-existing account with the attacker's password, MFA and sessions intact.

The sibling handlers already do this correctly: Verifications/Phone/Update.php:99-107 and Recovery/OTP/Update.php. The two email handlers were the outliers.

Fix

Mirror the phone handler in both: inside withTransaction, lock the user row with forUpdate, require deleteDocument('tokens', ...) to succeed (otherwise USER_INVALID_TOKEN), and only then write the sparse emailVerification update. An email change now either commits first — leaving no token to claim, so the confirmation is rejected — or waits behind the confirmation and resets the flag to false with the new address. The phone handler is unchanged.

The now-contradictory "we don't need it anymore" docblock above the delete is dropped: the delete's result is exactly what the handler needs.

Tests

Two e2e regressions in AccountCustomClientTest, modelled on the existing testUpdateAccountRecoveryConcurrently: fire 8 concurrent confirmations of one verification token (link route and OTP route) and assert exactly one 200 with seven 401s.

Before the fix:

testUpdateEmailVerificationConcurrently
  Exactly one concurrent confirmation may consume the verification token: [200,200,200,401,401,200,200,200]
testUpdateEmailVerificationOTPConcurrently
  Exactly one concurrent confirmation may consume the verification code: [200,200,200,200,200,200,200,200]

After the fix: OK (2 tests, 41 assertions).

🤖 Generated with Claude Code

Both email confirmation handlers validated the secret against an unlocked
user snapshot and then wrote emailVerification outside any transaction,
discarding the token delete's return value. An email change takes the user
row lock, stores the new address with emailVerification false and deletes
every verification token precisely so a token sent to the old address
cannot prove the new one; committing in that window left the new, unproven
address marked verified, which defeats the users/verified role and the
account-claim guard that only revokes credentials on unverified addresses.

Mirror the phone handler: lock the row with forUpdate inside
withTransaction, require deleteDocument on the token to succeed, and only
then set the flag. Cover both routes in e2e with concurrent confirmations
of one token, which previously all returned 200.

Co-Authored-By: Claude Opus 5 <[email protected]>
@luxor-code-review

luxor-code-review Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Review complete. No blocking issues — approved ✅; 3 nitpicks below.

🧹 Nitpicks (3) — 🟢 3 low
  • 🟢 #[Retry(count: 1)] on the new tests is a no-op (AccountCustomClientTest.php:2870) — The new tests carry #[Retry(count: 1)] (tests/e2e/Services/Account/AccountCustomClientTest.php:2870), but the only handler is RetrySubscriber::notify(), which logs the failure and increments self::$retryCounts — it never re-executes the test (tests/extensions/RetrySubscriber.php:19-53).
  • 🟢 Concurrent verification tests never assert the user is verified (AccountCustomClientTest.php:2909) — Both tests stop after counting status codes and never confirm the side effect they protect: the winning confirmation must actually mark the user verified (tests/e2e/Services/Account/AccountCustomClientTest.php:2908-2909).
  • 🟢 Throw USER_INVALID_TOKEN inside withTransaction triggers retries (Update.php:101) — Both verification actions throw Exception::USER_INVALID_TOKEN from inside the withTransaction closure when deleteDocument reports the token was already consumed (src/Appwrite/Platform/Modules/Account/Http/Account/Verifications/Email/OTP/Update.php:101-103).

This PR hardens email verification (both token-link and OTP flows) against concurrent token reuse by claiming the verification token inside a database transaction before it is validated, throwing USER_INVALID_TOKEN when it is already consumed. It adds e2e tests that exercise concurrent verification attempts via the client side.

Files Change
src/Appwrite/Platform/Modules/Account/Http/Account/Verifications/Email/Update.php, .../OTP/Update.php Claim verification tokens atomically via withTransaction, reject already-consumed tokens with USER_INVALID_TOKEN
tests/e2e/Services/Account/AccountCustomClientTest.php Adds concurrent verification tests (#[Retry(count: 1)], callConcurrently) covering link-token and OTP reuse protection

Reviewed commit: a9ff51e

@appwrite

appwrite Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

Both confirmation paths serialize with email changes and atomically consume the token; the added end-to-end tests cover concurrent claims.

The email-link and email-OTP confirmation handlers now claim their verification token inside a transaction while holding the user-row lock, matching the email-change locking path. Added end-to-end tests verify that concurrent attempts to consume either kind of token yield exactly one success.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 3
File Change
src/Appwrite/Platform/Modules/Account/Http/Account/Verifications/Email/Update.php Claims the email verification token and sets the verified flag under the user-row lock.
src/Appwrite/Platform/Modules/Account/Http/Account/Verifications/Email/OTP/Update.php Applies the same transactional token-claim behavior to OTP verification.
tests/e2e/Services/Account/AccountCustomClientTest.php Adds concurrent-consumption regressions for link and OTP email verification.

Reviewed a9ff51e · Details · Comment @appwrite review to re-run, or mention @appwrite with a question.

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

🟢 Tier S · Looks good to merge. Summary

@github-actions

github-actions Bot commented Nov 4, 2026

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.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/email-verification-under-user-lock (after).

Metric Before After Change
🚀 Requests/sec 185.85 180.6 ⚪ -2.8%
⏱️ Latency P50 92.52 ms 96.82 ms ⚪ +4.6%
⏱️ Latency P95 217.88 ms 222.6 ms ⚪ +2.2%
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 96.82 222.6 11,400 180.6 +4.72
Account 173.05 312.25 600 10.23 -14.44
TablesDB 93.72 174.51 6,200 100.65 +5.17
Storage 89.11 207.36 3,000 50.44 +6.49
Functions 134.93 259.7 1,600 27.56 -1.49

Top API waits (after)

API request Max wait (ms)
account.name.update 550.67
account.prefs.update 476.23
functions.variables.update 436.14
functions.variables.create 393.58
storage.buckets.create 390.25

@ChiragAgg5k
ChiragAgg5k merged commit 6150d5b into main Nov 10, 2026
36 checks passed
ChiragAgg5k added a commit that referenced this pull request Nov 12, 2026
…user-lock

fix(account): claim an email verification token under the user row lock [appwrite:appwrite:alert#4642]

(cherry picked from commit 6150d5b)
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.

2 participants