Skip to content

fix(account): keep MFA in force when an unverified address is claimed - #15144

Merged
ChiragAgg5k merged 3 commits into
mainfrom
fix/mfa-claim-bypass
Oct 31, 2026
Merged

ChiragAgg5k merged 3 commits into
mainfrom
fix/mfa-claim-bypass

Conversation

@ChiragAgg5k

@ChiragAgg5k ChiragAgg5k commented Oct 31, 2026 •

Copy link
Copy Markdown
Member

What

Proving an unverified email or phone (email OTP, magic URL, phone OTP, password recovery, signed-out team invite) claims the account via User::revokeCredentials(), which also deletes authenticators and sets mfa => false. Changing an account's email resets verification but keeps MFA on, so the new inbox alone yielded a fully authorised session.

PATCH /v1/account/email          -> emailVerification: false, mfa: true
POST  /v1/account/tokens/email   -> 201
POST  /v1/account/sessions/token -> 201
GET   /v1/account                -> 200, mfa: false, totp factor gone

Fix

When the account needs two factors (getMinimumFactors() > 1), skip the claim and leave the address unverified:

$guarded = $locked->getMinimumFactors() > 1;
if ($verification !== null && !$locked->getAttribute($verification, false) && !$guarded) {
    // revokeCredentials ...
}

The session is still issued but stays short of factors (user_more_factors_required) until the second factor is presented. Recovery still resets the password, which then also needs the second factor.

Applied to createSession (email/magic URL/phone tokens), PUT /v1/account/recovery, PUT /v1/account/recovery/otp, and signed-out membership acceptance.

Test

testClaimingUnverifiedEmailKeepsMFAInForce: TOTP + MFA on an unverified-email account, then magic URL and recovery each leave the session at user_more_factors_required, with mfa, the TOTP factor and emailVerification: false intact.

Related: appwrite-labs/cloud#6666

Signing in by email OTP, magic URL, phone OTP, password recovery or a signed-out team invite on an account whose address is unverified ran the account claim, which deleted the authenticators and turned MFA off before issuing the session. Changing the email resets its verification while MFA stays on, so control of the new inbox alone gave a fully authorised session.

When the account needs two factors the claim is skipped and the address is left unverified, so the new session stays short of factors until the TOTP or other factor is presented.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟠 2 high

💬 Inline comments (1)

  • 🟠 MFA guard lets email squatters keep live sessions on recovery — account.php:4727
📍 Findings outside the diff (1) — 🟠 1 high — defects on lines GitHub can't attach comments to

🟠 High — OAuth and id-token claim paths miss the MFA guard · account.php:2028–2048 · unchanged line

// app/controllers/api/account.php
2028	                    if (!$user->getAttribute('emailVerification', false)) {
2029	                        $authorization->skip(fn () => User::revokeCredentials($dbForProject, $user, $project));
2030	                        $dbForProject->purgeCachedDocument('users', $user->getId());
2031	
2032	                        try {
2033	                            $mqtt->revoke($project->getId(), $user->getId());
2034	                        } catch (\Throwable $error) {
2035	                            Console::error('Failed to revoke MQTT connections: ' . $error->getMessage());
2036	                        }
2037	
2038	                        // Sent before the request's own event, which would otherwise reach the registrant with the claimant's data
2039	                        (clone $queueForRealtime)

The PR's invariant — a proven address must not discard a second factor while MFA is in force — is applied to the magic-url, phone-token, recovery, and team-invite paths, but the two provider-claim paths still call User::revokeCredentials unconditionally on an unverified email (app/controllers/api/account.php:2028). That call nulls the password, wipes sessions, tokens, authenticators, identities and MFA/recovery codes, and line 2048 then marks the email verified. A provider-verified email alone can therefore dismantle MFA and take over an existing account, unlike the identical scenario through magic-url or recovery; the same unguarded claim exists in Sessions/IdToken/Create.php at line 438.

🧹 Nitpicks (1) — 🟢 1 low
  • 🟢 Magic-url secret extraction via raw strpos is brittle (AccountCustomClientTest.php:5131) — testClaimingUnverifiedEmailKeepsMFAInForce extracts the magic-url secret with substr($mail['text'], strpos($mail['text'], '&secret=', 0) + 8, 64) (tests/e2e/Services/Account/AccountCustomClientTest.php:5131).

This PR makes email verification and account claiming safe when MFA is already in force: when a user's getMinimumFactors() exceeds 1, the token/session claim path, both password-recovery endpoints, and team-invite acceptance skip credential revocation and the emailVerification write, preserving the user's sessions and second factor. A new e2e test in AccountCustomClientTest walks a magic-url sign-in and a recovery under MFA and asserts the user_more_factors_required challenge behavior.

Files Change
app/controllers/api/account.php Adds the MFA-guard check to the claim flow and both recovery endpoints, skipping revokeCredentials and the verification write when a second factor is in force
src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php Applies the same guard to signed-out membership acceptance so claimed sessions keep their factors
tests/e2e/Services/Account/AccountCustomClientTest.php Adds an e2e test asserting MFA-challenge enforcement after magic-url sign-in and password recovery, with email-link and TOTP helpers

Reviewed commit: a0d014f

@ghost

ghost commented Oct 31, 2026 •

Copy link
Copy Markdown

🟢 Tier S · Ready to merge

The incremental changes only add type annotations, and they correctly match the imported User class and the methods used on the locked documents.

The account sign-in and recovery flows, along with signed-out team invitation acceptance, preserve MFA and leave an address unverified when claiming it would bypass a required second factor. E2E tests cover the retained MFA state and factor across magic-link sign-in, recovery, and invitation acceptance. The latest changes add explicit User type annotations to locked user reads used by these flows.

Latest changes: Added @var User annotations for the locked user documents in account session and recovery flows and team membership status updates; these clarify the type without changing runtime behavior.

Verdict New comments Fixed Still open
✅ Approved 0 0 0
📂 Walkthrough · 4
File Change
app/controllers/api/account.php Preserves MFA during token-based sign-in and both password recovery flows, with E2E coverage; the latest commits annotate the locked user documents as User.
src/Appwrite/Platform/Modules/Teams/Http/Memberships/Status/Update.php Preserves MFA during signed-out invitation acceptance and adds a User annotation for the locked user document.
tests/e2e/Services/Account/AccountCustomClientTest.php Covers MFA and unverified-email state after magic-link sign-in and password recovery.
tests/e2e/Services/Teams/TeamsCustomClientTest.php Covers retained MFA and unverified-email state when accepting a signed-out team invitation.

Reviewed the commits since e00f2e1 · 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 · 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.

@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

@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 an MFA guard to the account-claim and password-recovery flows so a verified address alone cannot discard a second factor, with a new e2e test covering the magic-url and recovery paths.

Key findings

  • 🟠 OAuth and id-token claim paths miss the MFA guard — account.php:2028
  • 🟠 MFA guard lets email squatters keep live sessions on recovery — account.php:4727

Comment on lines 4727 to 4728
$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.

🟠 security · high

MFA guard lets email squatters keep live sessions on recovery

When MFA is in force, password recovery skips User::revokeCredentials yet still replaces the password (app/controllers/api/account.php:4727). A squatter who registered an unverified email can enroll TOTP with their own session before the real owner recovers; after recovery the password changes but the squatter's session and second factor survive, so they keep full access and the mailbox owner cannot even claim. The same guard exists in the duplicate recovery handler at app/controllers/api/account.php:5173 and in the session-claim path at app/controllers/api/account.php:257.

📋 Prompt for AI Agents

In app/controllers/api/account.php around lines 4724-4729 and the duplicate block around 5171-5175, the new $guarded = $locked->getMinimumFactors() > 1 check is used to skip User::revokeCredentials($dbForProject, $profile, $project) during password recovery. Change the logic so revokeCredentials still runs when the email is unverified (the password change must evict the registrant's sessions, tokens and MFA factors), and keep only the emailVerification => true update behind !$guarded. Apply the same split in the session-claim path at lines 257-263. Explain in a comment that the proven address justifies revoking the registrant's credentials, while only the verification flag stays unclaimed when a second factor is in force.

@github-actions

github-actions Bot commented Oct 31, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/mfa-claim-bypass (after).

Metric Before After Change
🚀 Requests/sec 200.01 206.72 ⚪ +3.4%
⏱️ Latency P50 85.95 ms 84.52 ms ⚪ -1.7%
⏱️ Latency P95 203.18 ms 192 ms 🟢 -5.5%
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 84.52 192 12,711 206.72 -11.18
Account 155.16 287.93 669 11.1 -5.25
TablesDB 81.15 143.55 6,913 113.96 -12.4
Storage 80.44 181.58 3,345 57.16 -18.26
Functions 120.03 224.06 1,784 31.35 -20.18

Top API waits (after)

API request Max wait (ms)
functions.create 415.22
account.name.update 352.64
account.prefs.update 351.53
storage.files.create 343.72
functions.variables.create 339.37

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