feat: harden portal security and auditability
This commit is contained in:
1 parent
7f1ecd9322
commit
21871bb9ff
26 files changed
+2664
-4
No files matched your search
@@ -0,0 +1,52 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { assertSameOrigin, CrossOriginRequestError } from "./origin";
|
||||
|
||||
function requestWithHeaders({
|
||||
origin,
|
||||
host,
|
||||
}: {
|
||||
origin?: string;
|
||||
host?: string;
|
||||
}): Request {
|
||||
const headers = new Headers();
|
||||
if (origin !== undefined) headers.set("origin", origin);
|
||||
if (host !== undefined) headers.set("host", host);
|
||||
return new Request("https://portal.example.de/api/test", { headers });
|
||||
}
|
||||
|
||||
test("rejects a cross-origin state-changing request", () => {
|
||||
const request = requestWithHeaders({ origin: "https://evil.example", host: "portal.example.de" });
|
||||
expect(() => assertSameOrigin(request)).toThrow(CrossOriginRequestError);
|
||||
expect(() => assertSameOrigin(request)).toThrowError(
|
||||
expect.objectContaining({ code: "CROSS_ORIGIN_REQUEST" }),
|
||||
);
|
||||
});
|
||||
|
||||
test("allows a same-origin request", () => {
|
||||
const request = requestWithHeaders({ origin: "https://portal.example.de", host: "portal.example.de" });
|
||||
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||
});
|
||||
|
||||
test("allows a request with no Origin header (same-page navigation)", () => {
|
||||
const request = requestWithHeaders({ host: "portal.example.de" });
|
||||
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||
});
|
||||
|
||||
test("matches host only, ignoring scheme", () => {
|
||||
const request = requestWithHeaders({ origin: "http://portal.example.de", host: "portal.example.de" });
|
||||
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||
});
|
||||
|
||||
test("matches host ignoring path in origin", () => {
|
||||
const request = requestWithHeaders({
|
||||
origin: "https://portal.example.de/some/path",
|
||||
host: "portal.example.de",
|
||||
});
|
||||
expect(() => assertSameOrigin(request)).not.toThrow();
|
||||
});
|
||||
|
||||
test("rejects when host header is missing", () => {
|
||||
const request = requestWithHeaders({ origin: "https://evil.example" });
|
||||
expect(() => assertSameOrigin(request)).toThrow(CrossOriginRequestError);
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
// ---------------------------------------------------------------------------
|
||||
// Same-origin guard for custom state-changing API routes.
|
||||
// Better Auth handles its own route; this guards the portal's custom handlers.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export class CrossOriginRequestError extends Error {
|
||||
readonly name = "CrossOriginRequestError";
|
||||
readonly code = "CROSS_ORIGIN_REQUEST" as const;
|
||||
|
||||
constructor() {
|
||||
super("Cross-origin request rejected");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares the request's `Origin` header host against the `Host` header.
|
||||
* Throws `CrossOriginRequestError` on mismatch. A request with no `Origin`
|
||||
* (same-page navigation, same-origin fetch) is allowed — the Origin header is
|
||||
* only sent on cross-origin state-changing requests per the fetch spec.
|
||||
* Only the host is compared (scheme and path are ignored).
|
||||
*/
|
||||
export function assertSameOrigin(request: Request): void {
|
||||
const origin = request.headers.get("origin");
|
||||
if (!origin) return; // Absent Origin = same-origin, allow.
|
||||
|
||||
const host = request.headers.get("host");
|
||||
if (!host) throw new CrossOriginRequestError();
|
||||
|
||||
let originHost: string;
|
||||
try {
|
||||
originHost = new URL(origin).host;
|
||||
} catch {
|
||||
throw new CrossOriginRequestError();
|
||||
}
|
||||
|
||||
if (originHost !== host) {
|
||||
throw new CrossOriginRequestError();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { createRateLimiter, loginPolicy, type RateLimitRepository } from "./rate-limit";
|
||||
|
||||
function createMockRepo(): RateLimitRepository & { counts: Map<string, number> } {
|
||||
const counts = new Map<string, number>();
|
||||
const repository: RateLimitRepository = {
|
||||
async incrementCount(key, _windowBoundary) {
|
||||
const current = (counts.get(key) ?? 0) + 1;
|
||||
counts.set(key, current);
|
||||
return { count: current };
|
||||
},
|
||||
};
|
||||
return { ...repository, counts };
|
||||
}
|
||||
|
||||
test("blocks the sixth login attempt in a fifteen-minute window", async () => {
|
||||
const repo = createMockRepo();
|
||||
const limiter = createRateLimiter(repo);
|
||||
|
||||
for (let i = 0; i < 5; i++) {
|
||||
expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(true);
|
||||
}
|
||||
expect((await limiter.consume("login:hash", loginPolicy)).allowed).toBe(false);
|
||||
});
|
||||
|
||||
test("returns retryAfterSeconds when blocked", async () => {
|
||||
const repo = createMockRepo();
|
||||
const limiter = createRateLimiter(repo);
|
||||
|
||||
for (let i = 0; i < 5; i++) await limiter.consume("login:hash", loginPolicy);
|
||||
const result = await limiter.consume("login:hash", loginPolicy);
|
||||
|
||||
expect(result.allowed).toBe(false);
|
||||
expect(result.retryAfterSeconds).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("allows up to the max attempts", async () => {
|
||||
const repo = createMockRepo();
|
||||
const limiter = createRateLimiter(repo);
|
||||
|
||||
const policy = { maxAttempts: 3, windowSeconds: 60 };
|
||||
for (let i = 0; i < 3; i++) {
|
||||
expect((await limiter.consume("key:hash", policy)).allowed).toBe(true);
|
||||
}
|
||||
expect((await limiter.consume("key:hash", policy)).allowed).toBe(false);
|
||||
});
|
||||
|
||||
test("tracks different keys independently", async () => {
|
||||
const repo = createMockRepo();
|
||||
const limiter = createRateLimiter(repo);
|
||||
|
||||
const policy = { maxAttempts: 1, windowSeconds: 60 };
|
||||
expect((await limiter.consume("a:hash", policy)).allowed).toBe(true);
|
||||
expect((await limiter.consume("b:hash", policy)).allowed).toBe(true);
|
||||
expect((await limiter.consume("a:hash", policy)).allowed).toBe(false);
|
||||
expect((await limiter.consume("b:hash", policy)).allowed).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
import "server-only";
|
||||
|
||||
import { sql } from "drizzle-orm";
|
||||
import type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||
|
||||
import { db } from "@/db/client";
|
||||
import { rateLimits } from "@/db/schema";
|
||||
import type * as schema from "@/db/schema";
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Types
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export type RateLimitPolicy = {
|
||||
maxAttempts: number;
|
||||
windowSeconds: number;
|
||||
};
|
||||
|
||||
export type RateLimitResult = {
|
||||
allowed: boolean;
|
||||
retryAfterSeconds: number;
|
||||
};
|
||||
|
||||
export type RateLimitRepository = {
|
||||
incrementCount(key: string, windowBoundary: number): Promise<{ count: number }>;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Policies — bounded server-side, not configurable via env (Global Constraint)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const loginPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 15 * 60 };
|
||||
export const registrationPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 };
|
||||
export const passwordResetPolicy: RateLimitPolicy = { maxAttempts: 5, windowSeconds: 60 * 60 };
|
||||
export const searchPolicy: RateLimitPolicy = { maxAttempts: 120, windowSeconds: 60 };
|
||||
export const downloadIntentsPolicy: RateLimitPolicy = { maxAttempts: 30, windowSeconds: 60 };
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Limiter factory
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createRateLimiter(repository: RateLimitRepository) {
|
||||
return {
|
||||
async consume(key: string, policy: RateLimitPolicy): Promise<RateLimitResult> {
|
||||
// ponytail: integer-arithmetic fixed window — upgrade to sliding window
|
||||
// if abuse patterns require it. No token-bucket library needed.
|
||||
const nowSeconds = Math.floor(Date.now() / 1000);
|
||||
const windowBoundary = Math.floor(nowSeconds / policy.windowSeconds);
|
||||
|
||||
const { count } = await repository.incrementCount(key, windowBoundary);
|
||||
|
||||
if (count <= policy.maxAttempts) {
|
||||
return { allowed: true, retryAfterSeconds: 0 };
|
||||
}
|
||||
|
||||
const windowEndSeconds = (windowBoundary + 1) * policy.windowSeconds;
|
||||
const retryAfterSeconds = Math.max(1, windowEndSeconds - nowSeconds);
|
||||
return { allowed: false, retryAfterSeconds };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Drizzle repository — atomic upsert via ON CONFLICT
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export function createRateLimitRepository(
|
||||
database: NodePgDatabase<typeof schema>,
|
||||
): RateLimitRepository {
|
||||
return {
|
||||
async incrementCount(key, windowBoundary) {
|
||||
const result = await database
|
||||
.insert(rateLimits)
|
||||
.values({
|
||||
key,
|
||||
windowBoundary,
|
||||
count: 1,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: [rateLimits.key, rateLimits.windowBoundary],
|
||||
set: {
|
||||
count: sql`${rateLimits.count} + 1`,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
})
|
||||
.returning({ count: rateLimits.count });
|
||||
return { count: result[0].count };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default singleton
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const rateLimiter = createRateLimiter(createRateLimitRepository(db));
|
||||
export const consumeRateLimit = rateLimiter.consume;
|
||||
Reference in new issue
Block a user