Skip to content

fix(frontends): close gap-analysis P0 breaks + P1 quick wins (admin MFA login, WebAuthn contract, logout, device approval) - #140

Merged
voidvec merged 5 commits into
masterfrom
feat/frontend-gap-p0-fixes
Aug 29, 2026
Merged

voidvec merged 5 commits into
masterfrom
feat/frontend-gap-p0-fixes

Conversation

@voidvec

@voidvec voidvec commented Aug 29, 2026

Copy link
Copy Markdown
Owner

背景

frontend-backend-gap-analysis(2026-08-26 快照,docs-local)在 #108 大改版后逐项复核(基线 382cb71):P0 六项全部仍在。本 PR 修复 P0 全部 + P1 快赢;Phase 2 项(组织管理页、Passkey 登录、Google/WeChat 绑定、spec 治理四项)另行处理。

修复清单

admin 控制台

  • E2 管理员 MFA 登录死循环:mfa_required 分支接通 POST /oauth2/mfa/verify(mfa_token+code+client_id+redirect_uri+一次性 code_verifier),login()/verifyMfa() 共用 applySession(),登录页增加 6 位码视图 + 错误横幅重试
  • E1 CallbackPage 死代码:调用不存在的 auth.handleCallback,且 json 登录流不经过该页——删除页面与路由(redirect_uri 参数保留)
  • E3 仪表盘失真:/health/ready 三态渲染(ok/degraded/unhealthy → 绿/琥珀/红)、组件圆点按实际值着色、删除 'Connected' 兜底;stats 补 logs_today 卡片
  • 设备审批页:新增 /devices(表单 user_code+user_id),承接从用户门户迁出的审批流
  • 日志:actor_id 筛选(后端已有参数)+ Target 列(target_type/target_id)
  • 用户:创建表单补 email_verified/mfa_enabled;roles_failed/warning、删除时 tokens_revoked=false 透传为错误提示
  • 令牌:批量吊销显示后端 count(原为静默成功)

用户门户

  • E1 WebAuthn 注册 100% 失败:begin 读嵌套 {options} + base64url 解码 challenge/user.id(原 atob 遇 -_ 必炸);finish 改发后端契约 {credential_id, public_key, name}(原发浏览器 attestation 信封必 400);凭据列表改渲染 credential_id/name/sign_count(原 cred.id/created_at 后端不存在);文案降级(登录入口待后端断言验证上线)
  • E3 登出协议失效:删 end_session(参数违反协议、400 先于会话清除、空 catch 吞错),改 POST /oauth2/logout(Bearer,吊销+清会话+backchannel 通知),与 admin store 对齐
  • E2 设备验证页:删除(路径 404 + 缺 user_id + 受众错配 → 迁 admin)
  • E7 consent 竞态:user_id 优先取服务端 URL 下发值;/consent 加 auth 守卫;双源皆空禁用提交(原必 500)
  • 恢复码丢弃(P0):10 个一次性恢复码启用后一次性展示(复制/下载/确认保存),原被静默丢弃且永不可再显
  • 401 刷新白名单:isOauthRoute 黑名单改显式端点白名单,userinfo 过期可自动刷新(原 UI 冻结为占位用户)
  • E5/E6 服务层契约:authorized-apps 解析、otpauth_uri 类型、refresh_token 可选、删虚构字段

config(后端行为修复,1 行规则 ×5 文件)

  • /oauth2/device/approve 补 rbac 规则——原规则缺失 + AuthorizationFilter 默认 DENY = 含 admin 在内全员 403(端点休眠;openapi 如实声明 admin 审批)

测试

  • mock 契约修复先行(E8:mfa/verify、authorized-apps、webauthn credentials/begin/finish、/oauth2/logout)
  • 新增用例:MFA 登录全流程(含错误重试)、设备审批、WebAuthn 注册(navigator.credentials 桩 + finish body 断言)、恢复码(含剪贴板)、MFA disable、consent 批准/拒绝(user_id 断言)、登出请求形态(Bearer + 无 end_session)、admin 删除/禁用用户与批量吊销首次点击执行、仪表盘诚实渲染

测试证据

  • 后端全量 full-test 8/8 PASS(rbac 变更无回归;OAuth2 端点 + admin 端点 55/55)
  • admin:build ✅ / vitest ✅ / eslint 0 errors / e2e 179 passed(6 skipped 为既有条件跳过)
  • user:tsc ✅ / build ✅ / vitest 24 ✅ / eslint 0 errors / e2e 109 passed
  • 方案经双子代理深度评审(后端契约逐条 file:line 核实 + 前端结构/测试策略核查),评审修订已回写方案文档

openapi / SDK / 版本影响

  • openapi.yaml 不改:全部为前端对齐既有实现。§2.3 四处规范-实现偏差(org 201、revoke-by-* 物理删除、/api/register 必填颠倒、device approve 受众描述)属 spec 描述修正,随独立 spec-governance PR 处理
  • SDK 不动:spec 未变,clients/python、clients/go 与漂移门不受影响
  • 版本号不变更:无 API 变更,不触发发版六处同步

评审新发现(本 PR 只登记,随 Phase 2 跟进)

  1. /oauth2/consent 无认证(高):路由无 filter、不校验 session 用户与 user_id 关系——知道 user_id 的匿名请求可代批/代拒;deny 分支不校验 redirect_uri(approve 校验,不对称)
  2. WebAuthn authenticateFinish 不验签(高):知道 credential_id 即可通过认证——Passkey 登录入口的前置条件
  3. verification_uri 默认指后端 origin 无页面(中);options.user.id 非 base64url 字节(低);logs 信封 total 为当前页行数(低)

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

@voidvec

voidvec commented Aug 29, 2026

Copy link
Copy Markdown
Owner Author

Code Review — RFC/正确性复核后的确认问题

经过对后端代码链路和 OAuth2/OIDC 相关 RFC 的严格复核,以下是确认的真实问题。


Critical: 用户门户 logout 竞态 — access token 同时被撤销和被用作 Bearer 认证

文件: frontends/user/src/services/authService.ts L138-172

logout() 将同一个 access token 通过 Promise.allSettled 并发发送到两个端点:

  • POST /oauth2/revoke — 使 token 失效
  • POST /oauth2/logout — 需要有效的 Bearer token(受 OAuth2AuthFilter 保护)

后端证据链:

  1. /oauth2/logout 受 OAuth2AuthFilter 保护 (SessionController.h:66)
  2. OAuth2AuthFilter 调用 plugin->validateAccessToken() 做 DB 查询验证 (OAuth2AuthFilter.cc:58)
  3. 单元测试 RevokeAccessToken_ThenValidateFails (TokenServiceTest.cc:488-512) 明确验证:revoke 后 validate 返回 nullptr
  4. /oauth2/logout handler 内部再调用 plugin->revokeAccessToken() 做二次撤销 (SessionController.cc:1250)

如果 /oauth2/revoke 先完成,/oauth2/logout 的 OAuth2AuthFilter 返回 401 invalid_token。后果:服务端 session 未清除,backchannel logout 通知不会发送给 RPs。

对比 admin store (admin/src/stores/auth.ts:263-291):access token 只发给 /oauth2/logout(该端点本身负责撤销 AT + 清除 session + fanout logout_token),refresh token 单独发给 /oauth2/revoke。无竞态。

修复建议:移除对 access token 的单独 /oauth2/revoke 调用——/oauth2/logout 本身已处理 access token 撤销:

const revokes: Promise<Response>[] = []
if (access) {
  // /oauth2/logout handles AT revocation + session cleanup + backchannel RP fanout
  revokes.push(fetch('/oauth2/logout', {
    method: 'POST',
    headers: { Authorization: `Bearer ${access}` },
    keepalive: true,
  }))
}
if (refresh) {
  revokes.push(fetch('/oauth2/revoke', {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: body(refresh),
    keepalive: true,
  }))
}
await Promise.allSettled(revokes)

Warning: e2e 测试 mock 使用旧的 { apps: [...] } 信封

文件: frontends/user/tests/e2e/account.spec.ts L298, L330

getAuthorizedApps() 已修复为读取 resp.data?.authorized_apps(userService.ts:39),但两个测试仍用旧信封覆写 mock:

  • L298: body: JSON.stringify({ apps: [] }) — "空列表" 测试
  • L330: body: JSON.stringify({ apps: [{ client_id: 'nameless-app', ... }] }) — "无名应用" 测试

authorized_apps 为 undefined → fallback 到 []。"空列表" 测试因 fallback 通过(错误原因),"无名应用" 测试渲染空列表而非预期的 nameless-app(可能不通过)。

修复:将两处 mock 改为 { authorized_apps: [...], total: N }。


Warning: setTokens 在 refresh 缺失时不清除 localStorage 中的旧 refresh_token

文件: frontends/user/src/services/http.ts L17-25

setTokens(access, refresh?) 仅在 refresh 为 truthy 时写入 localStorage。在 token rotation 场景中(后端只返回新 access_token),旧的已撤销 refresh_token 残留。下次页面加载 tryRestoreSession() 读取过期 token → refresh 失败 → 意外登出。

修复建议:

export function setTokens(access: string, refresh?: string) {
  accessToken = access
  refreshToken = refresh ?? null
  if (refresh) {
    localStorage.setItem('refresh_token', refresh)
  } else {
    localStorage.removeItem('refresh_token')
  }
}

Warning: TokensPage successMessage 在后续操作中永远不会被清除

文件: frontends/admin/src/pages/tokens/TokensPage.vue L91-134

successMessage 在 revokeByClient/revokeByUser 中设置,但在 revokeToken(单条撤销)和 fetchTokens 中从未清除。用户执行批量撤销后看到 "Revoked 5 token(s)",再执行其他操作时旧消息与新错误同时显示。

修复:在 fetchTokens() 和 revokeToken() 的 try 分支中添加 successMessage.value = ''。

voidvec added a commit that referenced this pull request Aug 29, 2026
…k envelopes, RT retention

Review triage (4 items, objective verdicts against RFCs and code):

1. Critical, real bug, fixed as suggested: user logout() sent the same
   access token concurrently to /oauth2/revoke and /oauth2/logout (Bearer).
   Whichever landed first invalidated the other's credentials — logout's
   OAuth2AuthFilter would 401, skipping the server-side session clear and
   the backchannel RP fanout. The access token now goes only to
   /oauth2/logout (which revokes it server-side, SessionController::logout),
   mirroring the admin store; refresh token stays on /oauth2/revoke. e2e
   now asserts revokes carry only the refresh token.

2. Warning, accepted with a factual correction: the two account.spec
   authorized-apps mocks used the fictional {apps:...} envelope. The tests
   did NOT fail (reviewer's 'may not pass' was wrong) because
   AuthorizedAppsPage has its own .apps first fallback and never calls the
   service layer — but they were exercising a dead branch instead of the
   real contract. Mocks now use {authorized_apps, total} and the page's
   dead .apps fallback is removed.

3. Warning, problem real but proposed fix rejected on RFC grounds:
   setTokens(access) with no refresh field did leave memory/storage
   divergent. The suggested localStorage.removeItem() violates RFC 6749 §6
   — when the server issues no new refresh token, the old one remains valid
   and must be KEPT; deleting it logs the user out. setTokens now leaves
   the refresh-token state untouched when the field is absent, and replaces
   it only when the server actually rotates it.

4. Warning, real, fixed with a corrected placement: stale successMessage
   was never cleared. Clearing inside fetchTokens (as suggested) wipes the
   message the bulk-revocation actions set right before calling it — each
   action now owns the banner lifecycle (clear up front, show outcome),
   fetchTokens no longer touches banners.

Also replaces the remaining token literals in auth.spec MFA mocks with the
generated-placeholder idiom (Mimosa L3 finding).
@voidvec

voidvec commented Aug 29, 2026

Copy link
Copy Markdown
Owner Author

评审意见逐条裁定(RFC/代码事实复核)

感谢评审——4 条全部核实。裁定:1 条真 bug(采纳修法)、2 条问题成立(修法/现象判断有修正)、1 条修法违反 RFC(采纳问题、否决修法)。修复已随 5f1b6ac1 推送,两前端 e2e 全绿(admin 180 / user 109)+ build/lint 全绿。

1. logout 竞态(Critical)✅ 真 bug,采纳修法

复核属实,且是本 PR 引入的回归:logout() 把同一 access token 并发发给 /oauth2/revoke 与 /oauth2/logout(Bearer)。证据链确认:OAuth2AuthFilter 走存储校验(OAuth2AuthFilter.cc:58),revoke 后 validate 失败(TokenServiceTest.cc:488-512),SessionController.h:66 挂 filter、SessionController.cc:1250 内部二次撤销。Promise.allSettled 无顺序保证,revoke 先落地 = logout 401 = session 不清 + backchannel 不发。从协议角度这也是使用错误:RFC 7009 撤销即时生效,客户端发起撤销后不得再依赖该 token 通过认证。已按建议修复:access token 只发 /oauth2/logout(服务端本身会撤销它),refresh token 保持走 /oauth2/revoke,与 admin store 模式一致。e2e 增加回归守卫:断言 revoke 请求体只含 refresh token、不含 access token。

2. authorized-apps 旧信封 mock(Warning)⚠️ 问题成立,现象判断修正后修复

一处事实修正:两处测试不会失败——AuthorizedAppsPage.vue:15 自己解析且 .apps 是第一 fallback,页面本就不调 userService.getAuthorizedApps()(该服务层方法是死代码修复),所以旧 mock 恰好喂给了页面的 fallback 分支,nameless-app 用例照常渲染。但评审指出的实质成立:测试在验证真后端永不返回的 mock 形状,真实契约路径(authorized_apps)零覆盖。已修:两处 mock 改 {authorized_apps, total},并删除页面里 .apps 死分支(真后端不返回该键),页面现在只解析真实信封。

3. setTokens 残留(Warning)⚠️ 问题成立,但建议修法违反 RFC 6749 §6,否决修法、另修

现象属实:setTokens(access)(refresh 字段缺失)会留下 内存 RT=null / localStorage=旧值 的不一致。但建议的 else { localStorage.removeItem('refresh_token') } 与 RFC 6749 §6 相反:只有服务端签发新 refresh token 时客户端才必须替换;响应未携带时旧 refresh token 仍然有效、应当保留——删除它会恰好制造评审所担心的“下次加载意外登出”。已按 RFC 正确语义修复:字段缺失时保持 RT 现状(内存与 storage 都不动),仅当服务端实际 rotation 时替换。备注:fulla 后端目前所有授权路径(authorization_code / rotation / MFA verify)都返回 refresh_token,该分支当前不可达,属类型层健壮性修复。

4. successMessage 残留(Warning)✅ 真,采纳问题、修正落点后修复

属实(本 PR 引入)。但按建议把清理放进 fetchTokens() 会自我冲突:批量吊销是“设 successMessage → 调 fetchTokens()”,fetchTokens 开头一清就把刚设的消息抹掉了(实测已复现)。已改为动作拥有横幅生命周期:三个 revoke 动作在发起请求前清两个横幅、结束时设结果;fetchTokens 不再触碰横幅。


本地验证:user 109/109、admin 180/180 e2e 全绿(含新增回归守卫),两前端 build + eslint 0 errors。等待 CI。

The endpoint is declared admin-gated in openapi.yaml (AuthorizationFilter),
but no rbac_rules entry existed for its path — and AuthorizationFilter
denies by default when no rule matches, so device approval returned 403
to every role including admin. The user-portal page calling it was also
wired to a nonexistent /oauth2/device/verify path; approval UI moves to
the admin console in the following commits (gap-analysis user E2).
…ser honesty fixes

Gap-analysis P0/P1 round for the admin console:

- MFA login loop (E2): an mfa_required response used to dead-end — the
  LoginPage ignored it and bounced back to /login forever, and the stashed
  PKCE verifier had no consumer. login()/verifyMfa() now share applySession();
  verifyMfa() consumes the one-shot verifier and calls POST /oauth2/mfa/verify
  (mfa_token+code+client_id+redirect_uri+code_verifier); LoginPage gains the
  6-digit code view with error-banner retry.
- CallbackPage (E1): removed — the json-mode login flow never redirects, and
  the page called a nonexistent auth.handleCallback (guaranteed TypeError).
  The registered redirect_uri string stays (login/token still send it).
- Device approval (E2): new /devices page + nav entry posting form-urlencoded
  user_code+user_id to /oauth2/device/approve (admin-audience now reachable
  thanks to the config rbac rule); replaces the broken user-portal page.
- Dashboard (E3): /health/ready rendered honestly — degraded status shows
  amber, component dots follow actual values, no hardcoded 'Connected'
  fallback; stats gain the previously dropped logs_today card.
- Logs: actor_id filter input (backend-supported, never exposed) and a
  Target column (target_type/target_id were fetched but never rendered).
- Users: create form gains email_verified/mfa_enabled; roles_failed/warning
  and delete-time tokens_revoked=false now surface as errors instead of a
  blanket success.
- Tokens: bulk revocation reports the backend count instead of silence;
  console.error residue cleaned.
- e2e: MFA flow end-to-end tests, device approval, logs/users/tokens
  click-throughs (first-ever delete/disable/revoke-by-client executions),
  dashboard honest-rendering cases; mocks for mfa/verify + device/approve.
…backup codes

Gap-analysis P0/P1 round for the user portal:

- WebAuthn registration (E1, was 100% broken): begin now reads the nested
  {options} envelope and base64url-decodes challenge/user.id (atob threw on
  the -_ alphabet); finish posts the backend contract {credential_id,
  public_key, name} instead of the raw browser attestation envelope.
  base64UrlDecode added next to the existing encoder in utils/pkce.ts.
  Credential list renders credential_id/name/sign_count (E4 — cred.id and
  created_at never existed server-side); copy no longer promises working
  passwordless sign-in while assertion verification is unimplemented.
- Logout protocol (E3): end_session carried client_id (not a parameter) and
  post_logout_redirect_uri without id_token_hint — a guaranteed 400 issued
  BEFORE session clear, so neither the server session nor backchannel RP
  notification ever happened, silently swallowed by an empty catch. Logout
  now keeps the two revokes and adds POST /oauth2/logout with the Bearer
  token (revokes + clears session + fans out logout_token), mirroring the
  admin store.
- Consent (E7): user_id prefers the server-provided query value over the
  racy store sub; /consent route gains the auth guard (fullPath redirect);
  with neither source present the actions disable instead of submitting a
  guaranteed-500 user_id=''.
- http.ts: the blanket '/oauth2/' no-refresh exclusion dropped userinfo from
  the auto-refresh path, freezing the UI as 'User' until an unrelated /api/*
  401 — replaced with an explicit credential-endpoint whitelist.
- MFA backup codes: the 10 one-time recovery codes were discarded, leaving
  no self-service recovery; they now show in a blocking one-time layer with
  copy/download before 'I have safely saved my codes'.
- Service/type contracts (E5/E6): getAuthorizedApps reads authorized_apps;
  setupMfa types otpauth_uri; TokenResponse.refresh_token optional (no more
  persisting 'undefined'); fictional User.mfa_enabled removed.
- DeviceVerifyPage deleted (nonexistent endpoint + admin-only audience);
  e2e mocks aligned to real contracts (otpauth_uri, authorized_apps,
  credential shapes, /oauth2/logout) and new specs cover the WebAuthn flow,
  backup codes, MFA disable, consent actions, and logout request shape.
Self-review catch during PR review: verifyMfa() cleared the stashed
code_verifier before the first attempt, so a wrong TOTP code burned it —
every retry then hit the token exchange with an empty verifier and failed
PKCE (TokenService rejects an empty code_verifier whenever a challenge is
bound to the code), turning the old login loop into a retry loop. The
verifier is now removed only after a successful verification, in both the
admin store and the user portal's authService. e2e regression test asserts
both attempts carry the same verifier.
…k envelopes, RT retention

Review triage (4 items, objective verdicts against RFCs and code):

1. Critical, real bug, fixed as suggested: user logout() sent the same
   access token concurrently to /oauth2/revoke and /oauth2/logout (Bearer).
   Whichever landed first invalidated the other's credentials — logout's
   OAuth2AuthFilter would 401, skipping the server-side session clear and
   the backchannel RP fanout. The access token now goes only to
   /oauth2/logout (which revokes it server-side, SessionController::logout),
   mirroring the admin store; refresh token stays on /oauth2/revoke. e2e
   now asserts revokes carry only the refresh token.

2. Warning, accepted with a factual correction: the two account.spec
   authorized-apps mocks used the fictional {apps:...} envelope. The tests
   did NOT fail (reviewer's 'may not pass' was wrong) because
   AuthorizedAppsPage has its own .apps first fallback and never calls the
   service layer — but they were exercising a dead branch instead of the
   real contract. Mocks now use {authorized_apps, total} and the page's
   dead .apps fallback is removed.

3. Warning, problem real but proposed fix rejected on RFC grounds:
   setTokens(access) with no refresh field did leave memory/storage
   divergent. The suggested localStorage.removeItem() violates RFC 6749 §6
   — when the server issues no new refresh token, the old one remains valid
   and must be KEPT; deleting it logs the user out. setTokens now leaves
   the refresh-token state untouched when the field is absent, and replaces
   it only when the server actually rotates it.

4. Warning, real, fixed with a corrected placement: stale successMessage
   was never cleared. Clearing inside fetchTokens (as suggested) wipes the
   message the bulk-revocation actions set right before calling it — each
   action now owns the banner lifecycle (clear up front, show outcome),
   fetchTokens no longer touches banners.

Also replaces the remaining token literals in auth.spec MFA mocks with the
generated-placeholder idiom (Mimosa L3 finding).
@wangrh0909
wangrh0909 force-pushed the feat/frontend-gap-p0-fixes branch from 5f1b6ac to cc10022 Compare August 29, 2026 14:06
@voidvec
voidvec merged commit 2eabbb8 into master Aug 29, 2026
7 checks passed
@voidvec
voidvec deleted the feat/frontend-gap-p0-fixes branch August 29, 2026 14:25
wangrh0909 pushed a commit that referenced this pull request Sep 10, 2026
… and hooks

Consolidates the recurring lessons from the 2026-08/09 engineering sessions
(previously only in AI-session memory) into versioned, tool-agnostic assets:

- skills: ci-gate-sync (sync-point policies for error codes/endpoints/
  migrations/headers), ci-failure-triage (cross-compiler WERROR blind spots,
  flake taxonomy), release-engineering (six-point + ~15 version carriers,
  tag recovery, PyPI first publish), pr-workflow (rebase-merge repair,
  rebase value-loss audit, PAT permission boundary), local-env-runbook
  (Windows/WSL/Docker/Mimosa/multi-session rules), test-methodology (two
  test layers, mock injection seam, Playwright pitfalls), and
  benchmark-methodology (wrk Lua model, A/B discipline, measurement-artifact
  taxonomy).
- rules (path-scoped): sync-points (8-point error-code and 5-point endpoint
  hard checklists), frontend-contract (verified frontend/backend contract
  facts), async-cpp-gotchas (traps beyond db-operations: Session::insert
  no-overwrite, callback double-move, ::drogon:: shadowing).
- commands: /preflight (local gate sweep before pushing), /ci-triage
  (failure classification workflow).
- hooks: local-gates.sh (wired to the git-commit PreToolUse hook, replacing
  the broken full-ctest gate), port-guard.sh, redis-watchdog.ps1.

Provenance (source retrospectives): ci-gate-sync/rules.sync-points from PR
#115/#141/#149/#157/#179/#180 CI post-mortems; release-engineering from the
v1.0.0-v1.1.0 release runs; test-methodology from the coverage push
(48.5%->57.2%) and PR #140/#156 e2e work; benchmark-methodology from the
four-product comparison campaign; local-env-runbook from environment
incident records. AGENTS.md indexes the new rules and skills.
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.

2 participants