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:
@@ -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