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,148 @@
import { NextResponse } from "next/server";
import { prisma } from "@capakraken/db";
import { createNotificationsForUsers } from "@capakraken/api";
import { logger } from "@capakraken/api/lib/logger";
import { verifyCronSecret } from "~/lib/cron-auth.js";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
/** Window over which auth events are analysed. */
const WINDOW_MS = 30 * 60 * 1000; // 30 minutes
/**
* Alert thresholds — tune per deployment if needed.
* Exported so tests can reference them without re-declaring magic numbers.
*/
export const THRESHOLDS = {
/** Total failed login attempts in the window before alerting. */
globalFailures: 20,
/** Failed attempts attributed to a single entityId (userId / IP placeholder) before alerting. */
perEntityFailures: 10,
};
export interface AnomalyReport {
windowStartedAt: string;
windowEndedAt: string;
totalFailures: number;
anomalies: Array<{ type: string; count: number; entityId: string | null }>;
}
/**
* Analyses recent auth audit events and returns detected anomalies.
* Exported for unit testing without an HTTP layer.
*/
export async function detectAuthAnomalies(windowMs = WINDOW_MS): Promise<AnomalyReport> {
const windowEnd = new Date();
const windowStart = new Date(windowEnd.getTime() - windowMs);
const failureEvents = await prisma.auditLog.findMany({
where: {
entityType: "Auth",
action: "CREATE",
summary: { startsWith: "Login failed" },
createdAt: { gte: windowStart, lte: windowEnd },
},
select: {
entityId: true,
summary: true,
},
});
const anomalies: AnomalyReport["anomalies"] = [];
// Global threshold: too many failures overall
if (failureEvents.length >= THRESHOLDS.globalFailures) {
anomalies.push({
type: "HIGH_GLOBAL_FAILURE_RATE",
count: failureEvents.length,
entityId: null,
});
}
// Per-entity threshold: one entity accumulating failures (brute-force pattern)
const countByEntity = new Map<string, number>();
for (const event of failureEvents) {
if (event.entityId) {
countByEntity.set(event.entityId, (countByEntity.get(event.entityId) ?? 0) + 1);
}
}
for (const [entityId, count] of countByEntity.entries()) {
if (count >= THRESHOLDS.perEntityFailures) {
anomalies.push({
type: "CONCENTRATED_FAILURES",
count,
entityId,
});
}
}
return {
windowStartedAt: windowStart.toISOString(),
windowEndedAt: windowEnd.toISOString(),
totalFailures: failureEvents.length,
anomalies,
};
}
/**
* GET /api/cron/auth-anomaly-check
*
* Scans recent auth audit events for brute-force / anomaly patterns and
* alerts ADMIN users when thresholds are exceeded.
*
* Protected by CRON_SECRET. Run every 30 minutes via cron or Vercel Cron.
*/
export async function GET(request: Request) {
const deny = verifyCronSecret(request);
if (deny) return deny;
try {
const report = await detectAuthAnomalies();
if (report.anomalies.length > 0) {
const adminUsers = await prisma.user.findMany({
where: { systemRole: "ADMIN" },
select: { id: true },
});
if (adminUsers.length > 0) {
const summary = report.anomalies
.map((a) =>
a.entityId
? `${a.type}: ${a.count} failures for entity ${a.entityId}`
: `${a.type}: ${a.count} total failures`,
)
.join("; ");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await createNotificationsForUsers({
db: prisma as any,
userIds: adminUsers.map((u) => u.id),
type: "SYSTEM_ALERT",
title: `Auth Anomaly Detected (${report.anomalies.length} signal${report.anomalies.length > 1 ? "s" : ""})`,
body: `${summary}. Window: ${report.windowStartedAt} ${report.windowEndedAt}. Review audit logs at /admin/settings.`,
category: "system",
priority: "CRITICAL",
link: "/admin/settings",
});
logger.warn(
{ anomalies: report.anomalies, window: { start: report.windowStartedAt, end: report.windowEndedAt } },
"Auth anomaly cron: anomalies detected and admins notified",
);
}
}
return NextResponse.json({
ok: true,
...report,
});
} catch (error) {
logger.error({ error, route: "/api/cron/auth-anomaly-check" }, "Auth anomaly cron failed");
return NextResponse.json(
{ ok: false, error: "Internal error" },
{ status: 500 },
);
}
}