Skip to content

fix(auth): close live connections when an account is claimed - #15062

Merged
ArnabChatterjee20k merged 12 commits into
mainfrom
security/claim-transport-revocation
Oct 29, 2026
Merged

ArnabChatterjee20k merged 12 commits into
mainfrom
security/claim-transport-revocation

Conversation

@ArnabChatterjee20k

@ArnabChatterjee20k ArnabChatterjee20k commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

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:

  • Realtime: the claim's own event (for example users.{id}.sessions.{id}.create from 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 is tokens.*.create, which does not re-check connections at all.
  • MQTT: the token exchange, OAuth, ID token and team invite claims never revoked the registrant's MQTT connections.

The fix

At every claim site, right after the claim is saved and the user cache is cleared, the route now:

  1. revokes the user's MQTT connections, with the same $mqtt->revoke() try/catch the other routes use (the two recovery routes already did this);
  2. publishes users.{userId}.sessions.delete with 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 the realtime pub/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 new Realtime. 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 an account socket, 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 with 401, and no message it received may carry a payload.

  • Without the realtime publish, the test fails at that path: the registrant receives the claim's own event (users.{id}.sessions.{id}.create or users.{id}.recovery.{id}.update) with the claimant's data. Each path was checked this way on its own. With no fix at all, the mqtt pub/sub channel showed 0 revoke messages.
  • With it, all five paths pass, and the channel showed 5 revoke messages, one per claim path.
  • RealtimeCustomClientTest::testConnectionEndsWithSession (normal sign-out paths) passes and sends the same 8 revoke messages as before.
  • The Account, Teams and Realtime e2e suites fail the same tests locally with and without the change, apart from the new claim test. The tests that fail in both runs depend on SMS or on parts of the local stack that differ from CI.

Related PRs and Issues

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs?

🤖 Generated with Claude Code

ArnabChatterjee20k and others added 2 commits October 28, 2026 18:44
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]>
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 1 medium

💬 Inline comments (1)

  • 🟡 Membership claim dispatches stale pre-revocation user snapshot — Update.php:264
🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Recovery flows revoke MQTT connections twice (account.php:4714) — Both password-recovery handlers call $mqtt->revoke() inline (app/controllers/api/account.php:4716 and the mirror around line 5153) and then dispatch CredentialsRevoked, whose new Connections listener also calls $mqtt->revoke (src/Appwrite/Bus/Listeners/Connections.php:41).

The change introduces a cross-process revocation signal: when a claim flow revokes a user's credentials, a new CredentialsRevoked event is dispatched and a new Connections listener publishes a realtime users.[userId].sessions.delete event so stale connections are closed.

Files Change
src/Appwrite/Bus/Events/CredentialsRevoked.php, app/listeners.php New bus event DTO and listener registration.
src/Appwrite/Bus/Listeners/Connections.php New listener that revokes MQTT connections and triggers the realtime sessions-delete event.
app/controllers/api/account.php, src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php, src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php Dispatch CredentialsRevoked from the claim/revocation flows (token exchange, OAuth, recovery, ID-token, membership status).
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php E2E coverage for connection invalidation on revocation.

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

@ghost

ghost commented Oct 28, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

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

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 4
File Change
app/controllers/api/account.php Adds MQTT revocation and a realtime session-delete event to account claim flows.
src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php Adds the same connection revocation behavior to ID-token account claims.
src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php Adds the same behavior when a signed-out user accepts a team invitation.
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php Covers socket closure across five account-claim flows and updates an existing close assertion.
🔇 Filtered out · 1

Findings Hansi considered but did not post.

Finding Why
Keep the empty-payload assertion scoped to claim sockets Verifier: The actor's session-delete payload is published, but this impersonated socket cannot receive it. app/realtime.php:1123-1125 subscribes using the target user's roles and ID; Realtime::fromPayload():1030-1033 addresses the actor event only to user:{actorId}. getSubscribers():619-622 requires a matching event role, so the target's subscription does not match even though both use the generic account channel. The actor event marks the socket for closure via getImpersonatorConnections (app/realtime.php:636,656-663), then sends only the payload-free 401 error (889-891). Thus the new assertion does not fail on the ordinary actor-session deletion described by the finding.

Reviewed c43f742 · 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 S · Looks good to merge. Summary

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

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

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]>
@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → security/claim-transport-revocation (after).

Metric Before After Change
🚀 Requests/sec 195.97 195.53 ⚪ -0.2%
⏱️ Latency P50 87.25 ms 87.84 ms ⚪ +0.7%
⏱️ Latency P95 204.53 ms 209.97 ms ⚪ +2.7%
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 87.84 209.97 12,483 195.53 +5.44
Account 167.23 327.08 657 10.91 +48.11
TablesDB 85.21 159.63 6,789 108.76 -0.54
Storage 81.55 190.68 3,285 54.62 -5.47
Functions 127.95 243.13 1,752 29.72 -12.9

Top API waits (after)

API request Max wait (ms)
account.name.update 651.63
storage.buckets.create 444.63
storage.files.create 430.42
account.prefs.update 425
tablesdb.rows.update 386.88

@ArnabChatterjee20k
ArnabChatterjee20k changed the base branch from security/account-claim-phone-parity to main October 29, 2026 06:52
ArnabChatterjee20k and others added 5 commits October 29, 2026 12:28
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]>
@ArnabChatterjee20k ArnabChatterjee20k changed the title fix(auth): end live connections when an account is claimed fix(auth): end live connections through one Connections resource, closing them before a claim's event Oct 29, 2026
@ArnabChatterjee20k ArnabChatterjee20k changed the title fix(auth): end live connections through one Connections resource, closing them before a claim's event fix(auth): close live connections when an account is claimed Oct 29, 2026
@ArnabChatterjee20k

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

ArnabChatterjee20k and others added 2 commits October 29, 2026 13:58
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]>
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@hansi-codes review

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@tenki-reviewer review

@luxor-code-review

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

Copy link
Copy Markdown

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 · unchanged line

// 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 identityWithMatchingEmail, the claim flow merges the existing user's data without checking emailVerification and never calls User::revokeCredentials, purgeCachedDocument, $mqtt->revoke, or the realtime sessions.delete event (app/controllers/api/account.php at line 2054; the mirrored resolveUser path has the same gap at src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php:472). A claimant whose provider-verified address matches an existing identity's providerEmail is logged into the registrant's account while the registrant keeps their password, sessions, identities, and MFA — precisely the state the claim mechanism is meant to eliminate. The email-match path directly above handles the same situation by revoking everything, so the two adoption paths disagree on the claim invariant.


This PR centralizes the "claim an unverified account by proving its email" flow across sign-in surfaces, adding token-based transactional claim helpers in app/controllers/api/account.php and reusing them from OAuth2, magic URL, phone, and password-recovery paths, plus the id-token resolver and membership status update.

Files Change
app/controllers/api/account.php Adds transactional claim helpers (token lock, user merge, credential revocation, MQTT revoke, realtime sessions.delete) and wires them into the account API paths.
src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php Extends resolveUser to adopt matching identities/users under the same claim rules.
src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php Applies claim handling when a membership confirmation reveals an existing user.
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php E2E coverage asserting session teardown events reach registered realtime clients.

Reviewed commit: 0f89011

@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

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@tenki-reviewer thanks. The identity-email adoption finding (account.php ~2046-2056 / IdToken resolveUser) points at a real gap, but it sits on lines this PR doesn't change, so it will be fixed in its own PR.

On the suggested fix: calling revokeCredentials when a sign-in adopts a user through a matching identity would be wrong. If that identity is the user's own verified link, signing in through it is the owner logging in, and revoking would wipe their password on every such login. The underlying problem is that the logged-in OAuth link path stores providerEmail without checking isEmailVerified(), and the identity-email adoption then trusts that address across providers. The fix belongs there: never store or match an unverified providerEmail. This PR stays limited to ending live connections on the existing claim paths.

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. No blocking issues — 2 nitpicks below.

🧹 Nitpicks (2) — 🟢 2 low
  • 🟢 Claim event fires even when revocation no-ops (account.php:256) — All claim sites set the claimed flag immediately after User::revokeCredentials(...), but that method early-returns without revoking anything when the user's status is false or its sequence is empty (src/Appwrite/Utopia/Database/Documents/User.php:285).
  • 🟢 Phone-claim path of account claim is untested (RealtimeCustomClientTest.php:1502) — The new testConnectionEndsWithAccountClaim covers only the email-proven claim paths (magic URL and team-invite confirmation), while the claim also triggers when a phone is proven: account.php maps TOKEN_TYPE_PHONE to phoneVerification and calls User::revokeCredentials with MESSAGE_TYPE_SMS (app/controllers/api/account.php:234), and the SMS branch clears the opposite channel (src/Appwrite/Utopia/Database/Documents/User.php:302).

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 revokeCredentials and a sessions.delete realtime event into both claim paths and locks the flow with a regression test.

Files Change
app/controllers/api/account.php On magic-url/phone token claim, revokes the claimed unverified account's sessions/credentials, purges cached user state, and emits a sessions.delete realtime event before issuing the new session.
src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php Same claim-and-revoke handling applied to the IdToken session creation path.
src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php On invite acceptance that claims an unverified account, revokes credentials/sessions with MQTT and realtime notification inside the existing transaction flow.
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php Adds an e2e test asserting the claiming user receives no realtime payload for the revoked session and the session is actually closed.

Reviewed commit: 0f89011

@ArnabChatterjee20k

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 S · Looks good to merge. Summary

@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@tenki-reviewer thanks, both nitpicks checked:

  • Claim event fires even when revocation no-ops: revokeCredentials() returns early only for a user with no sequence (never stored) or a blocked user. A blocked user's connections are already supposed to be closed (status === false is a revoked state in app/realtime.php), so an extra MQTT revoke and sessions.delete re-check for them only closes what should be closed. It never closes a connection that still has access, because the realtime server re-checks each connection against the stored user. Leaving it as is keeps every claim site simple.
  • Phone-claim path is untested: the phone OTP claim runs through the same $createSession closure, and the same if ($claimed) block, as the magic URL claim the test covers. The realtime e2e suite can't read SMS on every stack, while the revocation itself on that path is covered by AccountCustomClientTest::testCreatePhoneSessionRevokesUnverifiedAccountCredentials. Since c43f742 the test also covers recovery, ID token and OAuth claims.

@tenki-reviewer review

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 3 medium

💬 Inline comments (1)

  • 🟡 OAuth callback claim fires revokes without claim guard — account.php:2019
📍 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 · unchanged line

// 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 data

The email-match claim inside resolveUser calls User::revokeCredentials, purges the user cache, revokes MQTT connections and emits users.[userId].sessions.delete before the request creates its own session (src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php:439). None of this is wrapped in a transaction or guarded by a committed claim, unlike the createSession flow that sets a claimed flag inside withTransaction. If any later step of the request fails (e.g. session persistence), the pre-existing account is left with all credentials revoked and no new session issued.


🟡 Medium — OAuth and IdToken claims revoke without user row lock · account.php:2012–2021 · unchanged line

// 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 IdToken claim paths read emailVerification and call User::revokeCredentials without forUpdate and outside any transaction (app/controllers/api/account.php:2012). A concurrent magic-URL/OTP exchange can commit emailVerification = true and a fresh session under the lock while the OAuth path, having read the pre-commit unverified state, then revokes: a request that should fail with GENERAL_BAD_REQUEST instead revokes every session — including the one just created — and claims the account.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 claimed set even when revokeCredentials no-ops (account.php:257) — $claimed is set to true immediately after User::revokeCredentials(...) returns (app/controllers/api/account.php:257), and the OAuth callback enters its MQTT/realtime block unconditionally (app/controllers/api/account.php:2020), but revokeCredentials early-returns without revoking anything when the user has status === false or an empty sequence (src/Appwrite/Utopia/Database/Documents/User.php:285-287).

The change wires a $claimed flag into the token-exchange withTransaction in app/controllers/api/account.php, firing MQTT/realtime revocation only after a committed claim, and applies similar revocation blocks to the OAuth callback, ID-token, password-recovery, and membership-acceptance paths. A large new e2e test in tests/e2e/Services/Realtime/RealtimeCustomClientTest.php covers websocket close-frame behavior and event delivery for the claim flow.

Files Change
app/controllers/api/account.php Adds $claimed-gated MQTT revocation and manual sessions.delete realtime events to magic-URL/OTP, password-recovery, and OAuth callback claim paths
src/.../Sessions/IdToken/Create.php Revokes credentials, MQTT connections and emits realtime delete when an ID-token exchange adopts an unverified existing account
src/.../Memberships/Status/Update.php Fires the same revoke/realtime side effects when accepting a team invite claims the user's email
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php New e2e coverage for connection revocation and event ordering during account claims

Reviewed commit: c43f742

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

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

Comment thread app/controllers/api/account.php Resolved
@ArnabChatterjee20k
ArnabChatterjee20k merged commit fd11179 into main Oct 29, 2026
54 checks passed
@ArnabChatterjee20k

Copy link
Copy Markdown
Member Author

@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 main, not something this PR introduces. They're tracked separately and will be fixed in their own PR. This one stays limited to ending live connections on the existing claim paths.

@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 1 high

💬 Inline comments (1)

  • 🟠 Recovery deletes token before user lock, breaking claim ordering — account.php:4706

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.

Files Change
app/controllers/api/account.php Adds revokeCredentials/claim logic and applies it in magic-url, OAuth2 callback, recovery, phone, and id-token session paths, with transactional token-claim ordering.
src/Appwrite/Platform/Modules/Account/Http/Account/Sessions/IdToken/Create.php Extends id-token session creation to run the same claim/revocation flow.
src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php Applies the claimed-credential protocol when accepting a membership invite for an already-claimed account.
tests/e2e/Services/Realtime/RealtimeCustomClientTest.php Adds testConnectionEndsWithAccountClaim asserting the registrant's websocket closes with 401 before receiving any claimant payload, plus shared close-frame assertions.

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

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

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

Comment on lines 4706 to 4716
@@ -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;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

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