security: implement tickets #28-#35 + architecture decision #30

#28 - TOTP rate limiting (verifyTotp): added totpRateLimiter (10 req/30s),
  throws TOO_MANY_REQUESTS before DB hit; 16 unit tests including rate-limit
  exceeded + userId key isolation.

#29 - /api/reports/allocations role check: only ADMIN/MANAGER/CONTROLLER may
  access; returns 403 otherwise; 9 unit tests (401 unauthenticated, 403 for
  USER/VIEWER, 200 for allowed roles + xlsx format).

#31 - pgAdmin credentials moved out of docker-compose.yml into env vars;
  PGADMIN_PASSWORD is now required (:?) to prevent accidental plaintext
  exposure in committed files.

#34 - Server-side HTML sanitization for comment bodies via stripHtml():
  strips all tags + decodes safe entities before persistence; 16 unit tests
  covering passthrough, injection patterns, entity decoding.

#35 - MFA setup prompt banner (MfaPromptBanner): shown to ADMIN/MANAGER users
  without TOTP enabled; user-scoped localStorage snooze (7 days); links to
  /account/security; accessibility role=alert; 7 structural unit tests.

#33 - Auth anomaly alerting cron (/api/cron/auth-anomaly-check): detects
  HIGH_GLOBAL_FAILURE_RATE and CONCENTRATED_FAILURES in 30-minute window;
  CRITICAL notification to ADMINs; fail-closed via verifyCronSecret;
  10 unit tests.

#32 - MFA enforcement policy: added requireMfaForRoles field to SystemSettings
  schema + Prisma migration; auth.ts blocks login with MFA_REQUIRED_SETUP
  signal if role is enforced but TOTP not set up; signin page redirects to
  /account/security?mfa_required=1; settings schema + view model updated;
  11 unit tests.

#30 - API keys architecture decision documented in LEARNINGS.md; no code
  written — product decision required before implementation.

Co-Authored-By: claude-flow <ruv@ruv.net>
This commit is contained in:
2026-04-01 23:25:06 +02:00
parent f8550110eb
commit 435c871e1f
22 changed files with 1071 additions and 11 deletions
@@ -0,0 +1,117 @@
/**
* Unit tests for GET /api/reports/allocations — A01 role-check enforcement.
*
* Heavy dependencies (Prisma, PDF renderer, XLSX builder) are mocked so the
* test focuses purely on authentication and authorisation behaviour.
*/
import { describe, expect, it, vi } from "vitest";
// ─── auth mock ────────────────────────────────────────────────────────────────
const authMock = vi.hoisted(() => vi.fn());
vi.mock("~/server/auth.js", () => ({ auth: authMock }));
// ─── heavy dep stubs ─────────────────────────────────────────────────────────
vi.mock("@capakraken/db", () => ({
prisma: {
demandRequirement: { findMany: vi.fn().mockResolvedValue([]) },
assignment: { findMany: vi.fn().mockResolvedValue([]) },
user: { findMany: vi.fn().mockResolvedValue([]) },
},
}));
vi.mock("@capakraken/application", () => ({
buildSplitAllocationReadModel: vi.fn().mockReturnValue({ assignments: [] }),
}));
vi.mock("@capakraken/api", () => ({
anonymizeResource: vi.fn((r: unknown) => r),
getAnonymizationDirectory: vi.fn().mockResolvedValue({}),
}));
vi.mock("@react-pdf/renderer", () => ({
renderToBuffer: vi.fn().mockResolvedValue(Buffer.from("PDF")),
}));
vi.mock("react", async (importOriginal) => {
const actual = await importOriginal<typeof import("react")>();
return { ...actual, createElement: vi.fn().mockReturnValue(null) };
});
vi.mock("~/lib/workbook-export.js", () => ({
createWorkbookArrayBuffer: vi.fn().mockResolvedValue(new ArrayBuffer(8)),
}));
vi.mock("~/components/reports/AllocationReport.js", () => ({
AllocationReport: () => null,
}));
// ─── import route after mocks ─────────────────────────────────────────────────
import { GET } from "./route.js";
function makeRequest(url = "http://localhost/api/reports/allocations") {
return new Request(url);
}
// ─── tests ───────────────────────────────────────────────────────────────────
describe("GET /api/reports/allocations — authentication", () => {
it("returns 401 when no session exists", async () => {
authMock.mockResolvedValue(null);
const res = await GET(makeRequest());
expect(res.status).toBe(401);
});
it("returns 401 when session has no user", async () => {
authMock.mockResolvedValue({ user: null });
const res = await GET(makeRequest());
expect(res.status).toBe(401);
});
});
describe("GET /api/reports/allocations — authorisation (A01)", () => {
it("returns 403 for USER role", async () => {
authMock.mockResolvedValue({ user: { email: "user@example.com", role: "USER" } });
const res = await GET(makeRequest());
expect(res.status).toBe(403);
});
it("returns 403 for VIEWER role", async () => {
authMock.mockResolvedValue({ user: { email: "viewer@example.com", role: "VIEWER" } });
const res = await GET(makeRequest());
expect(res.status).toBe(403);
});
it("returns 403 when role is absent from session", async () => {
authMock.mockResolvedValue({ user: { email: "noRole@example.com" } });
const res = await GET(makeRequest());
expect(res.status).toBe(403);
});
it("returns 200 for ADMIN role (PDF)", async () => {
authMock.mockResolvedValue({ user: { email: "admin@example.com", role: "ADMIN" } });
const res = await GET(makeRequest());
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toContain("pdf");
});
it("returns 200 for MANAGER role (PDF)", async () => {
authMock.mockResolvedValue({ user: { email: "mgr@example.com", role: "MANAGER" } });
const res = await GET(makeRequest());
expect(res.status).toBe(200);
});
it("returns 200 for CONTROLLER role (PDF)", async () => {
authMock.mockResolvedValue({ user: { email: "ctrl@example.com", role: "CONTROLLER" } });
const res = await GET(makeRequest());
expect(res.status).toBe(200);
});
it("returns 200 for ADMIN role with xlsx format", async () => {
authMock.mockResolvedValue({ user: { email: "admin@example.com", role: "ADMIN" } });
const res = await GET(makeRequest("http://localhost/api/reports/allocations?format=xlsx"));
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toContain("spreadsheetml");
});
});
@@ -9,12 +9,19 @@ import { auth } from "~/server/auth.js";
import { AllocationReport } from "~/components/reports/AllocationReport.js";
import { createWorkbookArrayBuffer } from "~/lib/workbook-export.js";
const ALLOWED_ROLES = new Set(["ADMIN", "MANAGER", "CONTROLLER"]);
export async function GET(request: Request) {
const session = await auth();
if (!session?.user) {
return new NextResponse("Unauthorized", { status: 401 });
}
const userRole = (session.user as { role?: string }).role;
if (!userRole || !ALLOWED_ROLES.has(userRole)) {
return new NextResponse("Forbidden", { status: 403 });
}
const { searchParams } = new URL(request.url);
const startDate = searchParams.get("startDate") ? new Date(searchParams.get("startDate")!) : new Date();
const endDate = searchParams.get("endDate") ? new Date(searchParams.get("endDate")!) : new Date(Date.now() + 90 * 24 * 60 * 60 * 1000);