Skip to content

fix: issues batch 2 — #122/#144/#145/#146 - #157

Merged
wangrh0909 merged 7 commits into
masterfrom
fix/issues-batch-2
Sep 3, 2026
Merged

wangrh0909 merged 7 commits into
masterfrom
fix/issues-batch-2

Conversation

@voidvec

@voidvec voidvec commented Sep 2, 2026

Copy link
Copy Markdown
Owner

Summary

Implements the four remaining non-decision issues. Design doc was subagent-reviewed (APPROVE-WITH-CHANGES; all 4 mandatory findings incorporated: legacy-path amr mirror, shared mint/consume mutex, LoginPage inline form instead of the auth-guarded /security, prompt=none → login_required on the new authorize gates).

#122 — TotpUtils migration (refactor)

All fulla::common::utils::TotpUtils callers (MfaController legacy fallbacks, 6 test files) migrated to fulla::identity::totp; drogon copy deleted. CMake unchanged (glob + existing PUBLIC link).

#144 — consent flow hardening (security)

  • Bounded multi-slot nonce list (ConsentCsrfSlots, cap 5, TTL 600s, per-entry one-shot): two concurrent authorize flows on one session both complete consent. Zero contract change (no new URL params / frontend coupling).
  • MFA-pending gate: mfa_pending session marker set in the RequireMfa branch; authorize treats it as not-logged-in (prompt=none → error=login_required per OIDC Core §3.1.2.1), consent answers 401 AUTH_MFA_REQUIRED (4008).
  • amr pre-elevation fix (found during impl, present on master): session amr="pwd mfa"/auth_time were written BEFORE TOTP verification — a failed verify left the session MFA-elevated and a following silent re-auth minted an MFA-claimed code. Elevation now happens only after verification (wired path onTotpVerified prologue + legacy-path mirror — the legacy path never called the continuation).

#145 — forced first-login password change (security)

users.must_change_password (V029 + orm-gen). Set on the bootstrap admin (random AND env password) and opt-in on admin create/update. While flagged: login answers password_change_required, authorize redirects to the login page's inline change form (prompt=none → login_required), consent answers 403 AUTH_PASSWORD_CHANGE_REQUIRED (4009), MFA completion refuses to mint codes. Change path: new session-authenticated POST /oauth2/password/change (requires old_password, enforces min length, revokes all tokens, clears the flag) — a flagged account cannot obtain a Bearer token by design, so the PUT path would deadlock. PUT /api/me/password also clears the flag. Inline forms on both portals' LoginPage (password_change_required branch).

#146 — device verification_uri + audit total

  • verification_uri default = {admin_console.url}/admin/devices (new config key; the old default /oauth2/device had no page). Explicit device_authorization.verification_uri override kept. verification_uri_complete added (RFC 8628 §3.3.1) + DeviceApprovePage prefill from ?user_code=.
  • Audit total = real filtered count (count-then-page, per-Mapper try/catch).

Companion root-cause fix

Drogon Session::insert never overwrites an existing key (std::map semantics) — the single-slot nonce, amr elevation and markers all silently no-oped on rewrite. All re-writable session values now erase-first; stale markers cleared on fresh login.

Sync & gates

  • Error codes 4008/4009 across all sync points (catalog 32→34 + size literal, regression count, property-test override list, api-reference + website mirror).
  • openapi.yaml (new endpoint, login 200 variant, device schema, admin user create/update, /api/me) + regenerated openapi.json / Python / Go SDKs; Property4 fingerprint + route-manifest golden updated.
  • Gates: spec-governance OK (routes=87 docs=85 yaml=83); api-diff baseline ratified --force (additive + the mechanical TotpUtils header removal / generated dirtyFlag_ count the issue itself mandates); oasdiff clean with ONE errata entry (login anyOf variant — same shape as the mfa_required precedent).
  • Docs: configuration-guide §4a/§4b, deployment manual-admin SQL now sets the flag, ADR device-flow note updated.

Verification

Merge-order note (conflict surface)

feat/frontend-i18n (#109 WIP, uncommitted in the main checkout) rewrites both LoginPages and DeviceApprovePage. This PR's frontend diffs there are minimal and structural (branch + inline form + query prefill) — expect small textual conflicts; i18n strings for the new form should land in that branch's catalogs.

Fixes #122
Fixes #144
Fixes #145
Fixes #146

@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 added a commit that referenced this pull request Sep 2, 2026
…ong old_password, dual-key revoke, mfa_pending ordering, gate assertions

Adversarial PR review (FIX-FIRST) — both mandatory findings fixed:

- MAJOR 1: changePasswordForced success now demotes the session to
  anonymous (erases userId/sub/auth_time/amr/mfa_pending/mfa_code_challenge*
  alongside the marker) — the promised re-login is enforced, closing the
  single-factor authorization window for flagged MFA-enabled accounts (the
  must-change branch returns before RequireMfa, so no mfa_pending marker
  was ever set for them).
- MAJOR 2: wrong old_password now increments the account lockout counters
  (same thresholds as PostgresIdentityRepository::incrementFailedLogins) and
  the prod Hodor sub_limit covers ^/oauth2/password/change like /oauth2/login.
- MINOR 3: token revocation is dual-key (public sub OR internal id), matching
  the documented UserReadCache/social-flow contract.
- MINOR 4: regression assertions for #146 — audit total equals a direct SQL
  count under filters (TotalIsFilteredCount case), device response asserts
  /admin/devices default + verification_uri_complete user_code=; plus a
  MAJOR-1 regression case (post-change authorize with the old cookie must
  redirect to /login, no code).
- MINOR 5: the RequireMfa branch writes mfa_pending/mfa_code_challenge
  session state BEFORE the pending-binding DB update, so a DB failure can no
  longer leave a first-factor session that passes the gates.
@voidvec

voidvec commented Sep 2, 2026

Copy link
Copy Markdown
Owner Author

Adversarial subagent review verdict was FIX-FIRST — both mandatory findings and all three recommended minors are fixed in 1dfe661:

  • MAJOR 1 (single-factor window): changePasswordForced now demotes the session to anonymous on success (all login-state keys erased); regression case added (post-change authorize with the old cookie → /login, no code).
  • MAJOR 2 (brute-force surface): wrong old_password increments the lockout counters (same thresholds as incrementFailedLogins) + prod Hodor sub_limit for ^/oauth2/password/change.
  • MINOR 3: dual-key token revocation (sub OR internal id).
  • MINOR 4: audit total asserted against direct SQL count under filters; device response asserts /admin/devices default + verification_uri_complete.
  • MINOR 5: mfa_pending session marker written before the RequireMfa DB update.

Re-verified: full_test 8/8 (1-4 PASS, 5-8 SKIPPED per #119 junit proof), all new/adjacent integration cases green individually.

@voidvec voidvec left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probe

@voidvec voidvec left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

说明:GitHub 不允许对本人发起的 PR 提交 REQUEST_CHANGES,故以 COMMENT 事件提交,但结论不变:下面 5 条 MAJOR 建议在合入前解决(其中 MAJOR 1、2 是阻断级别)。

整体方向认可:ConsentCsrfSlots 多槽位设计、mfa_pending / must_change_password 双闸、以及 Session::insert 不覆盖这个根因定位都是对的。ConsentCsrfSlots 把锁覆盖整个 read-modify-write 的论证、writeSlots 里 erase-then-insert 的注释、elevateSessionAfterMfa 同时接进 wired/legacy 两条路径,都写得很扎实;Audit total 的 count-then-page 严格按 db-operations 规则做了每个 Mapper 独立 try-catch,是范本级的。

但根因修复只覆盖了同一个代码块里的一部分可重写 session 键,剩下几个比原 bug 更危险。以下 5 条 MAJOR 我都在 069c5b02 上逐条复核过,不是推测。


[MAJOR] 2 · changePasswordForced 只累加锁计数,不执行锁定

libs/drogon/src/controllers/SessionController.cc:1449 起。上一轮 review 的 MAJOR 2 补了「写」没补「读」:全函数没有任何 getValueOfLockedUntil() 读取点(grep 确认 SessionController.cc 里 LockedUntil 只出现在 1572-1585 的写入分支),所以锁定中的账号在这个端点上仍可无限次尝试 —— 锁形同虚设。

同处另两个缺口:

  • 成功改密后未轮换 session id(标准 session fixation 面;MAJOR 1 的修复手动 erase 了登录态键,但会话标识本身没换)。
  • new_password 只校验下限没有上限,超长输入会按 KDF 成本线性放大 CPU 消耗。

[MAJOR] 5 · TOTP 随机数结果未检查(#122 迁移把它推上生产路径)

libs/identity/src/mfa/TotpUtils.cc:118 generateSecret:crypto.secureRandomBytes(secretBytes, 20) 的返回值被丢弃。而 ICryptoProvider::secureRandomBytes 是 virtual bool,失败时 buffer 原样不动 → 20 字节未初始化栈内存被 base32 编码成 TOTP secret(generateBackupCodes 同)。被删掉的 drogon 副本至少有 RAND_bytes 兜底。

这个文件不在本 PR 的 diff 里,是 #122 的迁移让它在 MFA 注册路径上变成了承重墙,所以算本 PR 引入的回归。一行修复:判返回值,失败直接返回空 / 抛异常。


[MINOR]

  1. changePasswordForced 无 CSRF 防护:它接受 application/x-www-form-urlencoded 兜底(getParameter),而端点只靠浏览器会话鉴权、没有 nonce。prod/ci 靠 session_same_site: Lax 挡住,但 config.dev.json 是 Null。跨站表单 POST 可以刷锁定计数(DoS);旧口令已知时可直接改密。建议限定 JSON-only(顺带消掉上面的表单兜底)+ 绑定会话的 nonce。

  2. ConsentMultiFlowHttpTest.cc 测试污染:三个用例翻转共享 admin 行的 mfa_enabled 后用裸语句还原;MfaWrongCode_SessionNotElevated(388 行附近起)的还原语句排在 REQUIRE(!cookie.empty()) 之后,REQUIRE 失败即中止用例、跳过还原,把 MFA-enabled 的 admin 泄漏给后续整个套件。另两个用例(293、341 行附近)还原得早,三者不一致。建议统一用 scope guard。

  3. #144 的 amr 提升修复没有直接断言:Integration_P1_MfaWrongCode_SessionNotElevated 只验证 authorize 被拒,而这件事 mfa_pending 闸已经保证了 —— 即使 amr 仍在 TOTP 验证前写入,测试照样通过。建议补一条直接读 session amr 的断言(或经 id_token 的 amr / acr 声明间接断言)。

  4. 前端新表面零测试覆盖:两个门户的 ?must_change_password=1 内联表单、DeviceApprovePage 的 ?user_code= 预填,都没有新增 e2e/unit。PR 报了 180/111 e2e,但 frontends/ 下没有任何测试文件改动。

  5. V029 未加 NOT NULL:列可空意味着将来任何 must_change_password = false 形式的谓词都会漏掉 NULL 行。改成 NOT NULL DEFAULT FALSE 需要连带重跑 /orm-gen 和 tools/migration-check/baseline.json,先确认你们接受这个连锁再动。

[NIT]

  1. mfaTotpCrypto() / totpCrypto() / testCrypto() 三处重复实现了同一个「进程级 OpenSSL provider」helper —— 注释里已经点名了 CryptoUtils.h detail::cryptoProvider() 这个现成范式,直接复用即可。

  2. ConsentCsrfSlots::mint / consume 共用一把进程级 mutex,跨所有会话串行。当前量级没问题,建议注释里写明吞吐上限,避免后来人默认它可以无限扩展。


顺带说明:我把 PR head 拉到了本地只读分支 pr157 逐文件核对(未改动任何工作区文件),评审结束后可自行 git branch -D pr157。

@@ -662,6 +703,17 @@ void SessionController::login(
.count();
req->session()->insert("auth_time", static_cast<int64_t>(nowSecs));
req->session()->insert("amr", std::string("pwd"));

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MAJOR] 这四个登录态键仍然裸 insert,没有 erase-first。

PR 在紧邻的 711 / 716 行给 mfa_pending、must_change_password 补了 erase,但 userId(686) / sub(691) / auth_time(704) / amr(705) 漏了。按本 PR 自己确认的 Session::insert std::map 语义,第二次登录时这四个写入全是 no-op:

  • amr 保留上次的 "pwd mfa" → 静默 authorize 会为一个只做了口令认证的会话签出带 MFA 声明的 code,同时 acr=2。这正是 Problem (PR #141 review #10/#18 follow-ups) #144 要堵的漏洞,只是换了触发路径:本 PR 注释里自己举的场景(MFA 被管理员关掉后重新登录)在这里恰好绕过 —— 因为 mfa_pending 被 erase 了,但 amr 留着。
  • userId / sub 保留上一个账号 → 同一浏览器会话换账号登录(未显式 logout 时 session 不重建),签出的 code 归属旧 subject。

触发条件:前端登出走 /oauth2/logout(session()->clear())时不受影响;但只要用户在同一会话内直接再登录一次(登录页对已持有 session 的请求没有拦截)就会命中。

建议:在 if (success) 开头把 userId / sub / auth_time / amr / mfa_code_challenge* / mfa_pending 统一 erase 一遍,并顺带做 session id 轮换。

同一问题也存在于 libs/drogon/src/controllers/WebAuthnController.cc:533。

// password login.
if (req->session())
{
req->session()->insert("mfa_code_challenge", codeChallenge);

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MAJOR] mfa_code_challenge / mfa_code_challenge_method 同样裸 insert,且 MFA 完成后从不清理。

全仓检索:这两个键只有本处写入(824-825),唯一的 erase 在 changePasswordForced(1659-1660)——MfaController::verifyLogin 用完并不清理。所以同一会话内第二次 MFA 登录会沿用第一个 flow 的 PKCE challenge:签出的 code 绑到错误的 challenge 上,客户端用正确 verifier 兑换时 PKCE 校验失败(可用性),且 code 与本次 authorization request 的绑定关系是错的(正确性)。

建议:insert 前 erase;并在 MfaController::verifyLogin 读取 sessCodeChallenge(MfaController.cc:794-798)之后 erase 掉,与 mfa_pending 一起清。

// Same thresholds as PostgresIdentityRepository::
// incrementFailedLogins.
{
const int newFailedCount = user.getValueOfFailedLoginCount() + 1;

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MAJOR] 锁计数只写不读 —— 锁定中的账号在这个端点上仍可无限次尝试。

上一轮 review 的 MAJOR 2 修得对(错误旧口令计入锁定),但少了配套的读取侧:本函数里 LockedUntil 只出现在 1572-1585 的写入分支,没有任何 if (user.getValueOfLockedUntil() > nowSecs) return 401 的判断。结果是计数器和 locked_until 被写满了,请求却照常放行 —— 锁在这个端点上形同虚设。

建议在读库之后、校验 old_password 之前加一句与 PostgresIdentityRepository 登录路径一致的锁定判定(含哨兵值语义)。

同处另两个小缺口:成功改密后没有轮换 session id(session fixation);new_password 只校验下限没有上限,超长输入会按 KDF 成本线性放大 CPU 消耗。

if (!frontendUrl.empty() && frontendUrl.back() == '/')
frontendUrl.pop_back();
auto resp = ::drogon::HttpResponse::newRedirectionResponse(
frontendUrl + "/login?must_change_password=1"

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MAJOR] 重定向目标恒为 user 门户,与发起方 portal 无关。

这里和 SessionController::login(SessionController.cc:739 分支)都硬编码 custom_config.frontend.url(dev :5173 / prod app.example.com),而 admin 控制台是 :5174 / admin.example.com,且 frontends/admin/src/pages/LoginPage.vue 完全没有 must_change_password 的处理(grep 确认 frontends/ 下只有 user 门户有)——只有 user 门户的 LoginPage.vue 加了 route.query.must_change_password === '1' 分支。

影响的是 #145 的头号目标人群:bootstrap admin 在 admin 控制台用带标记的会话访问 /oauth2/authorize,会被弹到 user 门户的登录页。(走 admin 控制台的登录流程本身是通的 —— 那里靠 password_change_required JSON 分支,不走这条 302。)

建议按来源 portal 选 origin:用 client_id → portal 映射,或当请求来自 admin-console 时取 admin_console.url(本 PR 刚加的配置键);同时给 admin 的 LoginPage 补上同一个查询分支作为兜底。

auto slots = parseSlots(session);
for (auto it = slots.begin(); it != slots.end(); ++it)
{
if (it->nonce == nonce && (nowSeconds - it->ts) <= kTtlSeconds)

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MINOR] nonce 比较用 ==,非常数时间。

nonce 是攻击者可控输入,虽然它绑定会话且有 TTL,实际利用价值有限,但既然本文件已经把 fail-closed 当作设计原则,比较也建议保持同一标准:CRYPTO_memcmp 或手写累积 XOR。

另外未命中分支不清理过期槽(只有 mint 会剪枝),槽位会带着过期条目堆到 cap 上限。当前 cap=5 无所谓,但和上面的 fail-closed 原则放在一起看略显不一致。

REQUIRE(wrong != nullptr);
CHECK(wrong->getStatusCode() == k401Unauthorized);

REQUIRE(execSql("UPDATE users SET mfa_enabled = false, mfa_secret = NULL WHERE username = 'admin'"));

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MINOR] 还原语句排在 REQUIRE 之后,异常中止会污染整个套件。

本用例先 UPDATE users SET mfa_enabled = true(388 行附近),直到这里(407 行)才还原;中间的 REQUIRE(resp != nullptr) / REQUIRE(!cookie.empty()) 一旦失败即中止用例,还原语句被跳过 → admin 以 MFA-enabled 状态泄漏给后续所有用例,故障会级联放大且难定位。

同文件另两个用例(293、341 行附近)把还原放在取 cookie 之后、后续 REQUIRE 之前,是对的,三者不一致。建议统一:要么把还原紧跟在拿到 cookie 之后,要么用一个 RAII scope guard 在析构里还原。

voidvec added a commit that referenced this pull request Sep 3, 2026
…ockout read side, portal-aware redirect, RNG fail-closed, JSON-only change endpoint

All 5 MAJOR + 5 MINOR + 2 NIT findings from the review verified in code and
addressed:

- MAJOR 1: userId/sub/auth_time/amr (login + WebAuthn) now erase-first on
  every write; mfa_code_challenge* erased too; session id rotated on every
  fresh authentication (changeSessionIdToClient). Kills stale-account
  subject leakage and the stale amr='pwd mfa' re-login path.
- MAJOR 2: mfa_code_challenge(_method) erased in MfaController::verifyLogin
  after being threaded onto the issued code, so a second MFA login in one
  session binds its own PKCE challenge.
- MAJOR 3: changePasswordForced refuses locked accounts (read side of the
  lockout counters, login-path semantics) and caps new_password at 128
  chars (KDF cost amplification); success rotates the session id.
- MAJOR 4: must-change redirect follows the originating portal (new
  PortalUrl.h: admin_console.client_ids default [admin-console] ->
  admin_console.url/admin/login, else frontend.url/login); admin LoginPage
  gains the ?must_change_password=1 branch.
- MAJOR 5: identity totp generateSecret/generateBackupCodes check
  secureRandomBytes's bool (no more uninitialized-stack secrets/codes);
  MfaService guards empty secret / short backup-code vector.
- MINOR 6: /oauth2/password/change is JSON-only (cross-site form vector
  closed; openapi + SDKs regenerated).
- MINOR 7: RAII AdminMfaRestore/UnlockGuard in the tests — REQUIRE aborts
  can no longer leak mfa_enabled/locked state to the suite.
- MINOR 8: direct amr regression assertion — wrong TOTP -> MFA disabled ->
  password re-login -> id_token amr must be exactly 'pwd' (fails on the
  pre-fix elevation code).
- MINOR 9: e2e for the new surfaces — admin login forced-change flow (JSON
  contract + mismatch guard), ?must_change_password=1 both portals, device
  approval ?user_code prefill.
- MINOR 10: V029 column is NOT NULL DEFAULT FALSE (models + migration
  baseline regenerated).
- NIT 11: all totpCrypto()/mfaTotpCrypto()/testCrypto() duplicates collapse
  onto CryptoUtils.h detail::cryptoProvider().
- NIT 12: ConsentCsrfSlots mutex comment states the throughput ceiling.

Verified: full_test 8/8; admin tsc+build+184 e2e (6 skip); user build+113
e2e (2 skip)+31 unit; spec-governance routes=87 docs=85 yaml=83; oasdiff
clean; migration-check 29 entries.
@voidvec

voidvec commented Sep 3, 2026

Copy link
Copy Markdown
Owner Author

评审 12 条全部逐条核实(均属实)并在 5edf5e8 修复。逐条处置:

MAJOR(5/5 已修)

M1 裸 insert 四键 — login 的 if(success) 开头现在对 userId/sub/auth_time/amr/mfa_pending/must_change_password/mfa_code_challenge* 统一 erase 后再 insert,并调用 changeSessionIdToClient()(Drogon 公开 API:标记 needToChange,响应时 SessionManager 换 id 并保留旧槽 10s 给在途请求)。WebAuthnController:533 同修(含 mfa_pending/must_change_password 清理 + 轮换)。

M2 mfa_code_challenge — 写侧 erase-first;elevateSessionAfterMfa()(wired/legacy 两路共用)在签发 code 后 erase 两个键,第二次 MFA 登录必绑本次 challenge。

M3 锁只写不读 — 载入用户行后、验证旧密前加 getValueOfLockedUntil() > now 判定 → 401(登录路径同语义);new_password 上限 128(KDF 放大);成功回调追加 session id 轮换。新用例 LockedAccount_RefusedWith401(正确旧密 + 活锁 → 401、flag 不变)。

M4 重定向恒 user 门户 — 新 libs/drogon/include/fulla/drogon/utils/PortalUrl.h:client_id ∈ admin_console.client_ids(默认 ["admin-console"],可配置覆盖)→ admin_console.url/admin/login?must_change_password=1,否则 frontend.url/login?...;authorize 与 login form 分支共用。admin LoginPage 补 ?must_change_password=1 分支。既有 Authorize_BlockedAndPromptNone 用例扩充断言两 portal 的确切 Location。

M5 RNG 未检查 — totp::generateSecret/generateBackupCodes 判 secureRandomBytes 返回值(失败返回空/短向量);MfaService::setupSecret(空 secret)与 verifyAndEnable(短 backup 向量)加守卫。identity 库改动属本 PR 迁移的承重面回归,同意按本 PR 处理。

MINOR(5/5 已修)

M6 CSRF/表单兜底 — 端点改 JSON-only(跨站 form 无法产生 application/json + old_password 知识因子);openapi.yaml 去掉 form content、响应描述补 locked/上限语义,Python/Go SDK 再生。

M7 测试污染 — AdminMfaRestore/UnlockGuard RAII(析构还原),REQUIRE 中止不再泄漏 mfa_enabled/locked 状态;三用例统一。

M8 amr 无直接断言 — 新 Integration_P0_MfaWrongCodeThenRelogin_IdTokenAmrStaysPwd:MFA 开→错 TOTP→MFA 关→已知 verifier 的 PKCE 重登→兑换→解码 id_token,断言 amr 恰为 pwd(pre-fix 会是 pwd mfa,直接钉死该 bug)。

M9 前端零覆盖 — 新 spec ×2:admin(改密流含 JSON 契约断言 + mismatch 不发请求 + query 分支 + 设备 ?user_code 预填)、user(改密流 + query 分支)。

M10 V029 可空 — 改 BOOLEAN NOT NULL DEFAULT FALSE(未合入前就地改),orm-gen 再生(ToNull 访问器消失)+ migration 基线更新。

NIT(2/2)

N11 — 六处 helper 全部收敛到 CryptoUtils.h 的 detail::cryptoProvider()。
N12 — ConsentCsrfSlots mutex 注释写明全进程串行的吞吐上限与分片方向。

其它

  • MAJOR 1 顺带提出的「session id 轮换」:已按最强形态实现——每次新鲜认证(login/WebAuthn/改密成功)都轮换,而非仅改密后。
  • 你本地拉的只读分支 pr157 可更新到 5edf5e8 复核后删除。

验证

full_test 8/8(1-4 PASS 含 584×2 ctest;5-8 按 #119 跳过);admin tsc+build+184 e2e(+4 新);user build+113 e2e(+2 新)+31 unit;spec-governance routes=87 docs=85 yaml=83;oasdiff 零未豁免 breaking;migration-check 29 entries 全过;MSVC/GCC 未用函数差异已消(新增代码全部有调用点)。

wangrh0909
wangrh0909 previously approved these changes Sep 3, 2026
- #122: migrate all fulla::common::utils::TotpUtils callers (MfaController
  legacy fallbacks + 6 test files) to the identity-domain
  fulla::identity::totp free functions and delete the drogon copy.
- #144: consent CSRF nonce moves from a single session slot to a bounded
  multi-slot list (ConsentCsrfSlots, shared process mutex on mint+consume) so
  concurrent authorize flows no longer overwrite each other; MFA-pending
  sessions are marked (mfa_pending) and refused by the authorize/consent
  gates (401 AUTH_MFA_REQUIRED / error=login_required under prompt=none);
  amr=pwd-mfa session elevation now happens only AFTER TOTP verification
  (wired onTotpVerified prologue + legacy-path mirror).
- #145: users.must_change_password (V029) forces a password change at first
  login for the bootstrap admin and admin-created users (opt-in field on
  create/update); login answers password_change_required, authorize/consent/
  MFA-verify refuse to issue codes, and the new session-authenticated
  POST /oauth2/password/change (old_password verified, policy-checked, token
  revocation cascade, flag cleared) is the designated change path. Inline
  change-password forms on both login pages.
- #146: device verification_uri defaults to the real admin-console approval
  page (new admin_console.url config; explicit device_authorization.
  verification_uri override kept) + verification_uri_complete per RFC 8628
  3.3.1 with DeviceApprovePage prefill; audit log total is now the true
  filtered count (count-then-page).

Companion fixes found during implementation: Drogon Session::insert never
overwrites an existing key, so every re-writable session value (consent slot
list, auth_time/amr elevation, must_change_password marker) now erases
first; stale mfa_pending/must_change_password markers are cleared on fresh
login.

Sync: error codes AUTH_MFA_REQUIRED(4008)/AUTH_PASSWORD_CHANGE_REQUIRED
(4009) across catalog+regression/property tests+api-reference docs+website
mirror; openapi.yaml (+POST /oauth2/password/change, login 200 variant,
device schema, admin user create/update, /api/me) + regenerated
openapi.json/Python/Go SDKs; Property4 fingerprint + route-manifest golden
baselines; configuration-guide/deployment/ADR docs; api-diff baseline
ratified (additive + mechanical TotpUtils removal); one oasdiff errata
(login anyOf variant, same shape as the mfa_required precedent).

Fixes #122, fixes #144, fixes #145, fixes #146
…ong old_password, dual-key revoke, mfa_pending ordering, gate assertions

Adversarial PR review (FIX-FIRST) — both mandatory findings fixed:

- MAJOR 1: changePasswordForced success now demotes the session to
  anonymous (erases userId/sub/auth_time/amr/mfa_pending/mfa_code_challenge*
  alongside the marker) — the promised re-login is enforced, closing the
  single-factor authorization window for flagged MFA-enabled accounts (the
  must-change branch returns before RequireMfa, so no mfa_pending marker
  was ever set for them).
- MAJOR 2: wrong old_password now increments the account lockout counters
  (same thresholds as PostgresIdentityRepository::incrementFailedLogins) and
  the prod Hodor sub_limit covers ^/oauth2/password/change like /oauth2/login.
- MINOR 3: token revocation is dual-key (public sub OR internal id), matching
  the documented UserReadCache/social-flow contract.
- MINOR 4: regression assertions for #146 — audit total equals a direct SQL
  count under filters (TotalIsFilteredCount case), device response asserts
  /admin/devices default + verification_uri_complete user_code=; plus a
  MAJOR-1 regression case (post-change authorize with the old cookie must
  redirect to /login, no code).
- MINOR 5: the RequireMfa branch writes mfa_pending/mfa_code_challenge
  session state BEFORE the pending-binding DB update, so a DB failure can no
  longer leave a first-factor session that passes the gates.
CI static-checks M5 flagged the new migration as unratified; reviewed and
approved via migration_check.py --update-baseline (29 entries, V001..V029).
…on on GCC/Clang

linux/macos matrix builds failed on the anonymous-namespace helper that no
call site survived the runtime-minted-credentials revision (MSVC does not
diagnose unused static functions, so the local Windows build stayed green).
…ockout read side, portal-aware redirect, RNG fail-closed, JSON-only change endpoint

All 5 MAJOR + 5 MINOR + 2 NIT findings from the review verified in code and
addressed:

- MAJOR 1: userId/sub/auth_time/amr (login + WebAuthn) now erase-first on
  every write; mfa_code_challenge* erased too; session id rotated on every
  fresh authentication (changeSessionIdToClient). Kills stale-account
  subject leakage and the stale amr='pwd mfa' re-login path.
- MAJOR 2: mfa_code_challenge(_method) erased in MfaController::verifyLogin
  after being threaded onto the issued code, so a second MFA login in one
  session binds its own PKCE challenge.
- MAJOR 3: changePasswordForced refuses locked accounts (read side of the
  lockout counters, login-path semantics) and caps new_password at 128
  chars (KDF cost amplification); success rotates the session id.
- MAJOR 4: must-change redirect follows the originating portal (new
  PortalUrl.h: admin_console.client_ids default [admin-console] ->
  admin_console.url/admin/login, else frontend.url/login); admin LoginPage
  gains the ?must_change_password=1 branch.
- MAJOR 5: identity totp generateSecret/generateBackupCodes check
  secureRandomBytes's bool (no more uninitialized-stack secrets/codes);
  MfaService guards empty secret / short backup-code vector.
- MINOR 6: /oauth2/password/change is JSON-only (cross-site form vector
  closed; openapi + SDKs regenerated).
- MINOR 7: RAII AdminMfaRestore/UnlockGuard in the tests — REQUIRE aborts
  can no longer leak mfa_enabled/locked state to the suite.
- MINOR 8: direct amr regression assertion — wrong TOTP -> MFA disabled ->
  password re-login -> id_token amr must be exactly 'pwd' (fails on the
  pre-fix elevation code).
- MINOR 9: e2e for the new surfaces — admin login forced-change flow (JSON
  contract + mismatch guard), ?must_change_password=1 both portals, device
  approval ?user_code prefill.
- MINOR 10: V029 column is NOT NULL DEFAULT FALSE (models + migration
  baseline regenerated).
- NIT 11: all totpCrypto()/mfaTotpCrypto()/testCrypto() duplicates collapse
  onto CryptoUtils.h detail::cryptoProvider().
- NIT 12: ConsentCsrfSlots mutex comment states the throughput ceiling.

Verified: full_test 8/8; admin tsc+build+184 e2e (6 skip); user build+113
e2e (2 skip)+31 unit; spec-governance routes=87 docs=85 yaml=83; oasdiff
clean; migration-check 29 entries.
… regen

setMustChangePasswordToNull() disappears because V029 made the column NOT
NULL — the accessor (and the column) ship for the first time in this same
PR, so no released surface loses anything; same mechanical-generated-code
class as the earlier dirtyFlag_ count ratification.
…talogs

Rebase integration follow-up: PR #156 (vue-i18n) landed while this branch
was in review. The admin-side resolution folded into the rebased commits;
this commit moves the USER-portal form onto the same convention
(auth.login.passwordChange.* keys, en + zh-CN) instead of the raw English
strings, matching the admin side (login.passwordChange.*).
@voidvec

voidvec commented Sep 3, 2026

Copy link
Copy Markdown
Owner Author

已 rebase 到 #156 合入后的 master(分支头 f95c0f9,force-push 重写)。

冲突解决方式:以 #156 的 vue-i18n 结构为基底重植本 PR 的改动,并把新增的强制改密表单文案迁入 i18n catalog(不再硬编码英文)——admin 侧 login.passwordChange.*、user 侧 auth.login.passwordChange.*,en/zh-CN 双份、键位对齐(i18nKeys parity 测试过)。

完整性审计(防 rebase 静默丢失):

  • patch-id:6 个提交中 4 个与原链逐字节一致,2 个差异均为携带冲突解决的提交(预期内);
  • 后端目录(libs/apps/tests/tools/clients)与 rebase 前字节级一致,零回归面;
  • 净 diff 差异全部位于 frontends/ 且均为 i18n 融合内容;package-lock 版本 bump 被 master 吸收(feat(frontend): add en/zh-CN i18n via vue-i18n curated catalogs (ADR-0013) #156 已带 1.1.0)。

验证:admin tsc+build+190 e2e、user build+119 e2e+34 unit(含 i18n parity)全绿;CI 14/14 pass。合并后仍走 Rebase and merge。

@wangrh0909
wangrh0909 merged commit 6435f78 into master Sep 3, 2026
16 checks passed
wangrh0909 pushed a commit that referenced this pull request Sep 3, 2026
…ong old_password, dual-key revoke, mfa_pending ordering, gate assertions

Adversarial PR review (FIX-FIRST) — both mandatory findings fixed:

- MAJOR 1: changePasswordForced success now demotes the session to
  anonymous (erases userId/sub/auth_time/amr/mfa_pending/mfa_code_challenge*
  alongside the marker) — the promised re-login is enforced, closing the
  single-factor authorization window for flagged MFA-enabled accounts (the
  must-change branch returns before RequireMfa, so no mfa_pending marker
  was ever set for them).
- MAJOR 2: wrong old_password now increments the account lockout counters
  (same thresholds as PostgresIdentityRepository::incrementFailedLogins) and
  the prod Hodor sub_limit covers ^/oauth2/password/change like /oauth2/login.
- MINOR 3: token revocation is dual-key (public sub OR internal id), matching
  the documented UserReadCache/social-flow contract.
- MINOR 4: regression assertions for #146 — audit total equals a direct SQL
  count under filters (TotalIsFilteredCount case), device response asserts
  /admin/devices default + verification_uri_complete user_code=; plus a
  MAJOR-1 regression case (post-change authorize with the old cookie must
  redirect to /login, no code).
- MINOR 5: the RequireMfa branch writes mfa_pending/mfa_code_challenge
  session state BEFORE the pending-binding DB update, so a DB failure can no
  longer leave a first-factor session that passes the gates.
wangrh0909 pushed a commit that referenced this pull request Sep 3, 2026
…ockout read side, portal-aware redirect, RNG fail-closed, JSON-only change endpoint

All 5 MAJOR + 5 MINOR + 2 NIT findings from the review verified in code and
addressed:

- MAJOR 1: userId/sub/auth_time/amr (login + WebAuthn) now erase-first on
  every write; mfa_code_challenge* erased too; session id rotated on every
  fresh authentication (changeSessionIdToClient). Kills stale-account
  subject leakage and the stale amr='pwd mfa' re-login path.
- MAJOR 2: mfa_code_challenge(_method) erased in MfaController::verifyLogin
  after being threaded onto the issued code, so a second MFA login in one
  session binds its own PKCE challenge.
- MAJOR 3: changePasswordForced refuses locked accounts (read side of the
  lockout counters, login-path semantics) and caps new_password at 128
  chars (KDF cost amplification); success rotates the session id.
- MAJOR 4: must-change redirect follows the originating portal (new
  PortalUrl.h: admin_console.client_ids default [admin-console] ->
  admin_console.url/admin/login, else frontend.url/login); admin LoginPage
  gains the ?must_change_password=1 branch.
- MAJOR 5: identity totp generateSecret/generateBackupCodes check
  secureRandomBytes's bool (no more uninitialized-stack secrets/codes);
  MfaService guards empty secret / short backup-code vector.
- MINOR 6: /oauth2/password/change is JSON-only (cross-site form vector
  closed; openapi + SDKs regenerated).
- MINOR 7: RAII AdminMfaRestore/UnlockGuard in the tests — REQUIRE aborts
  can no longer leak mfa_enabled/locked state to the suite.
- MINOR 8: direct amr regression assertion — wrong TOTP -> MFA disabled ->
  password re-login -> id_token amr must be exactly 'pwd' (fails on the
  pre-fix elevation code).
- MINOR 9: e2e for the new surfaces — admin login forced-change flow (JSON
  contract + mismatch guard), ?must_change_password=1 both portals, device
  approval ?user_code prefill.
- MINOR 10: V029 column is NOT NULL DEFAULT FALSE (models + migration
  baseline regenerated).
- NIT 11: all totpCrypto()/mfaTotpCrypto()/testCrypto() duplicates collapse
  onto CryptoUtils.h detail::cryptoProvider().
- NIT 12: ConsentCsrfSlots mutex comment states the throughput ceiling.

Verified: full_test 8/8; admin tsc+build+184 e2e (6 skip); user build+113
e2e (2 skip)+31 unit; spec-governance routes=87 docs=85 yaml=83; oasdiff
clean; migration-check 29 entries.
@voidvec
voidvec deleted the fix/issues-batch-2 branch September 4, 2026 05:26
wangrh0909 pushed a commit that referenced this pull request Sep 7, 2026
…ation, coverage ratchet gate, signing-key rotation keystore

All three ratified by an adversarial re-review on current master (post
#156/#157); recommendations A/B/B confirmed unchanged, with #110-C noted as
degenerate (key rotation is the last remaining IAM-M1 item, and the repo
ships no helm/compose signing-key carrier, so the multi-secret concern was
moot).

#88-3 (decision A): end_session accepts client_id as the RP identification
when id_token_hint is absent (RP-Initiated Logout 1.0 §2.1); the
post_logout_redirect_uri must still be registered for that client (same
validateRedirectUri gate the aud candidates use — no open redirect; session
termination semantics unchanged, and a parameterless end_session already
logged out with no proof). With neither hint nor client_id the 400 envelope
stands. 3 new integration cases + 2 regressions.

#105 (decision B): local coverage ratchet. measure_coverage.py gains --json
and --ratchet BASELINE (fail when a non-exempt library drops >0.5pp below
baseline; <200-instrumented-line libs exempt; baseline lib missing from the
run fails = lost instrumentation; new libs pass until next re-baseline;
absent baseline = seed mode printing the JSON). coverage.yml gates the
existing job (seconds of added compute). Baseline JSON is committed in a
follow-up commit seeded from the first CI run.

#110 (decision B): signing-key rotation keystore. JwkManager loads a
multi-key store (signing_keystore_dir: <kid>.pem files + active_kid
marker), signs with the active kid, verifies by routing on the JWT header
kid across all loaded keys (absent kid tries all — RFC 7515 §4.1.4), and
publishes EVERY key in JWKS. A configured-but-broken keystore is a hard
startup failure (no silent fallback to another key source); the keystore
takes precedence over the single-key env/path sources. Rotation is a
documented 3-restart procedure (publish → switch → retire; see
configuration-guide §9, rewritten from the F-029 to-do). GET
/api/admin/oidc/keys now reports the live keystore (keys[] with
active/published status) instead of the hardcoded stub; ConfigManager's
production key check accepts signing_keystore_dir; endpoint scripts assert
the new shape. 7 new keystore unit tests (44/44 in JwkManagerTest).

Sync: openapi (end_session client_id param + description, jwks multi-key
note, admin keys response) + regenerated openapi.json/Python/Go SDKs;
api-diff baseline ratified --force (private-member/static-signature changes
with no released consumer); all 8 static gates green; full_test 8/8.

Fixes #88
Fixes #105
Fixes #110
voidvec added a commit that referenced this pull request Sep 9, 2026
- M1: the registerUser retry no longer routes through a std::function
  that captures its own shared_ptr (an unreachable reference cycle that
  leaked the HTTP response callback on an unauthenticated endpoint). The
  attempt is now a plain free function with an explicit retry counter —
  plain recursion, no self-referential capture in either AuthService.
- M2: generateUsername (identity) checks secureRandomBytes' return value
  and throws on failure — the buffer is left untouched on failure, so an
  unchecked read drew from uninitialized stack (same contract TotpUtils
  documents for its PR #157 review finding). Legacy side was already
  fail-closed via its UUID fallback; the parity comment is corrected.
- M4: markApproved reports (dbOk, found); UnexpectedRows on the find leg
  is a protocol-level miss (row reclaimed between lookup and update),
  reported as VALIDATION_DEVICE_CODE_INVALID instead of DB_CONNECTION_ERROR
  — symmetric with findByUserCode.
- M5: the readiness Redis guard now cancels its timer on the first real
  answer (TimerId + invalidateTimer via runInLoop; no-op if already
  fired) and the not-configured branch answers through the same CAS, so
  the single-answer invariant is structural. Dev configs enable Drogon's
  native 2s redis command timeout (timeout: -1 disabled it — the A-1
  root cause); the in-controller guard remains as the backstop for
  operator configs.
- M7: the identity registration/login paths now canonicalize emails,
  matching the legacy path (registration stored mixed case verbatim and
  lookup was exact-match, so mixed-case registrants could only log in
  with their exact-case email). V031 lowercases existing rows; the
  registration integration test re-asserts canonical storage.
- M8: the device-approve happy-path test deletes its seeded
  oauth2_device_codes row.
voidvec added a commit that referenced this pull request Sep 10, 2026
- M1: the registerUser retry no longer routes through a std::function
  that captures its own shared_ptr (an unreachable reference cycle that
  leaked the HTTP response callback on an unauthenticated endpoint). The
  attempt is now a plain free function with an explicit retry counter —
  plain recursion, no self-referential capture in either AuthService.
- M2: generateUsername (identity) checks secureRandomBytes' return value
  and throws on failure — the buffer is left untouched on failure, so an
  unchecked read drew from uninitialized stack (same contract TotpUtils
  documents for its PR #157 review finding). Legacy side was already
  fail-closed via its UUID fallback; the parity comment is corrected.
- M4: markApproved reports (dbOk, found); UnexpectedRows on the find leg
  is a protocol-level miss (row reclaimed between lookup and update),
  reported as VALIDATION_DEVICE_CODE_INVALID instead of DB_CONNECTION_ERROR
  — symmetric with findByUserCode.
- M5: the readiness Redis guard now cancels its timer on the first real
  answer (TimerId + invalidateTimer via runInLoop; no-op if already
  fired) and the not-configured branch answers through the same CAS, so
  the single-answer invariant is structural. Dev configs enable Drogon's
  native 2s redis command timeout (timeout: -1 disabled it — the A-1
  root cause); the in-controller guard remains as the backstop for
  operator configs.
- M7: the identity registration/login paths now canonicalize emails,
  matching the legacy path (registration stored mixed case verbatim and
  lookup was exact-match, so mixed-case registrants could only log in
  with their exact-case email). V031 lowercases existing rows; the
  registration integration test re-asserts canonical storage.
- M8: the device-approve happy-path test deletes its seeded
  oauth2_device_codes row.
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

2 participants