From f5f80fbc160f29f95edaf7944a7a1cb19865a16f Mon Sep 17 00:00:00 2001 From: Alajmah <55954113+Alajmah@users.noreply.github.com> Date: Fri, 9 Oct 2026 11:10:56 +0300 Subject: [PATCH] fix(limiter): Bearer-only identity derivation closes the rotation bypass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 ' 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> --- packages/web/src/middleware/rateLimiter.js | 16 +- .../tests/unit/rate-limiter-behavior.test.js | 68 ++------ .../tests/unit/rate-limiter-identity.test.js | 155 ++++++++++++++++++ 3 files changed, 184 insertions(+), 55 deletions(-) create mode 100644 packages/web/tests/unit/rate-limiter-identity.test.js diff --git a/packages/web/src/middleware/rateLimiter.js b/packages/web/src/middleware/rateLimiter.js index a70d78c5..5a3aad6a 100644 --- a/packages/web/src/middleware/rateLimiter.js +++ b/packages/web/src/middleware/rateLimiter.js @@ -18,10 +18,18 @@ export function rateLimiter(req, res, next) { return next(); } - // Identity: prefer API key, fall back to IP - const identity = req.headers.authorization?.slice(7)?.trim() - || req.ip - || "unknown"; + // Identity: a properly formed Bearer token, else the request IP. The + // recognition is EXACTLY apiKeyAuth's ("Bearer " prefix, case-sensitive, + // single space): anything looser re-opens the rotation bypass (e.g. + // "Bearer\t" or "bearer " are NOT Bearer for auth, + // so they must not mint limiter buckets either). Reproduced end-to-end + // in rate-limiter-behavior.test.js; remediation pinned in + // rate-limiter-identity.test.js. + const authHeader = req.headers.authorization; + const bearerToken = typeof authHeader === "string" && authHeader.startsWith("Bearer ") + ? authHeader.slice(7).trim() + : ""; + const identity = bearerToken || req.ip || "unknown"; const key = `ratelimit:${identity}`; diff --git a/packages/web/tests/unit/rate-limiter-behavior.test.js b/packages/web/tests/unit/rate-limiter-behavior.test.js index e58d76bb..51d96167 100644 --- a/packages/web/tests/unit/rate-limiter-behavior.test.js +++ b/packages/web/tests/unit/rate-limiter-behavior.test.js @@ -157,67 +157,33 @@ describe("rate limiter behavior (Unit C — existing semantics pinned)", () => { }); }); -describe("REPRODUCER (known defect, recorded not fixed): non-Bearer Authorization headers split rate buckets under session auth", () => { - // The limiter identity is `req.headers.authorization?.slice(7)?.trim() || req.ip` - // — the scheme is never checked. apiKeyAuth accepts a VALID SESSION COOKIE - // when the Authorization header is absent or not Bearer. Chained as in - // production (limiter before auth), a session-authenticated caller rotates - // arbitrary non-Bearer Authorization values to get a fresh bucket per - // request. This documents the bypass end-to-end with the REAL apiKeyAuth; - // the fix is a separate production decision per the #425 review. - +describe('REPRODUCER HISTORY (bypass FIXED by rate-limiter-identity remediation on this branch)', () => { + // The original end-to-end reproducer (130 rotating Basic headers from one + // session, all passing, 130 distinct buckets) documented the identity + // defect that the Bearer-only derivation now closes. Full fixed-scenario + // coverage lives in rate-limiter-identity.test.js; here we assert the + // original attack no longer reproduces against the CURRENT middleware. function buildApp() { const app = express(); app.use(rateLimiter); app.use(apiKeyAuth); - app.get("/api/anything", (req, res) => res.json({ ok: true })); + app.get('/api/anything', (req, res) => res.json({ ok: true })); return app; } - it("END-TO-END: 130 requests from ONE session, rotating Basic headers, all pass — the per-IP fallback they should have shared never applies", async () => { + it('the original rotation attack now throttles: 121st request is 429 on ONE shared bucket', async () => { const app = buildApp(); - const sessionCookie = "gitwire-session=valid-session"; + const sessionCookie = 'gitwire-session=valid-session'; + let last = 200; for (let i = 0; i < 130; i += 1) { const res = await supertest(app) - .get("/api/anything") - .set("Authorization", `Basic rotating-value-${i}`) // arbitrary non-Bearer - .set("Cookie", sessionCookie); - expect(res.status).toBe(200); + .get('/api/anything') + .set('Authorization', "Basic rotating-value-" + i) + .set('Cookie', sessionCookie); + last = res.status; + if (res.status === 429) break; } - // 130 DISTINCT buckets were created — one per rotated header value — - // while the SAME session authenticated every request. Without the - // rotating header, all 130 would share the IP bucket and the last 10 - // would have been 429'd. - expect(redisState.counts.size).toBe(130); - expect([...redisState.counts.values()].every((n) => n === 1)).toBe(true); - }); - - it("CONTROL: the SAME session WITHOUT the header trick throttles at 120/min on the shared IP bucket", async () => { - const app = buildApp(); - const sessionCookie = "gitwire-session=valid-session"; - for (let i = 0; i < 120; i += 1) { - const res = await supertest(app) - .get("/api/anything") - .set("Cookie", sessionCookie); - expect(res.status).toBe(200); - } - // The 121st request on the shared IP bucket is the exact boundary the - // rotation bypasses — pinned, not "somewhere within 130". - const boundary = await supertest(app) - .get("/api/anything") - .set("Cookie", sessionCookie); - expect(boundary.status).toBe(429); - }); - - it("MECHANISM: the limiter bucket key derives from the raw sliced header, scheme unchecked", async () => { - const a = await runMiddleware({ headers: { authorization: "Basic value-1" }, ip: "10.9.9.9" }); - const b = await runMiddleware({ headers: { authorization: "Basic value-2" }, ip: "10.9.9.9" }); - expect(a.passed).toBe(true); - expect(b.passed).toBe(true); - // Two buckets for one IP — the sliced values differ even though neither - // is a credential. - expect(redisState.counts.size).toBe(2); - expect([...redisState.counts.keys()].join("|")).toContain("alue-1"); // slice(7) of "Basic value-1" - expect([...redisState.counts.keys()].join("|")).toContain("alue-2"); + expect(last).toBe(429); + expect(redisState.counts.size).toBe(1); // the IP bucket, not per-header buckets }); }); diff --git a/packages/web/tests/unit/rate-limiter-identity.test.js b/packages/web/tests/unit/rate-limiter-identity.test.js new file mode 100644 index 00000000..272cf673 --- /dev/null +++ b/packages/web/tests/unit/rate-limiter-identity.test.js @@ -0,0 +1,155 @@ +// tests/unit/rate-limiter-identity.test.js +// Production remediation for the identity bypass reproduced in +// rate-limiter-behavior.test.js: limiter identity now recognizes ONLY a +// properly formed Bearer scheme; every other Authorization form (and its +// absence) falls back to the request IP — so rotating non-Bearer headers can +// no longer mint fresh buckets for a session-authenticated caller. +// +// The behavior pins (threshold, exclusions, fail-open) live in the behavior +// suite against the same middleware; this suite proves the identity contract +// change end-to-end and in the middleware directly. + +import { jest } from "@jest/globals"; + +const redisState = { counts: new Map(), failWith: null }; + +jest.unstable_mockModule("../../src/lib/queue.js", () => ({ + redis: { + incr: jest.fn(async (key) => { + if (redisState.failWith) throw redisState.failWith; + const next = (redisState.counts.get(key) ?? 0) + 1; + redisState.counts.set(key, next); + return next; + }), + pexpire: jest.fn(async () => 1), + get: jest.fn(async (key) => { + if (key.startsWith("gitwire:session:")) { + return key.endsWith(":valid-session") ? JSON.stringify({ principal: "session-user" }) : null; + } + return null; + }), + expire: jest.fn(async () => 1), + }, +})); +jest.unstable_mockModule("../../src/lib/logger.js", () => ({ + logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() }, +})); +jest.unstable_mockModule("../../config/index.js", () => ({ + config: { anthropic: { apiKey: "test" }, github: { appId: "1", privateKey: "k", clientId: "x", clientSecret: "x", webhookSecret: "s" }, server: { baseUrl: "x" } }, +})); + +process.env.API_KEY = "unit-test-api-key"; + +const { rateLimiter } = await import("../../src/middleware/rateLimiter.js"); +const { apiKeyAuth } = await import("../../src/middleware/auth.js"); + +const express = (await import("express")).default; +const supertest = (await import("supertest")).default; + +function buildApp() { + // Production mount order: limiter BEFORE authentication. + const app = express(); + app.use(rateLimiter); + app.use(apiKeyAuth); + app.get("/api/anything", (req, res) => res.json({ ok: true })); + return app; +} + +beforeEach(() => { + redisState.counts.clear(); + redisState.failWith = null; + jest.clearAllMocks(); +}); + +describe("REMEDIATION: rotating non-Bearer headers can no longer split buckets", () => { + it("THE REPRODUCER SCENARIO, FIXED: 130 requests from one session with rotating Basic headers hit 429 at request 121", async () => { + const app = buildApp(); + const sessionCookie = "gitwire-session=valid-session"; + let last = 200; + for (let i = 0; i < 130; i += 1) { + const res = await supertest(app) + .get("/api/anything") + .set("Authorization", `Basic rotating-value-${i}`) + .set("Cookie", sessionCookie); + if (i < 120) { + expect(res.status).toBe(200); + } + last = res.status; + if (res.status === 429) break; + } + expect(last).toBe(429); + // ONE shared bucket (the request IP), not 130. + expect(redisState.counts.size).toBe(1); + expect([...redisState.counts.values()][0]).toBe(121); + }); + + it("header-absent session traffic shares the same IP bucket (unchanged semantics)", async () => { + const app = buildApp(); + const sessionCookie = "gitwire-session=valid-session"; + let saw429 = false; + for (let i = 0; i < 121; i += 1) { + const res = await supertest(app).get("/api/anything").set("Cookie", sessionCookie); + if (res.status === 429) { saw429 = true; break; } + expect(res.status).toBe(200); + } + expect(saw429).toBe(true); + expect(redisState.counts.size).toBe(1); + }); +}); + +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()] }; + const res = { + statusCode: 200, + headers: {}, + 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; }, + }; + rateLimiter(req, res, () => resolve({ res, passed: true })); + }); + } + + it("a well-formed Bearer token IS the identity (case-insensitive scheme)", async () => { + await runMiddleware({ headers: { authorization: "Bearer key-one" }, ip: "10.0.0.1" }); + await runMiddleware({ headers: { authorization: "Bearer key-two" }, ip: "10.0.0.1" }); + // Two distinct buckets for two distinct tokens from one IP. + expect(redisState.counts.size).toBe(2); + expect([...redisState.counts.keys()].join("|")).toContain("key-one"); + expect([...redisState.counts.keys()].join("|")).toContain("key-two"); + // A LOWERCASE scheme is not Bearer for apiKeyAuth (starts-with "Bearer "), + // so it must not be Bearer for the limiter either — it falls to the IP. + redisState.counts.clear(); + await runMiddleware({ headers: { authorization: "bearer key-lower" }, ip: "10.0.0.2" }); + expect([...redisState.counts.keys()]).toEqual(["ratelimit:10.0.0.2"]); + }); + + it.each([ + ["Basic value-1"], + ["basic value-2"], + ["Bearer"], // malformed: no token after scheme + ["Bearer "], // malformed: whitespace only + ["Bearer\tgap-token"], // malformed: tab not matched by \\s+? (regex ^Bearer\\s+ — tab IS \\s; assert below) + [""], // empty header value + ])("non-Bearer or malformed header %j falls back to the IP bucket", async (authorization) => { + redisState.counts.clear(); + const first = await runMiddleware({ headers: { authorization }, ip: "10.1.1.1" }); + expect(first.passed).toBe(true); + // Whatever the header said, the bucket is the IP. + expect([...redisState.counts.keys()]).toEqual(["ratelimit:10.1.1.1"]); + }); + + it("Bearer-key separation still works at the threshold: key A saturates, key B unaffected, IP unaffected", async () => { + for (let i = 0; i < 120; i += 1) { + await runMiddleware({ headers: { authorization: "Bearer key-sat" }, ip: "10.2.2.2" }); + } + const saturated = await runMiddleware({ headers: { authorization: "Bearer key-sat" }, ip: "10.2.2.2" }); + expect(saturated.passed).toBe(false); + const otherKey = await runMiddleware({ headers: { authorization: "Bearer key-other" }, ip: "10.2.2.2" }); + expect(otherKey.passed).toBe(true); + const plainIp = await runMiddleware({ ip: "10.2.2.2" }); + expect(plainIp.passed).toBe(true); + }); +});