Repository navigation
feat: 错误码与错误信息标准化(前后端统一 Error Envelope) - #3
Merged
Merged
Conversation
… and frontend Introduce a single source-of-truth ErrorCatalog and unified Error Envelope for all Application_Endpoints, while keeping OAuth2 protocol endpoints RFC 6749 compliant. Backend (OAuth2Plugin/OAuth2Server): - Add ErrorCatalog (14 app codes + 12 OAuth2 protocol codes) with startup validateInvariants() fail-fast self-check - Refactor Error/ErrorTypes to string code, catalog-driven HTTP status, Envelope toJson, fromCode/fromException - Add RequestId (reuse X-Request-ID, UUID fallback), ErrorContext (production-mode gate), ErrorResponder (unified entry) - Make OAuth2ErrorHandler catalog-driven + WWW-Authenticate; HttpResponder emits VALIDATION envelope - Global exception handler in main.cc splits by path + wires Catalog self-check; migrate 15 controllers off ad-hoc formats Frontend (OAuth2Frontend/OAuth2Admin): - Add shared errorAdapter (normalizeError, never throws) + Error_Message_Catalog_FE (zh-CN) - Migrate interceptors and views/pages, remove native alert, wire 401 refresh-failure flows Docs/tests/CI: - Generate/validate api-reference error-code section from the catalog - Add 14 property tests, regression/example tests, endpoint-level integration tests, golden snapshots - Wire CI gating into ci-linux.yml and ci-windows.yml Verified: backend 200 test cases / 55629 assertions pass; frontend OAuth2Frontend 15 + OAuth2Admin 2 tests pass.
After the error-code-message-standardization feature, the frontend no longer displays the backend's raw error_description; it maps error.code to a localized message via the shared catalog. Update the login-failure e2e mocks to return the unified Error Envelope ({ error: { code: AUTH_INVALID_CREDENTIALS, ... } }) the real backend now returns, and assert the localized message '用户名或密码错误' instead of the legacy English 'Invalid username or password'.
- OAuth2Frontend: mock-api login-failure response + auth.spec assertion
- OAuth2Admin: inline login-failure mock + auth.spec assertion
Verified: OAuth2Frontend 48 e2e pass, OAuth2Admin 123 pass / 6 skipped, 0 failures.
The error-code-message-standardization migration routed controller 'resource not found' (404) and 'name already exists' (409) errors through ErrorResponder, where the catalog forced VALIDATION->400 and DB_CONSTRAINT_VIOLATION->500, dropping the pre-migration HTTP status semantics (violating Requirement 11.4). Fix (option A): let ErrorCatalog entries carry an explicit per-entry httpStatus override, and add two resource-oriented VALIDATION codes: - VALIDATION_RESOURCE_NOT_FOUND (3004, VALIDATION, 404) - VALIDATION_RESOURCE_CONFLICT (3005, VALIDATION, 409) Restore the pre-migration statuses by routing the not-found/conflict branches to the new codes across AdminController (16 not-found + 2 conflict), OrganizationController (1+1), UserSelfServiceController (4), EmailVerificationController (1), ApiDocController (2). Add 404/409 to ErrorResponder::toDrogonStatus. Update api-reference.md 5.1, the shared FE message catalogs (both apps), and the FE code-coverage property tests. Relax Property 4 so category-default and same-category-consistency sub-assertions apply only to non-overridden entries, while the runtime==catalog assertion still holds for all entries. Verified: OAuth2Test_test 200 cases / 55815 assertions pass; FE OAuth2Frontend 15 + OAuth2Admin 2 unit tests pass; live endpoint scripts ALL PASSED — test-admin-endpoints Test 3/14/23/28/36 -> 404, Test 20/29 -> 409, Test 37 -> 400; test-oauth2-endpoints 17/17.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6f6b894cdf
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Owner
Author
Code reviewFound 3 issues:
🤖 Generated with Claude Code - If this code review was useful, please react with 👍. Otherwise, react with 👎. |
问题: - OAuth2Admin构建时无法解析errorAdapter模块 - 缺少vue核心依赖 - 使用不稳定的Vite 8.x版本 - 相对路径导入在生产构建中失败 修复: - 添加vue ^3.5.0依赖到package.json - 将Vite从8.x降级到6.x,与OAuth2Frontend保持一致 - 配置vite.config.ts添加@路径别名指向src目录 - 更新tsconfig.json添加路径映射支持 - 将所有errorAdapter导入改为@/services/errorAdapter 测试: - ✅ 前端E2E测试: 48个通过 - ✅ 前端单元测试: 15个通过 - ✅ 后端测试: OAuth2Tests通过 - ✅ OAuth2Admin构建成功 (1.01秒) 影响范围: - OAuth2Admin构建配置和模块导入 - 错误消息目录同步更新 - 测试用例更新以验证错误处理
问题: - full_test_docker.bat脚本找不到docker-compose.yml文件 - 脚本期望文件在项目根目录,但实际在deploy/docker目录 修复: - 更新full_test_docker.bat中所有docker-compose.yml引用为deploy\docker\docker-compose.yml - 修复cleanup-docker.sh中的路径引用 - 共更新4处引用位置 验证: - ✓ Docker容器能正常启动 - ✓ PostgreSQL和Redis服务就绪 - ✓ 数据库初始化成功
问题: - docker-compose.yml使用相对路径导致构建失败 - context设为当前目录(.),但dockerfile路径又包含deploy/docker - 导致Docker在deploy/docker/deploy/docker查找文件 修复: - 将context路径改为../../(指向项目根目录) - 将OAuth2Admin的context改为../../OAuth2Admin - 更新所有volume挂载路径使用相对路径 - 修正prometheus配置文件路径为../observability/prometheus.yml 验证: - ✓ docker-compose config验证通过 - ✓ 所有路径映射正确 - ✓ PostgreSQL和Redis服务启动成功
修复docker-compose.debug.yml: - 更新项目挂载路径为../..(从deploy/docker指向项目根目录) 修复docker-compose.prod.yml: - 更新所有构建context为../.. - 修正OAuth2Admin的context为../../OAuth2Admin - 更新nginx配置文件路径为../../deploy/nginx - 修正所有volume挂载路径 - 更新prometheus配置路径为../observability/prometheus.yml 验证结果: - ✓ docker-compose.yml配置有效(6个服务) - ✓ docker-compose.debug.yml配置有效(3个服务) - ✓ docker-compose.prod.yml配置有效(7个服务) - ✓ 所有路径映射正确 注意: - prod配置需要环境变量文件,请参考文件顶部的使用说明
主要更新: 1. 修正所有docker-compose命令路径 - 更新为: docker-compose -f deploy/docker/docker-compose.yml - 明确说明需要在项目根目录执行 2. 新增配置文件说明表格 - docker-compose.yml (标准开发环境, 6个服务) - docker-compose.debug.yml (调试环境, 3个服务) - docker-compose.prod.yml (生产环境, 7个服务含Nginx) 3. 扩展使用场景 - 4.1 本地开发(推荐)- Docker数据库+本地后端前端 - 4.2 完整集成测试 - 全Docker栈 - 4.3 调试模式 - GDB调试 4. 新增常见问题排查 - 路径问题 - 端口冲突 - 数据库连接失败 - 性能优化建议 5. 添加快速参考章节 - 常用命令速查 - 服务端口映射表 版本: 2.1.0 -> 2.2.0
Owner
Author
resolved |
wangrh0909
approved these changes
Jun 4, 2026
voidvec
added a commit
that referenced
this pull request
Jul 29, 2026
…) + comment #4/#8/#9 P1 #6 (RFC 6749 §5.1): expires_in / id_token exp / device refresh TTL were hardcoded 3600/2592000; now use configured access_token_ttl/refresh_token_ttl (OAuth2Plugin getAccessTokenTtl()/getRefreshTokenTtl() accessors). 6 sites: TokenService auth_code expires_in + id_token exp + refresh expires_in; client_credentials + device_code issuance in TokenEndpointController. P1 #5 (RFC 8628 §3.4): device_code redemption now authenticates by client_type -- CONFIDENTIAL clients require a valid client_secret (validateClient); PUBLIC clients keep the client_id-vs-device-row binding. Lookup wrapped in a local lambda captured BY VALUE (not [&]) because it runs from getClient's async callback after token() has returned -- [&] would dangle deviceCodeHash/dbClient. P1 #3 (RFC 6749 §4.1.2 single-use): device-code redemption check-then-delete was non-atomic (two concurrent redemptions both issued). Replaced with a pre-issue atomic UPDATE...WHERE status='approved' RETURNING; affected-row gate makes exactly one concurrent winner issue, loser gets invalid_grant (fail- closed). UPDATE...RETURNING is a db-operations.md raw-SQL exemption. Comment-only (#4 [this] capture, #8 validateAccessToken no-self, #9 JWKS empty response): document existing-correct behavior, deter repeat review reports. Tests (live-server integration, PG+Redis): TokenExpiryTtlConfigTest, DeviceCodeClientAuthTest (conf no-secret rejects / conf secret ok / pub ok), DeviceCodeRaceConditionTest (concurrent redemption -> exactly one wins). All pass + no regressions (RFC6749 compliance 4504 assertions, auth_code E2E, refresh rotation, authorize PKCE passthrough). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
voidvec
added a commit
that referenced
this pull request
Aug 9, 2026
Addresses the actionable items from the PR #44 code review (benchmark review intentionally excluded). MINOR #1 (RateLimiter unbounded memory growth): RateLimiter.purgeOldLocked only ran for the accessed key, so attacker keys recording one failure and never touched again lingered indefinitely -> unbounded map growth under a distributed attack. Added RateLimiterConfig.maxBuckets (default 10000) and a sweepLocked() full purge triggered in recordFailure when the bucket count exceeds the cap (drops every bucket with no in-window failures). Triggered on the growth path, not the hot checkThrottled path. MINOR #2 (scope.find("openid") substring vs token match): userInfo + the device id_token path used scope.find("openid") (substring), inconsistent with the new hasScope() token match and susceptible to a `myopenid`-style false positive. Converted the two libs/drogon sites to hasScope(); for TokenService (libs/oauth2, cannot depend on libs/drogon) added a framework-free scopeContains() in the anonymous namespace and converted the auth-code + refresh id_token-issuance sites. MINOR #3 (Postgres LOG_DEBUG match result): removed the "Secret validation PASSED/FAILED" LOG_DEBUG to match the Redis path's F-004 removal (the match result is already observable via the HTTP status, so this is a uniformity fix, not a timing-side-channel fix). NIT #5 (error param urlEncode): buildAuthorizeErrorRedirect now urlEncodes the `error` param for defensive consistency with error_description/state. MINOR #4 (refresh_token double getClient): intentionally NOT fixed in this PR -- the reviewer flagged it as a non-blocking perf opportunity (redundant DB round-trip). Threading the client optional through dispatchGrant is invasive; deferred. Verified: build GREEN with AUTHFORGE_WERROR=ON (CI parity); manage.ps1 test-backend = 456/456; api-diff OK (additive RateLimiter declarations ratified at v1.0.0).
voidvec
added a commit
that referenced
this pull request
Aug 9, 2026
…og parity Addresses the round-2 review findings (the round-1 MINOR #1 fix had a hole; MINOR #3 parity was incomplete). Round-2 NEW #1 (RateLimiter cap bypassed via checkThrottled): The round-1 fix only ran sweepLocked() in recordFailure, but checkThrottled uses buckets_[key] (operator[] inserts an empty bucket for each new key). An attacker spamming unique (ip, client_id) keys through checkThrottled -- the hot pre-auth path -- WITHOUT ever triggering a failure grew buckets_ without bound; maxBuckets never tripped. Two-part fix: - checkThrottled now detects the new-insert case and runs sweepLocked() when the bucket count exceeds the cap (covers the no-failure growth vector). - sweepLocked now ENFORCES the cap: after purging expired/empty buckets, if the count still exceeds maxBuckets (many keys each holding in-window failures under a distributed attack), it evicts buckets by oldest most-recent failure until under cap. Previously it only dropped empties, so a real attack with non-empty buckets still grew unbounded. Round-2 NEW #2 (Memory log parity incomplete): removed the MemoryClientRepo "Secret validation PASSED/FAILED" LOG_DEBUG to match the Postgres (round-1) and Redis (F-004) removals. Now all three backends are consistent. Added a unit test (Unit_P1_Utils_RateLimiter_CapBoundedOnCheckThrottledInsert) that drives 200 unique keys through checkThrottled with no failures and a maxBuckets=10 cap, then 50 distinct failed keys + an insert, asserting the limiter stays functional and never spuriously throttles a never-failed key. Verified: build GREEN with AUTHFORGE_WERROR=ON (fixed a TimePoint::max() Windows-macro build error with (TimePoint::max)() along the way); manage.ps1 test-backend = 456/456 (incl. the new test's 4 assertions).
voidvec
added a commit
that referenced
this pull request
Aug 9, 2026
Addresses the actionable items from the PR #44 code review (benchmark review intentionally excluded). MINOR #1 (RateLimiter unbounded memory growth): RateLimiter.purgeOldLocked only ran for the accessed key, so attacker keys recording one failure and never touched again lingered indefinitely -> unbounded map growth under a distributed attack. Added RateLimiterConfig.maxBuckets (default 10000) and a sweepLocked() full purge triggered in recordFailure when the bucket count exceeds the cap (drops every bucket with no in-window failures). Triggered on the growth path, not the hot checkThrottled path. MINOR #2 (scope.find("openid") substring vs token match): userInfo + the device id_token path used scope.find("openid") (substring), inconsistent with the new hasScope() token match and susceptible to a `myopenid`-style false positive. Converted the two libs/drogon sites to hasScope(); for TokenService (libs/oauth2, cannot depend on libs/drogon) added a framework-free scopeContains() in the anonymous namespace and converted the auth-code + refresh id_token-issuance sites. MINOR #3 (Postgres LOG_DEBUG match result): removed the "Secret validation PASSED/FAILED" LOG_DEBUG to match the Redis path's F-004 removal (the match result is already observable via the HTTP status, so this is a uniformity fix, not a timing-side-channel fix). NIT #5 (error param urlEncode): buildAuthorizeErrorRedirect now urlEncodes the `error` param for defensive consistency with error_description/state. MINOR #4 (refresh_token double getClient): intentionally NOT fixed in this PR -- the reviewer flagged it as a non-blocking perf opportunity (redundant DB round-trip). Threading the client optional through dispatchGrant is invasive; deferred. Verified: build GREEN with AUTHFORGE_WERROR=ON (CI parity); manage.ps1 test-backend = 456/456; api-diff OK (additive RateLimiter declarations ratified at v1.0.0).
voidvec
added a commit
that referenced
this pull request
Aug 9, 2026
…og parity Addresses the round-2 review findings (the round-1 MINOR #1 fix had a hole; MINOR #3 parity was incomplete). Round-2 NEW #1 (RateLimiter cap bypassed via checkThrottled): The round-1 fix only ran sweepLocked() in recordFailure, but checkThrottled uses buckets_[key] (operator[] inserts an empty bucket for each new key). An attacker spamming unique (ip, client_id) keys through checkThrottled -- the hot pre-auth path -- WITHOUT ever triggering a failure grew buckets_ without bound; maxBuckets never tripped. Two-part fix: - checkThrottled now detects the new-insert case and runs sweepLocked() when the bucket count exceeds the cap (covers the no-failure growth vector). - sweepLocked now ENFORCES the cap: after purging expired/empty buckets, if the count still exceeds maxBuckets (many keys each holding in-window failures under a distributed attack), it evicts buckets by oldest most-recent failure until under cap. Previously it only dropped empties, so a real attack with non-empty buckets still grew unbounded. Round-2 NEW #2 (Memory log parity incomplete): removed the MemoryClientRepo "Secret validation PASSED/FAILED" LOG_DEBUG to match the Postgres (round-1) and Redis (F-004) removals. Now all three backends are consistent. Added a unit test (Unit_P1_Utils_RateLimiter_CapBoundedOnCheckThrottledInsert) that drives 200 unique keys through checkThrottled with no failures and a maxBuckets=10 cap, then 50 distinct failed keys + an insert, asserting the limiter stays functional and never spuriously throttles a never-failed key. Verified: build GREEN with AUTHFORGE_WERROR=ON (fixed a TimePoint::max() Windows-macro build error with (TimePoint::max)() along the way); manage.ps1 test-backend = 456/456 (incl. the new test's 4 assertions).
voidvec
added a commit
that referenced
this pull request
Aug 11, 2026
… hardening
Codex P1 (REAL, design-doc correctness fix): the design doc §5.4 wrongly
claimed 'no client write path exists today'. Verified ClientManagementService
exposes 4 runtime admin mutation paths (updateClient :280, resetClientSecret
:414, updateClientScopes :517, deleteClient :373) that bypass IClientRepository.
When cache.enabled=true these mutate Oauth2Clients directly without
invalidating authforge:cache:client:{clientId} → stale client served for up
to 300s TTL. Corrected §5.4 + added §8 risk row. Phase-1 mitigation:
cache.enabled defaults false; invalidation hooks are a tracked follow-up.
Owner #2 (REAL): cache.enabled=true + non-postgres storage was a silent no-op.
Added LOG_WARN in both the redis and memory branches so operators see the
cache is ignored.
Owner #1 (partly-fabricated API, but valid kernel): the reviewer's
fromJson()/cached.id API does not exist, but the defense-in-depth idea is
sound — deserializeClient now rejects a structurally-valid-but-empty clientId
as a miss (blank client would mask the real backing entry).
Owner #3 (style): emitMetric's opaque outcome[0] char dispatch replaced with
explicit std::string_view compare (survives label renames).
Full suite: 461 cases / 57331 assertions, all green.
voidvec
added a commit
that referenced
this pull request
Aug 12, 2026
… hardening
Codex P1 (REAL, design-doc correctness fix): the design doc §5.4 wrongly
claimed 'no client write path exists today'. Verified ClientManagementService
exposes 4 runtime admin mutation paths (updateClient :280, resetClientSecret
:414, updateClientScopes :517, deleteClient :373) that bypass IClientRepository.
When cache.enabled=true these mutate Oauth2Clients directly without
invalidating authforge:cache:client:{clientId} → stale client served for up
to 300s TTL. Corrected §5.4 + added §8 risk row. Phase-1 mitigation:
cache.enabled defaults false; invalidation hooks are a tracked follow-up.
Owner #2 (REAL): cache.enabled=true + non-postgres storage was a silent no-op.
Added LOG_WARN in both the redis and memory branches so operators see the
cache is ignored.
Owner #1 (partly-fabricated API, but valid kernel): the reviewer's
fromJson()/cached.id API does not exist, but the defense-in-depth idea is
sound — deserializeClient now rejects a structurally-valid-but-empty clientId
as a miss (blank client would mask the real backing entry).
Owner #3 (style): emitMetric's opaque outcome[0] char dispatch replaced with
explicit std::string_view compare (survives label renames).
Full suite: 461 cases / 57331 assertions, all green.
voidvec
added a commit
that referenced
this pull request
Aug 14, 2026
… fixes Critical #1: soft-deleted users can no longer log in - PostgresIdentityRepository: add deleted_at IS NULL filter to findByEmail, findByUsername, findById, findByPublicSub, getUserInfoWithRoles, getRoles(subject) — blocks login, userinfo, and token-issuance role resolution - deleteUser: revoke all access + refresh tokens for the deleted user (introspection/refresh copy subject from token rows, never query users) High #2: getUser now returns org_id in the response JSON Medium #3: listUsers search escapes LIKE wildcards (%/_) in query param q Medium #5: createUser/updateUser guard org_id/locked type coercion with isInt()/isBool() to prevent uncaught Json::LogicError in async callbacks Medium #6: deleteUser rejects self-deletion (admin cannot delete own account)
voidvec
added a commit
that referenced
this pull request
Aug 14, 2026
… fixes Critical #1: soft-deleted users can no longer log in - PostgresIdentityRepository: add deleted_at IS NULL filter to findByEmail, findByUsername, findById, findByPublicSub, getUserInfoWithRoles, getRoles(subject) — blocks login, userinfo, and token-issuance role resolution - deleteUser: revoke all access + refresh tokens for the deleted user (introspection/refresh copy subject from token rows, never query users) High #2: getUser now returns org_id in the response JSON Medium #3: listUsers search escapes LIKE wildcards (%/_) in query param q Medium #5: createUser/updateUser guard org_id/locked type coercion with isInt()/isBool() to prevent uncaught Json::LogicError in async callbacks Medium #6: deleteUser rejects self-deletion (admin cannot delete own account)
voidvec
added a commit
that referenced
this pull request
Aug 22, 2026
…; mitigation + validated guidance delivered Rewrites the investigation report's conclusion: the 'unbounded leak' verdict is RETRACTED — post-TTL heap profiling shows live allocations collapse 106MB -> 15MB after the session_timeout window (eviction works); the earlier 'no decay' observations never crossed the TTL boundary (3600s >> test horizon). Final numbers (real build, same-window controlled): - retention ~1.1KB per cookie-less request until TTL (steady state = QPS x session_timeout x 1.1KB) - discovery throughput tax -24% at ANY TTL (OFF/ON/OFF: 30.6k/23.2k/30.2k) - comparison-table 5,350MiB = 5.4M S1-storm sessions Delivered: bench TTL=30 (e13041f), validated deployment guidance with sizing table (deployment.md perf-tuning #3), ready-to-file upstream issue (upstream-drogon-session-issue.md; gh auth expired — one command once restored), diagnostic facilities kept in-tree (SIGUSR1 LSan/heap hook behind AUTHFORGE_LEAK_DIAG, leak-isolation.lua probe scenario). Pending: four-product comparison refresh on the TTL=30 profile (good machine window), research.md heaviest-stack warning update after it.
voidvec
added a commit
that referenced
this pull request
Aug 22, 2026
…; mitigation + validated guidance delivered Rewrites the investigation report's conclusion: the 'unbounded leak' verdict is RETRACTED — post-TTL heap profiling shows live allocations collapse 106MB -> 15MB after the session_timeout window (eviction works); the earlier 'no decay' observations never crossed the TTL boundary (3600s >> test horizon). Final numbers (real build, same-window controlled): - retention ~1.1KB per cookie-less request until TTL (steady state = QPS x session_timeout x 1.1KB) - discovery throughput tax -24% at ANY TTL (OFF/ON/OFF: 30.6k/23.2k/30.2k) - comparison-table 5,350MiB = 5.4M S1-storm sessions Delivered: bench TTL=30 (e13041f), validated deployment guidance with sizing table (deployment.md perf-tuning #3), ready-to-file upstream issue (upstream-drogon-session-issue.md; gh auth expired — one command once restored), diagnostic facilities kept in-tree (SIGUSR1 LSan/heap hook behind AUTHFORGE_LEAK_DIAG, leak-isolation.lua probe scenario). Pending: four-product comparison refresh on the TTL=30 profile (good machine window), research.md heaviest-stack warning update after it.
voidvec
added a commit
that referenced
this pull request
Aug 22, 2026
…; mitigation + validated guidance delivered Rewrites the investigation report's conclusion: the 'unbounded leak' verdict is RETRACTED — post-TTL heap profiling shows live allocations collapse 106MB -> 15MB after the session_timeout window (eviction works); the earlier 'no decay' observations never crossed the TTL boundary (3600s >> test horizon). Final numbers (real build, same-window controlled): - retention ~1.1KB per cookie-less request until TTL (steady state = QPS x session_timeout x 1.1KB) - discovery throughput tax -24% at ANY TTL (OFF/ON/OFF: 30.6k/23.2k/30.2k) - comparison-table 5,350MiB = 5.4M S1-storm sessions Delivered: bench TTL=30 (e13041f), validated deployment guidance with sizing table (deployment.md perf-tuning #3), ready-to-file upstream issue (upstream-drogon-session-issue.md; gh auth expired — one command once restored), diagnostic facilities kept in-tree (SIGUSR1 LSan/heap hook behind AUTHFORGE_LEAK_DIAG, leak-isolation.lua probe scenario). Pending: four-product comparison refresh on the TTL=30 profile (good machine window), research.md heaviest-stack warning update after it.
voidvec
added a commit
that referenced
this pull request
Aug 30, 2026
…loor, bootstrap self-heal, review cleanups Address PR #141 review (1 must-fix, 8 should-fix, quick considers): - #1 consent_csrf declared as a required query parameter in openapi.yaml and the C++ endpoint doc registration; apps/server/docs/api/openapi.json regenerated from a live server run; Python/Go clients regenerated. - #2 nonce one-shot is now atomic: the find/verify/erase sequence is serialized by a process-wide mutex (consent traffic is tiny; in-process session storage). - #3 identity AuthService no longer captures this in the async validateUser callback — the legacy-hash policy flag is value-captured (db-operations rule 4). - #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin user row is reused and role/mapping completed (partial failures self-heal on restart); the random password is printed only after the insert succeeded; a mapping failure no longer reports created=true. - #5 POST /api/admin/users enforces auth.min_password_length (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass. - #6 consent integration tests reworked: missing-nonce now drives the real authorize-minted slot (400), deny-to-unregistered-uri (400, no Location) and deny-to-registered-uri (302 access_denied) branches are covered. - #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT removed (PBKDF2 keeps salt empty); website i18n error table mirrored (3014/4007). - #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on failure instead of a single silent 2s probe. - #13 unique-violation detection layered (SqlError 23505 -> constraint name -> english/zh localized text), mirroring the PostgresSocialAccountRepository pattern. - #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged; #17 AGENTS.md consent.csp entry removed. Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14 admin UI hardcode (server now enforces; hint stays), #18 MFA-pending session through consent (pre-existing authorize behavior, tracked).
voidvec
added a commit
that referenced
this pull request
Aug 30, 2026
…loor, bootstrap self-heal, review cleanups Address PR #141 review (1 must-fix, 8 should-fix, quick considers): - #1 consent_csrf declared as a required query parameter in openapi.yaml and the C++ endpoint doc registration; apps/server/docs/api/openapi.json regenerated from a live server run; Python/Go clients regenerated. - #2 nonce one-shot is now atomic: the find/verify/erase sequence is serialized by a process-wide mutex (consent traffic is tiny; in-process session storage). - #3 identity AuthService no longer captures this in the async validateUser callback — the legacy-hash policy flag is value-captured (db-operations rule 4). - #4/#12 AdminBootstrapper reworked as ensure-* steps: an existing admin user row is reused and role/mapping completed (partial failures self-heal on restart); the random password is printed only after the insert succeeded; a mapping failure no longer reports created=true. - #5 POST /api/admin/users enforces auth.min_password_length (VALIDATION_PASSWORD_TOO_SHORT) — closing the admin bypass. - #6 consent integration tests reworked: missing-nonce now drives the real authorize-minted slot (400), deny-to-unregistered-uri (400, no Location) and deny-to-registered-uri (302 access_denied) branches are covered. - #7/#8 deployment.md: auto-bootstrap wording fixed, bogus ADMIN_SALT removed (PBKDF2 keeps salt empty); website i18n error table mirrored (3014/4007). - #9 main.cc bootstrap probes with backoff (5 attempts) and LOG_WARN on failure instead of a single silent 2s probe. - #13 unique-violation detection layered (SqlError 23505 -> constraint name -> english/zh localized text), mirroring the PostgresSocialAccountRepository pattern. - #11 gate-4 comment corrected; #15 CHANGELOG duplicate Unreleased merged; #17 AGENTS.md consent.csp entry removed. Considered-but-not-taken: #10 multi-slot nonces (tracked follow-up), #14 admin UI hardcode (server now enforces; hint stays), #18 MFA-pending session through consent (pre-existing authorize behavior, tracked).
voidvec
added a commit
that referenced
this pull request
Nov 9, 2026
…m connector-teardown race First tsan-nightly findings, round 2 (after the trantor suppressions took effect): 1. FIRST-PARTY race in OAuth2Plugin (fixed, not suppressed): initAndStart issues the admin-scope DB load via initStorage at :75, but constructs authorizationService_ ~150 lines later — the DbLoop callback (OAuth2Plugin.cc:718) read the member unsynchronized AND its if (authorizationService_) guard silently DROPPED the DB-loaded set when the callback won the race, falling back to the hardcoded default set (wrong admin-gate semantics for any deployment with non-default oauth2_scopes.requires_admin_role rows). Fix: mutex-ordered handshake — the callback stashes the set as pendingAdminScopes_ when the service does not exist yet; the construction site assigns the member AND flushes the stash under the same lock. IdentityService's static admin-class set is updated before the lock (unchanged behavior). 2. Upstream race suppressed with evidence (drogon/trantor frames only on both stacks): HttpRequestImpl dtor clearing the headers map vs trantor Connector::handleWrite still reading it during the full-stack smoke host teardown. tools/sanitizers/tsan.supp extended (#3); the triage-policy footer now points at this commit's first-party fix as the example of fix-not-suppress.
voidvec
added a commit
that referenced
this pull request
Nov 9, 2026
…(coverage gate green); admin-scope handshake race; tsan suppressions (#320) * fix(ci): first-nightly triage — ctest lookahead regex never matched; tsan suppressions for trantor races Both nightlies fired for the first time 2026-11-08 (new cron triggers, ~7h GitHub schedule delay) and both failed. Root causes are INHERITED defects the first real runs exposed: 1. Coverage gate leg (run 42472349551): the 'everything else' ctest filter -R '^(?!.*OAuth2Tests).*$' NEVER matched anything — ctest's regex engine (cmsys) cannot compile negative lookahead ('?+* follows nothing'), it matched zero tests, printed 'No tests were found!!!' and still EXITED 0. The 512 non-monolithic tests (every Contract repository test included) never executed on ANY coverage run since the pattern's introduction; the ratchet then read the missing library-layer data as regressions (identity 87.1->63.0, oauth2 88.8->74.4, common 74.3->66.1 — matching the v1.6.0-era partial-data signature exactly, now explained). Fix: POSIX-safe ctest -E '^OAuth2Tests$' exclude flag; evidence recorded in a comment at the call site. 2. tsan-nightly (run 42469207432): first genuine TSan run ever (the job had been dispatch-only since creation — the referenced suppression file never existed). Both findings are trantor-internal (Drogon's event-loop library): EventLoop::wakeup()'s cross-thread eventfd write vs createEventfd() setup, and MpscQueue's producer- side std::function move vs consumer read — the queue's publication protocol is the intended synchronization. Per the workflow's own triage policy these get documented suppressions: new tools/sanitizers/tsan.supp (per-race evidence + dated + the first-party-findings-are-fixed-not-suppressed rule), wired into TSAN_OPTIONS at both the job and ctest-step scopes via a workspace-absolute path. Verification: workflow_dispatch of both workflows on this branch — the gate leg now runs the full 513-test suite (ratchet verdict on complete data), tsan re-runs with suppressions to surface whatever genuine findings remain. * fix(plugin): admin-scope handshake race (TSan) + suppress the upstream connector-teardown race First tsan-nightly findings, round 2 (after the trantor suppressions took effect): 1. FIRST-PARTY race in OAuth2Plugin (fixed, not suppressed): initAndStart issues the admin-scope DB load via initStorage at :75, but constructs authorizationService_ ~150 lines later — the DbLoop callback (OAuth2Plugin.cc:718) read the member unsynchronized AND its if (authorizationService_) guard silently DROPPED the DB-loaded set when the callback won the race, falling back to the hardcoded default set (wrong admin-gate semantics for any deployment with non-default oauth2_scopes.requires_admin_role rows). Fix: mutex-ordered handshake — the callback stashes the set as pendingAdminScopes_ when the service does not exist yet; the construction site assigns the member AND flushes the stash under the same lock. IdentityService's static admin-class set is updated before the lock (unchanged behavior). 2. Upstream race suppressed with evidence (drogon/trantor frames only on both stacks): HttpRequestImpl dtor clearing the headers map vs trantor Connector::handleWrite still reading it during the full-stack smoke host teardown. tools/sanitizers/tsan.supp extended (#3); the triage-policy footer now points at this commit's first-party fix as the example of fix-not-suppress. * docs(changelog): Unreleased entries for the nightly-first-run triage * chore(api): ratify the additive OAuth2Plugin members (private handshake state)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
概述
统一 OAuth2 平台前后端的错误码与错误信息机制:建立单一权威来源的错误码目录(ErrorCatalog)与统一的 Error Envelope,前端经共享 errorAdapter 将错误码映射为本地化用户信息;同时保持 OAuth2 协议端点的 RFC 6749 §5.2 合规与既有 HTTP 状态码语义。
后端(OAuth2Plugin / OAuth2Server)
ErrorCatalog(单一权威来源):登记 16 个应用错误码 + 12 个 OAuth2 协议码,启动期validateInvariants()fail-fast 自检;支持条目级 httpStatus 显式覆盖。Error/ErrorTypes:字符串code、Catalog 驱动的 HTTP 状态码、Error EnvelopetoJson、fromCode/fromException。RequestId(复用X-Request-ID,UUID 兜底)、ErrorContext(生产模式判定)、ErrorResponder(Application 统一入口)。OAuth2ErrorHandler改为 Catalog 驱动并补全WWW-Authenticate;HttpResponder输出 VALIDATION 类 Envelope;main.cc全局异常处理器按路径分流并接入 Catalog 自检;15 个控制器迁移去除即兴错误格式。前端(OAuth2Frontend / OAuth2Admin)
errorAdapter(normalizeError,永不抛出)+Error_Message_Catalog_FE(zh-CN,镜像后端码)。alert,接通 401 刷新失败的会话失效跳转。文档 / 测试 / CI
api-reference.md错误码章节由 Catalog 生成并自动校验。ci-linux.yml/ci-windows.yml。回归修复(包含在本 PR)
VALIDATION_RESOURCE_NOT_FOUND(3004→404)、VALIDATION_RESOURCE_CONFLICT(3005→409),回填 5 个控制器恢复语义。验证
OAuth2Test_test:200 用例 / 55815 断言全部通过。