Repository navigation
feat(p2-4): externalize shared auth state to Redis with non-sticky multi-replica E2E - #390
Conversation
Codex Review Summary: ❌ FailedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
21a5654 to
b915f08
Compare
voidvec
left a comment
There was a problem hiding this comment.
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.
recordFailurebuilds the member as<nowMs>-<seq>whereseqis per-process (seq_{0}). Two replicas recording the same key in the same millisecond with equal sequence numbers overwrite each other (ZADDupdates, 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. makeBoundedCallbackin all three adapters schedules aloop->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/tokenthis is measurable. PreferTimerId+invalidateTimeron completion, or fire the fallback only when the client is known to buffer commands.- All three adapters send the Lua source with
EVALon every call. ConsiderEVALSHAwith 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 overshotmaxFailures(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 acount - maxFailures + 1-th member would be more accurate.RedisSharedStateStoresTest.ConsentChallengeStoreNullRedisOrEmptyArgsFailClosedonly exercises the null-client branch: with a live client the empty-arg guards returnNotFound, notUnavailable(the integration test at the bottom ofRedisSharedStateStoresIntegrationTestdoes cover the live-client case). Rename or tighten the unit test so the expectation reflects which branch is under test.authorizeanswers 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-staticshared_ptrbehind 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, orgconsumeOrgContext, and WebAuthnconsumeall 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. Unavailablefails 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 themaxSlotseviction keepsmaxSlots-1live entries before inserting, i.e. the bound is exact. - Registration's store path is equivalent to the memory path: consume confirms
presentedChallengeequals the server-stored challenge, and attestation/assertion verification binds the signedclientDataJSONto that same value. - Rate-limiter Lua prunes and counts in one script; sliding window,
PEXPIRErefresh, 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.txtgrowth is public-header extraction only. Both new test files land under globbed directories, so they are actually built and run.
f9439cf to
c3b9413
Compare
3b34d03 to
ab12432
Compare
voidvec
left a comment
There was a problem hiding this comment.
PR #390 Code Review — Blocking (P0) & High-Priority (P1) Findings
Reviewed at ab124329 (rebased onto origin/master 9fe36a27).
P0 / Blocking
-
CURLOPT_RESOLVEpassedconst char *instead ofstruct 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 toCURLOPT_RESOLVE, which expects astruct curl_slist *. In variadiccurl_easy_setopt, libcurl interprets the string bytes as acurl_sliststruct (data/next), causing immediate UB/segfault on any outbound webhook delivery whenallowPrivateTargets == false. - Fix: Build a
curl_slistviacurl_slist_append(nullptr, resolveEntries.c_str())(managed by RAIIunique_ptrwithcurl_slist_free_all, failing closed on allocation failure) and passresolveList.get()toCURLOPT_RESOLVE.
- Location:
-
CURLOPT_PROTOCOLSdeprecated in libcurl >= 7.85.0 (breaks Linux CI-Werror=deprecated-declarations)- Location:
apps/server/src/bootstrap/IdentityAssembly.cc:454 - Issue:
CURLOPT_PROTOCOLSfailsBuild & Test (linux)and all 3Optional Feature Matrixjobs under-DFULLA_WERROR=ON. Additionally, whenallowPrivateTargets == false,parseTargetUrl()only permitshttps://, so allowing HTTP in libcurl is broader than intended. - Fix: Guard with
#if defined(LIBCURL_VERSION_NUM) && LIBCURL_VERSION_NUM >= 0x075500to useCURLOPT_PROTOCOLS_STR(allowPrivateTargets ? "http,https" : "https"), falling back toCURLOPT_PROTOCOLSon older libcurl.
- Location:
P1 / High
- Session commit rollback revokes the wrong
ISessionStorekey after clearingsession_store_id- Locations:
libs/drogon/src/controllers/SessionController.cc:1100-1102libs/drogon/src/controllers/WebAuthnController.cc:725-727
- Issue: Both
commitAuthenticatedSessionfailure handlers calldetail::clearPasswordLoginAuthenticationState(*req->session())beforerevokeRequestSession(sessionStore, req). BecauseclearPasswordLoginAuthenticationStateerases"session_store_id",revokeRequestSessionfalls back toreq->session()->sessionId()(the Drogon cookie ID) instead of the newly rotatedsession_store_idUUID, leaving an orphaned active session record in Redis ifstore->puttimed out after writing. - Fix: Call
revokeRequestSession(sessionStore, req)beforeclearPasswordLoginAuthenticationState(*req->session()), matchingMfaController.cc:871-876and all other call sites.
- Locations:
0afc2a7 to
ac8c510
Compare
代码评审意见(仅记录 P0 阻断项与 P1 重要问题)基于当前 HEAD ( P0 阻断项
P1 重要问题
|
…e state to Redis ports
…rror=format-truncation
…ion rollback order
…uthn challenge overwrite
ac8c510 to
8de68cf
Compare
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).