Skip to content

fix(limiter): Bearer-only identity + IP-keyed pre-auth login throttle - #456

Closed
Alajmah wants to merge 1 commit into
masterfrom
security/limiter-identity-v2
Closed

Alajmah wants to merge 1 commit into
masterfrom
security/limiter-identity-v2

Conversation

@Alajmah

@Alajmah Alajmah commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

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/login authenticates by request-body password regardless of the Authorization header. Rotating Bearer <random-N> across password guesses minted a fresh bucket per attempt. The fix: /api/auth/login always 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 /api paths still derive identity from well-formed Bearer tokens.

Everything from #454 stands

  • The session-cookie rotation bypass stays closed: identity recognition is byte-for-byte 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.
  • Valid Bearer traffic keeps per-token buckets (pinned at the threshold: saturated key, other key, and IP independent).
  • Deployment facts documented on the record: no trust proxy 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). Invalid-Bearer Redis-key growth stays a TTL-bounded documented follow-up.
  • Threshold, exclusions, and fail-open semantics untouched.

Suites: identity 13 tests + behavior 9 pins + fixed-state reproducer history — all green. Holding at the merge gate — exact head a9a6f6c2200028432125905baa053ecd0dae7ec4.

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>
@Alajmah

Alajmah commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

/gitwire run review

@gitwire-hq

gitwire-hq Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

▶️ GitWire: Re-evaluation triggered for review. Results will appear shortly.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-09T09:06:04.375139Z a9a6f6c 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 chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +36 to +37
const PRE_AUTH_IP_IDENTITY_PATHS = ["/api/auth/login"];
const useIpIdentity = PRE_AUTH_IP_IDENTITY_PATHS.includes(req.path);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

@gitwire-hq gitwire-hq Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🤖 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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"];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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()] };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[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'.

@Alajmah

Alajmah commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

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.

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.

1 participant