Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
356 changes: 178 additions & 178 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@
"postcss": "8.5.22",
"sharp": "0.35.5",
"proxy-addr": "2.0.8",
"source-map-js": "1.2.2"
"source-map-js": "1.2.2",
"body-parser": "1.20.9"
},
"optionalDependencies": {
"sharp": "0.35.5"
Expand Down
2 changes: 1 addition & 1 deletion packages/demo-dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"start": "npx serve out"
},
"dependencies": {
"next": "15.5.24",
"next": "15.5.28",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"clsx": "^2.1.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/web-dashboard/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"clsx": "^2.1.1",
"date-fns": "^3.6.0",
"lucide-react": "^1.16.0",
"next": "16.3.8",
"next": "16.4.6",
"react": "19.2.4",
"react-dom": "19.2.4",
"recharts": "^2.15.4",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// src/middleware.ts
// Next.js middleware — redirects unauthenticated users to /login.
// src/proxy.ts (renamed from middleware.ts for Next.js 16.4+)
// Next.js proxy (formerly middleware) — redirects unauthenticated users to /login.
// Checks for the gitwire-session cookie on all page routes.
// Allows /login, /_next/*, and static assets without auth.

Expand All @@ -21,7 +21,7 @@ function isPublicAsset(pathname: string): boolean {
);
}

export function middleware(request: NextRequest) {
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;

// Allow public paths and static assets
Expand Down
2 changes: 1 addition & 1 deletion packages/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"pino": "^8.0.0",
"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.

},
"devDependencies": {
"eslint": "^8.0.0",
Expand Down
13 changes: 6 additions & 7 deletions packages/web/src/middleware/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import { config } from "../../config/index.js";
import { logger } from "../lib/logger.js";
import { redis } from "../lib/queue.js";
import { extractBearerToken } from "./bearerToken.js";

const SESSION_PREFIX = "gitwire:session:";

Expand Down Expand Up @@ -71,13 +72,11 @@ export async function apiKeyAuth(req, res, next) {
return next();
}

// Extract key from header or query param
let providedKey = null;

const authHeader = req.headers.authorization;
if (authHeader?.startsWith("Bearer ")) {
providedKey = authHeader.slice(7).trim();
}
// 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'.

// from the exact same forms auth accepts).
const providedKey = extractBearerToken(req.headers.authorization) || null;

// Check session cookie if no Bearer token
if (!providedKey) {
Expand Down
28 changes: 28 additions & 0 deletions packages/web/src/middleware/bearerToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// src/middleware/bearerToken.js
// Bearer-token extraction shared by apiKeyAuth (auth.js) and the rate limiter
// (rateLimiter.js). Both MUST recognize exactly the same Authorization forms:
// a case-sensitive "Bearer " scheme prefix with a single literal space. A
// looser recognizer on the limiter side re-opens the bucket-rotation bypass
// (rotating non-Bearer headers to mint fresh buckets); a stricter one would
// throttle callers apiKeyAuth accepts. Before this module existed the two
// implementations were unlinked copies kept in sync by comments — the corpus
// contract test in rate-limiter-identity.test.js now pins this one function
// for both callers.

/**
* Extract the Bearer token from an Authorization header value.
*
* Recognition is apiKeyAuth-EXACT: case-sensitive "Bearer " prefix (single
* literal space), then slice(7).trim(). Returns "" for every other form —
* wrong case ("bearer x"), tab separator ("Bearer\tx"), bare "Bearer",
* whitespace-only token, or a missing/non-string header.
*
* @param {string | undefined} authHeader
* @returns {string} the token, or "" when the header is not a well-formed
* Bearer credential.
*/
export function extractBearerToken(authHeader) {
return typeof authHeader === "string" && authHeader.slice(0, 7) === "Bearer "
? authHeader.slice(7).trim()
: "";
}
39 changes: 34 additions & 5 deletions packages/web/src/middleware/rateLimiter.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,43 @@

import { redis } from "../lib/queue.js";
import { logger } from "../lib/logger.js";
import { extractBearerToken } from "./bearerToken.js";

const WINDOW_MS = 60_000; // 1 minute window
const MAX_REQUESTS = 120; // 120 req/min per identity (~2 req/sec)

// Identity derivation, isolated from the handler so the middleware reads
// like the throttle it is (CodeQL's missing-rate-limiting model pairs
// credential reads inside a route handler with recognized limiter sinks;
// the derivation here IS the limiter's own identity selection).
//
// Contract:
// - A properly formed Bearer token is the identity on ordinary paths. The
// recognition is apiKeyAuth-EXACT because both callers share one
// implementation: extractBearerToken() in bearerToken.js (case-sensitive
// "Bearer " prefix, single space, slice(7).trim()). Anything looser
// re-opens the rotation bypass ("Bearer\t<x>" / "bearer <x>" are NOT
// Bearer for auth, so they must not mint buckets either) — reproduced in
// rate-limiter-behavior.test.js, pinned by the corpus contract test in
// rate-limiter-identity.test.js.
// - PRE-AUTHENTICATION route families ALWAYS key on the request IP: the
// limiter runs before authentication, so an unverified token must never
// become their throttle identity. Two families mount before apiKeyAuth
// (app.js): /api/auth/* (login authenticates by body password; check
// authenticates by session cookie via Redis; logout) and /api/bootstrap/*
// (state runs a DB query anonymously; first is bootstrap-gated). Every
// path under both prefixes matches, with trailing-slash and case
// tolerance (Express's default non-strict, case-insensitive-to-route
// routing serves those variants to the same handlers).
// - Everything else falls back to the request IP.
export function deriveLimiterIdentity(req) {
const isPreAuthPath = typeof req.path === "string"
&& (/^\/api\/auth(\/.*)?\/?$/i.test(req.path)
|| /^\/api\/bootstrap(\/.*)?\/?$/i.test(req.path));
const bearerToken = isPreAuthPath ? "" : extractBearerToken(req.headers.authorization);
return bearerToken || req.ip || "unknown";
}

/**
* Rate limiter middleware using Redis INCR + EXPIRE.
* Falls back to allowing all requests if Redis is unavailable.
Expand All @@ -18,11 +51,7 @@ 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";

const identity = deriveLimiterIdentity(req);
const key = `ratelimit:${identity}`;

redis
Expand Down
68 changes: 17 additions & 51 deletions packages/web/tests/unit/rate-limiter-behavior.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
});
});
Loading
Loading