Skip to content

fix(limiter): Bearer-only identity derivation closes the rotation bypass - #454

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

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

Conversation

@Alajmah

@Alajmah Alajmah commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

The separately authorized production remediation for the identity bypass reproduced in #453 (now merged). Narrowly bounded: one middleware change plus regressions; middleware order, 120/min threshold, health/webhook exclusions, and Redis fail-open semantics all unchanged.

The fix

Limiter identity now recognizes exactly what apiKeyAuth recognizes — the case-sensitive Bearer prefix with a single space — and uses the token as the identity; every other form (Basic …, lowercase bearer …, tab-separated, malformed, or absent) falls back to the request IP. The exact alignment is load-bearing: my first implementation used a looser regex (^Bearer\s+(.+)$/i), and the identity suite's own test cases caught that Bearer\t<rotating> and bearer <rotating> would have re-opened the bypass through forms auth rejects. The final derivation is startsWith("Bearer ") + slice(7).trim() — byte-for-byte the auth middleware's recognition.

Regressions (identity suite, 10 tests)

  • The reproducer scenario, fixed: 130 rotating-Basic requests from one valid session (real apiKeyAuth, production mount order) now hit 429 at request 121 on ONE shared bucket — bucket count asserted as exactly 1 with a count of 121.
  • Header-absent session traffic: unchanged (throttles on the shared IP bucket).
  • Well-formed Bearer tokens remain distinct identities.
  • Lowercase-scheme and tab-separator forms pinned to the IP bucket (the residual vectors the first draft missed).
  • Bearer separation at the threshold: saturated key, other key, and IP all independent.

The behavior suite's reproducer block now asserts the fixed state while documenting the historical defect; all existing behavior pins stand (19 across the two suites).

Holding at the merge gate — exact head f5f80fbc160f29f95edaf7944a7a1cb19865a16f. After merge and deploy, the 13 API-route alerts' false-positive classification can be revisited with both the chain evidence and the closed bypass.

The limiter sliced the raw Authorization header as its identity without
checking the scheme, while apiKeyAuth accepts a valid session cookie
whenever the header is absent or not Bearer — so a session-
authenticated caller rotating 'Authorization: Basic <anything>' minted
a FRESH rate bucket per request, defeating the per-IP fallback
(reproduced end-to-end with the real apiKeyAuth in the behavior suite).

Identity now recognizes EXACTLY what apiKeyAuth recognizes — the
case-sensitive 'Bearer ' prefix with a single space — and uses the
token as identity; every other form (Basic, lowercase bearer,
tab-separated, malformed, absent) falls back to the request IP. The
exact alignment is load-bearing: writing the recognition looser than
auth's re-opens the bypass through whichever forms auth rejects (the
identity suite pins 'bearer x' and 'Bearer\tx' to the IP bucket for
exactly this reason).

Unchanged by contract: 120/min threshold, /health + /webhooks
exclusions, Redis fail-open, window TTL.

Regressions (identity suite, 10): THE REPRODUCER SCENARIO FIXED —
130 rotating-Basic requests from one session hit 429 at request 121
on ONE shared bucket (count=121 asserted); header-absent session
traffic unchanged; well-formed Bearer tokens remain distinct
identities; lowercase-scheme and tab-separator forms fall back to IP;
Bearer separation at the threshold (saturated key, other key, and IP
all independent). The behavior suite's reproducer block now asserts
the fixed state (rotation throttles on one bucket) while documenting
the historical defect; all existing behavior pins stand (19 total).

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-09T08:13:51.232877Z f5f80fb 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: f5f80fbc16

ℹ️ 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 +29 to +30
const bearerToken = typeof authHeader === "string" && authHeader.startsWith("Bearer ")
? authHeader.slice(7).trim()

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 Keep unauthenticated Bearer values in the IP bucket

When requests target a pre-authentication route such as POST /api/auth/login, a caller can attach a fresh Authorization: Bearer <random> value to every password guess. app.js mounts rateLimiter before authRouter (lines 84–87), while the login handler only validates the body password (routes/auth.js lines 41–48), so each unauthenticated token creates a new Redis bucket and bypasses the intended 120-request limit. Only authenticated API keys should receive token-specific buckets; anonymous and pre-authentication traffic must remain keyed by IP.

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: 5
AI judgment: NEEDS DISCUSSION · Evidence: COMPLETE · Authority: advisory
Evidence complete · 3/3 changed files accounted for

Key issues

  • [HIGH] IP fallback derivation may be spoofable or NAT-colliding, partially resurrecting the bypass the PR claims to close 🔍 ⚠️ unverified

Other findings (4)

  • [low] Identity-suite test title and stale comment contradict the (correct) case-sensitive assertions
  • [medium] Case-sensitive scheme matching diverges from RFC 9110 and silently IP-buckets spec-compliant clients ⚠️ unverified
  • [medium] Unbounded bucket creation from arbitrary Bearer strings if the limiter evaluates before token validation ⚠️ unverified
  • [low] Bearer-only derivation silently re-buckets any non-Bearer auth scheme ⚠️ unverified

🔮 Devil's Advocate (3 turns): 4 missed risks found · 1 upheld


GitWire AI Review Gate (bundle-driven v2) · Structured schema · Scope-validated · Devil's Advocate · AI recommendation — maintainers and repository policy retain authority

Finding details (not annotatable inline)

  • [MEDIUM] Case-sensitive scheme matching diverges from RFC 9110 and silently IP-buckets spec-compliant clients

    The very tests the review cited prove that a lowercase 'bearer' scheme (valid per RFC 9110, which treats auth-scheme as case-insensitive) and tab-separated schemes fall back to the shared IP bucket. A spec-compliant client is therefore demoted to anonymous and, behind NAT/CGNAT, inherits strangers' rate budgets. The initial review complained about the test title describing this behavior but never flagged the behavior itself as a functional/spec deviation that should either be fixed or documented as an accepted hardening trade-off.

  • [HIGH] IP fallback derivation may be spoofable or NAT-colliding, partially resurrecting the bypass the PR claims to close

    The fix routes unauthenticated or odd-scheme traffic into IP buckets, but nothing in the review verifies how the IP is derived. If it is taken from X-Forwarded-For/X-Real-IP without a trusted-proxy gate, an attacker rotates buckets per request and the 'closed' rotation bypass reopens via headers instead of tokens. Conversely, behind CGNAT an attacker can exhaust the shared IP bucket to throttle bystanders. Either failure mode is more severe than anything the review raised and should have been explicitly checked or its deployment assumption documented.

  • [MEDIUM] Unbounded bucket creation from arbitrary Bearer strings if the limiter evaluates before token validation

    Bearer-only identity makes the raw token the bucket key. If the limiter runs on requests whose tokens have not yet been validated, an attacker can send random token strings to mint unlimited buckets — a memory-growth vector and a residual rotation path (every garbage string is a fresh identity). The review should have confirmed evaluation ordering (auth validation before limiting) or the existence of bucket caps/eviction; no finding addresses this architectural dependency of the fix.

  • [LOW] Bearer-only derivation silently re-buckets any non-Bearer auth scheme

    If GitWire/Octo-Lex honors any other credential anywhere (Basic, custom API-key headers), those requests now share IP budgets and lose per-identity limits — a behavior change smuggled into a 'fix' PR with no migration note or dual-scheme test coverage. Possibly moot if Bearer is the sole supported scheme, but the review should have stated that explicitly rather than leaving it unexamined.

setHeader(k, v) { this.headers[k] = v; },
status(code) { this.statusCode = code; return this; },
json(body) { this.body = body; resolve({ res, passed: false }); return this; },
};

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] Identity-suite test title and stale comment contradict the (correct) case-sensitive assertions

In rate-limiter-identity.test.js, the test titled "a well-formed Bearer token IS the identity (case-insensitive scheme)" asserts the opposite of its title: it explicitly verifies that lowercase "bearer key-lower" falls back to the IP bucket (i.e., scheme matching is case-sensitive). Since exact recognition is the load-bearing contract of this PR, a title claiming "case-insensitive" could mislead future maintainers into believing lowercase-Bearer forms mint token buckets — precisely the residual vector this remediation closes. Relatedly, the it.each comment for "Bearer\tgap-token" ("tab not matched by \s+? (regex ^Bearer\s+ — tab IS \s; assert below)") references the abandoned draft regex and is self-contradictory; the assertions themselves are correct against the shipped startsWith("Bearer ") logic. Suggested fix: retitle to e.g. "a well-formed Bearer token IS the identity (scheme matching is case-sensitive)" and replace the stale comment with "tab after scheme is not matched by startsWith("Bearer ")". Documentation-only; no runtime impact.

@Alajmah

Alajmah commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Adjudication — GitWire AI Review @ f5f80fb (NEEDS DISCUSSION, medium confidence, 5 findings)

Disposition: none blocking; the HIGH is refuted with verified deployment facts, one MEDIUM yields a real documented trade-off, one a recorded follow-up.

HIGH — "IP fallback may be spoofable (X-Forwarded-For) or NAT-colliding": refuted on spoofing, documented on sharing

  • Spoofing: not reachable. app.set('trust proxy') appears NOWHERE in the app (grep across packages/web/src — no matches). With trust proxy disabled, Express's req.ip is the direct TCP socket address; client-supplied X-Forwarded-For/X-Real-IP headers are never read for identity. Header rotation cannot mint buckets.
  • Sharing: real, pre-existing, and now documented. Production ingress is Cloudflare tunnel → the tunnel container IS the direct peer, so all tunnelled non-Bearer traffic shares one bucket (the tunnel's IP). That was equally true before this PR (the IP fallback had the same property) — the fix changes nothing about it, and it errs safe (a shared budget, not per-attacker budgets). Recorded here as the deployment assumption: per-client IP differentiation behind the tunnel would require trust-proxy configuration, which is a separate decision with its own spoofing trade-offs.

MEDIUM — "case-sensitive scheme diverges from RFC 9110": accepted trade-off, deliberately

The case sensitivity is byte-for-byte apiKeyAuth's recognition (startsWith("Bearer ")). A lowercase-bearer client is not Bearer-authenticated by the app either — IP-bucketing it is consistent with how the app itself treats it. Loosening the limiter beyond auth's recognition re-opens the rotation bypass through exactly the forms auth rejects (that residual vector was caught by this PR's own test cases during development and is pinned in the identity suite). The regression-suite title/comment inconsistency the finding also notes is real — cosmetic, recorded.

MEDIUM — "unbounded buckets from arbitrary Bearer strings": not a bypass; exposure unchanged, bounded by TTL

Verified against apiKeyAuth source: when a Bearer header is present, providedKey is set and the session-cookie path is never consulted — an invalid Bearer token gets 401 regardless of cookies. So garbage-Bearer rotation cannot ride a session (the reproduced bypass class). Unauthenticated garbage-Bearer floods mint Redis keys at 60s TTL each — the same exposure the pre-fix limiter had for ANY header value, bounded by TTL expiry; requests 401 anyway. A bucket cap/eviction policy is a recorded hardening follow-up, not a regression of this PR.

MEDIUM/LOW — "non-Bearer schemes silently re-bucketed": no supported scheme is affected

apiKeyAuth supports exactly two credentials: the Bearer key and the session cookie. Cookie traffic was ALWAYS IP-bucketed (correctly — that is the fallback the bypass abused). No Basic/custom-scheme consumer exists to re-bucket.

Gate state: all 21 checks green, mergeStateStatus: CLEAN, head f5f80fbc160f29f95edaf7944a7a1cb19865a16f — holding for maintainer clearance.

@Alajmah

Alajmah commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by the v2 PR: /api/auth/login now throttles on the request IP (unverified Bearer tokens never become its identity), with the end-to-end rotating-token regression.

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