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:
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* Unit tests for MFA enforcement via SystemSettings.requireMfaForRoles.
|
||||
*
|
||||
* Tests cover:
|
||||
* - requireMfaForRoles is returned by buildSystemSettingsViewModel
|
||||
* - buildSettingsUpdatePayload includes requireMfaForRoles in the DB payload
|
||||
* - buildSettingsUpdatePayload handles null (clear enforcement)
|
||||
* - Schema validation: valid roles accepted, invalid roles rejected
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildSettingsUpdatePayload,
|
||||
buildSystemSettingsViewModel,
|
||||
settingsUpdateInputSchema,
|
||||
} from "../router/settings-support.js";
|
||||
import type { RuntimeSecretField, RuntimeSecretStatus } from "../lib/system-settings-runtime.js";
|
||||
import { RUNTIME_SECRET_FIELDS } from "../lib/system-settings-runtime.js";
|
||||
|
||||
const emptyRuntimeSecrets = Object.fromEntries(
|
||||
RUNTIME_SECRET_FIELDS.map((field) => [
|
||||
field,
|
||||
{ configured: false, activeSource: "none", hasStoredValue: false, envVarNames: [] } satisfies RuntimeSecretStatus,
|
||||
]),
|
||||
) as Record<RuntimeSecretField, RuntimeSecretStatus>;
|
||||
|
||||
// Minimal stubs for required inputs
|
||||
function makeViewModelInput(
|
||||
requireMfaForRoles: string[] | null | undefined = undefined,
|
||||
) {
|
||||
return {
|
||||
settings: {
|
||||
requireMfaForRoles,
|
||||
},
|
||||
runtimeSettings: null,
|
||||
runtimeSecrets: emptyRuntimeSecrets,
|
||||
defaultSummaryPrompt: "",
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildSystemSettingsViewModel — requireMfaForRoles", () => {
|
||||
it("returns null when requireMfaForRoles is not set in DB", () => {
|
||||
const vm = buildSystemSettingsViewModel(makeViewModelInput(undefined));
|
||||
expect(vm.requireMfaForRoles).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null when requireMfaForRoles is explicitly null", () => {
|
||||
const vm = buildSystemSettingsViewModel(makeViewModelInput(null));
|
||||
expect(vm.requireMfaForRoles).toBeNull();
|
||||
});
|
||||
|
||||
it("returns the configured roles array", () => {
|
||||
const vm = buildSystemSettingsViewModel(makeViewModelInput(["ADMIN", "MANAGER"]));
|
||||
expect(vm.requireMfaForRoles).toEqual(["ADMIN", "MANAGER"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSettingsUpdatePayload — requireMfaForRoles", () => {
|
||||
it("includes requireMfaForRoles in DB payload when provided", () => {
|
||||
const { data } = buildSettingsUpdatePayload({ requireMfaForRoles: ["ADMIN"] });
|
||||
expect(data.requireMfaForRoles).toEqual(["ADMIN"]);
|
||||
});
|
||||
|
||||
it("sets requireMfaForRoles to null when explicitly cleared", () => {
|
||||
const { data } = buildSettingsUpdatePayload({ requireMfaForRoles: null });
|
||||
expect(data.requireMfaForRoles).toBeNull();
|
||||
});
|
||||
|
||||
it("omits requireMfaForRoles from payload when not provided (no change)", () => {
|
||||
const { data } = buildSettingsUpdatePayload({});
|
||||
expect("requireMfaForRoles" in data).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("settingsUpdateInputSchema — requireMfaForRoles validation", () => {
|
||||
it("accepts a valid array of system roles", () => {
|
||||
const result = settingsUpdateInputSchema.safeParse({ requireMfaForRoles: ["ADMIN", "MANAGER"] });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts an empty array (disable enforcement)", () => {
|
||||
const result = settingsUpdateInputSchema.safeParse({ requireMfaForRoles: [] });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts null (clear enforcement)", () => {
|
||||
const result = settingsUpdateInputSchema.safeParse({ requireMfaForRoles: null });
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects an invalid role string", () => {
|
||||
const result = settingsUpdateInputSchema.safeParse({ requireMfaForRoles: ["SUPERUSER"] });
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts omitted field (no change)", () => {
|
||||
const result = settingsUpdateInputSchema.safeParse({});
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.data?.requireMfaForRoles).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -88,6 +88,7 @@ describe("settings support", () => {
|
||||
imageProvider: "dalle",
|
||||
vacationDefaultDays: 30,
|
||||
timelineUndoMaxSteps: 50,
|
||||
requireMfaForRoles: null,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/**
|
||||
* Unit tests for the server-side stripHtml utility (A03 XSS prevention).
|
||||
*
|
||||
* Covers:
|
||||
* - Passthrough of plain text and mention tokens
|
||||
* - Stripping of common HTML injection patterns
|
||||
* - HTML entity decoding
|
||||
* - Edge cases (empty string, nested tags, self-closing tags)
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { stripHtml } from "../lib/strip-html.js";
|
||||
|
||||
describe("stripHtml — plain text passthrough", () => {
|
||||
it("returns plain text unchanged", () => {
|
||||
expect(stripHtml("Hello, world!")).toBe("Hello, world!");
|
||||
});
|
||||
|
||||
it("preserves mention tokens", () => {
|
||||
expect(stripHtml("Hey @[Alice](user_1) please check this")).toBe(
|
||||
"Hey @[Alice](user_1) please check this",
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves newlines and whitespace", () => {
|
||||
expect(stripHtml("Line 1\nLine 2\n indented")).toBe("Line 1\nLine 2\n indented");
|
||||
});
|
||||
|
||||
it("returns empty string unchanged", () => {
|
||||
expect(stripHtml("")).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stripHtml — HTML injection stripping (A03)", () => {
|
||||
it("strips a script tag and its content", () => {
|
||||
const result = stripHtml('<script>alert("xss")</script>normal text');
|
||||
expect(result).not.toContain("<script");
|
||||
expect(result).toContain("normal text");
|
||||
});
|
||||
|
||||
it("strips an img onerror payload", () => {
|
||||
const result = stripHtml('<img src=x onerror="alert(1)">text');
|
||||
expect(result).not.toContain("<img");
|
||||
expect(result).toContain("text");
|
||||
});
|
||||
|
||||
it("strips anchor tags with javascript: href", () => {
|
||||
const result = stripHtml('<a href="javascript:alert(1)">click me</a>');
|
||||
expect(result).not.toContain("<a");
|
||||
expect(result).toContain("click me");
|
||||
});
|
||||
|
||||
it("strips iframe tags", () => {
|
||||
const result = stripHtml('<iframe src="evil.com"></iframe>safe text');
|
||||
expect(result).not.toContain("<iframe");
|
||||
expect(result).toContain("safe text");
|
||||
});
|
||||
|
||||
it("strips nested tags", () => {
|
||||
const result = stripHtml("<b><i>bold italic</i></b>");
|
||||
expect(result).toBe("bold italic");
|
||||
});
|
||||
|
||||
it("strips self-closing tags", () => {
|
||||
const result = stripHtml("before<br/>after");
|
||||
expect(result).toBe("beforeafter");
|
||||
});
|
||||
|
||||
it("strips HTML comment injection", () => {
|
||||
const result = stripHtml("<!-- <script>alert(1)</script> -->text");
|
||||
expect(result).not.toContain("<");
|
||||
expect(result).toContain("text");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stripHtml — HTML entity decoding", () => {
|
||||
it("decodes & to &", () => {
|
||||
expect(stripHtml("cats & dogs")).toBe("cats & dogs");
|
||||
});
|
||||
|
||||
it("decodes < and > to < and >", () => {
|
||||
expect(stripHtml("1 < 2 > 0")).toBe("1 < 2 > 0");
|
||||
});
|
||||
|
||||
it("decodes " to double quote", () => {
|
||||
expect(stripHtml('say "hello"')).toBe('say "hello"');
|
||||
});
|
||||
|
||||
it("decodes ' and ' to single quote", () => {
|
||||
expect(stripHtml("it's fine and it's ok")).toBe("it's fine and it's ok");
|
||||
});
|
||||
|
||||
it("decodes to space", () => {
|
||||
expect(stripHtml("hello world")).toBe("hello world");
|
||||
});
|
||||
});
|
||||
@@ -4,18 +4,18 @@
|
||||
* Tests cover:
|
||||
* - generateTotpSecret: secret creation and DB write
|
||||
* - verifyAndEnableTotp: valid/invalid token, guard conditions
|
||||
* - verifyTotp (login): valid/invalid token, not-enabled guard
|
||||
* - verifyTotp (login): valid/invalid token, not-enabled guard, rate limiting
|
||||
* - getCurrentMfaStatus: status read
|
||||
*
|
||||
* otpauth is mocked so tests are deterministic and do not depend on
|
||||
* time-based code generation.
|
||||
* totpRateLimiter is mocked to allow/block independently of real Redis.
|
||||
*/
|
||||
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// ─── otpauth mock ────────────────────────────────────────────────────────────
|
||||
// Must be hoisted before imports that pull in the module under test.
|
||||
const totpValidateMock = vi.hoisted(() => vi.fn<() => number | null>());
|
||||
|
||||
vi.mock("otpauth", () => {
|
||||
@@ -31,6 +31,20 @@ vi.mock("otpauth", () => {
|
||||
return { Secret, TOTP };
|
||||
});
|
||||
|
||||
// ─── rate-limit mock ──────────────────────────────────────────────────────────
|
||||
// Default: rate limit allows all requests. Override in specific tests.
|
||||
const totpRateLimiterMock = vi.hoisted(() => vi.fn(async (_key: string) => ({
|
||||
allowed: true,
|
||||
remaining: 9,
|
||||
resetAt: new Date(Date.now() + 30_000),
|
||||
})));
|
||||
|
||||
vi.mock("../middleware/rate-limit.js", () => ({
|
||||
totpRateLimiter: totpRateLimiterMock,
|
||||
apiRateLimiter: vi.fn(async () => ({ allowed: true, remaining: 99, resetAt: new Date() })),
|
||||
authRateLimiter: vi.fn(async () => ({ allowed: true, remaining: 4, resetAt: new Date() })),
|
||||
}));
|
||||
|
||||
// ─── import after mock setup ─────────────────────────────────────────────────
|
||||
import {
|
||||
generateTotpSecret,
|
||||
@@ -177,6 +191,7 @@ describe("verifyTotp", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
totpValidateMock.mockReset();
|
||||
totpRateLimiterMock.mockResolvedValue({ allowed: true, remaining: 9, resetAt: new Date(Date.now() + 30_000) });
|
||||
});
|
||||
|
||||
const mfaUser = { id: "user_1", totpSecret: "TESTBASE32SECRET", totpEnabled: true };
|
||||
@@ -216,6 +231,31 @@ describe("verifyTotp", () => {
|
||||
verifyTotp(ctx as Parameters<typeof verifyTotp>[0], { userId: "user_1", token: "123456" }),
|
||||
).rejects.toThrow(TRPCError);
|
||||
});
|
||||
|
||||
it("throws TOO_MANY_REQUESTS when rate limit is exceeded", async () => {
|
||||
totpRateLimiterMock.mockResolvedValue({ allowed: false, remaining: 0, resetAt: new Date(Date.now() + 30_000) });
|
||||
const ctx = makePublicCtx({ user: { findUnique: vi.fn().mockResolvedValue(mfaUser) } });
|
||||
await expect(
|
||||
verifyTotp(ctx as Parameters<typeof verifyTotp>[0], { userId: "user_1", token: "123456" }),
|
||||
).rejects.toThrow(new TRPCError({ code: "TOO_MANY_REQUESTS", message: "Too many TOTP attempts. Please wait before trying again." }));
|
||||
});
|
||||
|
||||
it("does not check the token when rate limit is exceeded", async () => {
|
||||
totpRateLimiterMock.mockResolvedValue({ allowed: false, remaining: 0, resetAt: new Date() });
|
||||
const ctx = makePublicCtx({ user: { findUnique: vi.fn().mockResolvedValue(mfaUser) } });
|
||||
await expect(
|
||||
verifyTotp(ctx as Parameters<typeof verifyTotp>[0], { userId: "user_1", token: "123456" }),
|
||||
).rejects.toThrow(TRPCError);
|
||||
// DB user lookup must not happen when rate-limited
|
||||
expect(ctx.db.user.findUnique).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls the rate limiter with the userId as key", async () => {
|
||||
totpValidateMock.mockReturnValue(0);
|
||||
const ctx = makePublicCtx({ user: { findUnique: vi.fn().mockResolvedValue(mfaUser) } });
|
||||
await verifyTotp(ctx as Parameters<typeof verifyTotp>[0], { userId: "user_1", token: "123456" });
|
||||
expect(totpRateLimiterMock).toHaveBeenCalledWith("user_1");
|
||||
});
|
||||
});
|
||||
|
||||
// ─── getCurrentMfaStatus ──────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user