Repository navigation
fix(security): v1.4.1 — #78 end_session 验签 / #79#80 缓存双删 / #54#69 社交修复(+ #75 覆盖) - #85
Conversation
…log, next-phase plan progress-status: Phase 0 verdicts refreshed to 2026-08-23 TTL=30 comparison (five-scenario lead, cold-start 1.26s); Phase 1 ~60% (PyPI 1.4.0 live, README badge done); Phase 2 ~50% (backchannel full-stack PR #61 + social link/unlink PR #68); perf-optimization workstream added; issue section rewritten to current 15 open issues in 4 categories; milestones extended through v1.4.0 (2026-08-24). iam-architecture-audit: Backchannel Logout upgraded from 'backend delivered' to full-stack (PR #61, #55/#57 hardening, leftover #82); social link/unlink row annotated with 5 follow-up issues (#69/#70/#71/#73/#54); footer baseline bumped to v1.4.0. SUMMARY.md: staleness banner — numbers superseded by optimization program + competitor comparison; points to COMPARISON.md as authority (S2 8.9k→14.4k, S6 16.7k→49.3k etc.); original kept as pre-optimization baseline record. next-phase-implementation-plan (4th revision): all seven original workstreams (A1/A2/A3-badge/B1/B2/C1/C3) marked delivered; new focus = Tier1 security batch (#78 end_session signature verify, #79/#80 cache refill race, #54 soft-delete social bypass) → Tier2 social fixes (#69 token hash mismatch 401, #71 state validation, #70 mappings, #73 guard race) → Tier3 blog (M1) + docs site (M2) → Tier4 hygiene (#81/#72/#82/#83/#84/#66 + stale branch cleanup); parallel-safety map, risks, and 4 decision items.
…ssion end_session decoded the id_token_hint payload WITHOUT signature verification and used its sub claim as the backchannel-logout fan-out subject whenever no browser session existed — anyone knowing a user's public sub (disclosed to every RP that user logged into) could force that user's logout at all RPs with validly signed logout_tokens. - JwkManager::verifyJwt (new, exported): the symmetric counterpart of signJwt — strict RS256-only alg policy (no none/HS256 confusion), kid match when present, EVP_DigestVerify over the received header.payload, then claim policy: iss == configured issuer, exp > now (strict), sub non-empty. Hand-rolled base64url decode keeps the Domain layer drogon-free (arch-guard R1). - SessionController::endSession: a supplied hint MUST verify before any claim influences the logout decision; failures (malformed/bad alg/kid/ signature/issuer/expired/missing sub) and session-subject mismatches return 400 AUTH_INVALID_ID_TOKEN_HINT (new ErrorCatalog 4006, explicit 400 override) BEFORE finish() — no session clear, no RP notification. No-hint behavior is byte-identical to before (regression tests confirm). - Absent hint + post_logout_redirect_uri still 400 (documented pre-existing plain-text error, unchanged). - openapi.yaml: end_session GET/POST descriptions + 400 response updated to the verified-hint semantics; api-baseline ratified for the additive JwkManager change. Tests: 11 JwkManagerTest verifyJwt matrix cases (roundtrip, tampered payload/signature, alg=none/HS256, foreign-key kid, wrong issuer, expired incl. exact boundary, missing sub, missing exp, structural garbage, not-initialized); HTTP: forged-hint 400, garbage-hint 400, real auth-code id_token + registered post_logout_redirect_uri -> 302+state, session/hint subject mismatch -> 400; ErrorCatalogRegressionTest count 25 -> 26. Fixes #78
…e observability #79 (High): the cache-aside refill race. A reader whose Postgres read starts before an admin write commits could land its cache-fill SET after the post-commit invalidation DEL, pinning a rotated client_secret / revoked roles / stale profile for the full cache TTL (300s/120s) even though the DEL succeeded. Fix: one shared primitive, authforge::storage::redis::invalidateWithDoubleDelete — immediate DEL (unchanged commit-ordered timing) plus a delayed second DEL on the framework loop (default 200ms, cache.invalidation_double_delete_delay_ms, clamped [50,2000]), which evicts any racing refill whose read began before the commit. Residual (reads slower than the delay) stays TTL-bounded per wave-2-plan; full versioning remains deferred to #42 Phase 3. Refills deliberately stay plain SET (no NX): NX adds nothing against this race and would pin stale-first orderings — rationale in the §5.4 addendum. #80 (Medium): DEL failures on the invalidation paths were LOG_DEBUG. Every FAILED DEL attempt now increments authforge_cache_invalidation_failures_total{kind} via the IMetrics port and logs WARN (first failure) / ERROR (after the built-in single immediate retry). Soft-fail unchanged: Redis-down still means pass-through to Postgres, never client errors. Wiring: ClientCacheInvalidator + UserCacheInvalidator hooks (dropMemo kept synchronous) and RedisCachedTokenRepository::revokeAccessToken (the 60s negative marker kept; both positive-key DELs now double-delete) all share the one helper. Known documented residuals (§5.4 addendum): the 2s UserReadCache in-process memo, revokeTokenFamily TTL-bounded convergence (G1). api-baseline ratified for the new exported header. Tests: exact-race choreography (fill -> invalidate -> stale refill lands after immediate DEL -> delayed phase evicts it, GET nil) against live Redis (SKIP without); deterministic fault-injected RedisClient (sync exception path; a real dead-port client only buffers while retrying) asserting 4 counted attempts per invalidation with kind labels; all 10 existing Redis cache decorator/UserReadCache tests green. Fixes #79 Fixes #80
…y lookup path GitHubController::issueTokensForUser persisted access/refresh tokens RAW while every read path resolves the presented token via hashToken (UPPER(SHA256 hex)) before the repository lookup. A GitHub social session therefore 401'd on EVERY Bearer-authenticated endpoint, the refresh grant returned invalid_grant, and the raw refreshToken.accessToken mirror could never match revokeTokenFamily's hashed-column SQL — the social flow was read-only login theater. Storage now mirrors TokenService's grant issuance and TokenEndpointController's controller-constructed pairs (CryptoUtils:: hashToken and TokenCrypto::hashToken are byte-identical). Response bodies still return the raw strings; only persistence changes. No legacy migration: the raw-stored tokens were unusable from the day they were issued (issue #69's rationale; decision (b) in the task brief). Tests (SocialLoginHttpTest): refresh grant with the social refresh token (200 + rotated pair; every storage mode via vue-client public auth); PG-backed chain — introspect active:true (backend-svc Basic), userinfo 200 with the social token, and the FULL /api/me/social/links lifecycle (link -> list -> unlink) driven by the social token through the PR #68 numeric-dispatch branch, closing the #75 coverage gap. Fixes #69 Fixes #54 Fixes #75
Seven-point version sync to 1.4.1 (cmake/Version.cmake, CMakeLists.txt, conanfile.py, openapi.yaml info.version, admin/user package.json, clients/python pyproject.toml). Patch bump: pure security/defect fixes, additive-only SDK surface, no API changes. Fixes tracked in this release: #78 #79 #80 #54 #69 #75 (see CHANGELOG).
MemoryClientRepository read the bare "type" key, but every apps/server/config/*.json writes "client_type" — so a configured PUBLIC client (vue-client, all five configs) silently defaulted to CONFIDENTIAL in memory mode and rejected public-style (empty-secret) token requests with invalid_client. Surfaced by #69's refresh-grant e2e running under config.ci.json (the memory CI leg): the refresh grant 401'd on client auth before the token flow even started. The loader now prefers the canonical "client_type" and keeps "type" as a fallback for pre-canonical configs. Memory-mode behavior now matches the configured intent (and the PG seed's PUBLIC vue-client).
…t matrix, race determinism First full_test run surfaced five gaps in the v1.4.1 fix commits (all behavior already correct; assertions/docs/tests aligned): - api-reference.md error table + ErrorCatalogPropertyTest override registry: AUTH_INVALID_ID_TOKEN_HINT (4006, AUTHENTICATION, explicit 400) now registered in both consistency oracles (the doc test pins one documented row per catalog entry; the property test's httpStatus oracle exempts explicit overrides by code). - JwkManagerTest.VerifyJwt_SignedByOtherKey: both ephemeral keys share the hardcoded 'ephemeral-dev-key' kid, so the scenario landed on BadSignature; the forger now loads a PEM with an explicit distinct kid to pin the KidMismatch path. - JwkManagerTest.VerifyJwt_MissingExp: absent exp fails closed through the exp check (Expired), not the structural Malformed branch — test and JwkManager.h docs aligned to the implementation. - DelayedDoubleDelete race test: cross-connection DEL/SET reordering under load made the choreography nondeterministic; the test now waits for the immediate DEL to land before staging the racing refill, with the delayed phase at 1000ms so the wait can never observe it. - CHANGELOG: memory-mode client_type fix noted under 缺陷修复.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…scoping, race-test margin PR #85 code review (approve-with-comments) disposition: - decodeJwtPayloadClaims' header comment still carried the pre-#78 'hint is advisory / MAY skip verification' rationale; rewritten to state the caller-ordering invariant (only called post-verifyJwt). - invalidation_double_delete_delay_ms scoping: threading the knob into RedisCachedTokenRepository's ctor trips api-diff's BREAKING line-diff on the defaulted-parameter line (inappropriate for a patch release), so the knob is explicitly scoped to the client/user hooks instead — documented at the helper's declaration and the plugin's construction site. The token revoke path keeps the 200ms default; its negative- marker-before-DEL ordering already self-corrects racing refills. - Race test: delayed phase 1000 -> 2000ms, doubling the margin between the wait-for-immediate-DEL loop's budget and the delayed DEL's firing under loaded CI (the flake window was theoretical but cheap to close). - .gitignore: .zcode/tmp/ + .zcode/plans/ (same convention as .kiro/tmp/; these are per-session scratch, never meant for commits).
The #78 openapi edit dropped the POST variant's tags (get kept [OAuth2, OIDC]); the generators consequently re-filed the operation under the default tag (Python post_oauth2_end_session.py moved directories), tripping the clients-sdk drift gate on PR #85. Tags restored, spec re-validated (validator + governance OK), Go + Python clients regenerated to match — drift gates now green locally (regen --check passes).
voidvec
left a comment
There was a problem hiding this comment.
深度评审(第一性原理)— v1.4.1 安全修复
从"攻击者能做什么、代码是否在信任边界上犯错"出发,逐项核验了 #78/#79/#80/#54/#69 的实现与测试。核心结论:修复方向正确,验签门禁与 fail-closed 语义到位,未发现可利用漏洞。 以下按严重度列出建议。
确认正确的部分
#78 end_session 验签(核心)
- 验签门禁在
finish()之前、任何决策之前执行,失败即 400 且不清理会话、不通知 RP —— 正确。 - 签名校验用
EVP_DigestVerify+ SHA-256 对精确的header.payload字节,RS256 语义正确;EVP_DigestVerifyFinal对长度不符的签名返回 0 →BadSignature,fail-closed。 - 严格 alg(拒 none/HS256)、kid 匹配、iss/exp/sub 策略均正确。
- 主体一致性检查(浏览器会话 sub != hint sub → 400)正确,防止"用 A 的合法 hint 登出 B 的会话"。
- 无 hint 行为逐字节不变,前端零回归 —— 好。
- 立即 DEL + 事件循环延迟二次 DEL 的竞态闭合逻辑正确;失败计数(最多 4 次)与 WARN→重试→ERROR 语义与头注释一致。
- token revoke 路径用默认延迟、负缓存自愈的说明合理。
issueTokensForUser改哈希存储,utils::hashToken与TokenCrypto::hashToken逐字节一致(UPPER(SHA256 hex)),口径统一正确。MemoryClientRepository的client_type键名修复正确(type保留回退)。
🟡 MEDIUM — 建议改进
M1. verifyJwt 不校验 aud,且不区分 id_token 与 access_token
verifyJwt 只查 iss/exp/sub。由于签名已验,aud 可信,但它不校验 aud 是否为已知 client,也不校验 token 类型。我们签发的 access_token 同样满足 RS256+iss+exp+sub,若被当作 id_token_hint 传入,aud 会是资源方而非 client,post-logout redirect 校验会 fail-closed(安全),但语义上应区分。建议:在 verifyJwt 增加可选 expectedAud 参数,或在 endSession 校验 aud 为已注册 client。
M2. verifyJwt 未校验 nbf/iat
对登出场景影响小,但作为通用验签入口,建议补 nbf(若存在则 nbf <= nowSecs)以对齐 OIDC 语义。
🟢 LOW(可选优化)
L1. base64UrlDecode 未校验部分组的尾部零填充
remainder==2 时未校验低 4 位为 0,remainder==3 时未校验低 2 位为 0,非规范编码会被接受。因签名是对精确字节校验,不可利用,但严格解码器应拒绝。
L2. payload 双重解码
verifyJwt 内部解码 payload 验签后,endSession 又调用 decodeJwtPayloadClaims 二次解码。建议 verifyJwt 返回已验证的 payload(或提供 verifyAndDecode),避免重复 base64+JSON 解析。
L3. 多受众 aud(数组)会阻断 post-logout redirect
hintClientId 仅当 aud 为 string 时设置;若 id_token 的 aud 是数组,hintClientId 为空,post-logout redirect 校验失败(fail-closed,安全但功能缺口)。建议支持数组取首个/任一匹配 client。
L4. DelayedDoubleDelete 依赖事件循环
runAfter 依赖 drogon 事件循环;若在关闭窗口调用,二次 DEL 可能不执行。属 soft-fail(文档已注明),可接受,但建议在注释中明确该边界。
测试覆盖
JwkManagerTest覆盖全部JwtVerificationResult分支,含 BadAlg/KidMismatch/BadSignature/IssuerMismatch/Expired/MissingSubject —— 充分。SocialLoginPageTest覆盖 link→list→unlink 全生命周期 —— 充分。DelayedDoubleDeleteTest覆盖双删与失败计数 —— 充分。
总体:修复正确、测试充分,建议合并。 M1/M2 可作为后续增强项跟踪,不阻塞本次合并。
…scoping, race-test margin PR #85 code review (approve-with-comments) disposition: - decodeJwtPayloadClaims' header comment still carried the pre-#78 'hint is advisory / MAY skip verification' rationale; rewritten to state the caller-ordering invariant (only called post-verifyJwt). - invalidation_double_delete_delay_ms scoping: threading the knob into RedisCachedTokenRepository's ctor trips api-diff's BREAKING line-diff on the defaulted-parameter line (inappropriate for a patch release), so the knob is explicitly scoped to the client/user hooks instead — documented at the helper's declaration and the plugin's construction site. The token revoke path keeps the 200ms default; its negative- marker-before-DEL ordering already self-corrects racing refills. - Race test: delayed phase 1000 -> 2000ms, doubling the margin between the wait-for-immediate-DEL loop's budget and the delayed DEL's firing under loaded CI (the flake window was theoretical but cheap to close). - .gitignore: .zcode/tmp/ + .zcode/plans/ (same convention as .kiro/tmp/; these are per-session scratch, never meant for commits).
…ppends as additive _multiset_diff flags the old last-parameter line as removed when a declaration gains trailing parameters (the line's only change is a appended comma), tripping BREAKING for what is semantically an ADDITIVE change — PR #85 was forced to abandon threading a delay knob through RedisCachedTokenRepository's ctor over exactly this false positive. New _extract_defaulted_param_appends pairs each removed line R with its comma form in the added set and reclassifies the pair as additive, but ONLY when every co-added parameter-shaped line carries a default value (a non-defaulted append still breaks callers and stays BREAKING). Both brace styles handled (close-paren on its own line vs sharing the parameter line, via _strip_close_paren). Verified: layout-1 (PR #85's exact shape) and layout-2 append-with- defaults -> additive; non-defaulted append and real line removal -> still breaking; no-drift clean; current repo still matches baseline. Fixes #89
…rl, verifyAndDecode, ephemeral kid (#87) PR #85 review follow-ups, all in JwkManager + its one production caller: - M1: verifyJwt gains an optional expectedAudience pin (defaulted, so all existing call sites compile unchanged). aud is accepted as a string or an array of strings (RFC 7519 §4.1.3); a miss/absent aud fails closed as the new AudienceMismatch reason. Lets callers distinguish token types (an access token's aud is a resource, not the client). - M2: nbf is honored per RFC 7519 §4.1.5 -- optional, but when present must be numeric with nbf <= nowSecs (no leeway, mirroring exp); a non-numeric nbf is unevaluable and fails closed as Malformed. New NotYetValid reason. - L1: base64UrlDecode rejects non-canonical trailing zero bits (RFC 4648 §3.5): low 4 bits (2-symbol tail) / low 2 bits (3-symbol tail) must be zero. The signature still pins exact bytes, so this is strictness rather than an exploit, but a strict decoder must not bless them. - L2: verifyAndDecode returns the verified payload in one pass; SessionController::endSession uses it and the now-redundant decodeJwtPayloadClaims second base64+JSON decode is deleted (it had exactly one caller). - ephemeral fallback now honors a configured kid (default marker 'ephemeral-dev-key' preserved). jwtVerificationName covers the two new reasons. Test matrix extended (35 gtest cases in JwkManagerTest): nbf future/past/boundary/absent/ non-numeric, aud string/array/absent pinning, verifyAndDecode ok + rejection-reason out-param, non-canonical tail via header and signature segments (with a BadSignature control proving the tail check is what fires), ephemeral kid override. api-diff baseline ratified with --force per policy: signature change is source-compatible via the defaulted arg; enum values and methods are additive; construction sites are in-repo only.
…rl, verifyAndDecode, ephemeral kid (#87) PR #85 review follow-ups, all in JwkManager + its one production caller: - M1: verifyJwt gains an optional expectedAudience pin (defaulted, so all existing call sites compile unchanged). aud is accepted as a string or an array of strings (RFC 7519 §4.1.3); a miss/absent aud fails closed as the new AudienceMismatch reason. Lets callers distinguish token types (an access token's aud is a resource, not the client). - M2: nbf is honored per RFC 7519 §4.1.5 -- optional, but when present must be numeric with nbf <= nowSecs (no leeway, mirroring exp); a non-numeric nbf is unevaluable and fails closed as Malformed. New NotYetValid reason. - L1: base64UrlDecode rejects non-canonical trailing zero bits (RFC 4648 §3.5): low 4 bits (2-symbol tail) / low 2 bits (3-symbol tail) must be zero. The signature still pins exact bytes, so this is strictness rather than an exploit, but a strict decoder must not bless them. - L2: verifyAndDecode returns the verified payload in one pass; SessionController::endSession uses it and the now-redundant decodeJwtPayloadClaims second base64+JSON decode is deleted (it had exactly one caller). - ephemeral fallback now honors a configured kid (default marker 'ephemeral-dev-key' preserved). jwtVerificationName covers the two new reasons. Test matrix extended (35 gtest cases in JwkManagerTest): nbf future/past/boundary/absent/ non-numeric, aud string/array/absent pinning, verifyAndDecode ok + rejection-reason out-param, non-canonical tail via header and signature segments (with a BadSignature control proving the tail check is what fires), ephemeral kid override. api-diff baseline ratified with --force per policy: signature change is source-compatible via the defaulted arg; enum values and methods are additive; construction sites are in-repo only.
…rl, verifyAndDecode, ephemeral kid (#87) PR #85 review follow-ups, all in JwkManager + its one production caller: - M1: verifyJwt gains an optional expectedAudience pin (defaulted, so all existing call sites compile unchanged). aud is accepted as a string or an array of strings (RFC 7519 §4.1.3); a miss/absent aud fails closed as the new AudienceMismatch reason. Lets callers distinguish token types (an access token's aud is a resource, not the client). - M2: nbf is honored per RFC 7519 §4.1.5 -- optional, but when present must be numeric with nbf <= nowSecs (no leeway, mirroring exp); a non-numeric nbf is unevaluable and fails closed as Malformed. New NotYetValid reason. - L1: base64UrlDecode rejects non-canonical trailing zero bits (RFC 4648 §3.5): low 4 bits (2-symbol tail) / low 2 bits (3-symbol tail) must be zero. The signature still pins exact bytes, so this is strictness rather than an exploit, but a strict decoder must not bless them. - L2: verifyAndDecode returns the verified payload in one pass; SessionController::endSession uses it and the now-redundant decodeJwtPayloadClaims second base64+JSON decode is deleted (it had exactly one caller). - ephemeral fallback now honors a configured kid (default marker 'ephemeral-dev-key' preserved). jwtVerificationName covers the two new reasons. Test matrix extended (35 gtest cases in JwkManagerTest): nbf future/past/boundary/absent/ non-numeric, aud string/array/absent pinning, verifyAndDecode ok + rejection-reason out-param, non-canonical tail via header and signature segments (with a BadSignature control proving the tail check is what fires), ephemeral kid override. api-diff baseline ratified with --force per policy: signature change is source-compatible via the defaulted arg; enum values and methods are additive; construction sites are in-repo only.
Security & defect fixes: #78 #79 #80 #54 #69 (+ #75 coverage)
v1.4.1 — 五个开放 issue 的修复 + 一个顺带发现并修复的 memory-storage 配置解析缺陷。
#78 [High] — end_session 强制 id_token_hint 验签
/oauth2/end_session此前不验签解码 id_token_hint 并用其sub驱动 backchannel logout fan-out:知道任意用户公开 sub(每个该用户登录过的 RP 都知道)即可未认证强制其全 RP 登出。JwkManager::verifyJwt(新导出,signJwt 的对称验签入口):严格 RS256(拒 none/HS256 混淆)、kid 匹配、EVP_DigestVerify、iss/exp/sub 策略。域层无 drogon 依赖(arch-guard 过)。SessionController::endSession:hint 必须通过验签才能影响任何决策;失败/过期/issuer 不符/与浏览器会话主体不一致 → 400AUTH_INVALID_ID_TOKEN_HINT(ErrorCatalog 4006,显式 400,Error Envelope),在finish()之前返回(无会话清除、无 RP 通知)。注意(严格语义的代价):重启(临时密钥)或密钥轮换后重放旧 hint 会 400;窗口以 id_token 的 access-TTL 为界。§2.2 的"MAY skip verification"仅适用于 redirect-uri 匹配的 aud 用途——不适用于把 sub 当 fan-out 主体。
#79 [High] + #80 [Medium] — 缓存失效双删 + DEL 可观测
authforge/storage/redis/DelayedDoubleDelete.h:立即 DEL + 事件循环 200ms 后二次 DEL(cache.invalidation_double_delete_delay_ms,钳位 [50,2000])。回填侧保持 plain SET(NX 无增益——理由见设计文档 §5.4 增补)。client/user/token 三处失效路径统一接入。authforge_cache_invalidation_failures_total{kind}(IMetrics 端口)+ WARN→重试→ERROR。soft-fail 不变。#54 [High] — 软删除社交绕过(已在 master,本 PR 关闭)
主体修复 89c9634(8-16):四态
SocialLinkStatus、deleted_at IS NULL、locked 拒绝、MFA/自服务/consent 链全覆盖 + 389 行SoftDeleteSocialRepoTest+DeletedLinkedUser_Rejected401HTTP 测试。本 PR 携带其回归证据一并关闭(Fixes #54)。Google/WeChat 控制器为纯档案透传(无用户查询/发 token),无绕过面。#69 — 社交 token 哈希口径(+ #75 覆盖闭环)
issueTokensForUser改哈希存储(与 token endpoint 同口径,hashToken 实现逐字节一致)。社交会话从"每次 401 的登录剧场"恢复可用;refresh grant、revokeTokenFamily 的哈希列 SQL 随之打通。存量原文 token 本就不可用 → 直接失效(无迁移)。前端无需改动(GitHubCallbackPage的fetchUser()从此 200)。/api/me/social/links全生命周期(link→list→unlink,数字分发分支)的 HTTP 测试——PR feat(identity): social account link/unlink self-service (B2, v1.3.0) #68 评审遗留的覆盖缺口。顺带修复 — memory-storage client_type 键名
#69 的 refresh e2e 暴露:
MemoryClientRepository读"type",而全部 5 份配置写"client_type"→ memory 模式下配置为 PUBLIC 的 vue-client 静默变成 CONFIDENTIAL。加载器改为接受规范键client_type(type保留回退)。版本与门
verifyJwt方法、DelayedDoubleDelete.h新头,api-baseline 已批准)。Fixes #78
Fixes #79
Fixes #80
Fixes #54
Fixes #69
Fixes #75