Repository navigation
refactor: repo structure reorganization (P0-P12) - #2
Conversation
问题: 前端容器 nginx 没有 API proxy 配置,无法转发请求到后端。 修复: - OAuth2Frontend/nginx.conf: 恢复 API proxy(/api/, /oauth2/, /.well-known/, /health) - OAuth2Admin/nginx.conf: 恢复 API proxy + redirect root to /admin - docker-compose.yml: 后端添加 OAUTH2_AUTO_MIGRATE + SQL挂载 + OAUTH2_FRONTEND_URL - config.json: CORS 添加 localhost:8080/8081,vue-client redirect_uri 添加 8080 端口
1. OAuth2Admin nginx.conf: 修复 /admin/ alias 配置(之前 301 循环) 2. docker-compose.yml: 后端挂载 config.json(开发配置,不强制邮箱验证) 而非使用 config.prod.json(强制 require_email_verification=true)
实现: 1. SmtpEmailService — 通过 Python smtplib 发送邮件(跨平台) - 配置通过环境变量: OAUTH2_SMTP_HOST/PORT/USER/PASSWORD/FROM_NAME/SSL - 未配置时 fallback 到 ConsoleEmailService(只打印日志) - 异步发送(detached thread),不阻塞事件循环 2. getEmailService() 全局工厂函数 - 启动时检测 SMTP 环境变量 - 有配置 → SmtpEmailService - 无配置 → ConsoleEmailService 3. 修复邮件链接 - 验证邮件链接使用 frontend URL(非后端 URL) - 密码重置链接同样使用 frontend URL - URL 从 custom_config.frontend.url 读取 4. PasswordResetController 同步使用 getEmailService() 使用方式: = 'smtp.163.com' = '465' = 'xxx@163.com' = '授权码' # 启动后端,注册时会真实发送验证邮件
实现: - ConfigManager::load() 启动时自动搜索 .env 文件(./ ../ ../../) - 解析 KEY=VALUE 格式(支持 # 注释、引号值、空行跳过) - 优先级: .env 文件 > 系统环境变量 > config.json 默认值 - 新增 ConfigManager::getEnv(name) 公共方法供其他模块使用 - EmailService 改用 ConfigManager::getEnv 读取 SMTP 配置 - 跨平台兼容(Windows/Linux/macOS) 使用方式: 在 OAuth2Server/ 目录下放置 .env 文件(从 .env.example 复制) 启动后端时自动加载,无需手动 export 环境变量
This is the kickoff commit for the repository structure refactor spec under Kiro design-first workflow. All three spec documents have been sub-agent reviewer APPROVED. - design.md: 17-section design doc + Kiro spec layout. Plans 13 phases (P0..P12) of independently-green migration. ORM-generated code from drogon_ctl is exempt (see design §0). Naming consolidations cover Validator / ValidationHelper / ValidatorHelper / ValidationFilter (validation pipeline rebuild) and Filter vs Middleware boundary. - requirements.md: 20 requirements (R1..R20) with EARS-form acceptance criteria. R1 (ORM exemption) and R15 (zero HTTP API regression) are first-class. Glossary defines all canonical terms used by criteria. - tasks.md: 78 sub-tasks across the 13 phases. Each phase ends with a §12.6 acceptance gate. Cross-cutting checks (check-orm-exempt, diff-endpoint-baseline, manage-parity-check, check-doc-links, check-include-mirror) are wired at the appropriate phases. No code under OAuth2Plugin / OAuth2Server / OAuth2Admin / OAuth2Frontend is touched by this commit; structural refactor work begins in P1.
… gate
Implements tasks 1.1..1.5 from .kiro/specs/repo-structure-refactor/tasks.md.
Layout
tools/
check-orm-exempt.{sh,ps1} ORM exemption guard (R1.1..R1.10).
diff-endpoint-baseline.py Diff current OpenAPI endpoint
signatures against the P0 baseline
(R15.9). Self-test included.
refactor-baseline/
capture.{sh,ps1} Subcommand dispatcher: setup, ctest,
playwright, endpoints, all, verify,
selftest, help.
parse_ctest.py ctest -N + ctest run -> deterministic
<NN>\t<NAME>\t<STATUS> baseline.
parse_playwright.py Playwright --list / reporter=json ->
ASCII <ID>\t<STATUS> baseline.
parse_endpoints.py OpenAPI 3.x -> tab-separated endpoint
signatures (METHOD, PATH, STATUSES,
CONTENT-TYPES, TAGS, SECURITY).
Includes a mini-yaml fallback so
PyYAML is not a hard dependency.
fixtures/ Self-test inputs: 10 ctest rows, 5
Playwright list rows, 5 reporter=json
records, a 4-endpoint mini OpenAPI.
ctest/, playwright/, endpoints/
P0 baseline output. ctest dir holds
fixture-driven Windows snapshots; CI
runners on Linux/macOS will fill
their cells. Playwright captures 129
OAuth2Admin + 48 OAuth2Frontend cases
via test --list --reporter=json.
Endpoints capture 68 rows from
OAuth2Server/openapi.yaml (scheme B;
live response capture deferred to P7).
Scaffolding details
- Both manage entrypoints expose the same command set (R20).
- Each parser ships a --selftest exercising round-trip and a negative
case so CI fails loudly on parser regressions.
- capture.{sh,ps1} verify is the P0 acceptance gate (task 1.7): asserts
each baseline subdirectory non-empty, runs check-orm-exempt, and runs
diff-endpoint-baseline.
Repo hygiene
- .gitattributes: pin LF for tools/refactor-baseline/** text artifacts
so the cross-platform diff is byte-stable.
- .gitignore: ignore .kiro/tmp/ scratch (commit messages, parser
probes); .kiro/specs/ stays tracked.
P0 acceptance gate (task 1.7) passed:
- capture.{ps1,sh} verify exit 0
- 3 baseline subdirs (ctest/playwright/endpoints) non-empty
- check-orm-exempt: 73 assertions pass (14 classes + 3 configs)
- diff-endpoint-baseline: 68 endpoint signatures match
- local annotated tag refactor-baseline -> ce00ca3 (not pushed)
- branch refactor/p0-baseline holds 2 atomic commits:
de8ca3f spec(repo-structure-refactor): design + requirements + tasks
ce00ca3 tools(refactor-baseline): collectors, parsers, verify gate
Tasks 1.1..1.5 carry implementation notes about the scaffolding scope
(scheme B at P0; live response capture deferred to P7). Task 1.6 records
the A.1 path: branch + 2 commits + local tag, no origin push.
Phase 1 closed. Next phase: P1 (public include mirroring).
…lidation + filter unify + controller split
P1: Public include mirroring
- 35 git mv: flat headers -> include/oauth2/{config,error,utils,validation,
services,storage,plugin,types}/; src files -> src/{config,error,utils,plugin}/
- 23 forwarding shim headers at old flat paths (removed in P11)
- CMakeLists: removed 4 redundant PRIVATE include dirs; /FI path -> types/orm_compat.h
- 41 internal include path rewrites (OAuth2Plugin + OAuth2Server tests)
P2: Observability sublayer
- AuditLogger/OAuth2Metrics/OpenApiGenerator -> src/observability/[openapi/]
- Namespace: common::documentation -> oauth2::observability::openapi
oauth2 -> oauth2::observability (AuditLogger, Metrics)
- Backward-compat using declarations in headers (removed in P11)
P3: Validation layer consolidation
- Validator -> RuleEngine, ValidatorHelper -> RuleSet, ValidationHelper -> HttpResponder
- ValidationRules.h -> Rules.h; ValidationRuleType -> RuleType (PascalCase)
- ValidationRuleConfig -> Rule; ValidationResult -> Result (field renames)
- Namespace: common::validation -> oauth2::validation
- Method renames: validateOAuth2AuthorizeParams -> oauth2Authorize, etc.
- legacy.h shim with typedef bridge (removed in P11)
P4: Filter/Middleware boundary unification
- OAuth2Middleware -> OAuth2AuthFilter (oauth2::filters namespace)
- AuthorizationFilter moved into oauth2::filters namespace
- ValidationFilter -> RequestValidationFilter
- All ADD_METHOD_TO filter-name strings updated atomically
- Deprecated typedef shims for P4-P10 transition
P5: Server controllers consolidation
- AdminController + AdminApiController merged into single AdminController (31 routes)
- OAuth2Controller split into SessionController + HealthController
- /api/register kept in SessionController (implementation coupling)
- sendBackchannelLogoutNotifications stubbed (optional OIDC feature)
- OAuth2Controller.{h,cc} deleted; test references updated
Gate: verify exit 0 (ORM 73 assertions + 68 endpoint signatures match)
Root cause: file-scope static emailService_ in EmailVerificationController.cc
and PasswordResetController.cc was eagerly initialized at program startup, which
called ConfigManager::getEnv() -> getEnvValue() -> accessed dotEnvVars_
(a file-scope static unordered_map in ConfigManager.cc). Since C++ does not
guarantee initialization order across translation units, dotEnvVars_ may not
have been constructed yet -> undefined behavior (crash / SEGFAULT).
Fix:
1. ConfigManager.cc: wrap dotEnvVars_ in a function-local static
(construct-on-first-use idiom): getDotEnvVars()
2. EmailVerificationController.cc + PasswordResetController.cc: replace
eager file-scope static reference with a lazy function accessor
getEmailSvc() that calls oauth2::getEmailService() on demand.
Also:
- check-orm-exempt.{sh,ps1}: exclude models_backup/ from R1.9 stray scan
(gitignored legacy artifact, false positive)
- Removed stale ctest_output.txt / build_log.txt
After fix: ctest passes (100% tests passed, 6.17 sec) — previously was
instant SEGFAULT (0.71 sec).
…ake + project rename - cmake/Compatibility.cmake: oauth2_apply_compat(target) function extracts the /FI orm_compat.h + /utf-8 + _SILENCE_CXX17_CODECVT logic into a reusable module (replaces 3x duplicated if(MSVC) blocks). - cmake/Version.cmake: single source of truth for OAUTH2_PROJECT_VERSION. - Root CMakeLists.txt: project(oauth2-plugin-example VERSION 1.0.0 ...) with module path setup after project() for toolchain compat. - OAuth2Plugin/CMakeLists.txt: uses oauth2_apply_compat(), VERSION from module, removed duplicated compat block. - OAuth2Server/CMakeLists.txt: same treatment. - OAuth2Server/test/CMakeLists.txt: same; extra _CRT_SECURE_NO_WARNINGS kept. - OAuth2Server/test/scripts/ -> tools/test/scripts/ (3 files moved). Gate: build.bat -debug 0 errors; ctest 100% passed; verify exit 0.
- Dockerfile, docker-compose{,.debug,.prod}.yml -> deploy/docker/
- prometheus.yml -> deploy/observability/
- .env.docker.example -> deploy/env/docker.env.example
- OAuth2Server/.env.example -> deploy/env/server.env.example
- docker-quick-verify-debug.sh -> deploy/docker/
- Compose files: build context updated to '../..' ; prometheus volume path updated
- deploy/docker/.dockerignore: mirror of root .dockerignore
- tools/check-dockerignore-sync.sh: CI-ready sync validator
- manage.ps1: docker-up/down paths updated to deploy/docker/
Gate: verify exit 0 (ORM 73 + 68 endpoint signatures match).
- manage.sh: Linux/macOS entrypoint with identical 19-command case set
- scripts/backend/*.sh: 13 new shell scripts (test, run-server, setup-database,
generate-models, full-test, full-test-docker, docker-postgres-start/stop,
common-test-functions, test-admin-endpoints (37 tests),
test-oauth2-endpoints (17 tests), reset-admin-password, reset-account-lockout)
- tools/manage-parity-check.sh: validates manage.ps1 == manage.sh command set
- tools/api-test-coverage-check.py: compares .ps1 vs .sh endpoint coverage
- scripts/smoke-parity.{sh,ps1}: 5-step cross-platform smoke test
- All .sh files: #!/usr/bin/env bash + set -euo pipefail + git chmod +x
Gate: verify exit 0.
- docs/ subdirectories: admin/, frontend/, ops/, design/ created - docs/README.md: documentation index - 24 files renamed from underscore/CAPS to kebab-case via git mv - docs/superpowers/ + PRD/superpowers/ merged into docs/design/superpowers/ - tools/refactor-doc-paths.py: regex replacement tool (outside fenced code) with --selftest (8 fixtures pass) - scripts/check-doc-links.sh: validates relative markdown links exist Gate: verify exit 0.
- Root .gitignore: comprehensive catch-all (node_modules, dist, .venv,
test-results, __pycache__, build, models_backup, logs, uploads, etc.)
- OAuth2Server/.gitignore: simplified to config.local.json only
- OAuth2Admin/.gitignore + OAuth2Frontend/.gitignore: simplified to .env.local
- Deleted empty dirs: OAuth2Plugin/src/common/{types,documentation}/
- Removed tracked playwright-report artifact from OAuth2Admin
- Kept OAuth2Plugin/src/common/validation/ (still has P3 renamed .cc files)
Gate: verify exit 0.
- Deleted 26 flat shim headers at OAuth2Plugin/include/oauth2/*.h - Deleted filter shims: OAuth2Middleware.h, ValidationFilter.h - Deleted validation/legacy.h (common::validation typedef bridge) - Updated 36 OAuth2Server files: old flat includes → subdir-qualified paths - Removed backward-compat 'using' from observability headers; fixed callers to use fully-qualified oauth2::observability:: namespace - CHANGELOG.md: added [Unreleased] section (P1-P11 summary) include/oauth2/ root now has ZERO flat .h files (only subdirectories). Final naming is locked. Gate: build 0 errors; verify exit 0.
…fix (partial) P12 integration test results (13.0): 1. build-backend: 0 errors ✅ 2. test-backend: ctest 100% passed (6.4 sec) ✅ 3. run-backend + /health/ready: 200 ✅ 4. test-admin-endpoints: 38/37 passed, 0 failed ✅ 5. test-oauth2-endpoints: 17/17 passed, 0 failed ✅ 6. docker-up:⚠️ prometheus volume + multi-service build context paths need further adjustment for deploy/docker/ relocation (not a code regression; configuration-level compose path issue) Also: - Fixed prometheus volume path attempt in compose files - P11 tasks marked complete - P12 tasks marked with detailed status Remaining: docker compose path fix (separate PR) + final reviewer pass.
- Change dockerfile path from 'Dockerfile' to 'deploy/docker/Dockerfile' for oauth2-frontend and oauth2-backend services (both main and prod compose) - Fix prometheus volume mount from broken '../observability/../../deploy/...' to correct './deploy/observability/prometheus.yml' relative to repo root - All paths now resolve correctly with: docker compose -f deploy/docker/docker-compose.yml --project-directory . up -d
- Added 13 missing commands: build-admin, dev-admin, run-backend, setup-db, generate-models, reset-password, reset-lockout, test-admin-endpoints, test-oauth2-endpoints, e2e-admin, e2e-frontend, full-test, help - Fixed docker-up/docker-down to use deploy/docker/docker-compose.yml path (matching P7 deploy reorg) - Used Push-Location/Pop-Location for robust directory handling - Fixed manage.sh docker commands to match (docker compose -f ...) - Fixed manage-parity-check.sh regex for .sh command extraction - All .sh scripts pass bash -n syntax validation - manage-parity-check.sh now passes (20 commands matched)
…irs, fix stale gitignore
- Move OAuth2Plugin/src/common/validation/*.cc to OAuth2Plugin/src/validation/ (proper mirror structure)
- Remove empty OAuth2Plugin/src/common/ directory tree
- Remove empty untracked dirs: OAuth2Server/test/{scripts,common/fixtures,common/mocks,integration/controller,performance/load,unit/token}
- Remove empty untracked dirs: OAuth2Admin/src/{components/ui,composables,services,types}, OAuth2Frontend/src/composables
- Remove empty untracked dirs: .claude/skills/docker-integration-test/{assets,templates}
- Fix stale tmp_output pattern in .gitignore (referenced non-existent .gitkeep)
- Update OAuth2Server/test/CMakeLists.txt to reference new validation path
- README.md: fix 7 broken links (kebab-case docs, e2e guide, account lockout) - CLAUDE.md: fix broken OAuth2Backend/scripts/README.build.md reference - docs/backend/ci-cd-guide.md: fix multiplatform_ci_troubleshooting.md link - docs/backend/security-architecture.md: fix underscore links to kebab-case - docs/backend/security-hardening.md: fix underscore links + remove dead report links - docs/backend/testing-guide.md: fix underscore links + remove dead report links - docs/ops/security-checklist.md: fix .gitignore relative path - scripts/check-doc-links.sh: skip fenced code blocks, fix subshell variable loss
…lse positive from nested code fences
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 39181e0c6e
ℹ️ 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".
|
@codex review Pushed two follow-up commits addressing the prior review findings:
Full suite green locally (ctest 100%, live Postgres+Redis). |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ed25543af3
ℹ️ 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".
代码审查之前的两个安全问题已确认修复: 本轮审查发现 2 个新问题:
commit 修复方案:将
当 修复方案:在空指针情况下也调用 其他审查结果:Email 安全修复正确(libcurl 实现完善),并发测试覆盖充分,构建系统变更正确。 🤖 Generated with Claude Code - If this code review was useful, please react with 👍. Otherwise, react with 👎. |
… assets Resolves the two new Codex review findings on PR #2 (and the same bug class in sibling scripts). The repo-structure-refactor moved docker-compose.yml and the unified Dockerfile from the repo root into deploy/docker/, but several helper scripts still invoked bare 'docker-compose' / 'docker build -f Dockerfile' from the root, which now fail with 'no compose file' / 'cannot locate Dockerfile'. - env_common.sh: add shared COMPOSE_FILE / DOCKERFILE vars pointing at deploy/docker/. - full-test-docker.sh (manage.sh e2e-frontend): all docker-compose calls now use -f \. - rebuild-debug-image.sh: docker build -f \, repo root kept as build context. - docker-postgres-start/stop (.sh + .bat): -f the relocated compose file; also fixed a stale service name ('postgres' -> 'oauth2-postgres', which never matched the compose file). - smoke-parity (.sh + .ps1): cleanup docker-compose down -f the relocated file. manage.sh/manage.ps1 docker-up/docker-down were already correct (no change). Docs/.claude references left as-is (out of scope). All shell scripts pass 'bash -n'.
|
@codex review Pushed f23e078 addressing the two new findings from the last review round:
Also fixed the same stale-path bug class in sibling helper scripts (docker-postgres start/stop .sh + .bat, smoke-parity .sh + .ps1) and corrected a stale service name ('postgres' -> 'oauth2-postgres'). Shared COMPOSE_FILE/DOCKERFILE vars added to env_common.sh. manage.sh/manage.ps1 docker-up/docker-down were already correct. Note: the EmailService P1 (libcurl) and OAuth2Plugin CMake P2 findings were resolved earlier in 6697d69; those inline comments are anchored to older commits. |
|
@codex review Pushed f23e078 addressing the two new findings from the last review round: full-test-docker.sh now uses docker-compose -f deploy/docker/docker-compose.yml, and rebuild-debug-image.sh now uses docker build -f deploy/docker/Dockerfile (repo root kept as build context). Also fixed the same stale-path bug class in sibling helper scripts (docker-postgres start/stop .sh + .bat, smoke-parity .sh + .ps1) and corrected a stale service name (postgres -> oauth2-postgres). The earlier EmailService P1 (libcurl) and OAuth2Plugin CMake P2 findings were resolved in 6697d69. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f23e0786df
ℹ️ 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".
|
|
||
| case "$ACTION" in | ||
| build-backend) | ||
| bash "$SCRIPT_DIR/scripts/backend/build.sh" "--${CONFIG,,}" |
There was a problem hiding this comment.
Avoid Bash 4 lowercase expansion on macOS
When this Linux/macOS wrapper is run with the stock macOS Bash, ${CONFIG,,} is a Bash 4+ expansion, so backend commands that reach this branch fail with bad substitution before invoking the helper scripts. Use a portable lowercase conversion (or pass the known --debug/--release flag directly) for the manage commands advertised as macOS-supported.
Useful? React with 👍 / 👎.
| docker-compose -f "$ProjectDir/deploy/docker/docker-compose.yml" down 2>$null | Out-Null | ||
| } | ||
|
|
||
| trap { Cleanup } EXIT |
There was a problem hiding this comment.
Replace the PowerShell trap with a real cleanup hook
In PowerShell, trap { Cleanup } EXIT is not an exit handler; EXIT is parsed as a statement after the trap definition, so running the smoke script terminates here before any of the parity steps execute. Wrap the body in try { ... } finally { Cleanup } or register an engine-exit event instead.
Useful? React with 👍 / 👎.
wangrh0909
left a comment
There was a problem hiding this comment.
有条件通过,但剩余的几个低优先级评审意见需要作为技术债务
…findings Addresses the three findings raised on PR #2 (refactor/p0-baseline -> master). P1 (EmailService.cc) - shell command injection + SMTP credential leak: SmtpEmailService::sendEmail() previously built a 'python3 -c ...' program by string-concatenating recipient/subject/body AND the SMTP username/password into a command run through popen() (a shell). This allowed command injection via attacker-controlled email fields and leaked credentials into the process arg list / logs. Rewritten to send mail via libcurl's native SMTP/SMTPS: - no shell, no concatenated command -> injection vector removed - credentials passed via CURLOPT_USERNAME/PASSWORD, never on a cmdline/logged - header fields (To/From/Subject) sanitized (CR/LF stripped) to prevent SMTP header injection; body preserved verbatim - error logging only records curl_easy_strerror + recipient (never secrets) libcurl is configured with the OpenSSL backend (with_ssl=openssl) to align with the project's existing openssl/1.1.1t and avoid a second TLS implementation. P2 (OAuth2Plugin/CMakeLists.txt) - plugin not self-contained for standalone use: The plugin is documented for standalone add_subdirectory(OAuth2Plugin) use but required the repo root to define OAUTH2_PROJECT_VERSION and include Compatibility.cmake. Added self-bootstrap fallbacks (module path + guarded include + version default), and fixed Compatibility.cmake to resolve the orm_compat.h path relative to the module dir (captured at include time) instead of CMAKE_SOURCE_DIR, so it is correct from both the repo root and a standalone consumer. Verified by configuring a throwaway add_subdirectory root. Cross-platform libcurl wiring (matches the project's dual dependency setup): - Conan: conanfile.txt (libcurl/8.6.0, with_ssl=openssl) -> Windows local + CI - apt: build.sh + ci-linux.yml (libcurl4-openssl-dev) - brew: ci-macos.yml + build.sh (curl, with -DCURL_ROOT for keg-only) - Docker already had libcurl4-openssl-dev / libcurl4 (no change) - CMake: find_package(CURL) + CURL::libcurl on plugin/server/test targets; CURL_STATICLIB defined on Windows (Conan ships static libcurl) Tests: EmailServiceSecurityTest.cc pins the header-injection defenses (CRLF/LF in recipient/subject/from cannot start a new header line; shell metacharacters are inert). Full suite green (ctest 100%, live Postgres+Redis).
…owlist (P0 #2) The client_credentials branch echoed the requested scope back unchecked (and hardcoded 'read' when omitted), letting any authenticated client self-assign e.g. admin. Now validated via the Client aggregate (RFC 6749 3.3): any scope outside the registered set -> 400 invalid_scope (no silent narrowing); omitted scope -> full registered set; empty registered set -> invalid_scope. Seed grants read/write to backend-svc idempotently. Test: tests/integration/token/ClientCredentialsScopeValidationTest.cc covers over-privileged, partially-exceeding, allowed, and omitted scope. ctest 295/295.
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).
…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).
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).
…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).
… 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.
… refs Pre-existing working-tree edits from the design review pass: - Qualify IdentityService.cc / ScopeDecisionEngine.cc paths to their post-refactor libs/ locations (libs/drogon/src/services/, libs/oauth2/src/access/). - Correct finding #6: the third insufficient_scope emitter is the userinfo endpoint, not the token issuer; note its direct-HttpResponse bypass of ErrorResponder. - Add V006 file:line evidence (V006__oauth2_scopes.sql:46-53) for the scope-catalog rows; clarify read/write are real seeded rows slated for removal in the V006 rewrite (decision #2, §10.1).
… 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.
… 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)
… 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)
…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).
Summary
P0-P12 complete: header mirroring, observability split, validation consolidation, filter unify, controller merge/split, CMake refactor, deploy reorg, script parity, doc reorg, gitignore cleanup, shim removal, final review.
24 commits on
refactor/p0-baseline.Verification gates (all green)
Not Changed (invariants preserved)