{"id":"XE-1735","kind":"bounty","visibility":"public","source":"web","source_repo":"","source_ref":"","source_url":"","reporter_id":451,"title":"TOTP code can be used twice when two logins race (no row lock on the single-use step)","area":"other","claimed_tier":"minor","assessed_tier":null,"verdict":null,"duplicate_of":null,"tracked":false,"internal_ref":"","internal_url":null,"status":"triaging","closed_reason":null,"github_state":"","disclosed_at":null,"award_xe":null,"award_approved":false,"paid_ref":"","created_at":"2026-11-09T01:45:58.085273+00:00","updated_at":"2026-11-14T22:57:04.296924+00:00","source_created_at":null,"told_at":"2026-11-10T14:00:35.245901+00:00","status_changed_at":"2026-11-10T14:00:33.578103+00:00","url":"https://bounty.xe.network/XE-1735","body":"## Summary\r\n\r\n`totp_login` enforces single-use of a TOTP code by recording the accepted time step (`totp_last_step`) — but it does the read-verify-write as three separate steps with no row lock, no `FOR UPDATE`, and no atomic take. Two concurrent login requests in separate transactions both read the old step, both verify the same code, and both mint a live session. The desk knows this pattern: the status change path takes a row lock for exactly this reason (XE-0463), and the proposal-decision path re-reads with a lock (XE-0814). The TOTP path has neither. Sequential reuse is correctly blocked (XE-0820) — only the concurrent case escapes.\r\n\r\n## Impact\r\n\r\n- **One 6-digit code yields two live sessions.** The single-use guarantee a second factor is supposed to carry (\"a code is accepted once\", XE-0820) holds sequentially but not concurrently. Two sessions for the same user are created from a single code presentation.\r\n- **Bounded harm, hence Low.** The attacker must already present a valid code for the account — i.e. they hold the TOTP secret, have shoulder-surfed / phished one live code, or are the legitimate user double-submitting. The race does not let an attacker *guess* a code or bypass verification; it lets one valid code be spent twice. The window is one 30-second step (plus the ±1-step window the verifier allows), and the payoff is a second session, not privilege escalation: both sessions belong to the same user and carry the same roles.\r\n- **Detection is weak.** Both logins look identical in the log (`team.login`, `how: \"totp\"`); nothing flags that the same step was accepted twice.\r\n\r\n## Severity reasoning\r\n\r\n- **Low, not Medium:** exploiting it requires a valid code (the secret or one live code), the window is ~30 seconds, and the outcome is a duplicate session for the same account — not account takeover of someone else's account, not a privilege gain.\r\n- **Low, not informational:** the single-use property is an explicit, commented design goal (XE-0820), and the codebase already applies the locking fix to the two adjacent check-then-act paths. This is a real hole in a stated guarantee, with a known-good pattern sitting next to it.\r\n\r\n## Root cause\r\n\r\nThree facts combine:\r\n\r\n1. **Read-verify-write with no lock.** `totp_login` (`desk/api/authn.py:127-149`):\r\n\r\n   ```python\r\n   step = auth.totp_verify(secret, body.code, after_step=u.totp_last_step or 0)  # :137\r\n   ...\r\n   u.totp_last_step = step  # a code is accepted once (XE-0820)                    # :149\r\n   return await _sign_in(ctx, db, request, response, u, \"totp\")\r\n   ```\r\n\r\n   The step is read at `:137`, the new step is assigned at `:149`, and `_sign_in` commits (`desk/api/authn.py:36-46`, `await db.commit()`). Nothing between the read and the commit takes a lock on the user row: there is no `with_for_update` anywhere in `desk/api/authn.py`.\r\n\r\n2. **Each request runs in its own transaction.** `Db` is a per-request session (`desk/api/deps.py:13`, `desk/db.py:42-44` — `get_db` yields a fresh `AsyncSession` per request). Two concurrent `POST /v1/auth/totp/login` calls therefore run in separate transactions with separate snapshots: both read the same pre-login `totp_last_step`, both pass verification, both assign the same step, both call `create_session` (`desk/auth.py:102-115`, which just inserts a `Session` row — no uniqueness constraint on the step) and both commit. The second commit overwrites `totp_last_step` with the identical value, so no conflict ever surfaces.\r\n\r\n3. **The verifier's single-use check is only as strong as the stored step.** `totp_verify` (`desk/auth.py:337-349`) refuses a step at or before `after_step` — that is the whole single-use mechanism, and it depends on the caller having recorded the step before the next verification reads it. In the race, the second verification reads the step *before* the first request records it.\r\n\r\n**Contrast — the codebase already fixes this shape twice:**\r\n\r\n- `set_status` takes the row lock first: `lock()` (`desk/services/tickets.py:731-736`), \"so the check that follows is against what is in the database now, not what this request read a moment ago (XE-0463)\".\r\n- `decide` re-reads with a lock: `await db.refresh(pr, with_for_update=True)` (`desk/services/proposals.py:153`), \"two clicks in the same second decide it once (XE-0814)\".\r\n\r\nThe TOTP login path performs the same check-then-act shape with no equivalent lock.\r\n\r\n**What does NOT stop the race:**\r\n\r\n- The per-IP rate limit (`desk/api/authn.py:24-33`: `LIMIT, WINDOW = 10, 600` — 10 attempts per IP per 10 minutes) counts attempts; it does not serialize them. Two parallel attempts from one IP are both under the limit and both proceed.\r\n- `totp_verify`'s `window=1` (±1 step) widens the acceptable codes to three steps but does not change the race: any one of those steps can be spent twice the same way.\r\n\r\n## Reproduction\r\n\r\n### A. Code trace (primary evidence — CODE TRACE ONLY, no concurrent-execution harness run, no live desk run)\r\n\r\nVerified by code trace. **No live desk instance was run** (no Postgres/docker on the verification VM), and **no concurrent-execution harness was run** — the race was not demonstrated with two live parallel requests. The reproduction below is the interleaving the code permits, step by step:\r\n\r\n1. User `u` has `totp_last_step = N` (from an earlier login or setup).\r\n2. Two `POST /v1/auth/totp/login` requests, A and B, arrive concurrently with the same valid code for step `N+1`. Each gets its own session (`desk/db.py:42-44`).\r\n3. A reads `u.totp_last_step = N`, verifies: `totp_verify(secret, code, after_step=N)` returns `N+1`.\r\n4. B reads `u.totp_last_step = N` — A has not committed yet — and verifies the same way: returns `N+1`.\r\n5. A sets `u.totp_last_step = N+1`, calls `_sign_in`, creates session S_A, commits.\r\n6. B sets `u.totp_last_step = N+1` (same value, no conflict), calls `_sign_in`, creates session S_B, commits.\r\n7. Result: two live sessions from one code. A third, sequential attempt with the same code now correctly fails — `totp_verify` refuses step `N+1` because `after_step` is `N+1` — which is why only the concurrent case escapes.\r\n\r\n### B. Honesty note\r\n\r\nSequential reuse was *not* re-tested here; the claim that it is blocked rests on `totp_verify` (`desk/auth.py:337-349`, \"a step at or before `after_step` is refused\") and the XE-0820 comment at `desk/api/authn.py:149`. The race itself is a code-trace conclusion: the interleaving above follows from the absence of any lock in the path, but it was not executed against a running desk.\r\n\r\n## Dedup note\r\n\r\nClosest known work, by code reference — the live report list was not re-checked during this drafting pass, and the submitter should confirm against it before filing:\r\n\r\n- **XE-0820** — the single-use rule itself (\"a code is accepted once\"). This report is about the concurrent case that rule does not cover.\r\n- **XE-0463** — the row-lock pattern in `set_status` that the TOTP path lacks; **XE-0814** — the same pattern in proposal `decide`. Both are prior fixes for the same check-then-act shape in other paths.\r\n- **XE-0523** — the uniform \"that address and code do not match\" answer, unrelated to reuse.\r\n- No known report covers concurrent double-use of a TOTP code.\r\n\r\n## Suggested fix direction\r\n\r\n- Take the user row lock before verifying, mirroring `set_status`'s `lock()`: `await db.refresh(u, with_for_update=True)` (after `db.flush()`) before calling `totp_verify`, so the second concurrent request blocks until the first commits and then reads the updated `totp_last_step`.\r\n- Or make the take atomic: update `totp_last_step` with a conditional `UPDATE ... WHERE totp_last_step < :step` and require exactly one row affected, treating zero rows as a failed verification.\r\n- Either fix also covers the setup-confirm path (`totp_confirm`, `desk/api/authn.py:173-181`, which records `totp_last_step` the same way) if it shares the pattern — check it when fixing.\r\n\r\n## Payout address\r\n\r\n052e33e0ed9c43e2bdf07faff9a90d25642b51d53d96f49f5d45b81f6584b3da\r\n\r\n## References (file:line; desk @ 186af22)\r\n\r\n| Location | What it shows |\r\n|---|---|\r\n| `desk/api/authn.py:127-149` | `totp_login`: reads `totp_last_step`, verifies, then sets — no lock anywhere in the function |\r\n| `desk/api/authn.py:137` | `totp_verify(secret, body.code, after_step=u.totp_last_step or 0)` — the read half of the race |\r\n| `desk/api/authn.py:149` | `u.totp_last_step = step  # a code is accepted once (XE-0820)` — the write half, after verification |\r\n| `desk/api/authn.py:36-46` | `_sign_in` commits — the point at which the new step becomes visible to other transactions |\r\n| `desk/api/authn.py:24-33` | Per-IP limit (`LIMIT, WINDOW = 10, 600`): counts attempts, does not serialize them |\r\n| `desk/auth.py:337-349` | `totp_verify`: a step at or before `after_step` is refused — the single-use mechanism, and why sequential reuse is blocked |\r\n| `desk/auth.py:102-115` | `create_session`: inserts a session row; no uniqueness constraint on the step |\r\n| `desk/db.py:42-44` | `get_db` yields a fresh session per request — concurrent logins run in separate transactions |\r\n| `desk/services/tickets.py:731-736` | `lock()`: the row-lock pattern (XE-0463) the TOTP path lacks |\r\n| `desk/services/proposals.py:153` | `decide` re-reads with `with_for_update=True` (XE-0814) — same pattern, same reason |","patch_refs":[],"thread":[{"id":2142,"source":"desk","source_ref":"reply:1509","author":"Joseph Denne","team":true,"body":"Thank you for this report. We have read it against the code and it is being handled. The assessment and any award follow the fix. https://bounty.xe.network/XE-1735","created_at":"2026-11-10T14:00:19.792775+00:00"}]}