feat(api): add helmet security headers and rate limiting
- Add helmet middleware for secure HTTP response headers - Add express-rate-limit with three limiters: - authLimiter: per-IP, 20 req/15min on /api/auth/* - gameLimiter: per-user, 150 req/15min (not yet wired) - lobbyLimiter: per-user, 20 req/15min (not yet wired) - Set trust proxy for correct client IP behind Caddy - Add tests for all three limiters and helmet headers
This commit is contained in:
parent
1dfe391233
commit
9893ead689
6 changed files with 300 additions and 1 deletions
39
apps/api/src/app.test.ts
Normal file
39
apps/api/src/app.test.ts
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
import request from "supertest";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { createApp } from "./app.js";
|
||||
|
||||
const app = createApp();
|
||||
|
||||
describe("security headers (helmet)", () => {
|
||||
it("sets X-Content-Type-Options to nosniff", async () => {
|
||||
const res = await request(app).get("/api/v1/health");
|
||||
expect(res.headers["x-content-type-options"]).toBe("nosniff");
|
||||
});
|
||||
|
||||
it("sets X-Frame-Options to SAMEORIGIN", async () => {
|
||||
const res = await request(app).get("/api/v1/health");
|
||||
expect(res.headers["x-frame-options"]).toBe("SAMEORIGIN");
|
||||
});
|
||||
|
||||
it("removes X-Powered-By header", async () => {
|
||||
const res = await request(app).get("/api/v1/health");
|
||||
expect(res.headers).not.toHaveProperty("x-powered-by");
|
||||
});
|
||||
|
||||
it("sets Content-Security-Policy", async () => {
|
||||
const res = await request(app).get("/api/v1/health");
|
||||
expect(res.headers).toHaveProperty("content-security-policy");
|
||||
});
|
||||
});
|
||||
|
||||
describe("auth rate limiting", () => {
|
||||
it("returns 429 after exceeding the auth limit", async () => {
|
||||
const testApp = createApp();
|
||||
const limit = 20;
|
||||
for (let i = 0; i < limit; i++) {
|
||||
await request(testApp).post("/api/auth/sign-in");
|
||||
}
|
||||
const res = await request(testApp).post("/api/auth/sign-in");
|
||||
expect(res.status).toBe(429);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,20 +1,26 @@
|
|||
import express from "express";
|
||||
import type { Express } from "express";
|
||||
import { toNodeHandler } from "better-auth/node";
|
||||
import cors from "cors";
|
||||
import helmet from "helmet";
|
||||
import { auth } from "./lib/auth.js";
|
||||
import { apiRouter } from "./routes/apiRouter.js";
|
||||
import { errorHandler } from "./middleware/errorHandler.js";
|
||||
import cors from "cors";
|
||||
import { authLimiter } from "./middleware/rateLimiters.js";
|
||||
|
||||
export function createApp() {
|
||||
const app: Express = express();
|
||||
|
||||
app.set("trust proxy", 1);
|
||||
app.use(helmet());
|
||||
|
||||
app.use(
|
||||
cors({
|
||||
origin: process.env["CORS_ORIGIN"] || "http://localhost:5173",
|
||||
credentials: true,
|
||||
}),
|
||||
);
|
||||
app.use("/api/auth", authLimiter);
|
||||
app.all("/api/auth/*splat", toNodeHandler(auth));
|
||||
app.use(express.json());
|
||||
app.use("/api/v1", apiRouter);
|
||||
|
|
|
|||
179
apps/api/src/middleware/rateLimiters.test.ts
Normal file
179
apps/api/src/middleware/rateLimiters.test.ts
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { describe, it, expect, beforeEach } from "vitest";
|
||||
import { authLimiter, gameLimiter, lobbyLimiter } from "./rateLimiters.js";
|
||||
|
||||
import type { Session, User } from "better-auth";
|
||||
|
||||
// Minimal app to test the limiter in isolation
|
||||
function createTestApp() {
|
||||
const app = express();
|
||||
app.set("trust proxy", 1);
|
||||
app.use("/api/auth", authLimiter);
|
||||
app.all("/api/auth/*splat", (_req, res) => {
|
||||
res.status(200).json({ success: true });
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("authLimiter", () => {
|
||||
let app: ReturnType<typeof createTestApp>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Fresh app = fresh in-memory store = counters reset between tests
|
||||
app = createTestApp();
|
||||
});
|
||||
|
||||
it("allows requests under the limit through", async () => {
|
||||
const res = await request(app).post("/api/auth/sign-in");
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("returns 429 after exceeding the limit", async () => {
|
||||
const limit = 20;
|
||||
for (let i = 0; i < limit; i++) {
|
||||
await request(app).post("/api/auth/sign-in");
|
||||
}
|
||||
const res = await request(app).post("/api/auth/sign-in");
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.body).toEqual({
|
||||
success: false,
|
||||
error: "Too many requests, please try again later.",
|
||||
});
|
||||
});
|
||||
|
||||
it("sets RateLimit headers on responses", async () => {
|
||||
const res = await request(app).post("/api/auth/sign-in");
|
||||
expect(res.headers).toHaveProperty("ratelimit");
|
||||
});
|
||||
});
|
||||
|
||||
function fakeAuth(userId: string) {
|
||||
return (
|
||||
req: express.Request,
|
||||
_res: express.Response,
|
||||
next: express.NextFunction,
|
||||
) => {
|
||||
req.session = { session: {} as Session, user: { id: userId } as User };
|
||||
next();
|
||||
};
|
||||
}
|
||||
|
||||
function createGameTestApp(userId = "user-1") {
|
||||
const app = express();
|
||||
app.set("trust proxy", 1);
|
||||
app.use(fakeAuth(userId));
|
||||
app.use(gameLimiter);
|
||||
app.post("/game/start", (_req, res) =>
|
||||
res.status(200).json({ success: true }),
|
||||
);
|
||||
app.post("/game/answer", (_req, res) =>
|
||||
res.status(200).json({ success: true }),
|
||||
);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("gameLimiter", () => {
|
||||
it("allows requests under the limit through", async () => {
|
||||
const app = createGameTestApp();
|
||||
const res = await request(app).post("/game/start");
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("returns 429 after exceeding the limit", async () => {
|
||||
const app = createGameTestApp();
|
||||
const limit = 150;
|
||||
for (let i = 0; i < limit; i++) {
|
||||
await request(app).post("/game/answer");
|
||||
}
|
||||
const res = await request(app).post("/game/answer");
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.body).toEqual({
|
||||
success: false,
|
||||
error: "Too many requests, please try again later.",
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks limits per user, not per IP", async () => {
|
||||
const app = express();
|
||||
app.set("trust proxy", 1);
|
||||
|
||||
// Two routes, same limiter, different users
|
||||
app.use("/user1", fakeAuth("user-1"), gameLimiter, (_req, res) =>
|
||||
res.status(200).json({ success: true }),
|
||||
);
|
||||
app.use("/user2", fakeAuth("user-2"), gameLimiter, (_req, res) =>
|
||||
res.status(200).json({ success: true }),
|
||||
);
|
||||
|
||||
const limit = 150;
|
||||
for (let i = 0; i < limit; i++) {
|
||||
await request(app).post("/user1");
|
||||
}
|
||||
|
||||
// user-1 is exhausted
|
||||
const blocked = await request(app).post("/user1");
|
||||
expect(blocked.status).toBe(429);
|
||||
|
||||
// user-2 is unaffected
|
||||
const allowed = await request(app).post("/user2");
|
||||
expect(allowed.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
function createLobbyTestApp(userId = "user-1") {
|
||||
const app = express();
|
||||
app.set("trust proxy", 1);
|
||||
app.use(fakeAuth(userId));
|
||||
app.use(lobbyLimiter);
|
||||
app.post("/lobbies", (_req, res) => res.status(200).json({ success: true }));
|
||||
app.post("/lobbies/:code/join", (_req, res) =>
|
||||
res.status(200).json({ success: true }),
|
||||
);
|
||||
return app;
|
||||
}
|
||||
|
||||
describe("lobbyLimiter", () => {
|
||||
it("allows requests under the limit through", async () => {
|
||||
const app = createLobbyTestApp();
|
||||
const res = await request(app).post("/lobbies");
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("returns 429 after exceeding the limit", async () => {
|
||||
const app = createLobbyTestApp();
|
||||
const limit = 20;
|
||||
for (let i = 0; i < limit; i++) {
|
||||
await request(app).post("/lobbies");
|
||||
}
|
||||
const res = await request(app).post("/lobbies");
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.body).toEqual({
|
||||
success: false,
|
||||
error: "Too many requests, please try again later.",
|
||||
});
|
||||
});
|
||||
|
||||
it("tracks limits per user, not per IP", async () => {
|
||||
const app = express();
|
||||
app.set("trust proxy", 1);
|
||||
|
||||
app.use("/user1", fakeAuth("user-1"), lobbyLimiter, (_req, res) =>
|
||||
res.status(200).json({ success: true }),
|
||||
);
|
||||
app.use("/user2", fakeAuth("user-2"), lobbyLimiter, (_req, res) =>
|
||||
res.status(200).json({ success: true }),
|
||||
);
|
||||
|
||||
const limit = 20;
|
||||
for (let i = 0; i < limit; i++) {
|
||||
await request(app).post("/user1");
|
||||
}
|
||||
|
||||
const blocked = await request(app).post("/user1");
|
||||
expect(blocked.status).toBe(429);
|
||||
|
||||
const allowed = await request(app).post("/user2");
|
||||
expect(allowed.status).toBe(200);
|
||||
});
|
||||
});
|
||||
44
apps/api/src/middleware/rateLimiters.ts
Normal file
44
apps/api/src/middleware/rateLimiters.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import rateLimit from "express-rate-limit";
|
||||
import type { Request } from "express";
|
||||
|
||||
// TODO: When Valkey is wired up, swap the default in-memory store for
|
||||
// rate-limit-redis to persist limits across restarts:
|
||||
//
|
||||
// import { RedisStore } from "rate-limit-redis";
|
||||
// import { valkey } from "../lib/valkey.js";
|
||||
// Then add to each limiter: store: new RedisStore({ sendCommand: (...args) => valkey.call(...args) })
|
||||
|
||||
export const authLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 20,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
message: {
|
||||
success: false,
|
||||
error: "Too many requests, please try again later.",
|
||||
},
|
||||
});
|
||||
|
||||
export const gameLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 150,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
keyGenerator: (req: Request) => req.session!.user.id,
|
||||
message: {
|
||||
success: false,
|
||||
error: "Too many requests, please try again later.",
|
||||
},
|
||||
});
|
||||
|
||||
export const lobbyLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
limit: 20,
|
||||
standardHeaders: "draft-8",
|
||||
legacyHeaders: false,
|
||||
keyGenerator: (req: Request) => req.session!.user.id,
|
||||
message: {
|
||||
success: false,
|
||||
error: "Too many requests, please try again later.",
|
||||
},
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue