Skip to content

fix: P0 issues #143/#103/#70/#142 — consent mapping invariant, legacy-hash retirement, social login closure, real WebAuthn verification - #149

Merged
voidvec merged 19 commits into
masterfrom
fix/p0-issues-143-103-70-142
Sep 1, 2026
Merged

voidvec merged 19 commits into
masterfrom
fix/p0-issues-143-103-70-142

Conversation

@voidvec

@voidvec voidvec commented Aug 31, 2026

Copy link
Copy Markdown
Owner

Summary

Implements all four P0 issues from the reviewed plan v2 (+ v3 adjudications from three fresh review agents: architecture / adversarial RFC-correctness / CI-gates — all APPROVE-WITH-CHANGES, findings incorporated; the adjudication log lives in the plan file's v3 block).

Issue Theme One-liner
#143 self-registered/admin-created users 500 on consent Three idempotent layers give every user a (local, id) subject mapping: both creation paths + V027 one-time backfill + startup self-heal
#103 admin creds + legacy unsalted-SHA256 retirement allow_legacy_hash now false by default (missing key = closed), drogon legacy verify branch deleted, seeds/scripts → PBKDF2, bench_users.sql moved out of the prod image, policy rejection does NOT advance lockout, WARN+audit notifier (additive seam), helm passthrough
#70 Google/WeChat logins had no sign-in effect All three providers run one closed loop: mapping lookup → (first-login auto-create, global gate) → first-party token pair via shared SocialTokenIssuer storing public_sub (also fixes GitHub's existing 404-on-/api/me defect); issuance traced by SOCIAL_LOGIN_TOKEN_ISSUED audit (NOT a consent row — a consent row would silently satisfy the Tier-3 consent screen; explicit social consent is follow-up); 403 AUTH_SOCIAL_ACCOUNT_NOT_LINKED(5003); frontend SocialCallbackPage + gated Google button
#142 WebAuthn had zero cryptography (credential-id oracle) Real W3C L2 §7.1/§6.1 verification: libcbor-backed CborReader (depth/length/DoS limits) + ES256/fmt-none crypto core (53 unit tests), subject-bound registration challenges (Bearer flow, no cookie contract) + session-bound assertion challenges, unconditional consumption, UV=1 enforced & advertised, signCount clone policy, V028 clears the unverified legacy rows, raw-SQL fallbacks deleted (memory mode = explicit fail-closed), session established on success (amr hwk user)

Review-adjudicated deviations from the plan (v3)

Migration numbers

V027 (subject-mapping backfill, #143) and V028 (webauthn purge, #142) — both registered in the migration-check baseline. Later PRs take V029+.

Contract/gate status (all verified locally)

  • api-diff: additive seams only, baseline ratified (184 headers) — bool allowLegacyHash_ = true; untouched
  • oasdiff: 2 breaking entries (webauthn finish request bodies — the security fix itself) with errata reproducing oasdiff output; GitHub stale profile schema corrected
  • error codes: AUTH_SOCIAL_ACCOUNT_NOT_LINKED(5003/403), WEBAUTHN_INVALID_ATTESTATION(3015), WEBAUTHN_CHALLENGE_MISMATCH(3016) — catalog (both capacity literals) + api-reference §5.1 + ErrorCatalogDocTest
  • SDK: python + go regenerated (3 social endpoints, 4 webauthn endpoints, new schemas)
  • static gates: arch-guard / migration-check / naming / drogon-macro-bool / manage-parity / spec-governance / openapi-spec-validator / clients-sdk --check — all green locally

Testing

  • Backend full_test: 8/8 steps, 581/581 ctest ×2 configs (standard + config.ci.json), 59 OAuth2 + 52 admin endpoint scripts — all green
  • identity unit: 228/228 (incl. 53 crypto vectors); WebAuthnHttpTest rebuilt as 10 real-crypto chain cases (real P-256 keygen, hand-built CBOR)
  • Frontend user: unit 24, e2e 107 passed/2 skipped, build+lint green; admin: e2e 180 passed/6 skipped, build+lint green
  • New full-suite fallout found & fixed along the way (each with its own test): AdminBootstrapper fresh-insert missing salt (latent, NOT NULL violation), SDK package config missing find_dependency(libcbor) (SdkSmoke), PowerShell/bash $pbkdf2 interpolation corrupting the admin reset hash, setup-database seed list dropping the three client seeds

Versioning

No bump in this PR. Per docs/contribute/versioning-and-release.md §3 (security-hardening gray zone): target vehicle is v1.1.0 at release time, with the three ⚠️ Breaking (security hardening) items in the Release Notes + migration pointers (already drafted in CHANGELOG [Unreleased]).

Fixes #143, fixes #103, fixes #70, fixes #142

@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 Aug 31, 2026
…me, passkey liveness gate, UV alignment

B-1 (BLOCKER): the username-collision retry in AccountLinkFlow held its
self-referencing attempt function via weak_ptr only; with the fully
async production repository the initiating stack frame is gone when the
INSERT round-trip returns, so the retry (and the terminal error path)
silently dropped — the request hung until client timeout. The shared
synchronous test fake masked exactly this shape. Rewritten as a free
function recursing through a shared AttemptContext: the in-flight
repository callback strongly owns the context, the chain stays alive
across every round-trip, and all owners drop on the terminal branches.
Pinned by two new DeferredSocialAccountRepository tests that queue every
callback and drain it only AFTER login() returned (230/230 identity
tests).

M-1 (MAJOR): findByCredentialId now enforces user liveness on the
passkey path — soft-deleted (deleted_at IS NULL filter) and locked
(locked_until > now -> generic nullopt) users can no longer authenticate
via /oauth2/webauthn/authenticate/finish; parity with the password and
social paths (V024/#54 'disabled means cannot log in through ANY flow').

Minor: registration finish enforces UV=1 too (begin advertises required;
a UV-less registration would mint a credential that can never
authenticate); authenticateBegin mints ONE challenge instead of two
(the old path discarded a CSPRNG draw); the three remaining bare Mapper
constructions in PostgresWebAuthnRepository wrapped per
db-operations.md rule 1; subject-mapping backfill now RETURNING-counted
so the heal log is truthful.

Full suite re-verified after the fixes: full_test 8/8 steps, 583/583
ctest x2 configs, 55/55 admin endpoint scripts; identity 230/230;
static gates re-run green (api-diff/migration/arch/naming/
spec-governance/clients-sdk).
@voidvec

voidvec commented Aug 31, 2026

Copy link
Copy Markdown
Owner Author

对抗性评审处置(评审代理裁决 REQUEST-CHANGES → 全部处置完毕,626a0b8b)

级别 发现 处置
B-1 BLOCKER 社交自动建户用户名冲突重试的 weak_ptr 自引用在生产异步仓储下悬垂:发起栈帧在 INSERT 往返返回前已销毁 → 重试与终态错误路径都被静默丢弃 → 请求挂起。共享的同步测试 fake 恰好掩盖了该形态 已修:重写为自由函数 runAttempt 经共享 AttemptContext 递归——在飞的仓储回调强持有 ctx(链条跨每个 SQL 往返存活,终态分支全部释放);新增 DeferredSocialAccountRepository 双测试(队列化每个回调、login() 返回后才 drain)钉死该生命周期形态
M-1 MAJOR WebAuthn 断言路径缺用户存活门:软删/锁定用户的已注册 passkey 仍可换取浏览器会话(与密码/社交路径的 V024/#54 契约不一致) 已修:findByCredentialId 增加 deleted_at IS NULL 过滤 + locked_until > now 拒绝(generic nullopt,无状态泄漏)
m-1 注册 finish 未强制 UV,与 begin 广告的 required 不对齐(可注册出永远无法登录的凭证) 已修:注册侧同样强制 UV=1
m-2 PostgresWebAuthnRepository 三处裸 Mapper 构造违反 db-operations rule 1 已修:全部独立 try/catch + 回调失败
m-3 authenticateBegin 双重挑战生成(丢弃一次 CSPRNG) 已修:单次生成
NIT backfill 无 RETURNING → "healed N" 日志恒假 已修:RETURNING 1 计数
NIT createLinkedUser 将 DB 故障与用户名冲突同归 nullopt → 重试后误报 USERNAME_TAKEN 维持(接口注释已声明的取舍;B-1 修复后不再挂起)
NIT 同一断言并发双发可偶发双成功;认证成功不轮转会话 ID 维持(前者同账号无升权;后者与 SessionController::login 既有约定一致,登记 follow-up)

评审同时明确核实无误:#142 密码学逐步对照(COSE 定界/ED 跳过/signCount BE/rpIdHash/验签输入串/DER/tokenBinding/CborReader DoS 防护)、challenge 生命周期(无条件消费、TTL、预解析无绕过)、#70 publicSub 线程完整性、#103 翻转/锁定语义、#143 单次回调不变量、迁移幂等、旧部署无 webauthn 块 fail-closed。

修复后全量复验:full_test 8/8 步、583/583 ctest ×2 配置(+2 为新异步钉死测试)、55/55 admin 端点;identity 230/230;静态门复跑全绿。

voidvec added a commit that referenced this pull request Sep 1, 2026
…148 token system

PR #148 (Machined Trust) remapped the palette to OKLCH semantic tokens;
red-* is replaced by error-* (AppAlert's own error variant idiom). The
new #149 callback page still used the legacy red-* classes -- swap to
bg/text/border-error-* so it renders correctly under the remapped dark
palette. (The Google/WeChat login buttons already match: #148 kept the
GitHub button's neutral-* classes, and the neutral ramp is remapped in
place.)
@voidvec

voidvec commented Sep 1, 2026

Copy link
Copy Markdown
Owner Author

评审报告(已与分支代码逐条对齐复核)

评审范围:按安全优先级聚焦 4 个 P0 issue 的核心路径 —— WebAuthn 加密核心(CborReader / WebAuthnCrypto / WebAuthnService / Controller)、社交登录令牌签发(SocialTokenIssuer + 三个 provider + AccountLinkFlow)、遗留哈希退役(PasswordHasher / AuthService / Assembly)、consent 映射迁移(V027/V028)、Postgres 存储层与对应测试。前端、e2e、bench、文档为略读。

总体结论:整体质量非常高,未发现可被利用的高危漏洞。 加密流程、挑战绑定、降级路径均处理严谨,测试覆盖(含真实签名集成测试)扎实。以下按严重级别列出发现。


发现

[Medium] crossOrigin=true 被解析但未强制校验(WebAuthn L2 合规缺口)

  • 对位代码:libs/identity/src/webauthn/WebAuthnService.cc:257-279(注册)、:381-401(断言)只校验 type / challenge / origin 白名单,从未读取 clientData->crossOrigin;而 WebAuthnCrypto.cc:145-151 已正确解析该字段。
  • 该 RP 永远采用同源策略(origin 白名单 + 从不声明跨源支持),按 W3C WebAuthn L2 §7.1 step 9 / §6.1 step 5,服务端应拒绝 crossOrigin == true。
  • 攻击面:恶意顶层页面将 RP 以跨源 iframe 嵌入并驱动其 WebAuthn 仪式,用户在原语操作弹窗中完成真实手势,但处于易受误导的上下文 —— 这正是该字段设计要缓解的钓鱼向量。仍需真实用户手势,故非账号接管,判 Medium。
  • 建议:两个 finish 路径在 parseClientDataJSON 后加 if (parsed.crossOrigin) → fail,并补充 "crossOrigin=true 被拒绝" 的测试(当前测试仅覆盖解析)。

[Low] 注册挑战 map 无限增长(内存泄漏)

  • 对位代码:libs/identity/include/fulla/identity/WebAuthnService.h:377-384,unordered_map<subject, ChallengeEntry> + mutex;consumeRegistrationChallenge 仅在流程走完时 erase,TTL 只在消费时检查,无后台/惰性清理。
  • 用户 registerBegin 后放弃注册(不发 finish),条目永久驻留。长期运行下内存随「发起过注册的去重 subject 数」线性增长,大型部署可累积数百 MB。
  • 建议:TTL 到期惰性删除(消费前检查时清理过期项),或 map 超阈值时做过期清扫。
  • 另注:头文件注释自称 "TTL-bound" 略有夸大 —— TTL 只负责拒绝,不负责回收。

[Low] signCount 克隆检测存在 check-then-async-update 竞态

  • 对位代码:libs/identity/src/webauthn/WebAuthnService.cc:491-504:读 stored → 比较 → updateSignCount(..., [](bool) {}) 异步 fire-and-forget。
  • 同一真实凭证在两个并发会话中认证时(stored=5 / presented=6)可双双通过,克隆凭证的平行使用可逃逸检测。影响限于克隆检测:会话本身仍绑定「有效签名 + 已消费的会话挑战」(WebAuthnController.cc:488-489 无条件 erase),同会话重放已被关闭。
  • 建议:UPDATE ... WHERE sign_count = $old 判断受影响行数做原子更新,或按凭证串行化。

[Low] SocialTokenIssuer 未校验 social_token_client_id 是否为一等方/已注册客户端

  • 对位代码:libs/drogon/src/controllers/SocialTokenIssuer.cc socialTokenClientId() 读配置即签发,无任何对 client 是否存在、是否 first-party 的运行时校验;注释明确要求运维保证一等方。
  • 误配置为第三方 client id 时,社交登录会静默为第三方签发令牌且无 consent 交互。
  • 建议:装配/首次使用时校验 client 存在性并拒绝第三方 client。

[Info] AccountLinkFlow 将 DB 错误与用户名冲突混为一谈

  • 对位代码:libs/identity/src/social/AccountLinkFlow.h:80-92:createLinkedUser 返回 nullopt 时一律视为用户名冲突并重试一次,DB 故障也会被伪装成 VALIDATION_USERNAME_TAKEN 返回给客户端。
  • 注释(20-22 行)已明确承认该权衡,可接受;建议至少为重试仍失败时记录区分性日志。

[Info] 控制器对 clientDataJSON 双次解析(宽松 + 严格)

  • 对位代码:libs/drogon/src/controllers/WebAuthnController.cc:316-330(注册)、:491-505(断言)先用 jsoncpp 宽松 Json::Reader 提取 presentedChallenge,服务层再用严格解析复核。
  • 安全性上无绕过(严格解析是权威路径,重复 challenge 键会导致严格解析失败),仅存在冗余与潜在发散。建议控制器仅透传原始 clientDataJSON,让服务层单一权威解析。

[Info] 审计日志使用客户端提供的原始 rawId

  • 对位代码:libs/drogon/src/controllers/WebAuthnController.cc:372、:549:审计日志与响应均记录 input.rawId(客户端可控字符串),而存储的是规范化的 base64UrlEncode(authData->credentialId)。因查找时再次规范化,功能不受影响,仅一致性/日志注入面瑕疵。

做得好的地方(值得保留)

  1. CborReader 的 DoS 加固非常出色:结构预扫描在 materialize 树之前强制 128KiB 输入 / 8 层深度 / 1024 项 / 64KiB 字符串硬限制;load() 的 *consumed != size 交叉校验保证了预扫描与 libcbor 解析的结构一致性。
  2. 挑战无条件消费(consumeRegistrationChallenge / WebAuthnController.cc:488-489 先 erase 再验证)——杜绝有效性 oracle。
  3. 认证失败统一空 optional / 通用错误,无账号/凭证枚举。
  4. 遗留哈希退役策略正确:allow_legacy_hash 默认关闭、拒绝时不推进失败计数(避免锁定 oracle)、notifier 供观测、响应保持通用 AUTH_INVALID_CREDENTIALS。
  5. 注册不再信任客户端提交的 public_key:WebAuthnService.cc:320-323 只存 authData 内 COSE 原始字节 —— 这是 Problem (IAM hardening plan M1.1 / PR #140 review F2) #142 的核心修复点,代码确认到位。
  6. 注册强制 UP && UV && AT(:295)、断言强制 UP && UV(:454),与 begin 广告的 userVerification=required 闭环;userHandle 解码后与十进制内部 id 比较(:429-447),防凭证跨用户绑定。
  7. 会话字段(userId/sub/auth_time/amr)与 SessionController::login 逐字段一致(:533-540),WebAuthn 会话可被既有授权中间件识别。
  8. updateSignCount 修复(改用 found row 而非空对象,避免 NOT NULL 列导致 UPDATE 静默失败)。
  9. V027 幂等回填(ON CONFLICT DO NOTHING)、V028 数据清除有据可依(down 迁移显式 no-op),getInternalUserId 的 deleted_at IS NULL 存活门保证回填软删用户的映射无副作用。
  10. 测试覆盖扎实:WebAuthnCryptoTest 32 例、WebAuthnServiceTest、WebAuthnHttpTest、AdminBootstrapLegacyHashHttpTest 用真实 ECDSA/CBOR 构造,断言「关闭契约」而非内部实现。

建议合并前处理顺序

  1. crossOrigin 强制校验 + 测试(改动小、安全收益明确)
  2. 注册挑战 map 的过期清理
  3. signCount 原子更新(或至少在 PR 中注明为已知限制)

其余 Low/Info 项可作为后续 issue 跟进,不阻塞合并。

@voidvec

voidvec commented Sep 1, 2026

Copy link
Copy Markdown
Owner Author

外部评审处置(7 条发现全部先核实真伪再处置,23dd2b00)

级别 发现 真伪核实 处置
Medium crossOrigin=true 已解析未强制(L2 §7.1 step 9 / §6.1 step 5) 属实:WebAuthnCrypto 解析了字段,Service 两条 finish 路径都没读 已修:注册侧 → WEBAUTHN_CHALLENGE_MISMATCH,断言侧 → generic 401。新增 e2e:同钥有效签名 + crossOrigin=true → 401(证明拒绝的是跨源环境而非签名)
Low 注册挑战 map 只拒绝不回收(begin 后放弃的 subject 条目永久驻留) 属实:只有 consume 时 erase 已修:issue 时惰性清扫全表过期项(O(live subjects),无后台线程);头注释 "TTL-bound" 的夸大表述一并改正
Low signCount check-then-async-update 竞态(同计数并发双断言都过) 属实 已修:新增加性接口 updateSignCountIfCurrent(原子 CAS);PG 实现 UPDATE ... WHERE sign_count=$expected RETURNING 1;CAS 失败 = 同凭证并发断言 = 克隆/重放证据 → 拒绝。双零计数器(合法无计数器场景)跳过写入照常通过。顺带修掉 PG UPDATE 无 RETURNING 时 Result::size()==0 导致 CAS 恒败的坑(e2e 抓出)
Low social_token_client_id 未校验已注册(拼错 id 静默发无人能解析的 token) 属实 已修:发放前 getClient 门(未注册 → INTERNAL_ERROR + LOG_ERROR)。first-party 判定维持运维契约(数据模型无该标志位),文档已有强警示
Info AccountLinkFlow 把 DB 故障伪装成 USERNAME_TAKEN 属实,但接口头注释已明示此取舍(B-1 修复后不再挂起) 维持。域层无日志依赖,为区分日志加 notifier 注入面不成比例;follow-up 可做
Info clientDataJSON 控制器宽松解析 + 服务层严格解析双次 属实,评审自己也确认无绕过(严格解析是权威路径,宽松提取的 challenge 若与严格解析分歧 → fail closed) 维持。控制器需要 challenge 来调 service API;去重需改回调签名(SDK 面),收益纯美学
Info 审计/响应记录客户端原始 rawId 而非规范化 id 属实 半修:断言侧 WebAuthnAuthResult.credentialId(规范化形)落审计;注册侧响应保留回显客户端自己的 id(客户端自选标签,语义无害)

修复后全量复验:full_test 8/8 步、584/584 ctest ×2 配置(+1 crossOrigin e2e)、55/55 admin 端点、identity 231/231、静态门全绿、api-diff 加性缝重新 ratify(184 headers)。

评审"做得好的地方"清单(CborReader DoS 预扫描、无条件消费、枚举防护、#103 锁定语义、COSE 不信任客户端等 10 项)与我们的实现认知一致,无需动作。

… 500

Users created via self-registration (/api/register) and the admin API
(POST /api/admin/users) got no (local, <id>) row in
oauth2_subject_mappings; consent's getInternalUserId resolves users
exclusively through that table, so those users 500'd on
authorize -> consent.

Three idempotent layers:
- A1 PostgresIdentityRepository::create: every completion path (role
  lookup/assignment outcomes included) falls through to a
  INSERT ... ON CONFLICT (provider, subject) DO NOTHING mapping write
  before the callback; failure is logged and tolerated (mirrors role
  semantics — a loud failure would trap a USERNAME_TAKEN retry).
- A2 UserAdminService::createUser: same mapping write ahead of the 201.
- B  V027 one-time backfill (deliberately not filtering deleted_at;
  consent-side liveness checks reject soft-deleted users regardless).
- C  AdminBootstrapper::backfillLocalSubjectMappings startup self-heal
  (same SQL shape), scheduled from main.cc — turns the mapping into a
  startup invariant instead of a one-shot migration.

Tests: full self-register and admin-create consent chains (302 + code),
V027 rerun idempotency + id-consistency, startup backfill healing; the
manual re-seed workaround in ConsentAuthGateHttpTest is gone (the dev
seed already ships the admin mapping).

Fixes #143
The legacy verification path (sha256(password+salt), the pre-1.0 dev-seed
format) is retired and closed by default on every path:

- Assembly default flipped: IdentityAssembly treats a missing
  auth.allow_legacy_hash key as false (AuthService.h's field initializer
  stays true only so the api-diff SDK baseline line is untouched); all 5
  tracked configs set allow_legacy_hash=false.
- drogon PasswordHasher::verify rejects non-PBKDF2 hashes outright (the
  legacy branch is deleted); the rehash-on-login block in drogon
  AuthService became dead code and is removed. needsRehash is kept as the
  format discriminator (unit tests unchanged semantics).
- Identity-side policy denial fixed: a legacy rejection is NOT a wrong
  password — it no longer advances the account-lockout counter (username
  knowledge must not lock legacy users out, and a reopened window must
  not stay blocked by locked_until). New additive observability hook
  setLegacyHashRejectionNotifier wired to a WARN carrying the internal
  user id; the response stays generic AUTH_INVALID_CREDENTIALS (no
  oracle).
- Seeds/scripts converted to PBKDF2 (passwords unchanged): dev_admin_user
  seed, reset-admin-password.{sh,ps1}, common-test-functions.{sh,ps1}
  reset_admin_account.
- bench_users.sql moved to benchmarks/fulla/seed (benchmark-only; no
  longer shipped with the prod image via Dockerfile's seed COPY),
  converted to PBKDF2, and wired into benchmarks/fulla/setup.sh;
  setup-database.{sh,bat} now load an explicit seed list so bench users
  never land in a dev/test database.
- Docs: account-lockout runbook SQL (EN + zh-CN) rewritten to the PBKDF2
  hash; configuration-guide gains a 'legacy hash migration window' section
  with the corrected semantics (email/admin reset DOES migrate;
  change-password is rejected for legacy users; window reopen does not
  require unlocking); observability registers AUTH_LEGACY_HASH_REJECTED;
  README dev-compose notes PBKDF2 storage; testing-guide documents the
  full_test/bench serialization rule.
- Helm: secrets.bootstrapAdminPassword passthrough to
  FULLA_BOOTSTRAP_ADMIN_PASSWORD.
- Tests: PasswordHasherTest legacy cases rewritten to rejection
  semantics; AuthServiceTest covers window-closed rejection (no lockout
  advance, notifier fires, hash untouched) and explicit window reopen
  with rehash; new AdminBootstrapLegacyHashHttpTest covers bootstrapper
  idempotence, the first-boot env-password path (admin temporarily
  renamed away, exact restore), and HTTP-level legacy rejection with no
  lockout advance.

Legacy users migrate via password reset (rewrites PBKDF2) or a temporary
auth.allow_legacy_hash=true window; change-password cannot self-migrate
them. The identity-side window code is scheduled for removal in v1.1.

Fixes #103
…ssue first-party tokens

All three providers now run the same closed loop (upstream code exchange
-> subject-mapping lookup -> first-login auto-create -> first-party token
pair); Google/WeChat previously returned only the filtered profile —
linking them had no sign-in effect.

Service layer (identity):
- Google/WeChat services gain an additive setAccountRepository /
  setAutoCreate seam (constructors unchanged; assembly always injects the
  repo when built with WITH_SOCIAL + DB storage — profile-only remains
  the degraded direct-construction shape) and their Result structs carry
  userId/username/isNewUser/publicSub.
- New provider-agnostic AccountLinkFlow (src/-internal): the four-state
  resolution GitHub used (Linked / AccountUnavailable->generic 401 /
  RepositoryError->DB error, never falls through to creation / NoMapping
  -> auto-create gate), plus a one-shot random-suffix retry on username
  collision then VALIDATION_USERNAME_TAKEN. GitHub login() refactored
  onto the same helper; its NoMapping branch now also honors the gate.
- ISocialAccountRepository lookups/results carry users.public_sub (what
  token rows must store); Postgres implementation reads/returns it.

Token issuance (drogon):
- New shared SocialTokenIssuer (extracted from GitHubController): mints
  + persists the pair via plugin->saveTokenPair with token rows keyed on
  the PLATFORM SUBJECT (users.public_sub) — fixing the pre-existing
  GitHub defect where the internal numeric id was stored, making its
  tokens 404 on every Bearer-authenticated handler. Client configurable
  (external_auth.social_token_client_id, default vue-client, first-party
  only), scope openid profile email.
- Compliance: issuance writes a SOCIAL_LOGIN_TOKEN_ISSUED audit event
  (provider/client/scope/internal id), NOT an oauth2_user_consents row —
  a consent row would silently satisfy the consent screen's Tier-3 check
  and pre-approve the client for scopes the user was never prompted for.
  Explicit social-consent interaction registered as follow-up.
- Google/WeChat controllers gain the resolvePlugin seam and the
  account-linked path; GitHub issueTokensForUser delegates (tail-default
  publicSub param — additive seam; empty fails closed, no token minted
  against an unresolvable subject).

New error code AUTH_SOCIAL_ACCOUNT_NOT_LINKED (5003, AUTHORIZATION ->
403): 'not linked' is an authorization state the client can act on, not
an authentication failure; probing needs the target account's own
upstream code (no cross-user enumeration). Catalog (both capacity
literals) + api-reference 5.1 + openapi descriptions synced.

openapi/SDK: google/wechat 200 responses now the SocialLoginTokenResponse
schema with a 403 entry; GitHub's stale profile schema corrected to what
the runtime has returned since the linking flow landed. Python+Go SDKs
regenerated.

Frontend (user): generalized SocialCallbackPage (/callback/google,
/callback/wechat; login flow stores the token pair, link flow keeps the
#71 short-circuit), gated Google button on VITE_GOOGLE_CLIENT_ID
(unconfigured = hidden), WeChat desktop hint only (QR scan needs a
WeChat-enabled surface — explicit desktop flow is follow-up); env
example extended; e2e: google login-callback happy path added.

Tests: SocialMockFixture injects the fake account repo into Google/WeChat
(repos now carry synthesized publicSub); Google/WeChat happy paths assert
tokens + linkage; auto-create-off -> 403 with zero side effects; linked
WeChat user -> tokens without extra accounts; username-collision retry;
PG e2e maps the fake to the admin's real public_sub so social tokens
resolve across introspection/userinfo/links like password-flow tokens.

api-diff: additive seam ratified via --update-baseline (183 headers;
defaulted-param append recognized for issueTokensForUser).

Fixes #70
… (ES256, fmt none)

The WebAuthn endpoints previously performed ZERO cryptography:
registerFinish trusted client-submitted {credential_id, public_key}
verbatim, and authenticateFinish accepted a bare credential_id as proof
of possession (a credential-id oracle); the challenges written at begin
were never read back. This lands real W3C WebAuthn Level 2 §7.1/§6.1
verification:

Crypto core (libs/identity/src/webauthn/):
- CborReader: typed read-only wrapper over libcbor 0.13.0 (re-added via
  conan; PUBLIC link so test TUs including the header get <cbor/...>),
  with structure pre-scan limits: depth<=8, items<=1024, strings<=64KB,
  input<=128KB, indefinite-length rejected — DoS-hardened, never throws.
- WebAuthnCrypto: parseClientDataJSON (type/challenge/origin/tokenBinding
  — status 'present' rejected), parseAttestationObject (fmt='none' with
  empty attStmt only), parseAuthData (rpIdHash, flags UP/UV/AT/ED,
  signCount BE, credIdLen<=1023, COSE-key byte-range recovery, ED skip),
  parseCoseKeyEs256 (kty=2/alg=-7/crv=1/x,y 32B), verifyEs256Signature
  over authData || SHA256(clientDataJSON) via OpenSSL EVP.
  53 unit tests (fixed CBOR vectors + real P-256 keygen/signatures),
  shared with the HTTP tests via testing/WebAuthnTestBuilders.h.

Service (WebAuthnService, additive seams):
- Registration challenges bound to the Bearer SUBJECT (register routes
  sit behind OAuth2AuthFilter; the SPA sends no session cookie) in an
  in-process TTL-bound store (300s, single-instance documented);
  authentication challenges session-carried as challenge|issuedAt with
  code-level TTL. Both consumed UNCONDITIONALLY (no validity oracle).
- finishRegistrationVerified: challenge gate first, then
  clientDataJSON/attestation/authData/COSE checks; stores canonical
  base64url of RAW credential id + COSE bytes (client public_key field
  ignored). finishAuthenticationVerified: userHandle owner check,
  UV=1 enforced, signature verified against the STORED COSE key
  (findByCredentialId now returns publicKey), signCount clone policy
  (stored>0 && new<=stored -> reject + webauthn_clone_detected audit
  notifier; both-zero legal skip). Repository lookup gains publicKey +
  per-Mapper try/catch rule compliance; updateSignCount updates from the
  found row (partial-object update silently failed before).
- Legacy finishRegistration/finishAuthentication keep their SDK-baseline
  declarations but FAIL CLOSED (never store / never authenticate).

Controller:
- begin advertises EXACTLY what finish enforces: ES256 only (-257
  dropped), userVerification=required (UV-incapable authenticators
  excluded from the supported surface), user.id = base64url(internal id
  bytes), excludeCredentials from the user's stored credentials.
- finish accepts the browser PublicKeyCredential shapes; authenticate
  success establishes the session mirroring SessionController::login
  (userId/sub/auth_time/amr) — amr 'hwk user' (RFC 8176 values; the
  server cannot distinguish PIN vs biometrics, so no 'pin').
- The raw-SQL fallbacks are DELETED: memory-storage deployments get an
  explicit fail-closed envelope instead of a silently vulnerable path.

Migration V028 clears webauthn_credentials (every pre-existing row was
unverified client-asserted material that can never satisfy the new
verifier and preserved the credential-id oracle; DO-block form per the
migration checker's M4 rule). webauthn.rp_id/rp_origins config in all
tracked configs (prod as commented sample; empty allowlist = finish
fails closed); new error codes WEBAUTHN_INVALID_ATTESTATION(3015)/
WEBAUTHN_CHALLENGE_MISMATCH(3016) catalog+api-reference synced;
openapi request schemas for both finish endpoints + policy descriptions;
SDK regenerated; api-diff additive seams ratified (184 headers).

Frontend: SecurityPage sends the real attestation envelope (server
options threaded verbatim: ES256/UV-required/excludeCredentials); e2e
asserts the new body shape and the absence of the client public_key.

Tests: WebAuthnHttpTest rebuilt as 10 verified-chain cases (real P-256
material: registration 201 + stored COSE check, replay 400, duplicate
409, legacy-body rejection, begin policy, assertion 200 + session +
sign_count persistence, tampered signature/wrong origin/no challenge
401s, credential-id-only oracle killed); service tests cover the
challenge stores (unconditional consumption, TTL) and fail-closed
legacy contracts.

Fixes #142
…g dep, quoting, regression formula

- AdminBootstrapper first-boot insert set no salt: users.salt is NOT NULL,
  so the fresh-admin path failed on the constraint (latent since the
  bootstrapper landed — dev seeds always pre-created admin, the new
  #103 fresh-DB test exposed it). Set the empty-string salt like every
  other creation path.
- AdminBootstrapLegacyHashHttpTest rename guard now moves the EMAIL
  aside too: the bootstrapped admin carries admin@example.com and the
  renamed original still holding it tripped idx_users_email_unique (a
  genuinely fresh database has neither row).
- SDK packaging: fulla-identity's exported config lacked
  find_dependency(libcbor), so SdkSmoke's external
  find_package(fulla-identity) consumer failed with 'libcbor::libcbor
  not found' (libcbor is PRIVATE-linked but still crosses the export
  boundary as LINK_ONLY). Declared in DEPENDENCIES; libcbor linked
  directly on the identity TEST target for its direct CborReader
  includes.
- The four admin-reset scripts embedded the PBKDF2 hash in double
  quotes — bash/PowerShell expanded $pbkdf2 (empty variable) and wrote
  a corrupted hash to the admin row, 401-ing every later admin login
  (root cause of the first full-suite run's 52 endpoint failures).
  Single-quoted everywhere; setup-database now lists ALL four seed
  files (the earlier explicit-list change had dropped the three client
  seeds, breaking admin-console login).
- ErrorCatalogRegressionTest count formula +3 (#70 + #142 codes);
  GitHub conflicting-username test rewritten for the #70 retry
  semantics (suffixed retry succeeds; adoption still impossible).
…me, passkey liveness gate, UV alignment

B-1 (BLOCKER): the username-collision retry in AccountLinkFlow held its
self-referencing attempt function via weak_ptr only; with the fully
async production repository the initiating stack frame is gone when the
INSERT round-trip returns, so the retry (and the terminal error path)
silently dropped — the request hung until client timeout. The shared
synchronous test fake masked exactly this shape. Rewritten as a free
function recursing through a shared AttemptContext: the in-flight
repository callback strongly owns the context, the chain stays alive
across every round-trip, and all owners drop on the terminal branches.
Pinned by two new DeferredSocialAccountRepository tests that queue every
callback and drain it only AFTER login() returned (230/230 identity
tests).

M-1 (MAJOR): findByCredentialId now enforces user liveness on the
passkey path — soft-deleted (deleted_at IS NULL filter) and locked
(locked_until > now -> generic nullopt) users can no longer authenticate
via /oauth2/webauthn/authenticate/finish; parity with the password and
social paths (V024/#54 'disabled means cannot log in through ANY flow').

Minor: registration finish enforces UV=1 too (begin advertises required;
a UV-less registration would mint a credential that can never
authenticate); authenticateBegin mints ONE challenge instead of two
(the old path discarded a CSPRNG draw); the three remaining bare Mapper
constructions in PostgresWebAuthnRepository wrapped per
db-operations.md rule 1; subject-mapping backfill now RETURNING-counted
so the heal log is truthful.

Full suite re-verified after the fixes: full_test 8/8 steps, 583/583
ctest x2 configs, 55/55 admin endpoint scripts; identity 230/230;
static gates re-run green (api-diff/migration/arch/naming/
spec-governance/clients-sdk).
…d of regenerating

The Windows-profile lockfile regeneration dropped Linux-only graph
entries (util-linux-libuuid & co.), failing the Linux sanitizer/coverage
legs with 'Requirement not in lockfile requires'. Restore the master
lockfile (generated across the full platform matrix) and insert the
single new requirement by hand (RREV + timestamp from the local cache).
The CI property-test leg runs the dev server WITHOUT a live backend; the
post-login fetchUser chain can probe the refresh endpoint, and an
un-mocked pass-through dies with ECONNREFUSED, breaking the redirect
assertion (the local all-mocked run never saw it).
…rage contract

setTokens keeps the access token in memory only (http.ts — only the
refresh_token persists); the old assertions required a localStorage key
that is deliberately never written. Assert the persisted refresh_token,
the redirect, and the authenticated dashboard instead. The CI error-
context snapshot made this obvious: the login had actually succeeded
(Dashboard rendered) while the storage key stayed null.
… dead placeholder helper

The CI matrix builds with FULLA_WERROR=ON; GCC/Clang flagged a
CRLF-merge that glued two #include directives onto one line and an
unused placeholder function. Verified with a full local -DFULLA_WERROR=ON
rebuild.
…36 toolchain

- AdminBootstrapLegacyHashHttpTest: compare against drogon::HttpStatusCode
  instead of unsigned (MSVC C4389; GCC/Clang see the enum's underlying
  type as matching, so the CI -Werror matrix never caught it).
- Strip the non-ASCII punctuation introduced by this PR's comments
  (em dashes, arrows, section signs) from WebAuthnService.cc /
  GoogleAuthService.cc / WeChatAuthService.cc / AccountLinkFlow.h — they
  trigger MSVC C4819 on simplified-Chinese Windows (code page 936),
  another local-only warning class the CI matrix cannot see. The
  remaining C4819 carriers (WeChatAuthService's quoted WeChat-doc term,
  ICryptoProvider.h, examples/*, ...) are pre-existing on master and
  left as-is (comments only, zero runtime risk).
CREATE DATABASE needs the role to hold CREATEDB, DROP only needs
ownership — so a hand-created fulla_user (typical on WSL/local Linux
installs) drops fine and then dies on create, and the old error text
gave no repair path.

- sh (Linux/macOS/WSL): on create failure, check rolcreatedb; when the
  local postgres superuser is reachable via passwordless 'sudo -u
  postgres psql' (peer auth), grant CREATEDB once and retry the create;
  otherwise print the exact one-line fixes (native + docker forms).
- bat (Windows): no sudo path exists — print the exact superuser fix
  commands (native psql + docker exec forms) and exit non-zero.

Databases created by the official dev containers/compose are unaffected
(their POSTGRES_USER is a superuser).
…148 token system

PR #148 (Machined Trust) remapped the palette to OKLCH semantic tokens;
red-* is replaced by error-* (AppAlert's own error variant idiom). The
new #149 callback page still used the legacy red-* classes -- swap to
bg/text/border-error-* so it renders correctly under the remapped dark
palette. (The Google/WeChat login buttons already match: #148 kept the
GitHub button's neutral-* classes, and the neutral ramp is remapped in
place.)
The WSL report (CREATE DATABASE permission denied) exposed that the
scripts diagnosed nothing: DROP swallows every error by design, and the
CREATE failure printed one generic hint regardless of cause. Now every
root cause gets detected and its exact fix printed (sh), or a
message-matched fix table (bat):

  1. server unreachable  -> pg_isready exit-code probe (sh); connect-error
     table entry (bat)
  2. wrong password / missing role -> login probe; PostgreSQL answers both
     with the SAME error (anti-enumeration), so one fix block covers both
     (check FULLA_DB_PASSWORD, else CREATE ROLE from a superuser shell)
  3. role lacks CREATEDB -> rolcreatedb query; sh self-heals once via
     'sudo -u postgres psql' (peer auth, typical on Linux/WSL) and retries,
     else prints ALTER ROLE (native + docker forms)
  4. database exists and could not be dropped (open connection, e.g. a
     running fulla-server) -> detected by querying pg_database (NOT by
     message text -- localized Windows installs report it in GBK); prints
     the DROP ... WITH (FORCE) escape hatch

Implementation notes: classification is driven by exit codes and SQL
results only (psql message text is localized on Windows and LC_MESSAGES
cannot override the bundled catalog); probe SQL goes through stdin with
:'variable' interpolation (psql -c does not interpolate, keeping the
query parameterized); set -e is suspended around probes (a failed probe
is data, not an abort -- the first cut silently died there).

Verified locally by injecting each failure: wrong user, wrong password,
wrong port, and a pg_sleep session holding the database (both scripts
print the matching fix and exit non-zero; normal path unaffected).
When CREATE reports the database still exists, the suppressed DROP
failed for one of two reasons: an open connection, or the database's
owner is not the configured role (DROP needs ownership). Both share the
same superuser DROP ... WITH (FORCE) escape hatch; say both so the
operator is not sent hunting for a connection that does not exist.
…e sweep, signCount CAS, client registration check

External review of the branch (7 findings) — all verified real against
the code before fixing:

[Medium] crossOrigin=true parsed but never enforced (L2 7.1 step 9 /
6.1 step 5): this RP declares no cross-origin support (strict origin
allowlist), so a ceremony driven inside a cross-origin iframe — the
phishing vector the field exists to surface — must be rejected. Both
finish paths now fail on crossOriginPresent && crossOrigin (registration
side: WEBAUTHN_CHALLENGE_MISMATCH; assertion side: the generic
rejection). New e2e: same-key VALID signature with crossOrigin=true
answers 401.

[Low] registration-challenge map never reclaimed entries for subjects
that begin but never finish (TTL rejected, never erased). Lazy sweep on
every issue (O(live subjects)); header comment's 'TTL-bound' claim
corrected to say what it actually does.

[Low] signCount clone check was read-compare-then-async-update: two
concurrent assertions with the same counter both passed. Now an atomic
compare-and-set via the new additive IWebAuthnRepository::
updateSignCountIfCurrent (PG: conditional UPDATE ... RETURNING 1 —
Result::size() is 0 without RETURNING, caught by the e2e suite; losing
the CAS = concurrent assertion of the same credential = clone/replay
evidence -> reject; both-zero counters skip the write, the legal
no-counter case). Interface default keeps in-memory fakes working.

[Low] SocialTokenIssuer minted tokens for social_token_client_id without
checking the client is REGISTERED — a typo'd id silently produced
tokens no introspection/refresh path could resolve. getClient gate
before issuance (INTERNAL_ERROR + LOG_ERROR when unregistered);
first-party-ness stays an operator contract (no data-model flag), as
documented.

[Info] assertion-side audit/response now carries the server-normalized
credential id (WebAuthnAuthResult.credentialId) instead of the
client-submitted encoding. Registration-side response keeps echoing the
client's id (harmless, client-chosen label of its own credential).

Verified: full_test 8/8 steps, 584/584 ctest x2 configs, 55/55 admin
endpoints; identity 231/231; static gates green; api-diff additive
seams re-ratified (184 headers).
@voidvec
voidvec force-pushed the fix/p0-issues-143-103-70-142 branch from ea1f62d to 7fe3123 Compare September 1, 2026 04:47
@voidvec
voidvec merged commit a06d39c into master Sep 1, 2026
16 checks passed
voidvec added a commit that referenced this pull request Sep 1, 2026
…me, passkey liveness gate, UV alignment

B-1 (BLOCKER): the username-collision retry in AccountLinkFlow held its
self-referencing attempt function via weak_ptr only; with the fully
async production repository the initiating stack frame is gone when the
INSERT round-trip returns, so the retry (and the terminal error path)
silently dropped — the request hung until client timeout. The shared
synchronous test fake masked exactly this shape. Rewritten as a free
function recursing through a shared AttemptContext: the in-flight
repository callback strongly owns the context, the chain stays alive
across every round-trip, and all owners drop on the terminal branches.
Pinned by two new DeferredSocialAccountRepository tests that queue every
callback and drain it only AFTER login() returned (230/230 identity
tests).

M-1 (MAJOR): findByCredentialId now enforces user liveness on the
passkey path — soft-deleted (deleted_at IS NULL filter) and locked
(locked_until > now -> generic nullopt) users can no longer authenticate
via /oauth2/webauthn/authenticate/finish; parity with the password and
social paths (V024/#54 'disabled means cannot log in through ANY flow').

Minor: registration finish enforces UV=1 too (begin advertises required;
a UV-less registration would mint a credential that can never
authenticate); authenticateBegin mints ONE challenge instead of two
(the old path discarded a CSPRNG draw); the three remaining bare Mapper
constructions in PostgresWebAuthnRepository wrapped per
db-operations.md rule 1; subject-mapping backfill now RETURNING-counted
so the heal log is truthful.

Full suite re-verified after the fixes: full_test 8/8 steps, 583/583
ctest x2 configs, 55/55 admin endpoint scripts; identity 230/230;
static gates re-run green (api-diff/migration/arch/naming/
spec-governance/clients-sdk).
voidvec added a commit that referenced this pull request Sep 1, 2026
…148 token system

PR #148 (Machined Trust) remapped the palette to OKLCH semantic tokens;
red-* is replaced by error-* (AppAlert's own error variant idiom). The
new #149 callback page still used the legacy red-* classes -- swap to
bg/text/border-error-* so it renders correctly under the remapped dark
palette. (The Google/WeChat login buttons already match: #148 kept the
GitHub button's neutral-* classes, and the neutral ramp is remapped in
place.)
@voidvec
voidvec deleted the fix/p0-issues-143-103-70-142 branch September 2, 2026 05:27
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