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:
@@ -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 ──────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
|
||||
@@ -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(),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
58
src/lib/db/migrations/0041_role_permissions_edit_keys.sql
Normal file
58
src/lib/db/migrations/0041_role_permissions_edit_keys.sql
Normal file
@@ -0,0 +1,58 @@
|
||||
-- Backfill the new `documents.edit` and `files.edit` permission keys on
|
||||
-- every existing row in `roles.permissions`. The schema (RolePermissions
|
||||
-- in src/lib/db/schema/users.ts) added these keys to close the silent-403
|
||||
-- traps on PATCH /api/v1/documents/[id], /cancel, /remind, /watchers, and
|
||||
-- PATCH /api/v1/files/[id] — each used a permission key that did not exist
|
||||
-- in the schema, so withPermission()'s `resourcePerms[action]` returned
|
||||
-- undefined and 403'd every non-superadmin call.
|
||||
--
|
||||
-- Backfill rule:
|
||||
-- documents.edit ← documents.create (anyone who can create can edit)
|
||||
-- files.edit ← files.upload (same rationale)
|
||||
--
|
||||
-- jsonb_set with create_missing=true (the default) inserts the key only
|
||||
-- when it's absent, so re-runs are idempotent and the migration is safe
|
||||
-- against a partial run.
|
||||
|
||||
UPDATE roles
|
||||
SET permissions = jsonb_set(
|
||||
permissions,
|
||||
'{documents,edit}',
|
||||
COALESCE(permissions->'documents'->'create', 'false'::jsonb),
|
||||
true
|
||||
)
|
||||
WHERE permissions->'documents' IS NOT NULL
|
||||
AND NOT (permissions->'documents' ? 'edit');
|
||||
|
||||
UPDATE roles
|
||||
SET permissions = jsonb_set(
|
||||
permissions,
|
||||
'{files,edit}',
|
||||
COALESCE(permissions->'files'->'upload', 'false'::jsonb),
|
||||
true
|
||||
)
|
||||
WHERE permissions->'files' IS NOT NULL
|
||||
AND NOT (permissions->'files' ? 'edit');
|
||||
|
||||
-- Same backfill on per-port overrides (`port_role_overrides.permissions`)
|
||||
-- so an override that flipped a sibling permission stays consistent.
|
||||
|
||||
UPDATE port_role_overrides
|
||||
SET permissions = jsonb_set(
|
||||
permissions,
|
||||
'{documents,edit}',
|
||||
COALESCE(permissions->'documents'->'create', 'false'::jsonb),
|
||||
true
|
||||
)
|
||||
WHERE permissions->'documents' IS NOT NULL
|
||||
AND NOT (permissions->'documents' ? 'edit');
|
||||
|
||||
UPDATE port_role_overrides
|
||||
SET permissions = jsonb_set(
|
||||
permissions,
|
||||
'{files,edit}',
|
||||
COALESCE(permissions->'files'->'upload', 'false'::jsonb),
|
||||
true
|
||||
)
|
||||
WHERE permissions->'files' IS NOT NULL
|
||||
AND NOT (permissions->'files' ? 'edit');
|
||||
@@ -288,6 +288,13 @@
|
||||
"when": 1778300000000,
|
||||
"tag": "0040_error_events",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 41,
|
||||
"version": "7",
|
||||
"when": 1778400000000,
|
||||
"tag": "0041_role_permissions_edit_keys",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ export type RolePermissions = {
|
||||
documents: {
|
||||
view: boolean;
|
||||
create: boolean;
|
||||
edit: boolean;
|
||||
send_for_signing: boolean;
|
||||
upload_signed: boolean;
|
||||
delete: boolean;
|
||||
@@ -54,6 +55,7 @@ export type RolePermissions = {
|
||||
files: {
|
||||
view: boolean;
|
||||
upload: boolean;
|
||||
edit: boolean;
|
||||
delete: boolean;
|
||||
manage_folders: boolean;
|
||||
};
|
||||
|
||||
@@ -42,6 +42,7 @@ const ALL_PERMISSIONS: RolePermissions = {
|
||||
documents: {
|
||||
view: true,
|
||||
create: true,
|
||||
edit: true,
|
||||
send_for_signing: true,
|
||||
upload_signed: true,
|
||||
delete: true,
|
||||
@@ -63,7 +64,7 @@ const ALL_PERMISSIONS: RolePermissions = {
|
||||
record_payment: true,
|
||||
export: true,
|
||||
},
|
||||
files: { view: true, upload: true, delete: true, manage_folders: true },
|
||||
files: { view: true, upload: true, edit: true, delete: true, manage_folders: true },
|
||||
email: { view: true, send: true, configure_account: true },
|
||||
reminders: {
|
||||
view_own: true,
|
||||
@@ -116,6 +117,7 @@ const DIRECTOR_PERMISSIONS: RolePermissions = {
|
||||
documents: {
|
||||
view: true,
|
||||
create: true,
|
||||
edit: true,
|
||||
send_for_signing: true,
|
||||
upload_signed: true,
|
||||
delete: true,
|
||||
@@ -137,7 +139,7 @@ const DIRECTOR_PERMISSIONS: RolePermissions = {
|
||||
record_payment: true,
|
||||
export: true,
|
||||
},
|
||||
files: { view: true, upload: true, delete: true, manage_folders: true },
|
||||
files: { view: true, upload: true, edit: true, delete: true, manage_folders: true },
|
||||
email: { view: true, send: true, configure_account: true },
|
||||
reminders: {
|
||||
view_own: true,
|
||||
@@ -190,6 +192,7 @@ const SALES_MANAGER_PERMISSIONS: RolePermissions = {
|
||||
documents: {
|
||||
view: true,
|
||||
create: true,
|
||||
edit: true,
|
||||
send_for_signing: true,
|
||||
upload_signed: true,
|
||||
delete: false,
|
||||
@@ -211,7 +214,7 @@ const SALES_MANAGER_PERMISSIONS: RolePermissions = {
|
||||
record_payment: true,
|
||||
export: true,
|
||||
},
|
||||
files: { view: true, upload: true, delete: false, manage_folders: true },
|
||||
files: { view: true, upload: true, edit: true, delete: false, manage_folders: true },
|
||||
email: { view: true, send: true, configure_account: true },
|
||||
reminders: {
|
||||
view_own: true,
|
||||
@@ -264,6 +267,7 @@ const SALES_AGENT_PERMISSIONS: RolePermissions = {
|
||||
documents: {
|
||||
view: true,
|
||||
create: true,
|
||||
edit: true,
|
||||
send_for_signing: true,
|
||||
upload_signed: true,
|
||||
delete: false,
|
||||
@@ -285,7 +289,7 @@ const SALES_AGENT_PERMISSIONS: RolePermissions = {
|
||||
record_payment: true,
|
||||
export: true,
|
||||
},
|
||||
files: { view: true, upload: true, delete: false, manage_folders: false },
|
||||
files: { view: true, upload: true, edit: false, delete: false, manage_folders: false },
|
||||
email: { view: true, send: true, configure_account: true },
|
||||
reminders: {
|
||||
view_own: true,
|
||||
@@ -338,6 +342,7 @@ const VIEWER_PERMISSIONS: RolePermissions = {
|
||||
documents: {
|
||||
view: true,
|
||||
create: false,
|
||||
edit: false,
|
||||
send_for_signing: false,
|
||||
upload_signed: false,
|
||||
delete: false,
|
||||
@@ -359,7 +364,7 @@ const VIEWER_PERMISSIONS: RolePermissions = {
|
||||
record_payment: false,
|
||||
export: false,
|
||||
},
|
||||
files: { view: true, upload: false, delete: false, manage_folders: false },
|
||||
files: { view: true, upload: false, edit: false, delete: false, manage_folders: false },
|
||||
email: { view: true, send: false, configure_account: false },
|
||||
reminders: {
|
||||
view_own: true,
|
||||
|
||||
@@ -91,6 +91,17 @@ export const rateLimiters = {
|
||||
* without dropping data. The shared-secret header gates abuse; this
|
||||
* limiter is just a defensive backstop in case the secret leaks. */
|
||||
websiteIntake: { windowMs: 60 * 60 * 1000, max: 500, keyPrefix: 'websiteintake' },
|
||||
/** Portal sign-in: 5 attempts per 15min per (ip,email) bucket. Defends
|
||||
* against credential stuffing on /api/portal/auth/sign-in. */
|
||||
portalSignIn: { windowMs: 15 * 60 * 1000, max: 5, keyPrefix: 'portal:signin' },
|
||||
/** Portal forgot-password: 3/hour/IP. Tighter than sign-in because it
|
||||
* triggers an outbound email and is the primary email-enumeration
|
||||
* vector (timing differences between known/unknown). */
|
||||
portalForgot: { windowMs: 60 * 60 * 1000, max: 3, keyPrefix: 'portal:forgot' },
|
||||
/** Portal activate / reset / set-password: 10/hour/IP. Bounds brute-
|
||||
* force against the 32-byte token (random walk math is in our favour
|
||||
* but a tight ceiling keeps the search space practically infeasible). */
|
||||
portalToken: { windowMs: 60 * 60 * 1000, max: 10, keyPrefix: 'portal:token' },
|
||||
} as const satisfies Record<string, RateLimitConfig>;
|
||||
|
||||
export type RateLimiterName = keyof typeof rateLimiters;
|
||||
|
||||
Reference in New Issue
Block a user