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/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.

[MEDIUM] zod major bump (3 → 4) with no accompanying source changes — verify v4 compatibility

packages/web/package.json jumps zod from ^3.22.0 to ^4.6.6. That is a major-version upgrade and Zod 4 ships real breaking changes: z.record() now requires both key and value schemas (single-arg form throws at schema-definition time), the message: customization parameter was renamed to error on many APIs, error formatting changed, and some string-format methods are deprecated/removed. No source changes in packages/web accompany this bump, so either the existing schemas are already v4-safe, or validation code breaks/alters behavior at runtime even though a build/audit gate passes. Suggested fix: grep packages/web/src for single-argument z.record( calls and message: options in schemas, and run the schema-dependent integration tests against v4 before merging. If usage is confirmed compatible, consider pinning exactly 4.6.6+ (matching the advisory floor) rather than a caret range that floats across future majors.

},
"devDependencies": {
"eslint": "^8.0.0",
Expand Down
39 changes: 34 additions & 5 deletions packages/web/src/middleware/rateLimiter.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,39 @@ import { logger } from "../lib/logger.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 (apiKeyAuth-EXACT recognition:
// case-sensitive "Bearer " prefix, single space, slice(7).trim()) is the
// identity on ordinary paths. 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 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 authHeader = req.headers.authorization;
const isPreAuthPath = typeof req.path === "string"
&& (/^\/api\/auth(\/.*)?\/?$/i.test(req.path)
|| /^\/api\/bootstrap(\/.*)?\/?$/i.test(req.path));
const bearerToken = !isPreAuthPath && typeof authHeader === "string" && authHeader.slice(0, 7) === "Bearer "
? authHeader.slice(7).trim()
: "";
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