Skip to content

fix(limiter): pre-auth family coverage + advisory remediation + structural bearer lockstep (v8) - #463

Closed
Alajmah wants to merge 2 commits into
masterfrom
security/limiter-identity-v8
Closed

Alajmah wants to merge 2 commits into
masterfrom
security/limiter-identity-v8

Conversation

@Alajmah

@Alajmah Alajmah commented Nov 20, 2026

Copy link
Copy Markdown
Contributor

Summary

Round 3 of the limiter identity remediation, carrying the pre-auth family extension, advisory remediation, and the review-adjudication corrections from #460 → #462 → here. Supersedes #460 and #462 (both held; heads superseded by this chain).

What this fixes

1. Rate-limiter identity bypass — pre-auth route families (the #460 hold)

deriveLimiterIdentity() now keys the two pre-auth route families on the request IP for every request, closing the last mint-a-bucket-per-request surfaces:

  • /api/auth/* — login (body-password auth), check (session-cookie auth), logout. These mount at app.js:87, before apiKeyAuth at app.js:96.
  • /api/bootstrap/* — state (anonymous DB query), first (bootstrap-gated). Mount at app.js:93, before apiKeyAuth.

Family matching is prefix-based with trailing-slash and case tolerance (/^\/api\/auth(\/.*)?\/?$/i, same shape for bootstrap) — Express's default non-strict, case-insensitive-to-route routing serves all 8 path variants to the same handlers, and all 8 are regressions.

2. Bearer recognition lockstep — now structural (the #462 review finding)

apiKeyAuth (auth.js) and deriveLimiterIdentity (rateLimiter.js) previously held unlinked copies of the same recognition rule, kept in sync only by comments. Both now call one shared implementation:

  • packages/web/src/middleware/bearerToken.js — extractBearerToken(): case-sensitive "Bearer " prefix (single literal space), slice(7).trim().
  • 12-case corpus contract test (rate-limiter-identity.test.js) pins the single rule both mechanisms depend on: a header authenticates exactly when the shared recognizer extracts a token; the limiter keys on that token exactly when the recognizer extracts one. A recognized-but-invalid token still mints its own bucket on ordinary paths (documented in-test), while pre-auth families force the IP regardless.
  • Also fixes the garbled corpus comment that cited a nonexistent ^Bearer\s+ regex — that misdescription is what seeded review finding 3's divergence theory; the actual auth code (startsWith("Bearer ")) is byte-identical in recognition to the limiter's, so no divergence exists.

3. Advisory remediation (the #457 master-push failure)

package from to advisories
next (web-dashboard) 16.3.8 16.4.6 3 critical (≤16.4.0) + high
next (demo-dashboard/landing) 15.5.24 15.5.28 15.5-line advisory floor
@next/swc-* (8 platforms) 16.3.3 16.4.6 version alignment (mismatch crashes build)
body-parser (override) 1.20.3 1.20.9 GHSA-27r3
zod ^3.22.0 ^4.6.6 GHSA-mrhx

Required for next 16.4.x: middleware.ts → proxy.ts (file AND function-export rename — the deprecated middleware convention). The dashboard build was verified locally under 16.4.6; the demo dashboard build was verified locally under 15.5.28 (this round). The demo-dashboard manifest now pins 15.5.28 to match the lockfile (the v7 hand-carry left the manifest at 15.5.24 — any npm install would have silently reverted the advisory floor; npm ci dry-run now verifies consistent).

Verification

  • Web: 38 limiter tests (17 identity + 9 behavior + 12 contract) + 15 triage-pr-guards (imports auth.js) — all green
  • Lockfile: npm ci --dry-run passes (manifest↔lockfile consistent)
  • Builds: web-dashboard green under next 16.4.6 (prior round); demo-dashboard green under 15.5.28 (this round)
  • Audit gate: 0 high/critical
  • zod v4 compatibility (review finding 1): the three consumers (config/index.js, ciHealJobService.js, issueFixJobService.js) use only v4-stable APIs (z.object/.string/.union/.enum/.literal/.coerce, .optional/.default/.refine(fn, "msg"), parsed.error.issues — the v4-native shape, not v3's .errors); all three are covered by green test suites (config-validator, ci-heal-job-service, issue-fix-analysis-safety)

Review-adjudication notes (carried from #462)

  • Finding 1 (zod v4): verified compatible — evidence above.
  • Finding 2 (garbled comment): VALID — fixed (corpus comment rewritten; root cause also addressed structurally).
  • Finding 3 (Bearer divergence): premise false — apiKeyAuth has no regex and no whitespace tolerance (auth.js:78 pre-refactor: startsWith("Bearer ")); Bearer\t… is rejected by BOTH mechanisms. Seeded by the finding-2 comment, now fixed.
  • Finding 4 (lockstep by comment): VALID — fixed structurally (shared helper + corpus contract test).
  • Finding 5 (uneven compat scrutiny): gap closed — demo dashboard build verified under 15.5.28; manifest/lockfile consistency now enforced; dashboard (16.4.6) was already build-verified in v7.
  • Finding 6 (throttling legit unauthenticated traffic): premise false — the limiter at app.js:84 has always covered /api/auth and /api/bootstrap (they mount after it); this chain changes the identity KEY on those routes (per-rotated-token → per-IP), not the coverage, and the window/threshold (120/min) is unchanged. The behavioral delta for a legitimate caller is strictly: a stable token on a pre-auth route now shares the IP bucket instead of having a private one — which is the intended brute-force tightening.

…n (next 16.4.6, body-parser, zod)

PRE-AUTH EXTENSION (maintainer finding on #460): /api/auth/check
(session-cookie Redis lookup) and /api/bootstrap/state + /first
(anonymous DB work) mount before apiKeyAuth and carried the same
bucket-rotation mechanism. The pre-auth match now covers the COMPLETE
/api/auth/* and /api/bootstrap/* families (prefix regex, case +
trailing-slash tolerant). Bearer identity unchanged for ordinary
authenticated routes. Three new regressions: AUTH-CHECK end-to-end
(130 rotating-Bearer session requests → 429@121 ONE bucket);
BOOTSTRAP-STATE end-to-end (130 anonymous → 429@121 ONE bucket);
FAMILY VARIANTS (8 path forms all key on the IP).

THREE-LAYER REMEDIATION (carried): session-cookie rotation closed
(apiKeyAuth-exact recognition); pre-auth login closed (IP-keyed);
route-variant closed (trailing slash + case); derivation isolated
(derived as an exported function — the CodeQL missing-rate-limiting
model pairing resolved without behavior change).

ADVISORY REMEDIATION (the #457 master-push CI failed on seven new
advisories, three critical, on next ≤16.4.0):
- next 16.3.8→16.4.6 (dashboard; GHSA-2464 critical, GHSA-673q
  critical, GHSA-p3m5 high): requires middleware.ts→proxy.ts rename
  (function export renamed too) + @next/swc platform binaries
  hand-carried to 16.4.6 (the version mismatch crashed builds with
  'Cannot read properties of undefined (reading project)').
- next 15.5.24→15.5.28 (landing; same advisories' 13.x-15.x range).
- body-parser 1.20.6→1.20.9 (override; GHSA-27r3 high).
- zod 3.25.76→4.6.7 (web; GHSA-mrhx high).
Lockfile entries hand-carried with registry integrities (npm on
Windows refused to re-resolve overrides + platform binaries — the
known quirk).

VERIFICATION: audit gate 0 high/critical; limiter identity (17) +
behavior (9) + webhook body-limit (14) = 40 tests green; dashboard
5 suites / 66 tests green; dashboard build verified locally
(compiled successfully, 29/29 static pages).

Signed-off-by: Alajmah <55954113+Alajmah@users.noreply.github.com>
…t; demo-dashboard manifest sync

Adjudication corrections for the v7 chain (#462 review):

- apiKeyAuth and deriveLimiterIdentity held unlinked copies of the same
  Bearer recognition rule, kept in sync only by comments. Both now call a
  shared extractBearerToken() (bearerToken.js), and a 12-case corpus
  contract test pins the one rule both mechanisms depend on — divergence
  in either direction becomes a test failure, not a silent re-opening of
  the bucket-rotation bypass.
- Fixed a garbled test comment that cited a nonexistent ^Bearer\s+ regex
  for the tab-scheme case; apiKeyAuth actually uses a literal starts-with
  "Bearer " check, byte-identical to the limiter's recognition.
- demo-dashboard manifest pinned next 15.5.24 while the hand-carried
  lockfile resolves 15.5.28 — any npm install would have silently
  reverted the advisory floor. Manifest now matches the lockfile (npm ci
  dry-run verified); demo dashboard build verified green under 15.5.28.

Limiter semantics unchanged: 38 limiter tests + 15 triage-pr-guards green.

Signed-off-by: Alajmah <55954113+Alajmah@users.noreply.github.com>
@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-20T20:23:59.994024Z
We couldn’t complete this review. Comment @codex review to try again.
e4b17b7 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.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

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

Other findings (5)

  • [low] Major zod upgrade (3 to 4) bundled into a security patch without any migration changes
  • [low] Lockstep guarantee overstated: query-param API-key auth has no limiter identity counterpart
  • [medium] Pre-auth limiter identity derived from attacker-controlled Authorization header enables bucket rotation ⚠️ unverified
  • [low] Pre-auth per-IP coverage can lock out legitimate users behind shared egress IPs ⚠️ unverified
  • [low] Shared bearer helper's secret comparison not shown to be constant-time ⚠️ unverified

🔮 Devil's Advocate (2 turns): 3 missed risks found · 2 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] Pre-auth limiter identity derived from attacker-controlled Authorization header enables bucket rotation

    deriveLimiterIdentity considers only the Authorization header — on pre-auth endpoints that header is fully attacker-controlled. If an unverified/fake bearer token gets hashed into its own identity bucket rather than falling back to IP, an attacker can rotate arbitrary token strings to obtain a fresh rate-limit bucket on every request, defeating exactly the brute-force protection the 'pre-auth family coverage' claims to add. The review audited the auth-vs-limiter identity equivalence (Finding #1) but never asked whether the identity is trustworthy for requests that fail authentication. This needs explicit verification of the invalid-token fallback path before the lockstep claim is safe.

  • [LOW] Pre-auth per-IP coverage can lock out legitimate users behind shared egress IPs

    If 'pre-auth family coverage' extends IP-based (or IP-fallback) limits to unauthenticated endpoints such as login/bootstrap, users behind corporate NAT, CGNAT, or shared VPN egress share a single bucket. One noisy client or an active scanner can 429 an entire office during login, turning a security control into an availability incident. The review evaluated limiter identity precision but not the collective-punishment trade-off of IP-keyed pre-auth limits, which is the standard counterweight to this design.

  • [LOW] Shared bearer helper's secret comparison not shown to be constant-time

    The 'structural bearer lockstep' consolidates bearer handling into a single helper consumed by both auth and limiter identity derivation. If that helper (or the key/token comparison against stored secrets) uses plain string equality rather than crypto.timingSafeEqual, the refactor concentrates a timing side channel into one chokepoint reachable from two call paths. The review verified identity equivalence between the two mechanisms but not the cryptographic safety of the newly shared comparison code — the natural follow-up question this refactor begs.

Comment thread packages/web/package.json
"pino-pretty": "^10.0.0",
"yaml": "^2.9.0",
"zod": "^3.22.0"
"zod": "^4.6.6"

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] Major zod upgrade (3 to 4) bundled into a security patch without any migration changes

packages/web/package.json jumps zod from ^3.22.0 to ^4.6.6. Zod 4 ships breaking API changes (error-customization signatures, z.record arity requirements, removed/deprecated helpers, changed error shape). This PR touches no validation source code, so zod-4 compatibility is unverified from the diff; if the web package uses any affected API, request-time validation on auth/session/bootstrap routes could break after deploy. The stated advisory remediation (next bumps, body-parser pin) does not obviously require a zod major bump. Suggest confirming the web package is zod-4 compatible via typecheck and full test run, or splitting this bump into its own PR so a runtime regression cannot ride in under a security fix.

}
// Extract key from header or query param.
// Recognition lives in the shared bearerToken.js helper so apiKeyAuth and
// the rate limiter cannot drift apart (the limiter derives its identity

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] Lockstep guarantee overstated: query-param API-key auth has no limiter identity counterpart

The new comment in auth.js claims the limiter 'derives its identity from the exact same forms auth accepts', and the corpus test frames bearerToken.js as the single rule both mechanisms depend on. However, apiKeyAuth still extracts a key from a query parameter as well (the retained 'Extract key from header or query param' comment; only the header branch moved into the shared helper), while deriveLimiterIdentity considers only the Authorization header. Consequence: a caller authenticating via query-param key is throttled per-IP, so distinct keys behind one shared IP share a single bucket and one caller at that IP can exhaust another tenant's quota. This is pre-existing behavior (the old limiter also ignored query params), not a regression introduced here, but the newly added 'exact same forms' claim is inaccurate and could mislead future security audits. Either mirror the query-param key in the limiter identity or soften the comment to 'the same Authorization header forms'.

@Alajmah

Alajmah commented Nov 20, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #464 (v9): the review's finding 2 exposed a stale auth.js comment claiming a query-param auth channel that does not exist (predates this chain, preserved by the v8 refactor) — fixed there. All 5 findings adjudicated with evidence in #464's body. Head chain: e4b17b7 → d3f3fa2.

@Alajmah Alajmah closed this Nov 20, 2026
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