Repository navigation
fix(auth): close live connections when an account is claimed - #15062
Conversation
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claiming an unverified account deleted the registrant's sessions inside the transaction, but nothing told realtime or MQTT. The registrant's realtime connections stayed open long enough to receive the claim's own event, which carries the claimant's new session, and their MQTT connections stayed open. Every claim site now dispatches CredentialsRevoked once the claim is committed. The Connections listener revokes the user's MQTT connections and publishes the same realtime event as signing out everywhere, which closes the registrant's connections before the claim's event reaches them. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Review complete. 🟡 1 medium 💬 Inline comments (1)
🧹 Nitpicks (1) — 🟢 1 low
The change introduces a cross-process revocation signal: when a claim flow revokes a user's credentials, a new
One medium-severity issue was found in the membership status update flow (stale user snapshot dispatched with the event); a couple of low-severity robustness notes in the recovery flows and listener were also recorded. Reviewed commit: d2b489e |
🟢 Tier S · Ready to mergeThe change publishes a session-delete realtime event and revokes MQTT connections when an unverified account is claimed through token exchange, OAuth, ID-token sign-in, recovery, or a signed-out team invitation. It adds an end-to-end test covering the main claim flows and checks that the registrant's socket closes without receiving the claimant's data.
📂 Walkthrough · 4
🔇 Filtered out · 1Findings Hansi considered but did not post.
Reviewed |
Security rulesNo new WARNING or ERROR findings from security rules. 6 existing findings tracked in
|
There was a problem hiding this comment.
Expand to see previous review
This PR adds a CredentialsRevoked bus event and a Connections listener that revokes MQTT connections and closes realtime sessions when claimed credentials are invalidated, wired into the token-exchange, OAuth, recovery, ID-token, and team-membership flows.
Key findings
- 🟡 Membership claim dispatches stale pre-revocation user snapshot — Update.php:264
Carry the user revokeCredentials changed out of the transaction, and reset the claim at the start of each attempt so a retried transaction cannot report a claim it rolled back. Co-Authored-By: Claude Opus 5.5 <[email protected]>
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
Connections::revoke() ends the MQTT connections that lost access and leaves realtime connections to the request's own user event, as today. Connections::close() also re-validates the realtime connections at once, so they close before anything else the request publishes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every route that revoked MQTT connections inline now makes one call. Behaviour is unchanged: the same MQTT revoke, errors still logged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each claim site calls Connections::close(), so the registrant's realtime connections close before the request's own event, which carries the claimant's new session, and their MQTT connections are revoked. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claim sites close connections through Connections directly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@hansi-codes review |
Claim sites revoke MQTT in the same try/catch as every other route and publish the realtime sign-out on a copy of queueForRealtime before the request's own event. Every other route is back to main's code. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@hansi-codes review |
|
@tenki-reviewer review |
|
Review complete. 🟠 1 high 📍 Findings outside the diff (1) — 🟠 1 high — defects on lines GitHub can't attach comments to🟠 High — Identity-email adoption path skips unverified-account revocation · account.php:2046–2056 · // app/controllers/api/account.php
2046 if ($user->isEmpty() && !empty($providerEmail)) {
2047 $identityWithMatchingEmail = $dbForProject->findOne('identities', [
2048 Query::equal('providerEmail', [$providerEmail]),
2049 ]);
2050 if (!$identityWithMatchingEmail->isEmpty()) {
2051 if (!$isVerified) {
2052 $failureRedirect(Exception::GENERAL_BAD_REQUEST);
2053 }
2054 $user->setAttributes($dbForProject->getDocument('users', $identityWithMatchingEmail->getAttribute('userId'))->getArrayCopy());
2055 }
2056 }When a user is adopted via This PR centralizes the "claim an unverified account by proving its email" flow across sign-in surfaces, adding token-based transactional claim helpers in
Reviewed commit: 0f89011 |
|
@tenki-reviewer thanks. The identity-email adoption finding (account.php ~2046-2056 / IdToken On the suggested fix: calling |
|
Review complete. No blocking issues — 2 nitpicks below. 🧹 Nitpicks (2) — 🟢 2 low
When a new signup's email/phone is later verified by an existing account claiming it, the claimant's stale sessions and credentials were left alive. This change wires
Reviewed commit: 0f89011 |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@hansi-codes review |
|
@tenki-reviewer thanks, both nitpicks checked:
@tenki-reviewer review |
|
Review complete. 🟡 3 medium 💬 Inline comments (1)
📍 Findings outside the diff (2) — 🟡 2 medium — defects on lines GitHub can't attach comments to🟡 Medium — Id-token claim revokes sessions before session creation · Create.php:437–458 · // src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php
437 $user->setAttributes($userWithEmail->getArrayCopy());
438 if (!$user->getAttribute('emailVerification', false)) {
439 $authorization->skip(fn () => User::revokeCredentials($dbForProject, $user, $project));
440 $dbForProject->purgeCachedDocument('users', $user->getId());
441
442 try {
443 $mqtt->revoke($project->getId(), $user->getId());
444 } catch (\Throwable $error) {
445 Console::error('Failed to revoke MQTT connections: ' . $error->getMessage());
446 }
447
448 // Sent before the request's own event, which would otherwise reach the registrant with the claimant's dataThe email-match claim inside 🟡 Medium — OAuth and IdToken claims revoke without user row lock · account.php:2012–2021 · // app/controllers/api/account.php
2012 $userWithEmail = $dbForProject->findOne('users', [
2013 Query::equal('email', $emails),
2014 ]);
2015 if (!$userWithEmail->isEmpty()) {
2016 if (!$isVerified) {
2017 $failureRedirect(Exception::GENERAL_BAD_REQUEST);
2018 }
2019 $user->setAttributes($userWithEmail->getArrayCopy());
2020 if (!$user->getAttribute('emailVerification', false)) {
2021 $authorization->skip(fn () => User::revokeCredentials($dbForProject, $user, $project));The token-exchange path deliberately locks the user row — its comment states the lock orders the claim against access-invalidating writes (app/controllers/api/account.php:247) — but the new OAuth callback and 🧹 Nitpicks (1) — 🟢 1 low
The change wires a
Reviewed commit: c43f742 |
There was a problem hiding this comment.
Expand to see previous review
This PR adds account-claim side effects — MQTT connection revocation and users.[userId].sessions.delete realtime events — across the magic-URL/OTP, password-recovery, OAuth2, ID-token, and team-invite flows so registrants of unverified emails lose their sessions when the address is claimed.
Key findings
- 🟡 Id-token claim revokes sessions before session creation — Create.php:437
- 🟡 OAuth callback claim fires revokes without claim guard — account.php:2019
- 🟡 OAuth and IdToken claims revoke without user row lock — account.php:2012
|
@tenki-reviewer on the two outside-the-diff findings in the review of c43f742 (the ID-token claim's ordering against session creation, and the OAuth and ID-token claims not taking the row lock the token exchange uses): both describe how the claim already works on |
|
Review complete. 🟠 1 high 💬 Inline comments (1)
The change adds an account-claim protocol across the account API's session-creation paths: when a claimant proves ownership of an email or phone already attached to a registrant, the registrant's credentials are revoked and their sessions killed before the claimant's session is issued.
One high-severity ordering issue remains: the recovery transactions delete the token before acquiring the user row lock, inverting the serialization the other claim paths use. Reviewed commit: c43f742 |
There was a problem hiding this comment.
This PR implements cross-credential account claiming: proven email/phone credentials now revoke the registrant's existing sessions, tokens, and identities before the claimant's session is created, with an end-to-end realtime test asserting the socket closes before any claimant payload is delivered.
Key findings
- 🟠 Recovery deletes token before user lock, breaking claim ordering — account.php:4706
| @@ -4668,6 +4712,7 @@ | |||
| $locked = $authorization->skip(fn () => $dbForProject->getDocument('users', $profile->getId(), forUpdate: true)); | |||
| if (!$locked->getAttribute('emailVerification', false)) { | |||
| $authorization->skip(fn () => User::revokeCredentials($dbForProject, $profile, $project)); | |||
| $claimed = true; | |||
| } | |||
There was a problem hiding this comment.
🟠 bug · high
Recovery deletes token before user lock, breaking claim ordering
Both recovery transactions delete the token before acquiring the user row lock, inverting the ordering that guards against a concurrent address change (app/controllers/api/account.php:4706-4716 and app/controllers/api/account.php:5146-5157). A recovery request deletes the token (winning the claim), then waits on the user lock; the email-change transaction (Users/Http/Users/Email/Update.php:145-210) holds that lock, deletes all email-proving tokens and resets emailVerification to false, then commits. The recovery transaction resumes on the now-different address, revokes credentials, and writes emailVerification => true in the same update as the new password, marking an address that was never proven as verified. By contrast, $createSession (app/controllers/api/account.php:241-258) takes the user lock first, exactly to order against the address-change transaction.
📋 Prompt for AI Agents
In app/controllers/api/account.php, in the password-recovery transaction (around lines 4704-4730) and the OTP recovery transaction (around lines 5145-5171), reorder the transaction body so the user row lock is taken first — $locked = $authorization->skip(fn () => $dbForProject->getDocument('users', $profile->getId(), forUpdate: true)); — before getDocument('tokens', ...) and deleteDocument('tokens', ...), keeping the emailVerification check against $locked and returning null when the delete fails. This restores the serialization against the email-change transaction (Users/Http/Users/Email/Update.php) that $createSession relies on, so a recovery token can never prove an address that was swapped mid-flight.
What does this PR do?
When someone proves the email or phone of an account that was registered but never verified, the account is claimed:
User::revokeCredentials()deletes the registrant's sessions, tokens, factors and so on. Nothing told the live connections about it:users.{id}.sessions.{id}.createfrom the token exchange) re-checks the user's connections. The registrant's connection is closed, but only after that event has been delivered to it. So the registrant's socket received the claimant's new session (IP, device, location) as its last message. On the OAuth token flow the claim's event istokens.*.create, which does not re-check connections at all.The fix
At every claim site, right after the claim is saved and the user cache is cleared, the route now:
$mqtt->revoke()try/catch the other routes use (the two recovery routes already did this);users.{userId}.sessions.deletewith an empty payload, before the request's own event. This is the same event as signing out everywhere: the realtime server closes every connection whose session is gone. Both events go through therealtimepub/sub channel in order, so the registrant's socket is closed before the claimant's data is sent.Claim sites: token exchange (magic URL / email OTP / phone OTP), OAuth2 redirect, ID token sessions, both recovery routes, and accepting a team invite while signed out.
The realtime event is sent through a copy of the injected
queueForRealtime, not a newRealtime. That keeps the edition's own class (Cloud replaces this resource) and leaves anything the route itself queued on it untouched.Other routes that end access (sign out, password change, MFA, block, delete...) are unchanged. There, the realtime server delivers the route's own event to the connection and then closes it, which is how a client learns it was signed out.
Test Plan
New e2e test
RealtimeCustomClientTest::testConnectionEndsWithAccountClaim. The registrant holds anaccountsocket, then the address's owner claims the account in one of five ways: magic URL, accepting a team invite while signed out, password recovery, ID token sign-in, and OAuth sign-in. Each time, the socket must close with401, and no message it received may carry a payload.users.{id}.sessions.{id}.createorusers.{id}.recovery.{id}.update) with the claimant's data. Each path was checked this way on its own. With no fix at all, themqttpub/sub channel showed 0revokemessages.revokemessages, one per claim path.RealtimeCustomClientTest::testConnectionEndsWithSession(normal sign-out paths) passes and sends the same 8revokemessages as before.Related PRs and Issues
Checklist
🤖 Generated with Claude Code