Repository navigation
fix(auth): tie phone tokens and invite verification to the address they reached - #14819
Conversation
…ey reached Phone sign-in and verification tokens are not bound to a number, so they stayed redeemable after the account's phone changed. Delete outstanding phone tokens and phone MFA challenges when the number changes, through both the account and the users API, as an email change already does for email tokens. Accepting a team invite marked the email verified even when the invite went out by SMS. Mark only the address the invite reached, and leave both unverified when the user has an email and a phone on file, since the invite could have gone to either. Co-Authored-By: Claude <[email protected]>
|
Review complete. 🟡 2 medium 💬 Inline comments (1)
📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to🟡 Medium — Phone change skips the transaction email change uses · account.php:4093–4117 · // app/controllers/api/account.php
4093 try {
4094 $user = $dbForProject->updateDocument('users', $user->getId(), $user);
4095 $oldTarget = \array_find($user->getAttribute('targets', []), static fn (Document $target): bool => $target->getAttribute('identifier') === $oldPhone);
4096
4097 if ($oldTarget instanceof Document && !$oldTarget->isEmpty()) {
4098 $authorization->skip(fn () => $dbForProject->updateDocument('targets', $oldTarget->getId(), $oldTarget->setAttribute('identifier', $phone)));
4099 }
4100
4101 $sequence = $user->getSequence();
4102 if ($oldPhone !== $phone && $sequence !== '' && $sequence !== null) {
4103 $authorization->skip(function () use ($dbForProject, $sequence) {
4104 $dbForProject->deleteDocuments('tokens', [Both phone-change paths perform the user update, target handling, and token/challenge purge without a transaction: the self-service path ( The change hardens phone-identity flows: when a phone number changes, existing phone tokens and MFA challenges for that user are purged, and membership confirmation now sets only the verification flag matching the user's available channels instead of always flipping
Reviewed commit: 9f11085 |
🟢 Tier S · Ready to mergeThis PR invalidates phone tokens, MFA challenges, and pending invitations when their destination address changes. It also binds invite acceptance to a known address channel and coordinates issuance and redemption with address updates using user-row locks, with new E2E coverage for these flows.
📂 Walkthrough · 9
🔇 Filtered out · 1Findings Hansi considered but did not post.
Reviewed |
There was a problem hiding this comment.
This PR invalidates phone-type tokens and MFA challenges when a user's phone changes (self-service and admin paths) and makes membership confirmation set email/phone verification based on which channel the user has, with new e2e coverage.
Key findings
- 🟡 Dual-channel invitee never gets verified on confirm — Update.php:133
- 🟡 Phone change skips the transaction email change uses — account.php:4093
| $verification = match (true) { | ||
| $hasEmail && !$hasPhone => 'emailVerification', | ||
| $hasPhone && !$hasEmail => 'phoneVerification', | ||
| default => null, | ||
| }; | ||
|
|
||
| if ($verification !== null) { | ||
| $targetUser->setAttribute($verification, true); | ||
| $authorization->skip(fn () => $dbForProject->updateDocument('users', $targetUser->getId(), new Document([$verification => true]))); | ||
| } |
There was a problem hiding this comment.
🟡 bug · medium
Dual-channel invitee never gets verified on confirm
When the invited user has both an email and a phone, the match falls to default => null and no verification flag is written (src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php:133-142). Invitations are delivered to email first when both channels are supplied (Memberships/Create.php:502), so confirming such an invite proves the email address, yet emailVerification is no longer set — a regression from the previous unconditional emailVerification = true. The channel the invite was actually sent to is never recorded on the membership document, so the inference cannot be correct for dual-address users; downstream gates checking verification (e.g. MFA factor enablement) see the user as unverified.
📋 Prompt for AI Agents
Two changes: (1) In src/Appwrite/Platform/Modules/Teams/Http/Memberships/Create.php around lines 299-318 (and the re-send path around line 372), store the invite channel on the membership document — set 'email' => $email when the invite was sent to email, otherwise 'phone' => $phone — adding the attributes to the memberships schema in app/config/collections/projects.php if required. (2) In src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php lines 130-142, replace the $hasEmail/$hasPhone match(true) inference: if the membership records an email, set 'emailVerification' => true; if it records a phone, set 'phoneVerification' => true; only fall back to the current inference when the membership has no recorded channel. Currently a user with both an email and a phone who confirms an email invite gets no verification flag set (default => null), a regression from the previous unconditional emailVerification = true. Update e2e coverage in tests/e2e/Services/Teams for a dual-channel invitee asserting the invited channel becomes verified on confirm.
There was a problem hiding this comment.
This is deliberate. A user with both addresses can receive an invite by email or, when invited by phone only, by SMS, and the membership does not record which. The previous unconditional emailVerification = true is exactly what lets an SMS invite mark an unproven email verified, so for dual-address users the safe choice is to mark neither; they verify through the normal email/phone verification flows. Recording the channel on the membership would need a new attribute plus a migration for every project, which this fix avoids on purpose. Single-address users (the common invite case) still get the invited channel verified.
There was a problem hiding this comment.
The reasoning is understandable, but the 'safe choice' argument has a concrete correctness cost: today, a dual-channel user who receives and confirms an email invite ends up with neither address verified, which is a regression from the old behavior and breaks downstream gates (MFA factor enablement, etc.) that expect at least one verified channel after a successful invite confirmation. The old code was wrong to blindly set emailVerification when the invite may have gone by SMS, but the new code overcorrects by setting nothing.
The 'normal verification flows' fallback isn't a safe default — it silently degrades the UX for a class of users who have legitimately proved ownership of the invited channel. Recording the invite channel on the membership (as the prompt suggests) is the minimal correct fix; it avoids the SQL-injection-style ambiguity without requiring the user to re-verify. If the schema migration is the blocker, a lighter alternative is to derive the channel at confirm time from context already available (e.g. the secret type or the invite payload) rather than from the user's current address set — but doing nothing for dual-channel users is not the right tradeoff.
There was a problem hiding this comment.
Confirming an email invite proves the email only if the invite actually went to the email, and nothing stored today says that. The "secret type" and invite payload are not available at confirm time: the secret is a random value with no channel, and the URL params are client-controlled, so trusting a channel param would bring back the original issue. When an existing user with both an email and a phone is invited by phone, Create sends the SMS, and the user state looks exactly like an emailed invite. So any rule based on user state that marks the email verified for dual-address users keeps the original issue. Marking nothing in that case is the only safe option without storing the channel. Storing it means a membership attribute plus a migration across every project and shared-tables host, which I am deliberately keeping out of this security fix. Dual-address users can still verify through createVerification / createPhoneVerification.
There was a problem hiding this comment.
The argument is coherent, but it leaves dual-channel users in a worse state than before this PR: a successful email-invite confirmation now produces zero verified channels, breaking downstream gates that depend on at least one verified address post-confirmation. The 'nothing stored says which channel was used' point is precisely the gap that needs closing — either by recording the channel at invite time or by another reliable signal at confirm time. Accepting 'mark neither' as a permanent policy (rather than a temporary safe default) means the fix is incomplete for dual-channel users. The finding remains open until the channel is recorded on the membership (or an equivalent mechanism is in place) so confirm can set the correct flag. The current diff is unchanged from the original finding and does not resolve the issue.
There was a problem hiding this comment.
With e2ea6b8 a pending invite is voided whenever the email or phone changes, so at confirm time the user's addresses are exactly the ones on file when the invite was sent. The only case left ambiguous is a user who had both addresses at invite time; for them, marking neither is the safe rule, and they can verify through the normal flows. Recording the delivery channel on the membership would settle it, but it needs a schema change and a migration across every project, so it is better as a follow-up than as part of this fix.
There was a problem hiding this comment.
The latest reply from @ChiragAgg5k references commit e2ea6b8 which purportedly voids pending invites when the user's email or phone changes — but even if that guarantee holds, it does not resolve the dual-channel ambiguity. A user who had both email and phone at invite time (and still has both at confirm time) still hits 'default => null' and gets no verification flag set. The local hunk is unchanged from the original finding, confirming the regression is still present for that case. The commit cited only removes a different attack surface (address substitution after invite); it does not record the delivery channel or fix the match logic. Recording the channel on the membership remains the correct resolution, and the finding stays open.
✨ 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
|
Saving the number and deleting phone tokens in separate steps left old-number tokens usable if the cleanup failed, since a retry saw no change. Run both in one transaction under a row lock, as the email change does, and cover pending phone MFA challenges in the e2e test. Co-Authored-By: Claude <[email protected]>
A phone token could be inserted for a stale number if the number changed between looking the user up and creating the token, after the change had already cleared outstanding tokens. Create phone sign-in and verification tokens under the same user row lock the phone update takes, and refuse when the number no longer matches. Co-Authored-By: Claude <[email protected]>
…rship-channel # Conflicts: # app/controllers/api/account.php
|
@hansi-codes review |
…change A pending team invite proves the address it was delivered to, so accepting it after the email or phone changed would verify an address that never received it. Clear the secret of the user's unconfirmed memberships when either address changes, as already done for tokens. Also create phone MFA challenges under the user row lock with a phone recheck, so a code cannot be issued for a number that is being replaced. Co-Authored-By: Claude <[email protected]>
|
@hansi-codes review |
An accept request that passed the secret check before an address change voided the invite could still confirm it, create a session and verify the new address. Lock the user and the membership, recheck the stored secret, and set verification from the locked user inside the confirm transaction; create the session only after it commits. Co-Authored-By: Claude <[email protected]>
|
@hansi-codes review |
The findings that requested changes are resolved. See the summary comment for what is still open.
An invite created while the invitee's address was changing could write its secret after the change voided pending invites and still go out to the old address. Recheck the address under the user row lock before sending, and void the invite if it moved. On acceptance, create the session in the same transaction as the confirmation so a failure cannot use up the invite without signing the user in. Co-Authored-By: Claude <[email protected]>
|
@hansi-codes review |
…oved The stale-address cleanup ran after the lock was released and cleared whatever secret was stored, which could wipe a newer resend that had already been delivered. Clear it inside the locked transaction, and only if the stored secret is still the one this request wrote. Co-Authored-By: Claude <[email protected]>
|
Addressed "Stale invite cleanup can void a concurrent resend" in 7dd2213: when the address moved, the secret is now cleared inside the same locked transaction (user row and membership both @hansi-codes review |
…fied Co-Authored-By: Claude <[email protected]>
|
Added the missing assertion in 576814e: @hansi-codes review |
An email challenge is checked only against its stored code, so one mailed to the old address could still complete MFA after the account moved to a new one. Both email-update paths now delete the user's pending email challenges, as the phone paths already do for phone challenges.
|
@hansi-codes review |
The findings that requested changes are resolved. See the summary comment for what is still open.
The users MFA challenge endpoint only returns codes for the custom factor, so the email-update regression test now takes the code from the challenge email sent to the user's current address.
Only phone challenges rechecked the address under the user row lock, so an email challenge could load the old address, insert after an email change deleted the user's challenges, and stay redeemable from the old mailbox. Email challenges now take the same lock and recheck the current email.
The email-change invite invalidation had coverage; the phone-change counterpart did not. The test changes the number after an SMS invite and checks the old secret is refused and the phone stays unverified.
|
@hansi-codes review |
|
@hansi-codes review |
…s them The code was stored under the user row lock but queued after the lock was released, so an address change could commit in between, delete the code, and the request still sent it to the old address. Phone tokens, phone verifications and email or phone MFA challenges now build their message first and queue it inside the same transaction that rechecks the address and stores the code. MFA challenges are also stored only after their delivery checks pass, so a refused request no longer leaves a challenge behind.
|
@hansi-codes review |
…rship-channel fix(auth): tie phone tokens and invite verification to the address they reached (cherry picked from commit 3c889fc)
What this fixes
In three places, proof that someone controls a phone number or email address keeps working after the account has moved to a different one. Each case is shown below with real requests against a local stack, first on
mainand then on this branch.401 user_invalid_tokenemailVerification, even when the invite went out by SMS401 team_invalid_secret1. Phone codes outlive a number change
Phone tokens (sign-in OTP and phone verification, both
TOKEN_TYPE_PHONE) are matched by user and secret, not by number. Changing the email already deleted outstanding email tokens; changing the phone did nothing. Phone numbers get recycled, so the old number's next owner could sign in with a code that was texted there.This happens through both
PATCH /v1/account/phoneandPATCH /v1/users/:userId/phone. Phone tokens and phone MFA challenges are now also created under the same user row lock, after rechecking that the number has not changed. So a code issued at the same moment as a number change is either refused or cleared by the change.2. An SMS invite marks the email verified
PATCH /v1/teams/:teamId/memberships/:membershipId/statusalways setemailVerification = true, because accepting an invite used to prove you read the email. Phone invites reuse the same endpoint, so an SMS invite "verified" an email address that never received anything.The membership does not record which channel was used. To avoid a new attribute and a migration, the channel is inferred from what the user has on file:
The last row gives up a convenience: users with both an email and a phone now verify through the normal flows instead.
3. Invites outlive an address change
Pending invites stayed redeemable after the user's email or phone changed. Whoever still read the old inbox could join the team, and the acceptance then marked the new address verified.
This applies to the account and users APIs for both email and phone. The inviter can resend the invite to the new address.
Changes
app/controllers/api/account.php(PATCH /v1/account/phone,/v1/account/email, phone token creation) andUsers/Http/Users/{Phone,Email}/Update.php: delete phone tokens and phone challenges on a number change, void pending invites on either change, and issue phone tokens under the user row lock.Account/Http/Account/MFA/Challenges/{Create,Update}.php: create phone challenges under the same lock, and claim a challenge under that lock when it is answered, so one cleared by a number change getsuser_invalid_token.Teams/Http/Memberships/Status/Update.php: pickemailVerificationorphoneVerificationfrom the addresses on file, written as a sparse update.Teams/Http/Memberships/Create.php: after storing the invite, recheck the invitee's address under the user lock. If it changed in the meantime, the invite's secret is voided and the request returns400asking to send it again.Tests
AccountCustomClientTest::testCreateSessionWithPhoneAfterPhoneUpdate: phone tokens issued before a server-side or user-side number change are refused with 401, and so is a phone MFA challenge.TeamsCustomClientTest::testCreateMembershipByPhone: accepting an SMS invite marks the phone verified and the email not verified.TeamsCustomClientTest::testUpdateMembershipStatusByPhoneKeepsEmailUnverified: a user with both an email and a phone accepts an SMS invite; neither is marked.TeamsCustomClientTest::testUpdateMembershipStatusAfterEmailChange/…AfterPhoneChange: an invite sent to the previous address is refused withteam_invalid_secret.docker compose up), running the same requests onmain(d5ccf14) and on this branch (7d2fbae).Related: appwrite-labs/cloud#6666