Repository navigation
fix(auth): a login that issued no session must not look like one that did (#2322) - #2357
Conversation
Daily-mode scoped audit of fix/2322-mfa-challenge-response-shape (PR #2357). Zero findings — every change in the diff removes a response field, so the posture delta is a net reduction in disclosure on the one trust boundary it touches. Checks actually executed rather than asserted: the enterprise-docs-guard PCRE run locally against the branch (the PR changes docs/**, so the guard runs in CI — clean, and the new prose never uses the forbidden two_factor identifier), vendored-copy parity (Invariant #5), secrets archaeology over the commit range, lockfile integrity after the worktree npm ci, and a search for any generated client or strict validator that would distinguish field-absent from field-null. Records the one credential-hygiene issue /review caught pre-merge (a doc example echoing the response body, which carries the short-lived challenge_token) as closed, and two residual risks deferred to the issue owner: the RFC 6749 status code, and role policy sweeping machine credentials into a human-interactive second factor. Verification was in-context rather than by subagent, per the standing instruction not to spawn agents unrequested — noted in the report so the substitution is visible.
… did (#2322) When enterprise 2FA defers a login, `POST /token` answered HTTP 200 carrying `access_token: null` AND `token_type: "bearer"` — a password grant that issued no session, describing itself as a bearer grant. Any client reading the token field without checking it stored nothing, reported success, and produced unexplained 401s on its next call, far from the cause. Trinity shipped three such clients: the MCP server (checked `response.ok`, not the payload) and both CLI login paths. The issue's stated root cause — a challenge-scoped token that `get_current_user` rejects — is not what fires. `mfa_gate.gate_login` never sets `access_token`; `Token` defaults it to `None` and the route had no `response_model_exclude_none`, so the field was null and `MFA_CHALLENGE_SCOPE` was never reached. Verified against v0.8.5, the reporting instance's version, which is byte-identical here. Root-cause correction posted on the issue. `/token` was the outlier, not the pattern: of the three `gate_login` consumers, the email route and the enterprise SSO redirect already omitted the token fields on a challenge. This brings the third into line rather than inventing a contract. - `Token.token_type` becomes Optional; both `/token` routes serialize with `response_model_exclude_none=True`. Two clean shapes: a grant carries `access_token` + `token_type`, a challenge carries neither. This also fixes the second half — every successful login, OSS-only builds included, used to carry all four 2FA fields as null, contradicting `Token`'s own docstring. - `mcp-server`: `authenticate()` verifies it received a session, with a distinct message when a second factor is the cause; `TokenResponse` fields are now optional so TypeScript enforces the check at the next call site. - `cli`: one `_require_access_token()` helper at all four read sites — exits non-zero, points at MCP API keys, and writes no profile. Worth noting for triage: the policy arm is the worse trigger. `gate_decision` returns `required=True` for every admin/creator-role account the moment the role policy is enabled, so one admin toggle defers every unattended credential on those roles *before anyone has enrolled*. Tests: 12 new (9 backend, 3 CLI, 3 MCP — the backend ones edition-agnostic via the OSS `mfa_gate` seam, so they run with no enterprise submodule present), each mutation-verified by removing the guard and watching it go red. Full unit suite vs base `76615f26`: identical failure sets, +9 passing. Deliberately NOT changed, both deferred to the issue: `/token` still answers 200 for a deferred grant (RFC 6749 says error; moving it breaks `stores/auth.js` at two call sites), and whether a role policy should sweep machine credentials into a human-interactive second factor at all. Fixes #2322
…il-route pin (#2322) Three findings from the pre-landing review of this branch, all in the same "the fix reached the code but not everything that behaves like a client" family the original commit was about. I1 — the doc example I added echoed the whole response body on failure (`echo "...: $resp"`), which prints the short-lived `challenge_token` to stderr. Script stderr routinely lands in CI logs. Now prints a fixed message. I2 — the consumer sweep covered all three first-party code clients and the API reference, but `grep -rn access_token docs/` still found `getting-started/overview.md` and `agents/agent-session.md` teaching `json.load(sys.stdin)['access_token']`: the exact blind read, in the two documents a new operator copies first. The API reference taught the checked pattern while getting-started taught the unchecked one. Both now use `.get('access_token')` with an explicit empty check. I3 — `/api/auth/email/verify` was the consumer that was ALREADY correct, cited as the reference behaviour in three documents and the previous commit message, and pinned by nothing. It carries no `response_model` on purpose (the raw challenge dict has no `access_token` key at all); adding one later would silently reintroduce the #2322 shape on the one route that never had it. Two tests now pin both its shapes, and the route carries a comment saying why it has no `response_model`. Mutation-verified: `response_model=Token` there turns them red. Also captures two durable classes in learnings.md: an editable install pins a package to ONE checkout, so a worktree's tests can exercise code you did not change (`trinity_cli` resolves to the main checkout from any worktree — it is how I2 nearly shipped green); and documentation is a call-site, so a response-contract change must sweep `docs/` on equal footing with source, grepping the field name rather than the endpoint. Verified: 11 backend (was 9), 10 CLI, both root lints clean.
Daily-mode scoped audit of fix/2322-mfa-challenge-response-shape (PR #2357). Zero findings — every change in the diff removes a response field, so the posture delta is a net reduction in disclosure on the one trust boundary it touches. Checks actually executed rather than asserted: the enterprise-docs-guard PCRE run locally against the branch (the PR changes docs/**, so the guard runs in CI — clean, and the new prose never uses the forbidden two_factor identifier), vendored-copy parity (Invariant #5), secrets archaeology over the commit range, lockfile integrity after the worktree npm ci, and a search for any generated client or strict validator that would distinguish field-absent from field-null. Records the one credential-hygiene issue /review caught pre-merge (a doc example echoing the response body, which carries the short-lived challenge_token) as closed, and two residual risks deferred to the issue owner: the RFC 6749 status code, and role policy sweeping machine credentials into a human-interactive second factor. Verification was in-context rather than by subagent, per the standing instruction not to spawn agents unrequested — noted in the report so the substitution is visible.
…s 403 (#2322) Implements the issue's own Suggested Fix, which the previous commits deliberately stopped short of: "return 401/403 with {"detail": "mfa_required", "challenge_token": "..."} and no access_token field ... fix /token (the OAuth2-shaped surface) to fail loudly." A password grant that issued no session is an error for the grant (RFC 6749 §5.2). Three outcomes, three status codes: 200 session issued — access_token + token_type 403 second factor pending — detail: "mfa_required" + the challenge, no token 401 credentials rejected — no session and no challenge 403 and NOT 401. The issue permits either; 401 is actively wrong here, and both first-party clients are the proof: * trinity_cli/client.py::_handle_response treats 401 as "your session expired, run `trinity login`" and hard-exits — nonsense during login. * main.js registers a GLOBAL axios 401 interceptor that calls authStore.logout() and redirects to /login. Safe today only because of a `currentPath !== '/login'` guard; wiring a mid-flight login refusal into "your session died" machinery is a trap for whoever next moves the login form. Semantically the credentials were CORRECT — authentication is incomplete, not rejected, which is why OAuth providers answer mfa_required with 403. `test_the_403_is_not_a_401` pins the choice so a later tidy-up cannot silently re-arm either behaviour. All four surfaces moved together: - backend returns a JSONResponse so the challenge fields sit beside `detail` (the shape the issue specifies), with the 403 declared in the OpenAPI - frontend reads the challenge off error.response.data in the catch branch - CLI: TrinityAPIError now carries the parsed `body`, and _exit_on_login_error maps a 403+mfa_required to the actionable message on all four login handlers - MCP client parses the body BEFORE the status check — otherwise the one failure with a specific cause reports a bare "Forbidden" Clients branch on the BOOLEAN mfa_required, never on parsing `detail`. Deliberate asymmetry, documented rather than hidden: /api/auth/email/verify keeps its 200. The issue scopes the RFC change to "/token (the OAuth2-shaped surface)" and that route is a bespoke JSON endpoint, not a grant. The invariant both satisfy is "no response ever presents a session that was not issued" — each via the mechanism its own contract calls for. New pins: the 401-vs-403 choice, and that a WRONG password stays 401 and carries no challenge (a rejected credential must never be handed a challenge token). Mutation-verified: reverting to the 200 body fails 6, 403→401 fails 6. Tests 13 backend (+2) / 10 CLI / 5 MCP (+2). Full unit suite vs base 76615f2: 21 failed / 12057 passed against base's 23 / 12042 — zero regressions (the two non-reproducing base failures are flaky capacity-meter tests, unrelated). MCP 269 pass, tsc clean, both root lints clean, enterprise-docs-guard clean.
The audit listed the RFC 6749 status code as residual risk R1; it was implemented in 2baef98. Appended as an addendum rather than rewriting the finding — the report is a point-in-time record. Notes the two security-relevant properties of the 403, both newly pinned: a rejected password still returns 401 and carries no challenge (so a caller who never proved the first factor is never handed a challenge token), and 403 was chosen partly because 401 drives the frontend's global logout interceptor and the CLI's re-login exit — both of which would make the refusal LESS legible, which is the defect class the issue is about. R2 stays open and is explicitly not a defect.
Running the step the sprint pipeline prescribes and I went around. It found
nine more call-sites of the blind `access_token` read, which is exactly the
class this PR added to learnings.md — and my own /review sweep missed them
because it was scoped to `src docs/user-docs scripts` rather than the field
name across the tree. The lesson said "grep the field name, not the endpoint";
I then ran a scoped grep.
Stale documentation of code this PR changed:
- mcp-orchestration.md transcribed the OLD MCP client verbatim
(`this.token = data.access_token;`) — the exact line the fix replaces.
Updated, with a note that password auth is the legacy path (prod runs
MCP_REQUIRE_API_KEY=true).
- role-model.md's test plan used `jq -r .access_token` twice, plus a caveat
that an empty token now means a 403 second-factor challenge.
Same blind read, seven more places, all now `// empty` / `.get(... ) or ''`:
AGENT_NETWORK_DEMO.md, user-docs quick-start + monitoring,
docs/testing/{audit-trail-manual-test-plan,GEMINI_TESTING_PLAN,phases/PHASE_00_SETUP},
and AGENTS.md.
Deliberately NOT changed, with the line stated rather than silently skipped:
.github/workflows/{build-without-submodule,container-security}.yml and
tests/test_ip_rate_limit_fix.py authenticate against throwaway instances we
control, where 2FA cannot be enabled. Docs teach patterns humans copy; those
do not — and editing CI workflows on an auth PR widens the blast radius for
no benefit.
Also adds the feature-flows index changelog row, which is the other half of
what /sync-feature-flows maintains.
Full-repo re-sweep after the fix is clean outside those three exemptions.
Verified: 13 backend, 10 CLI, both lints, enterprise-docs-guard.
… case study The entry said 'three docs' and credited the /review sweep with finding them. What actually happened: /review found two, and the SKIPPED /sync-feature-flows later found nine more — including a feature flow transcribing the old client code verbatim. The instructive half was missing entirely. The miss was not carelessness about docs (the first sweep deliberately included docs/user-docs); it was SCOPE — a path list encodes a guess about where the pattern lives, and that guess had already been wrong once. The lesson now says: grep the whole tree, then subtract the hits you can justify leaving, because an explicit exemption is reviewable and a path that was never scanned is not. Also records the structural note: /validate-pr reported 'Feature Flows OK' throughout, because it checks whether flow docs were touched, not whether the sweep behind them was complete. A learnings entry that is wrong about its own case study is worse than none — /autoplan reads this file before planning.
d916e74 to
33abbeb
Compare
vybe
left a comment
There was a problem hiding this comment.
Validated after rebase onto dev. Fixes #2322 (closing keyword present). All 21 non-skipped checks pass; regression diff clean across all six seeds (base 12130 → head 12143, 0 failures either side, No new failures). e2e green, and the PR is correctly unlabelled-ui-free — it does touch src/frontend/src/stores/auth.js, and frontend-e2e ran anyway.
Substance. The fix is right and, more importantly, it is applied at all three surfaces that were reading the field without checking it — Invariant #13's whole point. A password grant that issues no session now answers 403 rather than 200 {access_token: null, token_type: "bearer"}, and the MCP server (client.ts, which checked response.ok and nothing else), both CLI login paths (trinity_cli/client.py, commands/auth.py) and the frontend store all learn about it. A one-sided fix here would have left the exact silent-401-far-from-the-cause failure the issue describes, just from a different client.
test_2322_mfa_challenge_response.py is the named regression test; test_cli_admin_login.py covers the CLI half; auth-challenge.test.ts the MCP half. A CSO --diff audit rode along (docs/security-reports/cso-diff-2026-08-21-2322-mfa-challenge-shape, 0 findings) with an addendum recording R1 closed — appropriate for an auth-path change, and the review pipeline asks for it on this PR type.
Rebase note. Conflicted on docs/memory/learnings.md after #2333 landed — a pure append-vs-append at the same insertion point. Resolved keep-both, ordered by entry date (the file is chronological ascending); verified no duplicate headings and no surviving markers. tests/registry.json came through clean and still parses at 200 entries.
Security scan clean — the two secret-shaped hits are test fixtures (eyJ-challenge, eyJ-real). No new env var, no new backend package, no host paths or mode flips.
Summary
When enterprise 2FA defers a login,
POST /tokenanswered HTTP 200 carryingaccess_token: nullandtoken_type: "bearer"— a password grant that issued no session, describing itself as a bearer grant. Any client reading the token field without checking it stored nothing, reported success, and produced unexplained 401s on its next call, far from the cause.Trinity ships three such clients: the MCP server (checked
response.ok, never the payload) and both CLI login paths. All three are fixed here.The contract now
A password grant that issued no session is an error for the grant (RFC 6749 §5.2). Three outcomes, three status codes:
{access_token, token_type}{detail: "mfa_required", mfa_required: true, mfa_enrolled, enrollment_required, challenge_token}{detail: "Incorrect username or password"}— never a challenge403 and not 401, though the issue permits either — 401 is actively wrong here, and both first-party clients are the proof:
trinity_cli/client.py::_handle_responsetreats 401 as "your session expired, runtrinity login" and hard-exits. During login that message is nonsense.main.jsregisters a global axios 401 interceptor that callsauthStore.logout()and redirects to/login. Safe today only because of acurrentPath !== '/login'guard — wiring a mid-flight login refusal into "your session died" machinery is a trap for whoever next moves the login form.Semantically the credentials were correct: authentication is incomplete, not rejected, which is why OAuth providers answer
mfa_requiredwith 403. Pinned bytest_the_403_is_not_a_401so a later tidy-up can't silently re-arm either behaviour. Clients branch on the booleanmfa_required, never on parsingdetail.Root-cause correction (posted on the issue)
The issue's stated mechanism — a challenge-scoped token that
get_current_userrejects — is not what fires.mfa_gate.gate_loginnever setaccess_token;Tokendefaulted it toNoneand the route had noresponse_model_exclude_none, so the field was null andMFA_CHALLENGE_SCOPEwas never reached. A naive client never presentschallenge_tokenas a bearer.The real chain:
resp.json()["access_token"]→None→Authorization: Bearer None→ 401. Verified empirically against the real router, and againstv0.8.5(the reporting instance's version), which is byte-identical in both files. The issue's stated minimum fix — "remove/null theaccess_tokenfield" — was already shipped; what remained was the contract, which is what this PR delivers.Changes
models.py/routers/auth.py— the deferred case returns aJSONResponse403 so the challenge fields sit besidedetail(the shape the issue specifies), with the 403 declared in the OpenAPI.Token.token_typebecomesOptionaland the success path serializes withresponse_model_exclude_none=True, which fixes the second half of the bug: every successful login, OSS-only builds included, used to carry all four 2FA fields asnull, contradictingToken's own docstring.stores/auth.js— the challenge now arrives on the error path; read offerror.response.data.cli/—TrinityAPIErrorcarries the parsedbody, and_exit_on_login_errormaps a 403 +mfa_requiredto an actionable message across all four login handlers._require_access_tokenstays as a belt for any future 2xx-without-a-session.mcp-server/src/client.ts— parses the body before the status check; otherwise the one failure with a specific, actionable cause reports a bare "Forbidden".TokenResponsefields are optional so TypeScript enforces the check at the next call site.['access_token']read.One deliberate asymmetry
/api/auth/email/verifykeeps its 200, omittingaccess_tokenas it always has. The issue scopes the RFC change to "/token(the OAuth2-shaped surface)", and that route is a bespoke JSON endpoint, not a grant. The invariant both satisfy is no response ever presents a session that was not issued — via the mechanism each contract calls for. Pinned on both sides so the asymmetry is deliberate rather than drift.Worth noting for triage
The policy arm is the worse trigger and isn't what the issue leads with.
gate_decisionreturnsrequired=Truefor every admin/creator-role account the moment the role policy is enabled — so flipping the policy defers every unattended admin/creator credential instantly, before anyone has enrolled. One toggle, no user action, and the rollout hasn't started.Test Plan
28 tests across three surfaces, each guard mutation-verified — removed, watched it go red, restored:
tests/unit/test_2322_mfa_challenge_response.pyexclude_none→ 6 fail ·token_typenon-Optional → 4 fail ·response_modelon the email route → 2 failtests/test_cli_admin_login.py(extended)src/mcp-server/src/auth-challenge.test.tsmfa_gateseam, so they run with no enterprise submodule present. Both trigger arms covered (enrolled; policy-required-but-not-enrolled), plus wrong password stays 401 and carries no challenge.tsc --noEmitclean.76615f26: zero regressions. Base 23F/12042P, head 21F/12057P;commempty on the HEAD side. The pre-existing failures are IPv6-mapped-address and capacity-meter tests on this machine; two of them didn't reproduce this run (flaky, not fixed here).lint_root_test_placement+lint_sys_modulesclean;enterprise-docs-guardPCRE run locally — clean.Test placement note: the CLI tests went into the existing
test_cli_admin_login.pyrather than a new file. A new root-level test is rejected bylint_root_test_placement.py(#1895 — root tests are collected by no per-PR job), buttests/unit/is also wrong:requirements-test.txtdeliberately excludestrinity_cli, and the #660 contract is that a barepytest unit/runs green after installing only that file.test_cli_admin_login.pyis already grandfathered in the baseline. Honest consequence: like every existing CLI test, these run in the nightly integration job, not the per-PR gate — pre-existing boundary, tracked by #1896.Reviews run
/review— 0 critical, 3 informational, all fixed in05e84bfc: a doc example that echoed the response body (which carries the short-livedchallenge_token), two more docs teaching the blind read, and the email route being cited as the reference behaviour while pinned by nothing./cso --diff— 0 findings. Report atdocs/security-reports/cso-diff-2026-08-21-2322-mfa-challenge-shape.{md,json}, with an addendum recording R1 as closed by this PR./validate-pr— APPROVE. One warning, fixed: this description had gone stale against the 403 change./sync-feature-flows— run late, and it earned its place. It found nine more copies of the blindaccess_tokenread that/review's sweep missed, because that sweep was scoped tosrc docs/user-docs scriptswhile the defect sat one directory over indocs/memory/anddocs/testing/. The worst of them:feature-flows/mcp-orchestration.mdtranscribed the old MCP client verbatim —this.token = data.access_token;, the exact line this PR replaces. Also updatedrole-model.md's test plan,AGENT_NETWORK_DEMO.md,user-docs/quick-start.md,user-docs/guides/deploying/monitoring.md, threedocs/testing/plans, andAGENTS.md, plus the feature-flows index changelog row.Three copies are deliberately left:
.github/workflows/{build-without-submodule,container-security}.ymlandtests/test_ip_rate_limit_fix.pyauthenticate against throwaway instances we control where 2FA cannot be enabled. Docs teach patterns humans copy; those don't — and editing CI workflows on an auth PR widens the blast radius for nothing.Still deferred to @vybe
Whether a role policy should sweep machine credentials into a human-interactive second factor at all. That's the root of the policy-arm trigger and a new capability rather than a fix — Trinity has no service-account principal, and any exemption is a second-factor bypass by construction. The supported answer today is that automation uses an MCP API key (
trinity_mcp_*), which isn't subject to the flow; the docs in this PR now say so.Fixes #2322
🤖 Generated with Claude Code