Repository navigation
fix(auth): issue tokens from MFA login verification (U-MFA-002) - #9
Conversation
MfaController::verifyLogin only stored mfa_verified in a server-side session and never returned access_token/refresh_token. The stateless SPA client never sends cookies, so after entering a correct TOTP code the frontend had no way to authenticate and login got stuck (U-MFA-002). verifyLogin now accepts client_id/redirect_uri (already sent by authService.ts) and, after TOTP succeeds, generates an authorization code via OAuth2Plugin::generateAuthorizationCode and immediately exchanges it for tokens via exchangeCodeForToken, returning access_token/refresh_token in the same response. No PKCE on this leg since the first-factor /oauth2/login step does not use PKCE today. Also appends a review addendum to PRD/mfa_auth_code_pkce_design.md documenting the session-state/CSRF gaps in the proposed Authorization Code + PKCE + hosted-login-page architecture, and splits that broader migration out as a separate follow-up (not implemented here). Verified: OAuth2Test_test.exe 228/228 cases (55933 assertions), backend E2E scripts test-oauth2-endpoints.ps1 (55/55) and test-admin-endpoints.ps1 (0 failed), frontend Playwright e2e (19/19) and vitest (15/15), plus a manual real-backend run of the full register->login->mfa-setup-> mfa-verify->access-protected-resource flow.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
代码审查结论整体方向正确——TOTP 验证通过后服务端直接生成 auth code 并兑换 token,符合 §7 最小修复方案的设计,且前端 🔴 P0-1:
|
评审意见自我复核(修正 P0-1 表述)对刚才的评审做了一次代码复核,发现 P0-1 表述有误,需更正;P0-2 和 P1 经核对准确。修正如下: P0-1 修正:不是"任意 client_id",而是"任意已注册的 PUBLIC client_id"原评审说"用合法 mfa_token + 任意 client_id 即可拿到 token"——这是过度表述。实际链路是:
真正的风险是:用合法 修复不变:在 额外澄清:scope 越权不成立(我复核时排除了一项误报)复核时曾担心请求体里 P0-2 / P1 复核结论:准确
修正后的合入建议:P0-1(client_id 一致性校验,严重度从"任意 client"下调为"跨已注册 PUBLIC client 授权混淆")和 P0-2(redirect_uri 白名单)仍建议修,但 P0-1 的紧急度因"需已注册 client + 需用户自己有效的 mfa_token"两个前提而低于最初表述。 |
- OAuth2Admin/package-lock.json, OAuth2Frontend/package-lock.json: npm audit fix output (security/dependency updates). - OAuth2Admin/src/main.ts: remove top-level await on restoreSession(). The router beforeEach guard already awaits the deduped ensureSessionRestored() before protected routes, so the one-shot session restore completes before first render regardless. Top-level await broke the Vite es2020 build target (esbuild transpile error). Mirrors the OAuth2Frontend fire-and-forget pattern.
Regenerate the Drogon ORM model for the users table so it matches the V022 migration's mfa_pending_client_id / mfa_pending_redirect_uri columns. The Users.cc model was previously absent from the project (only a stale backup existed); it is now generated with getter/setter coverage for both new nullable columns, consistent with the orm-gen project convention of regenerating ORM models after any schema change.
PR #9's MfaController::verifyLogin issued OAuth2 tokens after a correct TOTP check but never verified the second-factor request's client_id / redirect_uri against the first-factor login that produced the mfa_token. Because mfa_token is just std::to_string(internalId) with no client binding, an attacker holding a valid mfa_token + correct TOTP code could substitute any other registered client's client_id / redirect_uri and receive a token minted for that other client (P0-1), and redirect_uri was never checked against the whitelist on this leg (P0-2). Fix (per .kiro/specs/mfa-cross-client-auth-fix): - V022 migration: add mfa_pending_client_id / mfa_pending_redirect_uri nullable columns on users (substrate for the login-session binding). - SessionController::login: when returning mfa_required, persist the request's client_id / redirect_uri as the pending binding BEFORE the response is sent; fail closed (DB_QUERY_ERROR) if the UPDATE fails so verifyLogin never runs against a stale/missing binding. - MfaController::verifyLogin: after the TOTP check (ordering preserved), run validateClient -> validateRedirectUri -> pending-binding equality; all three reject with AUTH_INVALID_CREDENTIALS (401) so an unregistered client, a non-whitelisted redirect_uri, a mismatched binding, and a wrong TOTP code are indistinguishable from the outside (no client-registration oracle). On a fully successful verification, clear the pending binding back to NULL (best-effort; tokens are already issued and cannot be un-issued). Tests (15 new DROGON_TEST cases, all green; full suite 243 cases / 56035 assertions pass with zero regressions): - Property1 exploratory: unregistered client / non-whitelisted redirect_uri / cross-client confusion / null-binding edge case (confirmed the bug on unfixed code: cases 2 & 3 issued real tokens). - Property5/6: DB-state coverage of pending-binding persist (login), overwrite, clear-on-success, and keep-on-reject. - Property7: preservation baseline (matching-binding issuance, wrong TOTP, unknown mfa_token, missing fields, non-MFA login). - Integration: happy-path end-to-end + cross-client rejection confirms no oauth2_access_tokens row is created for rejected attempts. Out of scope (unchanged): mfa_token format/lifetime/randomness, scope validation in verifyLogin, PKCE on the MFA leg, and consumeAuthCode's existing redirect_uri equality logic for the general authorization_code grant flow.
|
两条 P0 已在最新推送中修复(commit P0-1(跨已注册 client 授权混淆)— 已修复 ✅你第 3 条评论里的自我修正是对的:真正的风险是跨已注册 PUBLIC client,不是"任意 client_id"。我在写探索测试时实测验证了这条链路,和你的复核完全一致:
修复方案(commit
修复后 Case 3 由 200 签发变为 401 P0-2(redirect_uri 白名单)— 已修复 ✅修复在同一 commit: 关于 no-oracle:三层新增校验( P1(
|
…) + comment #4/#8/#9 P1 #6 (RFC 6749 §5.1): expires_in / id_token exp / device refresh TTL were hardcoded 3600/2592000; now use configured access_token_ttl/refresh_token_ttl (OAuth2Plugin getAccessTokenTtl()/getRefreshTokenTtl() accessors). 6 sites: TokenService auth_code expires_in + id_token exp + refresh expires_in; client_credentials + device_code issuance in TokenEndpointController. P1 #5 (RFC 8628 §3.4): device_code redemption now authenticates by client_type -- CONFIDENTIAL clients require a valid client_secret (validateClient); PUBLIC clients keep the client_id-vs-device-row binding. Lookup wrapped in a local lambda captured BY VALUE (not [&]) because it runs from getClient's async callback after token() has returned -- [&] would dangle deviceCodeHash/dbClient. P1 #3 (RFC 6749 §4.1.2 single-use): device-code redemption check-then-delete was non-atomic (two concurrent redemptions both issued). Replaced with a pre-issue atomic UPDATE...WHERE status='approved' RETURNING; affected-row gate makes exactly one concurrent winner issue, loser gets invalid_grant (fail- closed). UPDATE...RETURNING is a db-operations.md raw-SQL exemption. Comment-only (#4 [this] capture, #8 validateAccessToken no-self, #9 JWKS empty response): document existing-correct behavior, deter repeat review reports. Tests (live-server integration, PG+Redis): TokenExpiryTtlConfigTest, DeviceCodeClientAuthTest (conf no-secret rejects / conf secret ok / pub ok), DeviceCodeRaceConditionTest (concurrent redemption -> exactly one wins). All pass + no regressions (RFC6749 compliance 4504 assertions, auth_code E2E, refresh rotation, authorize PKCE passthrough). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…loor, bootstrap self-heal, review cleanups Address PR #141 review (1 must-fix, 8 should-fix, quick considers): - #1 consent_csrf declared as a required query parameter in openapi.yaml and the C++ endpoint doc registration; apps/server/docs/api/openapi.json regenerated from a live server run; Python/Go clients regenerated. - #2 nonce one-shot is now atomic: the find/verify/erase sequence is serialized by a process-wide mutex (consent traffic is tiny; in-process session storage). - #3 identity AuthService no longer captures this in the async validateUser callback — the legacy-hash policy flag is value-captured (db-operations rule 4). - #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin user row is reused and role/mapping completed (partial failures self-heal on restart); the random password is printed only after the insert succeeded; a mapping failure no longer reports created=true. - #5 POST /api/admin/users enforces auth.min_password_length (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass. - #6 consent integration tests reworked: missing-nonce now drives the real authorize-minted slot (400), deny-to-unregistered-uri (400, no Location) and deny-to-registered-uri (302 access_denied) branches are covered. - #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT removed (PBKDF2 keeps salt empty); website i18n error table mirrored (3014/4007). - #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on failure instead of a single silent 2s probe. - #13 unique-violation detection layered (SqlError 23505 -> constraint name -> english/zh localized text), mirroring the PostgresSocialAccountRepository pattern. - #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged; #17 AGENTS.md consent.csp entry removed. Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14 admin UI hardcode (server now enforces; hint stays), #18 MFA-pending session through consent (pre-existing authorize behavior, tracked).
…loor, bootstrap self-heal, review cleanups Address PR #141 review (1 must-fix, 8 should-fix, quick considers): - #1 consent_csrf declared as a required query parameter in openapi.yaml and the C++ endpoint doc registration; apps/server/docs/api/openapi.json regenerated from a live server run; Python/Go clients regenerated. - #2 nonce one-shot is now atomic: the find/verify/erase sequence is serialized by a process-wide mutex (consent traffic is tiny; in-process session storage). - #3 identity AuthService no longer captures this in the async validateUser callback — the legacy-hash policy flag is value-captured (db-operations rule 4). - #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin user row is reused and role/mapping completed (partial failures self-heal on restart); the random password is printed only after the insert succeeded; a mapping failure no longer reports created=true. - #5 POST /api/admin/users enforces auth.min_password_length (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass. - #6 consent integration tests reworked: missing-nonce now drives the real authorize-minted slot (400), deny-to-unregistered-uri (400, no Location) and deny-to-registered-uri (302 access_denied) branches are covered. - #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT removed (PBKDF2 keeps salt empty); website i18n error table mirrored (3014/4007). - #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on failure instead of a single silent 2s probe. - #13 unique-violation detection layered (SqlError 23505 -> constraint name -> english/zh localized text), mirroring the PostgresSocialAccountRepository pattern. - #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged; #17 AGENTS.md consent.csp entry removed. Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14 admin UI hardcode (server now enforces; hint stays), #18 MFA-pending session through consent (pre-existing authorize behavior, tracked).
背景
E2E 测试用例
U-MFA-002(MFA 验证成功后登录阻断)失败:MfaController::verifyLogin在 TOTP 校验通过后只把mfa_verified写入服务端 Session,响应体里没有access_token/refresh_token。前端 SPA 是无状态的(不发 Cookie),拿不到 token,导致二次验证通过后登录卡死。后续对该改动的安全评审又发现两个 P0 缺陷(跨客户端授权混淆),在本 PR 一并修复。
改动
1. 基础修复:
MfaController::verifyLogin发 token(U-MFA-002)client_id/redirect_uri(前端authService.ts已经在传,未改前端)OAuth2Plugin::generateAuthorizationCode生成授权码,再exchangeCodeForToken立即兑换,把access_token/refresh_token/id_token直接放进响应体/oauth2/login本身不走 PKCE,因此这一步兑换也不做 PKCE 校验,代码注释里说明了原因2. 安全加固:修复 P0-1 / P0-2(跨客户端授权混淆)
问题:
verifyLogin发 token 时只校验client_id/redirect_uri非空,从不校验客户端是否注册、redirect_uri是否在该客户端白名单内,也不校验它们是否与首因子/oauth2/login产生该mfa_token时用的是同一对。由于mfa_token只是std::to_string(internalId)、无任何客户端绑定,攻击者拿到一个有效mfa_token+ 正确 TOTP 后,可改用另一个已注册客户端的client_id/redirect_uri领到绑定到那个客户端的 token(P0-1);redirect_uri在这条调用链上根本未过白名单(P0-2)。修复:
users表新增可空列mfa_pending_client_id/mfa_pending_redirect_uri,作为首因子登录会话绑定的载体。SessionController::login:返回mfa_required之前,先把本次请求的client_id/redirect_uri写入绑定列;UPDATE 失败则 fail-closed(DB_QUERY_ERROR,不发mfa_token),避免verifyLogin拿到陈旧/缺失的绑定。MfaController::verifyLogin:TOTP 校验通过后(顺序保持不变),依次执行validateClient→validateRedirectUri→ 待定绑定相等性比对;三层校验任一失败都以AUTH_INVALID_CREDENTIALS(401)拒绝,使未注册客户端、非白名单redirect_uri、不匹配的绑定、错误 TOTP 码在外部不可区分(无客户端注册探针)。完全成功的验证后,best-effort 把绑定清回NULL(token 已签发无法撤回,故仅尽力清理)。orm-gen惯例,Users.h/Users.cc重生成以匹配新列(原项目中Users.cc缺失,现已补齐)。明确不在本次范围:
mfa_token的格式/有效期/随机性、verifyLogin的 scope 校验、MFA 第二步的 PKCE、以及consumeAuthCode在通用 authorization_code 流程上的现有redirect_uri相等性逻辑。3.
PRD/mfa_auth_code_pkce_design.md追加评审补充章节,指出原方案(Authorization Code + PKCE + 后端托管登录页)里缺失的会话状态传递清单、CSRF/open-redirect 风险点、与现有 GitHub 登录/consent 流程的兼容性问题、受影响测试清单,并将该架构迁移拆分为独立的后续提案(本 PR 不实施)。
验证
OAuth2Test_test.exe:243/243 用例,56035 断言全过(含本次新增 15 个 MFA 跨客户端修复测试,零回归)scripts/backend/test-oauth2-endpoints.ps1:55/55(含 MFA 相关 Test 21-24)scripts/backend/test-admin-endpoints.ps1:0 failedauth.spec.ts):19/19mfa_required→提交 TOTP→拿到access_token→用该 token 访问/api/me成功安全修复专项测试(新增 15 个
DROGON_TEST)采用 bug-condition 方法论(先在未修复代码上探索反例 → 固化基线 → 实现修复 → 复核):
redirect_uri/ 跨客户端混淆 / 空绑定边界。已在未修复代码上坐实 P0-1/P0-2(Case 2/3 确实签发了真实 token)。mfa_token、缺字段、非 MFA 登录——修复前后行为一致。oauth2_access_tokens行)。