Skip to content

feat(p2-4): externalize shared auth state to Redis with non-sticky multi-replica E2E - #390

Merged
voidvec merged 7 commits into
masterfrom
feat/p2-4a-shared-state-stores
Dec 2, 2026
Merged

voidvec merged 7 commits into
masterfrom
feat/p2-4a-shared-state-stores

Conversation

@voidvec

@voidvec voidvec commented Nov 29, 2026 •

Copy link
Copy Markdown
Owner

Combines P2-4a (IFailureRateLimiter, IConsentChallengeStore, IWebAuthnChallengeStore Redis ports) and P2-4b (RedisSessionStateBridge for cross-replica Drogon session hydration/persist/invalidation, live Redis tests, tests/e2e/multi-replica non-sticky nginx smoke suite, and interop.yml multi-replica-e2e job).

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-29T11:07:29.108920Z
We couldn’t complete this review. Comment @codex review to try again.
21a5654 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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
voidvec force-pushed the feat/p2-4a-shared-state-stores branch from 21a5654 to b915f08 Compare November 29, 2026 11:36
wangrh0909
wangrh0909 previously approved these changes Nov 29, 2026

@voidvec voidvec left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: P2-4a shared-state stores (rate limiter / consent challenge / WebAuthn challenge)

Reviewed at 21a56541 against 31214d4b (36 files, +4040/-337). CI was still running when I started; nothing here depends on the red/green state. Overall the design is sound: three framework-agnostic ports, Redis adapters that keep single-use semantics atomic in Lua, fail-closed handling for CSRF/WebAuthn challenge backends, and controller wiring that keeps the legacy in-process path when the backend is memory. Findings below; none is a clear "must block the merge", but items 1–3 should be settled before anyone sets shared_state.*=redis in a real deployment.

Must settle before enabling the Redis backends in production

1. Every /oauth2/token response now waits for a Redis write.

In TokenEndpointController::withRateLimitGate, the final response is only forwarded inside the recordSuccess/recordFailure completion callback:

limiter->recordFailure(rlKey, [sharedOriginal, resp]() { (*sharedOriginal)(resp); });

With RedisFailureRateLimiter's default timeoutSeconds = 2.0, a degraded Redis delays every token response — success and failure — by up to 2 s (check 2 s + account 2 s on the failure path). /oauth2/token is the hottest endpoint, and the legacy path responds synchronously. Suggest: respond first and account fire-and-forget (the next request's checkThrottled reads Redis anyway; the only cost is a marginally weaker guarantee under a concurrent burst), or at least use a much shorter bound for the account step (e.g. 100–250 ms) and keep the longer bound only for the pre-gate check.

2. The Redis branches of the controllers are not exercised by any test.

All new coverage is store-level (RedisSharedStateStoresTest, RedisSharedStateStoresIntegrationTest, SharedStateStoresTest). No test config ever sets shared_state.*, so:

  • AuthorizationEndpointController's mint path (CSRF + org context, ~76 lines),
  • ConsentContextController's peek/peekOrgContext path,
  • SessionController::consent's consume/consumeOrgContext path,
  • WebAuthnController's store-mode begin/finish (~341 lines),

are never executed with consentChallengeStore_/challengeStore_ non-null. That is the most security-sensitive new code in the PR (CSRF single-use, challenge single-use, org re-gate) and it currently has zero end-to-end coverage. Add one integration variant (a test config with shared_state: {rate_limit: redis, consent: redis, webauthn: redis} gated on FULLA_REDIS_HOST, which the linux CI job already provides) that drives authorize → consent and WebAuthn register/authenticate through HTTP.

Related: the store-level tests self-skip when getRedisClientOrNull() returns null, so on macOS/Windows test_redis_host is empty and those cases pass vacuously. That is pre-existing behaviour, but it means the linux job is the only place these run — worth pinning in the PR description so a future CI change does not silently drop them.

3. Fail-open on the rate limiter is silent.

RedisFailureRateLimiter's header documents fail-open as a deliberate anti-self-DoS choice (good), but the implementation drops to "allowed" on RedisException, on timeout, and with a null client without any log, metric, or LOG_WARN rate-limit. For /oauth2/token (client-secret brute force via client_credentials) and the email-resend endpoint, a Redis outage therefore removes brute-force protection invisibly. Two asks: (a) log/delimit a warning or bump a counter whenever checkThrottled degrades to 0 because of an error/timeout, so operators can see it; (b) note that IFailureRateLimiter::CheckCallback has no status parameter, so a caller cannot choose fail-closed even if it wants to — that asymmetry versus ISessionStore/IConsentChallengeStore (both carry a status enum) is worth revisiting, or at least a comment on the port saying fail-open is part of the contract.

Important

4. Requested redis backend silently degrades to the legacy in-memory path.

IdentityAssembly::wireSharedStateStores logs LOG_WARN ... staying on legacy in-memory paths when needRedis is true but no "default" Redis client is registered, then leaves the pointers null. For the rate limiter this only splits the counter; for the consent challenge store the consequence is correctness: a CSRF nonce minted on replica A cannot be consumed on replica B, so in a load-balanced deployment every consent-screen login becomes a coin flip between "works" and VALIDATION_INVALID_INPUT — and the only signal is one startup warning. Same class of issue as #389's session-store fallback: fail fast (refuse to start, or make the degradation explicit in the API/UI) when redis was requested.

5. The shared_state knobs and four env vars are undocumented.

shared_state.rate_limit / .consent / .webauthn / .backend plus FULLA_SHARED_STATE_BACKEND, FULLA_RATE_LIMIT_BACKEND, FULLA_CONSENT_CHALLENGE_BACKEND, FULLA_WEBAUTHN_CHALLENGE_BACKEND appear only in IdentityAssembly.cc — no shipped config, docs, or docker env example references them (same gap as session.store in #389). Please document precedence (specific env > specific config key > global env > global config), and state the operational contract: memory backend is single-replica only; consent/WebAuthn Redis branches fail closed (500) during an outage, so a Redis outage blocks consent-screen logins and passkey login on every replica.

6. Org-context Unavailable is treated as "no org binding", while CSRF fails closed.

In SessionController::consent, a CSRF Unavailable returns 500, but consumeOrgContext maps Unavailable → std::nullopt, which takes the if (!orgStashed.has_value()) { issueConsentCode(std::nullopt, false); return; } branch — i.e. the org membership / MFA-policy re-check is skipped and consent is recorded at the personal level. The legacy in-memory path can't be "unavailable", so this failure mode is new. If dropping the binding is considered safe (it only downgrades to a personal consent, never widens scope), say so in a comment; otherwise fail closed like CSRF. ConsentContextController's peekOrgContext has the same Unavailable → org: null, which is harmless (display only) — worth a one-line comment distinguishing the two.

7. Three implementations per port; the memory ones are dead code in production.

MemoryFailureRateLimiter, MemoryConsentChallengeStore and MemoryWebAuthnChallengeStore are only referenced by tests: the assembly's memory branch resets the pointers and the controllers fall back to RateLimiter::instance() / ConsentCsrfSlots / the session-carried WebAuthn challenge. Meanwhile IFailureRateLimiter.h states "Default implementation is MemoryFailureRateLimiter". Either wire the memory port implementations as the actual default (single code path, and the port's semantics get exercised in every run) or fix the comment and keep the three production paths — but note that today the memory impls' parity with the legacy paths (slot eviction order, expiry edge cases) is only asserted by unit tests, not by any HTTP test.

8. Redis and legacy rate-limiter configuration are parsed twice.

OAuth2Plugin configures RateLimiter::instance() from auth.rate_limit, and wireSharedStateStores parses the same block again for RedisFailureRateLimiter. They happen to match today (same isUInt() checks, same defaults), but this is a drift trap the moment one side gains a key. Extract one parse helper.

Minor

  • ZSET member collisions across replicas. recordFailure builds the member as <nowMs>-<seq> where seq is per-process (seq_{0}). Two replicas recording the same key in the same millisecond with equal sequence numbers overwrite each other (ZADD updates, not adds) → a lost failure count. Rare mid-life (the counters diverge), plausible right after a restart. Prefix the member with a per-process instance id/UUID.
  • makeBoundedCallback in all three adapters schedules a loop->runAfter(timeoutSeconds, ...) timer on every call, including the fast path, and never invalidates it. At 2 s (limiter) / 5 s (challenge stores) that is one retained timer per request; on /oauth2/token this is measurable. Prefer TimerId + invalidateTimer on completion, or fire the fallback only when the client is known to buffer commands.
  • All three adapters send the Lua source with EVAL on every call. Consider EVALSHA with a fallback, or at least a comment that script caching is not used.
  • checkThrottled's Retry-After is computed from the oldest member only. When the count overshot maxFailures (concurrent requests all recording before the next check), the reported wait is shorter than needed and the client will collect another 429. Self-correcting, but a count - maxFailures + 1-th member would be more accurate.
  • RedisSharedStateStoresTest.ConsentChallengeStoreNullRedisOrEmptyArgsFailClosed only exercises the null-client branch: with a live client the empty-arg guards return NotFound, not Unavailable (the integration test at the bottom of RedisSharedStateStoresIntegrationTest does cover the live-client case). Rename or tighten the unit test so the expectation reflects which branch is under test.
  • authorize answers a failed mint with a bare plain-text 500 (newHttpResponse() + "Consent challenge storage unavailable") instead of the JSON error envelope used everywhere else in that controller.
  • EmailVerificationService's limiter is a file-static shared_ptr behind a mutex set from assembly — fine for the single-app process, but it is global mutable state that tests and any future second instance have to coordinate. A member on the service (as with the controllers) would be cleaner.

Verified good

  • Single-use semantics are atomic everywhere: CSRF consumeCsrf, org consumeOrgContext, and WebAuthn consume all do GET+delete inside one Lua script, and the WebAuthn consume deletes even on a wrong challenge (no validity oracle), matching the in-memory behaviour that the integration test also pins.
  • Unavailable fails closed for CSRF peek/consume, consent-context CSRF, and WebAuthn store/consume — no accidental fail-open on the security gates.
  • The org-context value layout (orgId:exp:seq) and CSRF layout (exp:seq) are parsed consistently between mint/peek/consume, and the maxSlots eviction keeps maxSlots-1 live entries before inserting, i.e. the bound is exact.
  • Registration's store path is equivalent to the memory path: consume confirms presentedChallenge equals the server-stored challenge, and attestation/assertion verification binds the signed clientDataJSON to that same value.
  • Rate-limiter Lua prunes and counts in one script; sliding window, PEXPIRE refresh, and success-reset semantics match the legacy limiter's documented behaviour.
  • Wiring runs from registerBeginningAdvice (so Redis clients are registered), before the memory-mode early return, and shutdown nulls every controller setter and resets the state pointers.
  • No new error codes, no OpenAPI/route changes; api-baseline.txt growth is public-header extraction only. Both new test files land under globbed directories, so they are actually built and run.

@voidvec voidvec changed the title feat(p2-4a): externalize in-process rate-limit, WebAuthn, and consent state to Redis feat(p2-4): externalize shared auth state to Redis with non-sticky multi-replica E2E Nov 29, 2026
wangrh0909
wangrh0909 previously approved these changes Nov 29, 2026
wangrh0909
wangrh0909 previously approved these changes Nov 30, 2026
@voidvec
voidvec force-pushed the feat/p2-4a-shared-state-stores branch 2 times, most recently from 3b34d03 to ab12432 Compare December 2, 2026 02:14

@voidvec voidvec left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR #390 Code Review — Blocking (P0) & High-Priority (P1) Findings

Reviewed at ab124329 (rebased onto origin/master 9fe36a27).

P0 / Blocking

  1. CURLOPT_RESOLVE passed const char * instead of struct curl_slist * (UB / crash on real webhook delivery)

    • Location: apps/server/src/bootstrap/IdentityAssembly.cc:452-453
    • Issue: setOption(CURLOPT_RESOLVE, resolveEntries.c_str()) passes a raw C-string to CURLOPT_RESOLVE, which expects a struct curl_slist *. In variadic curl_easy_setopt, libcurl interprets the string bytes as a curl_slist struct (data/next), causing immediate UB/segfault on any outbound webhook delivery when allowPrivateTargets == false.
    • Fix: Build a curl_slist via curl_slist_append(nullptr, resolveEntries.c_str()) (managed by RAII unique_ptr with curl_slist_free_all, failing closed on allocation failure) and pass resolveList.get() to CURLOPT_RESOLVE.
  2. CURLOPT_PROTOCOLS deprecated in libcurl >= 7.85.0 (breaks Linux CI -Werror=deprecated-declarations)

    • Location: apps/server/src/bootstrap/IdentityAssembly.cc:454
    • Issue: CURLOPT_PROTOCOLS fails Build & Test (linux) and all 3 Optional Feature Matrix jobs under -DFULLA_WERROR=ON. Additionally, when allowPrivateTargets == false, parseTargetUrl() only permits https://, so allowing HTTP in libcurl is broader than intended.
    • Fix: Guard with #if defined(LIBCURL_VERSION_NUM) && LIBCURL_VERSION_NUM >= 0x075500 to use CURLOPT_PROTOCOLS_STR (allowPrivateTargets ? "http,https" : "https"), falling back to CURLOPT_PROTOCOLS on older libcurl.

P1 / High

  1. Session commit rollback revokes the wrong ISessionStore key after clearing session_store_id
    • Locations:
      • libs/drogon/src/controllers/SessionController.cc:1100-1102
      • libs/drogon/src/controllers/WebAuthnController.cc:725-727
    • Issue: Both commitAuthenticatedSession failure handlers call detail::clearPasswordLoginAuthenticationState(*req->session()) before revokeRequestSession(sessionStore, req). Because clearPasswordLoginAuthenticationState erases "session_store_id", revokeRequestSession falls back to req->session()->sessionId() (the Drogon cookie ID) instead of the newly rotated session_store_id UUID, leaving an orphaned active session record in Redis if store->put timed out after writing.
    • Fix: Call revokeRequestSession(sessionStore, req) before clearPasswordLoginAuthenticationState(*req->session()), matching MfaController.cc:871-876 and all other call sites.

@voidvec
voidvec force-pushed the feat/p2-4a-shared-state-stores branch from 0afc2a7 to ac8c510 Compare December 2, 2026 03:17
@voidvec

voidvec commented Dec 2, 2026

Copy link
Copy Markdown
Owner Author

代码评审意见(仅记录 P0 阻断项与 P1 重要问题)

基于当前 HEAD (feat/p2-4a-shared-state-stores vs origin/master) 审查。

P0 阻断项

  1. MfaController::verifyLogin 在 !req->session() 分支永不调用 done(),导致请求永久挂死

    • 位置:libs/drogon/src/controllers/MfaController.cc:831-892(elevateSessionAfterMfa)
    • 问题:elevateSessionAfterMfa 仅在 if (req->session()) 内调用了 done() 或 commitAuthenticatedSession(...),缺少 else { done(); }。当无 cookie session(req->session() == nullptr)的请求走到 sendSuccess -> elevateSessionAfterMfa(...) 时,done() 与 (*sharedCb)(...) 永远不会被触发,HTTP 请求会一直挂起直至超时。
    • 建议修复:在 lambda 开头增加 if (!req->session()) { done(); return; }。
  2. RedisSessionStateBridge 的 makeBoundedCallback 在 timeoutSeconds <= 0.0 或事件循环未运行时立即同步触发失败回调

    • 位置:libs/drogon/src/adapters/RedisSessionStateBridge.cc:33-43
    • 问题:与同 PR 中另外 3 个 Redis 适配器不同,此处多了 else { finish(timeoutArgs...); }。当 timeoutSeconds <= 0.0 或在非运行中 Drogon 事件循环(如单测 stub)调用时,会先同步触发超时失败回调并将 done 置为 true,导致随后发起的 execCommandAsync 真实响应被全部丢弃。
    • 建议修复:移除 else { finish(timeoutArgs...); } 分支,与其余 3 个 Redis 适配器保持一致;并将 if (!redisClient_ || sessionId.empty()) 提前到 makeBoundedCallback 之前。

P1 重要问题

  1. RedisSessionStateBridge::persistResponse 通过 PreSendingAdvice 异步 fire-and-forget 写/删 Redis,存在跨副本读后写竞态与静默写失败

    • 位置:libs/drogon/src/adapters/RedisSessionStateBridge.cc:366-417、apps/server/src/bootstrap/IdentityAssembly.cc:657-665
    • 问题:persistResponse 在同步 registerPreSendingAdvice 钩子中异步发起 saveSnapshot/deleteSnapshot,不等待 Redis ACK 即发出响应。多副本非粘性路由下,客户端收到登录/MFA 升级后的 Set-Cookie 并立即请求另一副本时,可能早于 Redis SET 落盘触发误判未登录;写/删失败也仅 LOG_WARN。
    • 建议修复:关键状态边界(登录、MFA 升级、WebAuthn 完成、登出、强制改密)在响应回调前显式等待 saveSnapshot/deleteSnapshot 完成,PreSendingAdvice 仅做只读 refreshTtl 兜底。
  2. shutdownIdentityServices() 遗漏重置 state.sessionStateBridge

    • 位置:apps/server/src/bootstrap/IdentityAssembly.cc:1770-1790
    • 问题:清理阶段重置了其余 shared-state store,但未调用 state.sessionStateBridge.reset(),可能导致进程关闭或同进程多套件集成测试 teardown 后全局 advice 仍拦截请求并滞留 RedisClientPtr。
    • 建议修复:在 shutdownIdentityServices() 中补充 state.sessionStateBridge.reset();。
  3. MfaController::verifyLogin 的 commitAuthenticatedSession 位于 exchangeCode 和 clearPendingBinding 之后,与失败可重试语义矛盾

    • 位置:libs/drogon/src/controllers/MfaController.cc:850-900, 1030-1045, 1345-1365
    • 问题:注释声明失败时保留 MFA 过渡态可重试,但实际先签发了 token 并删除了 pending 绑定;若 ISessionStore 写入失败返回 500,用户既无法重试又在 DB 留下孤立已签发 token。
    • 建议修复:将 commitAuthenticatedSession 提前到 clearPendingBinding / exchangeCode 之前执行,或在失败时同步撤销已签发 token。
  4. WebAuthnController::authenticateBegin 内存分支写入 session 前缺少 erase

    • 位置:libs/drogon/src/controllers/WebAuthnController.cc(authenticateBegin 末尾,insert("webauthn_auth_challenge", ...))
    • 问题:Drogon Session::insert 为 std::map::insert 语义(key 已存在时静默不覆盖)。同一 session 取消并重试 WebAuthn 登录时旧 challenge 不会被覆盖,导致后续 authenticateFinish 必败。
    • 建议修复:在 insert 前补充 req->session()->erase("webauthn_auth_challenge");。

@voidvec
voidvec force-pushed the feat/p2-4a-shared-state-stores branch from ac8c510 to 8de68cf Compare December 2, 2026 06:24
@voidvec
voidvec merged commit dbb83db into master Dec 2, 2026
16 checks passed
@voidvec
voidvec deleted the feat/p2-4a-shared-state-stores branch December 3, 2026 01:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants