Repository navigation
Conversation
Two-layer remediation of the rate-limit identity bypass family:
1. Session-cookie rotation bypass (CLOSED): limiter identity recognizes
EXACTLY apiKeyAuth's scheme ('Bearer ' prefix, case-sensitive, single
space, slice(7).trim()) — byte-for-byte the auth middleware's
recognition, deliberately: writing it looser re-opens the bypass
through forms auth rejects (Bearer\t<rotating>, bearer <rotating> —
caught by the identity suite's own cases during development). Every
other Authorization form falls back to the request IP. End-to-end
regression: 130 requests from one valid session with rotating Basic
headers hit 429 at request 121 on ONE shared bucket.
2. Pre-authentication login bypass (CLOSED): the limiter runs before
authentication, so an unverified Bearer token must never become the
throttle identity on an endpoint that authenticates by other means —
/api/auth/login validates the request-body password. Login attempts
now ALWAYS derive identity from the request IP. End-to-end
regression: 130 login attempts with rotating random Bearer tokens
hit 429 at request 121 on ONE shared bucket (each attempt still
401s at the route).
Unchanged by contract: 120/min threshold, /health + /webhooks
exclusions, Redis fail-open, window TTL, valid-Bearer per-token
buckets on non-login paths (pinned). Deployment fact documented:
no trust proxy is configured anywhere — req.ip is the socket
address, so forwarded-header spoofing cannot mint buckets; tunnelled
traffic shares the tunnel peer's bucket (pre-existing, errs safe).
Suites: identity (13: reproducer-fixed, lowercase/tab forms, Bearer
separation, login end-to-end/no-header/non-login) + behavior (9 pins
+ fixed-state reproducer history). Invalid-Bearer Redis-key growth
remains a TTL-bounded documented hardening follow-up.
Signed-off-by: Alajmah <55954113+Alajmah@users.noreply.github.com>
|
/gitwire run review |
|
|
Codex Review SummaryThis 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. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: a9a6f6c220
ℹ️ 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".
| const PRE_AUTH_IP_IDENTITY_PATHS = ["/api/auth/login"]; | ||
| const useIpIdentity = PRE_AUTH_IP_IDENTITY_PATHS.includes(req.path); |
There was a problem hiding this comment.
Match every login path spelling accepted by Express
When an attacker posts to /api/auth/login/ or a mixed-case variant such as /api/auth/LOGIN, Express's default non-strict, case-insensitive routing still invokes the login handler, but this exact includes(req.path) check returns false. The rotating random Bearer token then becomes the limiter identity, giving every password guess a fresh bucket and preserving the brute-force bypass this change is intended to close; match the login route using the same path semantics as Express.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
🤖 AI Code Review — 💬 Needs discussion
Confidence: medium · Findings: 3
AI judgment: NEEDS DISCUSSION · Evidence: COMPLETE · Authority: advisory
Evidence complete · 3/3 changed files accounted for
Key issues
- [HIGH] .trim() on the sliced Bearer token breaks the claimed byte-for-byte parity with apiKeyAuth, leaving a whitespace-variant rotation bypass (
packages/web/src/middleware/rateLimiter.js) 🔮 - [HIGH] Pre-auth path check is an exact req.path match — trailing slash or different case re-opens the login bucket-minting bypass (
packages/web/src/middleware/rateLimiter.js) 🔮
Other findings (1)
- [low] Test title contradicts its assertion: scheme is case-sensitive, not 'case-insensitive'
🔮 Devil's Advocate (2 turns): 3 upheld
GitWire AI Review Gate (bundle-driven v2) · Structured schema · Scope-validated · Devil's Advocate · AI recommendation — maintainers and repository policy retain authority
|
|
||
| const authHeader = req.headers.authorization; | ||
| const bearerToken = !useIpIdentity && typeof authHeader === "string" && authHeader.startsWith("Bearer ") | ||
| ? authHeader.slice(7).trim() |
There was a problem hiding this comment.
[HIGH] .trim() on the sliced Bearer token breaks the claimed byte-for-byte parity with apiKeyAuth, leaving a whitespace-variant rotation bypass
The diff's own invariant is 'recognition is EXACTLY apiKeyAuth's ... anything looser re-opens the rotation bypass', but the extraction applies .trim() to authHeader.slice(7). For 'Bearer ' (double space) or values with interior padding, the limiter keys on the trimmed token ('') while a strict single-space-prefix extraction in auth yields ' ' (invalid); under a /^Bearer\s+(.+)/ extraction the padded variants diverge differently but still diverge (e.g. trailing-tab). In both cases there exist whitespace variants where the limiter treats the value as a per-request-unique token identity but auth does not authenticate it: rotating 'Bearer x1', 'Bearer x2', ... against any non-login /api path mints a fresh bucket per request, and when a session cookie is present and auth falls back to session on a failed Bearer parse (the exact fallback the original Basic-header bypass exploited), the 130-requests-all-200 reproducer still succeeds. The whitespace cases are also unpinned by the new tests, which only use clean single-space tokens. Fix: extract the credential exactly as auth.js does (share one helper, no independent trim), and add identity tests pinning double-space and padded-token variants against the real apiKeyAuth.
| // unauthenticated caller can rotate random Bearer values to mint a fresh | ||
| // bucket per password-guess. Those endpoints always key on the request | ||
| // IP — an unverified token must never become their throttle identity. | ||
| const PRE_AUTH_IP_IDENTITY_PATHS = ["/api/auth/login"]; |
There was a problem hiding this comment.
[HIGH] Pre-auth path check is an exact req.path match — trailing slash or different case re-opens the login bucket-minting bypass
PRE_AUTH_IP_IDENTITY_PATHS.includes(req.path) is an exact string comparison, but Express routing is by default case-insensitive and trailing-slash tolerant (strict: false, caseSensitive: false). 'POST /api/auth/login/' and 'POST /API/AUTH/LOGIN' both reach the login route handler, yet their req.path values ('/api/auth/login/', '/API/AUTH/LOGIN') do not match the list, so useIpIdentity is false and the identity falls back to the (rotatable) Bearer token. An attacker rotating random 'Bearer ' values against the trailing-slash URL mints a fresh bucket per password guess — the exact bypass this PR fixes, one character away. The new tests only exercise the canonical path. Fix: normalize before comparing (e.g. req.path.replace(//+$/, '').toLowerCase()), or resolve the match with the same routing options the app mounts with; add tests for the trailing-slash and case variants. Also verify the list covers every pre-auth endpoint (register/refresh/password-reset if present) — a hardcoded exact-path list silently keys any future pre-auth route on unverified tokens.
| describe("identity derivation contract (middleware-level)", () => { | ||
| function runMiddleware({ headers = {}, ip } = {}) { | ||
| return new Promise((resolve) => { | ||
| const req = { path: "/api/anything", headers, ip, get: (h) => headers[h.toLowerCase()] }; |
There was a problem hiding this comment.
[LOW] Test title contradicts its assertion: scheme is case-sensitive, not 'case-insensitive'
The test 'a well-formed Bearer token IS the identity (case-insensitive scheme)' asserts the opposite of its title: 'bearer key-lower' (lowercase scheme) is expected to fall back to the IP bucket, i.e. the scheme recognition is case-sensitive, matching the middleware comment. The contradictory title will mislead future audits of the identity contract (exactly the kind of audit this PR's security reasoning depends on). Rename to something like 'a well-formed Bearer token IS the identity; a lowercase scheme is not Bearer and falls back to the IP'.
|
Superseded by the v3 PR: trailing-slash/case-tolerant pre-auth matching with the variant regression; the .trim()-parity HIGH refuted with apiKeyAuth's own parse; test title corrected. |
Supersedes #454 with the required pre-authentication correction (branch updates ruleset-refused).
The new correction: login attempts throttle on the IP
Your P1 finding was right — the limiter runs before authentication, so it cannot validate a Bearer token, and
/api/auth/loginauthenticates by request-body password regardless of the Authorization header. RotatingBearer <random-N>across password guesses minted a fresh bucket per attempt. The fix:/api/auth/loginalways derives identity from the request IP — an unverified token never becomes the throttle identity on an endpoint that doesn't authenticate by token.End-to-end regression (the exact required proof): 130 login attempts with rotating random Bearer tokens → 429 at request 121 on ONE shared bucket (bucket count = 1, counter = 121, each attempt still 401s at the route). Plus: no-header login traffic shares the same single bucket; non-login
/apipaths still derive identity from well-formed Bearer tokens.Everything from #454 stands
apiKeyAuth's ("Bearer "prefix, case-sensitive, single space); every other form falls back to the IP. The reproducer-fixed regression (130 rotating-Basic session requests → 429 at 121 on one bucket) and the residual-vector pins (lowercase scheme, tab separator) carry over.trust proxyanywhere —req.ipis the socket address, so forwarded-header spoofing cannot mint buckets; tunnelled traffic shares the tunnel peer's bucket (pre-existing, errs safe). Invalid-Bearer Redis-key growth stays a TTL-bounded documented follow-up.Suites: identity 13 tests + behavior 9 pins + fixed-state reproducer history — all green. Holding at the merge gate — exact head
a9a6f6c2200028432125905baa053ecd0dae7ec4.