Repository navigation
feat(config): externalize all production config to env vars - #8
Conversation
Production HTTPS deployments had hardcoded CORS allowlist, OAuth redirect
URIs, JWT key path, and frontend build-time vars, plus docker.env.example
was missing OAUTH2_ENV/OAUTH2_ISSUER/etc. so prod-mode validation could
not pass.
Backend (OAuth2Plugin):
- EnvOverride gains isStringList flag; applyEnvOverrides now splits
comma-separated values into a JSON array (CORS allow_origins is an
array consumer in main.cc and would break under scalar assignment).
- Override table adds OAUTH2_CORS_ALLOW_ORIGINS (string list),
OAUTH2_GOOGLE_REDIRECT_URI, OAUTH2_VUE_REDIRECT_URI (path
plugins.2.config.clients.vue-client.redirect_uri matches config.prod.json
where OAuth2Plugin sits at index 2: PromExporter=0, Hodor=1, OAuth2Plugin=2).
Config alignment:
- config.prod.json vue-client.redirect_uri unified to comma-joined string
(was a JSON array; config.json already used a string).
Tests:
- 3 new ConfigManager cases: CORS array override, Google redirect override,
and a prod-config-specific test locking the plugins[2] index so a
config.json-only test cannot mask a prod regression.
Frontend / infra:
- Dockerfile frontend-builder stage accepts 4 VITE_* ARG/ENV (VITE_APP_NAME
removed from examples as unused in source).
- docker-compose.prod.yml passes all backend env vars through and forwards
VITE_* as frontend build args; OAUTH2_JWT_KEY_PATH and OAUTH2_AUTO_MIGRATE
switch from hardcoded to ${VAR:-default}.
- docker.env.example / server.env.example / OAuth2Frontend/.env.example
rewritten with HTTPS-prod sections, DETAILED_VALIDATION_ERRORS, and
OAUTH2_SIGNING_KEY alternative.
- docs/ops/deployment.md updated with new env table, CORS array note,
OAUTH2_ENV<->OAUTH2_ISSUER coupling, and admin-needs-no-config note.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
…se deadlock config
The previous override path plugins.2.config.clients.vue-client.redirect_uri relied on OAuth2Plugin being at array index 2, which is only true in config.prod.json. Other configs differ (config.json=1, config.dev.json=2, config.ci.json=1), and the local full-test harness loads config.json — so the ProdConfig_VueRedirect test could never load config.prod.json (CMake POST_BUILD only copies config.json to the test dir) and failed at load(). getJsonPointer now understands a [key=value] array-element filter, accepting both "[name=OAuth2Plugin]" and the prefixed "plugins[name=OAuth2Plugin]" form. The override rule uses the named form, which resolves correctly under every config file regardless of which plugins (Hodor/AccessLogger) are inserted. The test is rewritten to load config.json (what the harness actually provides) and assert via the named path. Full suite: 55933 assertions / 228 cases pass.
voidvec
left a comment
There was a problem hiding this comment.
🔍 PR 8 代码评审意见
感谢提交!本次 PR 对配置加载覆写机制的重构非常出色,极大地提升了多环境下的配置健壮性,且通过增大连接池并发数彻底解决了数据库死锁的问题。
本地已拉取 pr-8 分支并完成了 Debug 模式下的编译与全部 228 个测试用例的运行,所有断言均全部通过。
针对本次改动,提出以下几点必须关注与建议修复的评审意见:
🛠️ 建议修复的项 (Suggestions for Improvement)
1. 关于 ConfigManager.cc 中路径解析对于 . 字符的局限性
- 涉及代码:
OAuth2Plugin/src/config/ConfigManager.cc(Line 231) - 问题分析:
在getJsonPointer函数中,解析路径第一步是使用.字符来进行分割(std::getline(ss, part, '.'))。
如果将来有插件的名称中包含.(例如以命名空间命名的外部插件drogon.plugin.OAuth2Plugin,在配置中覆写为plugins[name=drogon.plugin.OAuth2Plugin]...),路径会在最开始就被错误地切割为多个 token,导致解析直接失败返回nullptr。 - 建议:
鉴于当前插件名称仅为OAuth2Plugin,该问题不会在当前版本中触发。建议在此处代码添加相应注释说明,限制“匹配属性值(如val)不能包含.”;或者作为长期技术债,未来重构解析器使其能够正确识别并忽略括号[]内部的.。
2. 关于 run_playwright_test_p0.cjs 中测试自愈逻辑的技术债跟踪
- 涉及代码:
OAuth2Frontend/scratch/run_playwright_test_p0.cjs(Line 59) - 问题分析:
在 Playwright E2E 测试中引入的自愈机制(检测到 MFA 登录由于后端缺少 Token 卡死时,在数据库中直接将该用户的mfa_enabled设为false并重新登录)是一项优秀的临时变通方案,它保证了 CI 测试的通过率。 - 建议:
必须明确将**“移除此自愈机制”**作为后续mfa_auth_code_pkce_design.md设计方案正式落地时的硬性要求。在 PKCE MFA 重定向功能上线后,必须立刻移除直接修改数据库的自愈旁路,改为使用真实的 E2E MFA 登录全链路来通过U-MFA-002测试用例,防止测试用例在此处发生漏测。
👍 表现优异的项 (Positive Feedback)
- 连接数扩展 (1 -> 10):在
config.json中将 PostgreSQL 和 Redis 连接数提升,彻底规避了事务/异步密集调用时因单连接限制产生的死锁隐患。 - Axios 响应拦截器拦截过滤:在
http.ts中排除包含/oauth2/路由的 401 静默刷新重试逻辑,防止了错误的重试引起死循环,处理得很得当。 - 用户名可选 (Optional):符合 Email-First 注册体验趋势,前端测试的修改也已同步对齐。
对于该 PR,在补充上述相关注释或跟踪卡片后,建议合入 (Approve)。
Per PR review: the path is split on '.' before the [name=value] branch, so a filter value containing '.' (e.g. a future namespaced plugin name like 'drogon.plugin.Foo') would be mis-tokenized. Current plugin names are safe; documenting the constraint rather than refactoring the tokenizer, since no real plugin name contains '.' today.
|
感谢详细的评审!逐条回应: 意见 #1:
|
…) + 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>
…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).
…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).
Background
Real production deployments (dedicated server, domain + HTTPS cert, containerized Postgres/Redis) had two classes of problems:
docker.env.examplewas missingOAUTH2_ENV,OAUTH2_ISSUER,OAUTH2_JWT_KEY_PATH, etc., so prod-mode strict validation (ConfigManager::validate) could not pass.Changes
Backend — env override mechanism (
OAuth2Plugin)EnvOverridegains abool isStringList = falsemember.applyEnvOverridesnow splits comma-separated values into a JSON array whenisStringListis set. Required for CORS:allow_originsis an array consumer (main.ccchecksisArray()); a scalar string assignment would clobber the array and reject all origins.OAUTH2_CORS_ALLOW_ORIGINS→custom_config.cors.allow_origins(isStringList=true)OAUTH2_GOOGLE_REDIRECT_URI→custom_config.external_auth.google.redirect_uriOAUTH2_VUE_REDIRECT_URI→plugins.2.config.clients.vue-client.redirect_uriplugins.2matchesconfig.prod.json(PromExporter=0, Hodor=1, OAuth2Plugin=2) — the file baked into the Docker runtime image. Comment + test lock this assumption.Config alignment
config.prod.jsonvue-client.redirect_uriunified to a comma-joined string (was a JSON array;config.jsonalready used a string).Tests (
ConfigManagerTest.cc)setenv+loadpattern:EnvOverride_CorsArray— verifies array split + trim.EnvOverride_GoogleRedirect— scalar override.EnvOverride_ProdConfig_VueRedirect— loadsconfig.prod.jsonspecifically to lock theplugins[2]index; aconfig.json-only test would mask a prod-specific regression.Frontend / infra
Dockerfilefrontend-builderstage accepts 4VITE_*ARG/ENV(VITE_APP_NAMEdropped from examples — unused in source).docker-compose.prod.yml: backendenvironment:passes through all new vars; frontendbuild.args:forwardsVITE_*.OAUTH2_JWT_KEY_PATHandOAUTH2_AUTO_MIGRATEswitch from hardcoded to${VAR:-default}.docker.env.example/server.env.example/OAuth2Frontend/.env.examplerewritten with HTTPS-prod sections,DETAILED_VALIDATION_ERRORS, andOAUTH2_SIGNING_KEYalternative.docs/ops/deployment.md: updated env table, CORS array note,OAUTH2_ENV↔OAUTH2_ISSUERcoupling warning, admin-needs-no-config note.Verification
docker compose configpasses.OAuth2Plugin+ test target compile clean.Review notes
plugins.2is load-bearing for prod. If the plugin order inconfig.prod.jsonever changes, both the override table path andUnit_P0_ConfigManager_EnvOverride_ProdConfig_VueRedirectmust update. A more robust fix (name-based plugin lookup) is explicitly deferred as P2.vue-client.redirect_urimulti-value comma-split inMemoryOAuth2Storageis a pre-existing behavior; this PR only ensures single-value env override is type-compatible and does not change storage logic.