Files
pn-new-crm/tests/integration/storage/proxy-route.test.ts
Matt Ciaccio ade4c9e77d fix(audit-v2): platform-wide post-merge hardening across 5 domains
Five-domain audit (security, routes, DB, integrations, UI/UX) ran after
the cf37d09 merge. Critical + high-impact items landed here; deferred
medium/low items indexed in docs/audit-final-deferred.md (now organised
into a "Audit-final v2" section).

Security:
- Storage proxy tokens now bind to op (`'get'` vs `'put'`). A long-lived
  download URL minted by `presignDownload` for an emailed brochure can no
  longer be replayed against the proxy PUT to overwrite the original
  storage object. `verifyProxyToken` requires `expectedOp` and rejects
  mismatches; legacy tokens missing `op` fail-closed. Regression tests
  added.
- Markdown email merge values are now markdown-escaped (`[`, `]`, `(`,
  `)`, `*`, `_`, `\`, backticks, braces) before substitution into the
  rep-authored body. A malicious value like `[click here](https://evil)`
  stored in `client.fullName` no longer survives `escapeHtml` to render
  as a real `<a href>` in the outbound email. Phishing-via-merge-field
  closed; regression tests added.
- Middleware now performs an Origin/Referer check on
  POST/PUT/PATCH/DELETE to `/api/v1/**`. Defense-in-depth on top of
  better-auth's SameSite=Lax cookie. Webhooks/public/auth/portal routes
  exempt as they don't carry the session cookie.

Routes:
- Template management routes were calling `withPermission('documents',
  'manage', ...)` — but `documents` doesn't have a `manage` action. The
  registry has `document_templates.manage`. Every non-superadmin was
  getting 403'd on the seven template endpoints. Fixed across the
  /admin/templates surface.
- Custom-fields permission resource is hardcoded to `clients` regardless
  of which entity (yacht/company/etc.) the values belong to. Documented
  as deferred (requires per-entity routes).

DB:
- documentSends: every parent FK (client_id, interest_id, berth_id,
  brochure_id, brochure_version_id) now uses ON DELETE SET NULL so the
  audit trail outlasts hard-deletes. The denormalized columns
  (recipient_email, document_kind, body_markdown, from_address) were
  added precisely for this. Migration 0035.
- Polymorphic discriminators on yachts.current_owner_type and
  invoices.billing_entity_type now have CHECK constraints — typos like
  `'clients'` vs `'client'` were silently inserting unreachable rows
  before. Migration 0036.

Integrations:
- Email attachment resolution (`src/lib/email/index.ts`) was importing
  MinIO directly instead of `getStorageBackend()`. Filesystem-backend
  deployments would have broken every email-with-attachment send. Now
  routes through the pluggable abstraction per CLAUDE.md.
- Documenso DOCUMENT_OPENED webhook filter relaxed: v2 may omit
  `readStatus` or send lowercase, so an event that was the SIGNAL of an
  open was being silently dropped. Now treats any recipient on a
  DOCUMENT_OPENED event as opened.

UI/UX:
- Expense detail used to render `receiptFileIds` as opaque UUID badges —
  reps couldn't view the receipt they uploaded. Now renders an image
  thumbnail (via `/api/v1/files/[id]/preview`) plus a Download link for
  PDFs. Closed the "where's my receipt?" loop in the expense flow.
- Expense detail Edit + Archive buttons now `<PermissionGate>` and the
  archive mutation surfaces success/error toasts instead of silent 403s.
- Brochures admin: setDefault/archive/create mutations now have onError
  toasts (only onSuccess existed before).
- Removed broken bulk-upload link in scan/page (route doesn't exist;
  used a raw `<a>` triggering a full reload to a 404).

Test status: 1168/1168 vitest passing. tsc clean.

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

161 lines
5.3 KiB
TypeScript

/**
* Integration test: GET /api/storage/[token]
*
* Exercises the §14.9a critical mitigations on the live route:
* - HMAC verification: a token signed with the wrong secret is rejected.
* - Expiry: an expired token is rejected.
* - Single-use replay: a token used twice (within the replay TTL) is
* rejected the second time.
* - Happy path: a valid token streams the file with correct headers.
*
* The storage backend itself is mocked to a FilesystemBackend rooted in a
* tempdir. Redis is mocked to an in-memory map so the test doesn't need
* a live Redis.
*/
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import * as path from 'node:path';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const VALID_KEY = 'a'.repeat(64);
// Hoisted in-memory Redis. The proxy route uses SET NX EX, so we model
// just enough behaviour to track keys that have been seen.
const redisStore = new Map<string, string>();
vi.mock('@/lib/redis', () => ({
redis: {
set: vi.fn(async (key: string, value: string, ..._args: unknown[]) => {
// _args = ['EX', ttl, 'NX'] in our usage. Honour NX semantics.
const nxIndex = _args.findIndex((a) => a === 'NX');
if (nxIndex >= 0 && redisStore.has(key)) return null;
redisStore.set(key, value);
return 'OK';
}),
},
}));
vi.mock('@/lib/logger', () => ({
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
}));
beforeAll(() => {
process.env.EMAIL_CREDENTIAL_KEY = VALID_KEY;
process.env.BETTER_AUTH_SECRET = 'a'.repeat(64);
});
describe('GET /api/storage/[token]', () => {
let storageRoot: string;
let backend: import('@/lib/storage/filesystem').FilesystemBackend;
let getMock: ReturnType<typeof vi.fn>;
beforeEach(async () => {
redisStore.clear();
storageRoot = await mkdtemp(path.join(tmpdir(), 'pn-storage-route-'));
// Use the real FilesystemBackend so the resolution / realpath logic is
// genuinely exercised; mock just `getStorageBackend()` to return it.
const { FilesystemBackend } = await import('@/lib/storage/filesystem');
backend = await FilesystemBackend.create({
root: storageRoot,
proxyHmacSecretEncrypted: null,
});
getMock = vi.fn(async () => backend);
vi.doMock('@/lib/storage', async () => {
const real = await vi.importActual<typeof import('@/lib/storage')>('@/lib/storage');
return { ...real, getStorageBackend: getMock };
});
});
afterEach(async () => {
vi.doUnmock('@/lib/storage');
await rm(storageRoot, { recursive: true, force: true });
});
async function callRoute(token: string) {
const { GET } = await import('@/app/api/storage/[token]/route');
return GET(new Request(`http://test/api/storage/${token}`) as never, {
params: Promise.resolve({ token }),
});
}
it('serves a file with a valid token (happy path)', async () => {
await backend.put('berths/abc/file.txt', Buffer.from('hello world'), {
contentType: 'text/plain',
});
const presigned = await backend.presignDownload('berths/abc/file.txt', {
expirySeconds: 60,
filename: 'file.txt',
contentType: 'text/plain',
});
const token = presigned.url.split('/api/storage/').pop()!;
const res = await callRoute(token);
expect(res.status).toBe(200);
expect(res.headers.get('Content-Type')).toBe('text/plain');
expect(res.headers.get('X-Content-Type-Options')).toBe('nosniff');
const text = await res.text();
expect(text).toBe('hello world');
});
it('rejects a token signed with the wrong HMAC secret', async () => {
await backend.put('berths/abc/file.txt', Buffer.from('hello'), {
contentType: 'text/plain',
});
const { signProxyToken } = await import('@/lib/storage/filesystem');
const badToken = signProxyToken(
{
k: 'berths/abc/file.txt',
e: Math.floor(Date.now() / 1000) + 60,
n: 'nonce',
op: 'get' as const,
},
'wrong-secret',
);
const res = await callRoute(badToken);
expect(res.status).toBe(403);
const body = await res.json();
expect(body.error).toMatch(/Invalid|expired/i);
});
it('rejects an expired token', async () => {
await backend.put('berths/abc/file.txt', Buffer.from('hello'), {
contentType: 'text/plain',
});
const { signProxyToken } = await import('@/lib/storage/filesystem');
const expiredToken = signProxyToken(
{
k: 'berths/abc/file.txt',
e: Math.floor(Date.now() / 1000) - 1,
n: 'nonce',
op: 'get' as const,
},
backend.getHmacSecret(),
);
const res = await callRoute(expiredToken);
expect(res.status).toBe(403);
});
it('refuses to replay a token a second time within the TTL', async () => {
await backend.put('berths/abc/file.txt', Buffer.from('hello'), {
contentType: 'text/plain',
});
const presigned = await backend.presignDownload('berths/abc/file.txt', {
expirySeconds: 60,
});
const token = presigned.url.split('/api/storage/').pop()!;
const first = await callRoute(token);
expect(first.status).toBe(200);
await first.text();
const second = await callRoute(token);
expect(second.status).toBe(403);
const body = await second.json();
expect(body.error).toMatch(/already used/i);
});
});