test(server): Phase 3 — HTTP route integration (auth + RBAC guards)

Boots the REAL Fastify app over a fresh in-memory DB (buildServer({ db }), driven by
app.inject — no listen) to exercise the security seam end to end:

- routes.test.ts (7): /health open; login rejects bad creds and sets token+csrf
  cookies on good ones; an unauthenticated GET /api/occupancy is 401; a site:read-only
  role GETs occupancy but is 403 on PUT /api/site-config (the permission gate, with a
  valid CSRF so the 403 is the perm check); an admin passes the same PUT; and a mutation
  with the auth cookie but NO csrf header is 403 (double-submit enforced).

Adds seedUser()/login() helpers (real bcrypt + the real /api/auth/login route) and
LOG_LEVEL=silent in the vitest env so asserted 401/403 responses don't flood output.

server 75/75 green (8 suites).

Claude-Session: https://claude.ai/code/session_01Xcm6ikLgGoCxxHrxtjkk5V
This commit is contained in:
2026-06-21 16:20:14 +02:00
parent 352c643009
commit 7e912e193b
3 changed files with 154 additions and 3 deletions
+103
View File
@@ -0,0 +1,103 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { createTestDb } from "@parking/db/testing";
import { type Db } from "@parking/db";
import type { FastifyInstance } from "fastify";
import { buildServer } from "../server.js";
import { seedUser, login } from "../test-helpers.js";
// HTTP integration: boot the REAL Fastify app over a fresh in-memory DB (no listen —
// app.inject drives it) and exercise the auth + RBAC guards end to end. The point is the
// security seam: no token → 401, wrong permission → 403, CSRF required on mutations, and
// a correctly-scoped user passes. (vitest.config sets JWT_SECRET/EVENT_SIGNING_KEY.)
let db: Db;
let close: () => void;
let app: FastifyInstance;
beforeEach(async () => {
const t = createTestDb();
db = t.db;
close = t.close;
app = await buildServer({ db });
await app.ready();
});
afterEach(async () => {
await app.close();
close();
});
describe("health + login", () => {
it("GET /health is open", async () => {
const res = await app.inject({ method: "GET", url: "/health" });
expect(res.statusCode).toBe(200);
expect(res.json()).toEqual({ status: "ok" });
});
it("login with bad credentials is rejected", async () => {
await seedUser(db, { username: "alice", password: "right-password" });
const res = await app.inject({ method: "POST", url: "/api/auth/login", payload: { username: "alice", password: "wrong" } });
expect(res.statusCode).toBeGreaterThanOrEqual(400);
});
it("login with good credentials sets auth + csrf cookies", async () => {
await seedUser(db, { username: "alice", password: "right-password" });
const res = await app.inject({ method: "POST", url: "/api/auth/login", payload: { username: "alice", password: "right-password" } });
expect(res.statusCode).toBe(200);
const names = res.cookies.map((c) => c.name);
expect(names).toContain("parking_token");
expect(names).toContain("parking_csrf");
});
});
describe("auth guard — no token", () => {
it("GET /api/occupancy without a session is 401", async () => {
const res = await app.inject({ method: "GET", url: "/api/occupancy" });
expect(res.statusCode).toBe(401);
});
});
describe("RBAC permission gate", () => {
it("a site:read-only user can GET occupancy but is 403 on PUT site-config", async () => {
const { username, password } = await seedUser(db, {
username: "viewer", roleId: "viewer", permissions: ["site:read"],
});
const { cookie, csrf } = await login(app, username, password);
// GET allowed (site:read).
const get = await app.inject({ method: "GET", url: "/api/occupancy", headers: { cookie } });
expect(get.statusCode).toBe(200);
// PUT requires site:update — which this role lacks → 403 (with valid CSRF, so the
// 403 is the PERMISSION check, not CSRF).
const put = await app.inject({
method: "PUT", url: "/api/site-config",
headers: { cookie, "x-csrf-token": csrf },
payload: { capacity: 50 },
});
expect(put.statusCode).toBe(403);
});
it("an admin user passes the same PUT", async () => {
const { username, password } = await seedUser(db, { username: "boss", roleId: "admin" });
const { cookie, csrf } = await login(app, username, password);
const put = await app.inject({
method: "PUT", url: "/api/site-config",
headers: { cookie, "x-csrf-token": csrf },
payload: { capacity: 50 },
});
expect(put.statusCode).toBeLessThan(300);
});
});
describe("CSRF double-submit on mutations", () => {
it("a mutation with the auth cookie but NO csrf header is 403", async () => {
const { username, password } = await seedUser(db, { username: "boss", roleId: "admin" });
const { cookie } = await login(app, username, password);
const put = await app.inject({
method: "PUT", url: "/api/site-config",
headers: { cookie }, // csrf header deliberately omitted
payload: { capacity: 50 },
});
expect(put.statusCode).toBe(403);
});
});
+48 -3
View File
@@ -1,7 +1,8 @@
import { randomUUID } from "node:crypto";
import { tariffs, tariffVersions, type Db } from "@parking/db";
import type { TariffStructure } from "@parking/shared";
import type { FastifyBaseLogger } from "fastify";
import bcrypt from "bcrypt";
import { roles, rolePermissions, tariffs, tariffVersions, users, type Db } from "@parking/db";
import type { Permission, TariffStructure } from "@parking/shared";
import type { FastifyBaseLogger, FastifyInstance } from "fastify";
import { EventLog } from "./event-log.js";
import { SoftwareSigner, buildVerifier } from "./signer.js";
@@ -61,3 +62,47 @@ export function seedTariff(
export function minutesAgo(minutes: number): string {
return new Date(Date.now() - minutes * 60_000).toISOString();
}
// --- HTTP integration scaffolding (route tests via app.inject) -----------------
/** Seed a user with a role. `admin` role grants every permission (ADMIN_PERMS);
* any other role gets exactly the `permissions` listed. Returns the credentials. */
export async function seedUser(
db: Db,
opts: { username?: string; password?: string; roleId?: string; permissions?: Permission[] } = {},
): Promise<{ username: string; password: string; roleId: string }> {
const username = opts.username ?? "tester";
const password = opts.password ?? "test-password-123";
const roleId = opts.roleId ?? "admin";
if (roleId !== "admin") {
db.insert(roles).values({ id: roleId, name: roleId, builtin: 0 }).onConflictDoNothing().run();
for (const p of opts.permissions ?? []) {
db.insert(rolePermissions).values({ roleId, permission: p }).onConflictDoNothing().run();
}
} else {
// The admin role row must exist for the FK; ADMIN_PERMS is resolved in code.
db.insert(roles).values({ id: "admin", name: "admin", builtin: 1 }).onConflictDoNothing().run();
}
db.insert(users).values({
id: randomUUID(),
username,
passwordHash: await bcrypt.hash(password, 10),
roleId,
}).run();
return { username, password, roleId };
}
/** Log in via the real auth route and return the cookie header + CSRF token to
* replay on subsequent requests (mutations need both the cookie and the header). */
export async function login(
app: FastifyInstance,
username: string,
password: string,
): Promise<{ cookie: string; csrf: string }> {
const res = await app.inject({ method: "POST", url: "/api/auth/login", payload: { username, password } });
if (res.statusCode !== 200) throw new Error(`login failed: ${res.statusCode} ${res.body}`);
const setCookies = res.cookies;
const cookie = setCookies.map((c) => `${c.name}=${c.value}`).join("; ");
const csrf = setCookies.find((c) => c.name === "parking_csrf")?.value ?? "";
return { cookie, csrf };
}
+3
View File
@@ -10,6 +10,9 @@ export default defineConfig({
env: {
EVENT_SIGNING_KEY: "test-event-signing-key-0123456789",
JWT_SECRET: "test-jwt-secret-0123456789abcdef",
// Silence the Fastify request logger — route tests assert 401/403 responses,
// whose error logs would otherwise flood the test output.
LOG_LEVEL: "silent",
},
},
});