Files
pn-new-crm/tests/unit/security-error-responses.test.ts
Matt Ciaccio 4723994bdc feat(errors): platform-wide request ids + error codes + admin inspector
End-to-end error-handling overhaul. A user hitting any failure now sees
a plain-text message + stable error code + reference id. A super admin
can paste the id into /admin/errors/<id> for the full request shape,
sanitized body, error stack, and a heuristic likely-cause hint.

REQUEST CONTEXT (AsyncLocalStorage)
- src/lib/request-context.ts mints a per-request frame carrying
  requestId + portId + userId + method + path + start timestamp.
- withAuth wraps every authenticated handler in runWithRequestContext
  and accepts an upstream X-Request-Id header (validated shape) or
  generates a fresh UUID. The id ALWAYS leaves on the X-Request-Id
  response header, including early-return 401/403/4xx paths.
- Pino logger reads from the same context via mixin — every log
  line emitted during the request automatically carries the ids
  with no per-call threading.

ERROR CODE REGISTRY
- src/lib/error-codes.ts defines stable DOMAIN_REASON codes with
  HTTP status + plain-text user-facing message (no jargon, written
  for the rep on the phone with a customer).
- New CodedError class wraps a registered code + optional
  internalMessage (admin-only — never sent to client).
- Existing AppError subclasses got plain-text default rewrites so
  legacy throw sites improve immediately without migration.
- High-impact services migrated to specific codes:
  expenses (RECEIPT_REQUIRED, INVOICE_LINKED), interest-berths
  (CROSS_PORT_LINK_REJECTED), berth-pdf (PDF_MAGIC_BYTE / PDF_EMPTY /
  PDF_TOO_LARGE / VERSION_ALREADY_CURRENT), recommender
  (INTEREST_PORT_MISMATCH).

ERROR ENVELOPE
- errorResponse always sets X-Request-Id header + requestId field.
- 5xx responses include a "Quote error ID …" friendly line.
- 4xx kept clean (validation, permission, not-found don't pollute
  the inspector — they're already in audit log).

PERSISTENCE (error_events table, migration 0040)
- One row per 5xx, keyed on requestId, with method/path/status/error
  name+message/stack head (4KB cap)/sanitized body excerpt (1KB cap;
  password/token/secret/etc keys redacted)/duration/IP/UA/metadata.
- captureErrorEvent extracts Postgres SQLSTATE/severity/cause.code
  so the classifier can recognize FK / unique / NOT NULL / schema-
  drift violations.
- Failure to persist is logged-not-thrown.

LIKELY-CULPRIT CLASSIFIER (src/lib/error-classifier.ts)
- 4-pass heuristic (first match wins):
  1. Postgres SQLSTATE → human reason (23503 FK, 23505 unique,
     42703 schema drift, 53300 connection limit, …)
  2. Error class name (AbortError, TimeoutError, FetchError,
     ZodError)
  3. Stack-path patterns (/lib/storage/, /lib/email/, documenso,
     openai|claude, /queue/workers/)
  4. Free-text message keywords (econnrefused, rate limit, timeout,
     unauthorized|invalid api key)
- Returns { label, hint, subsystem } for the inspector badge.

CLIENT SIDE
- apiFetch throws structured ApiError with message + code + requestId
  + details + retryAfter.
- toastError() helper renders the standard 3-line toast:
  plain message / Error code: X / Reference ID: Y [Copy ID].

ADMIN INSPECTOR
- /<port>/admin/errors lists captured 5xx with status badge + path +
  likely-culprit badge + truncated message + reference id. Filter by
  status code; auto-refresh via TanStack Query.
- /<port>/admin/errors/<requestId> deep-dive: request shape, full
  error name+message+stack, sanitized body excerpt, raw metadata,
  registered-code lookup (so admin can compare to what user saw),
  likely-culprit hint with subsystem tag.
- /<port>/admin/errors/codes is the in-app code reference page —
  every registered code grouped by domain prefix, searchable, with
  HTTP status + user message inline. Linked from inspector header
  so admins can flip to it while triaging.
- Permission: admin.view_audit_log. Super admins see all ports;
  regular admins port-scoped.
- system-monitoring dashboard now surfaces error_events alongside
  permission_denied audit + queue failed jobs (RecentError gains
  source: 'request' variant).

DOCS
- docs/error-handling.md walks through coded errors, plain-text
  message guidelines, client toasting, admin inspector usage,
  persistence rules, classifier internals, pruning, and the
  legacy → CodedError migration path.

MIGRATION SAFETY
- Audit confirmed all 41 migrations (0000-0040) apply cleanly in
  journal order against an empty DB. 0040 references ports(id)
  which exists from 0000. 0035/0038 don't deadlock under sequential
  psql -f. Removed redundant idx_ds_sent_by from 0038 (created in
  0037).

Tests: 1168/1168 vitest passing. tsc clean.
- security-error-responses tests updated for plain-text messages
  + new optional response keys (code/requestId/message).
- berth-pdf-versions tests assert stable error codes via
  toMatchObject({ code }) rather than message regex.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 14:12:59 +02:00

247 lines
9.2 KiB
TypeScript

/**
* Security: Error Response Sanitization
*
* Verifies that errorResponse() never leaks stack traces, SQL queries,
* internal file paths, or other sensitive server-side details to callers.
*
* Rule from SECURITY-GUIDELINES.md:
* "Error responses must NEVER contain stack traces, SQL queries, or internal paths"
*/
import { describe, expect, it, vi } from 'vitest';
// ── Mock next/server before importing the module under test ──────────────────
// NextResponse is a Next.js runtime class unavailable in a plain Node environment.
// We replace it with a minimal shim that captures status + body.
vi.mock('next/server', () => {
class MockNextResponse {
readonly status: number;
private body: unknown;
constructor(body: unknown, init?: { status?: number }) {
this.body = body;
this.status = init?.status ?? 200;
}
async json() {
return this.body;
}
static json(body: unknown, init?: { status?: number }) {
return new MockNextResponse(body, init);
}
}
return { NextResponse: MockNextResponse };
});
// Mock the logger so error-level calls don't pollute test output
vi.mock('@/lib/logger', () => ({
logger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
},
}));
import {
AppError,
ForbiddenError,
NotFoundError,
RateLimitError,
ValidationError,
errorResponse,
} from '@/lib/errors';
// ─────────────────────────────────────────────────────────────────────────────
describe('Error response security — AppError subclasses', () => {
it('AppError returns correct status without leaking constructor args', async () => {
const error = new AppError(400, 'Bad request', 'BAD_REQUEST');
const response = errorResponse(error);
expect(response.status).toBe(400);
const body = await response.json();
expect(body.error).toBe('Bad request');
expect(body.code).toBe('BAD_REQUEST');
// Stack trace must never appear in the response body
expect(JSON.stringify(body)).not.toMatch(/at\s+\w+/); // no call-site lines
expect(JSON.stringify(body)).not.toContain('node_modules');
});
it('NotFoundError returns 404 with plain-text message, not entity internals', async () => {
const error = new NotFoundError('Client');
const response = errorResponse(error);
expect(response.status).toBe(404);
const body = await response.json();
// Message is now plain-text user-facing (no jargon, lowercased entity).
expect(body.error).toBe("We couldn't find that client. It may have been removed.");
expect(body.code).toBe('NOT_FOUND');
expect(JSON.stringify(body)).not.toContain('stack');
});
it('ForbiddenError returns 403', async () => {
const error = new ForbiddenError();
const response = errorResponse(error);
expect(response.status).toBe(403);
const body = await response.json();
expect(body.code).toBe('FORBIDDEN');
});
it('RateLimitError returns 429 with retryAfter but no stack', async () => {
const error = new RateLimitError(60);
const response = errorResponse(error);
expect(response.status).toBe(429);
const body = await response.json();
expect(body.retryAfter).toBe(60);
expect(JSON.stringify(body)).not.toMatch(/stack|node_modules/i);
});
it('ValidationError returns 400 with details array, no internal paths', async () => {
const error = new ValidationError('Invalid input', [
{ field: 'email', message: 'Invalid email format' },
]);
const response = errorResponse(error);
expect(response.status).toBe(400);
const body = await response.json();
expect(body.details).toHaveLength(1);
expect(body.details[0].field).toBe('email');
expect(JSON.stringify(body)).not.toContain('src/');
expect(JSON.stringify(body)).not.toContain('G:\\');
});
});
describe('Error response security — unknown / native errors', () => {
it('native Error with SQL content returns generic 500', async () => {
const error = new Error('SELECT * FROM users WHERE id = 1; DROP TABLE users;--');
const response = errorResponse(error);
expect(response.status).toBe(500);
const body = await response.json();
expect(body.error).toBe('Internal server error');
expect(JSON.stringify(body)).not.toContain('SELECT');
expect(JSON.stringify(body)).not.toContain('DROP TABLE');
});
it('native Error with Windows file path returns generic 500 without path', async () => {
const error = new Error(
'at Object.<anonymous> (G:\\Repos\\new-pn-crm\\src\\lib\\db\\index.ts:15:3)',
);
const response = errorResponse(error);
expect(response.status).toBe(500);
const body = await response.json();
expect(body.error).toBe('Internal server error');
expect(JSON.stringify(body)).not.toContain('G:\\');
expect(JSON.stringify(body)).not.toContain('src\\lib');
});
it('native Error with node_modules path returns generic 500 without path', async () => {
const error = new Error('ENOENT: no such file at /app/node_modules/pg/lib/connection.js');
const response = errorResponse(error);
expect(response.status).toBe(500);
const body = await response.json();
expect(body.error).toBe('Internal server error');
expect(JSON.stringify(body)).not.toContain('node_modules');
expect(JSON.stringify(body)).not.toContain('ENOENT');
});
it('native Error with Postgres relation message returns generic 500', async () => {
const error = new Error('relation "users" does not exist');
const response = errorResponse(error);
expect(response.status).toBe(500);
const body = await response.json();
expect(body.error).toBe('Internal server error');
expect(JSON.stringify(body)).not.toContain('relation');
expect(JSON.stringify(body)).not.toContain('"users"');
});
it('null thrown value returns generic 500', async () => {
const response = errorResponse(null);
expect(response.status).toBe(500);
const body = await response.json();
expect(body.error).toBe('Internal server error');
});
it('string thrown returns generic 500', async () => {
const response = errorResponse('something went wrong internally');
expect(response.status).toBe(500);
const body = await response.json();
expect(body.error).toBe('Internal server error');
// The raw string must not appear in the response
expect(JSON.stringify(body)).not.toContain('something went wrong internally');
});
});
describe('Error response security — ZodError', () => {
it('ZodError returns 400 with VALIDATION_ERROR code', async () => {
const { ZodError, ZodIssueCode } = await import('zod');
const error = new ZodError([
{
code: ZodIssueCode.invalid_type,
expected: 'string',
received: 'number',
path: ['name'],
message: 'Expected string, received number',
},
]);
const response = errorResponse(error);
expect(response.status).toBe(400);
const body = await response.json();
expect(body.code).toBe('VALIDATION_ERROR');
expect(body.details).toBeDefined();
expect(Array.isArray(body.details)).toBe(true);
});
it('ZodError details contain field + message, no internal paths', async () => {
const { ZodError, ZodIssueCode } = await import('zod');
const error = new ZodError([
{
code: ZodIssueCode.too_small,
minimum: 1,
type: 'string',
inclusive: true,
path: ['fullName'],
message: 'String must contain at least 1 character(s)',
},
]);
const response = errorResponse(error);
const body = await response.json();
const bodyStr = JSON.stringify(body);
expect(bodyStr).not.toContain('src/');
expect(bodyStr).not.toContain('node_modules');
expect(bodyStr).not.toContain('.ts:');
// The field path is safe to expose (it's user-visible)
expect(body.details[0].field).toBe('fullName');
});
});
describe('Error response security — response shape invariants', () => {
it('every AppError response body follows { error, code } shape', async () => {
const errors = [
new AppError(400, 'Bad request', 'BAD_REQUEST'),
new NotFoundError('Invoice'),
new ForbiddenError('Cannot delete'),
new RateLimitError(30),
];
for (const err of errors) {
const body = await errorResponse(err).json();
expect(typeof body.error).toBe('string');
expect(body.error.length).toBeGreaterThan(0);
// Stack must never appear
expect(body).not.toHaveProperty('stack');
}
});
it('500 response body carries error + code (and requestId when in-flight)', async () => {
const response = errorResponse(new Error('db connection refused'));
const body = await response.json();
// Allowed keys for a 500 response. `code` is always present; `requestId`
// and `message` only appear when an active request context is in scope.
const allowed = new Set(['error', 'code', 'requestId', 'message']);
for (const key of Object.keys(body)) {
expect(allowed.has(key)).toBe(true);
}
expect(body.error).toBe('Internal server error');
expect(body.code).toBe('INTERNAL');
expect(body).not.toHaveProperty('stack');
});
});