fix(security): tier-0 audit blockers (next CVE, role gate, perm traps, key validation, rate limits)

Closes the five highest-risk findings from
docs/audit-comprehensive-2026-05-05.md so the platform is not exposed
while the rest of the audit backlog (1 CRIT + 18 HIGH + 32 MED + 23 LOW)
is worked through:

* CVE-2025-29927 — bump next 15.1.0 → 15.2.9; nginx strips
  X-Middleware-Subrequest at the edge as defense-in-depth.
* Cross-tenant role escalation — POST/PATCH/DELETE on /admin/roles now
  require super-admin (was: any holder of admin.manage_users).  Adds
  shared `requireSuperAdmin(ctx)` helper.
* Silent-403 traps — `documents.edit` and `files.edit` keys added to
  RolePermissions; seeded role values updated; migration 0041 backfills
  the new keys on every existing roles+port_role_overrides JSONB.  File
  routes remap the dead `create` action to `upload` / `manage_folders`.
* Berth-PDF / brochure register endpoints — reject body.storageKey
  unless it matches the namespace the matching presign endpoint issued
  (prevents repointing a tenant's PDF at foreign-port bytes).
* Portal auth rate limits — sign-in 5/15min/(ip,email),
  forgot-password 3/hr/IP, activate/reset/set-password 10/hr/IP.  Adds
  `enforcePublicRateLimit()` for non-`withAuth` routes.

Test status unchanged: 1168/1168 vitest, tsc clean.

Refs: docs/audit-comprehensive-2026-05-05.md (CRITICAL, HIGH §§1–4)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Matt Ciaccio
2026-05-05 18:33:13 +02:00
parent 4723994bdc
commit 312779c0c5
24 changed files with 1489 additions and 126 deletions

View File

@@ -8,7 +8,7 @@ import { db } from '@/lib/db';
import { portRoleOverrides, ports, userPortRoles, userProfiles } from '@/lib/db/schema';
import { type RolePermissions } from '@/lib/db/schema/users';
import { createAuditLog } from '@/lib/audit';
import { errorResponse } from '@/lib/errors';
import { errorResponse, ForbiddenError } from '@/lib/errors';
import { logger } from '@/lib/logger';
import { runWithRequestContext, getRequestContext } from '@/lib/request-context';
import {
@@ -250,6 +250,31 @@ export function withAuth(
};
}
// ─── requireSuperAdmin ───────────────────────────────────────────────────────
/**
* Throws ForbiddenError when the caller is not a super-admin. Use inside
* route handlers (after withAuth) for endpoints that mutate global, cross-
* tenant state — global roles, cross-port migrations, system jobs.
*
* Logs the denied attempt to the audit trail (mirrors withPermission).
*/
export function requireSuperAdmin(ctx: AuthContext, attemptedAction = 'super_admin_only'): void {
if (ctx.isSuperAdmin) return;
logger.warn({ userId: ctx.userId, attemptedAction }, 'Super-admin gate denied');
void createAuditLog({
userId: ctx.userId,
portId: ctx.portId,
action: 'permission_denied',
entityType: 'super_admin',
entityId: '',
metadata: { attemptedAction },
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
});
throw new ForbiddenError('Super admin access required');
}
// ─── withPermission ──────────────────────────────────────────────────────────
/**

View File

@@ -1,6 +1,13 @@
import { NextRequest } from 'next/server';
import { NextRequest, NextResponse } from 'next/server';
import { z, ZodSchema } from 'zod';
import {
checkRateLimit,
rateLimiters,
rateLimitHeaders,
type RateLimiterName,
} from '@/lib/rate-limit';
/**
* Base list query schema shared by all paginated list endpoints.
*/
@@ -22,10 +29,7 @@ export type BaseListQuery = z.infer<typeof baseListQuerySchema>;
* Parses URL search params against a Zod schema.
* Throws a ZodError on validation failure (caught by `errorResponse`).
*/
export function parseQuery<T extends ZodSchema>(
req: NextRequest,
schema: T,
): z.infer<T> {
export function parseQuery<T extends ZodSchema>(req: NextRequest, schema: T): z.infer<T> {
const params = Object.fromEntries(req.nextUrl.searchParams.entries());
return schema.parse(params);
}
@@ -41,3 +45,52 @@ export async function parseBody<T extends ZodSchema>(
const body = await req.json();
return schema.parse(body);
}
/**
* Best-effort client IP from forwarded headers. The trusted proxy is
* nginx (which sets `x-forwarded-for` from `$proxy_add_x_forwarded_for`),
* so the leftmost token is the original client. Falls back to a literal
* `unknown` so the per-IP key still exists when running outside the
* proxy (dev, tests).
*/
export function clientIp(req: NextRequest): string {
const xff = req.headers.get('x-forwarded-for');
if (xff) {
const first = xff.split(',')[0]?.trim();
if (first) return first;
}
return req.headers.get('x-real-ip') ?? 'unknown';
}
/**
* Wraps an unauthenticated route handler with a per-IP (or per-key) rate
* limit. Used for portal/auth endpoints that have no session yet — the
* `withRateLimit` helper in api/helpers.ts is keyed on `ctx.userId` and
* cannot apply here.
*
* If `keySuffix` is provided, it's appended to the IP so a single client
* IP can't exhaust an unrelated user's bucket (e.g. for sign-in we key
* on `${ip}:${email}` so per-account brute force is the bottleneck and
* a noisy NAT IP doesn't deny everyone).
*/
export async function enforcePublicRateLimit(
req: NextRequest,
name: RateLimiterName,
keySuffix?: string,
): Promise<NextResponse | null> {
const config = rateLimiters[name];
const identifier = keySuffix ? `${clientIp(req)}:${keySuffix}` : clientIp(req);
const result = await checkRateLimit(identifier, config);
if (result.allowed) return null;
const retryAfterSec = Math.max(1, Math.ceil((result.resetAt - Date.now()) / 1000));
return NextResponse.json(
{ error: 'Too many requests. Please try again shortly.', retryAfter: retryAfterSec },
{
status: 429,
headers: {
...rateLimitHeaders(result),
'Retry-After': retryAfterSec.toString(),
},
},
);
}