diff --git a/src/__tests__/helpers/error-envelope.ts b/src/__tests__/helpers/error-envelope.ts new file mode 100644 index 000000000..960c78856 --- /dev/null +++ b/src/__tests__/helpers/error-envelope.ts @@ -0,0 +1,35 @@ +/** + * Error-envelope helpers for tests that compare whole response bodies. + * + * `apiHandler` stamps every error envelope with `meta.requestId`, a fresh id + * per request. A test that proves two refusals are byte-identical (an + * enumeration oracle check) compares everything else: the id is random, the + * same for no two requests, and says nothing about the account. + */ + +/** The body text with `meta.requestId` removed, `meta` dropped when empty. */ +export function withoutRequestId(text: string): string { + let body: unknown; + try { + body = JSON.parse(text); + } catch { + return text; + } + if (typeof body !== "object" || body === null || Array.isArray(body)) { + return text; + } + const record = { ...(body as Record) }; + const meta = record.meta; + if (typeof meta === "object" && meta !== null && !Array.isArray(meta)) { + const rest = { ...(meta as Record) }; + delete rest.requestId; + if (Object.keys(rest).length === 0) delete record.meta; + else record.meta = rest; + } + return JSON.stringify(record); +} + +/** A response's body text with `meta.requestId` removed. */ +export async function bodyWithoutRequestId(res: Response): Promise { + return withoutRequestId(await res.text()); +} diff --git a/src/app/api/auth/login/__tests__/constant-work.test.ts b/src/app/api/auth/login/__tests__/constant-work.test.ts index 6490b756a..a41edac7b 100644 --- a/src/app/api/auth/login/__tests__/constant-work.test.ts +++ b/src/app/api/auth/login/__tests__/constant-work.test.ts @@ -80,6 +80,7 @@ vi.mock("next/headers", () => ({ import { POST } from "../route"; import { prisma } from "@/lib/db"; import { verifyPasswordOrDummy } from "@/lib/auth/password"; +import { bodyWithoutRequestId } from "@/__tests__/helpers/error-envelope"; function makeRequest(): NextRequest { return new NextRequest("http://localhost/api/auth/login", { @@ -159,7 +160,7 @@ describe("POST /api/auth/login — constant work across the refusals", () => { vi.mocked(prisma.user.findFirst).mockResolvedValue(account as never); const res = await POST(makeRequest()); statuses.push(res.status); - bodies.push(await res.text()); + bodies.push(await bodyWithoutRequestId(res)); } expect(new Set(statuses)).toEqual(new Set([401])); expect(new Set(bodies).size).toBe(1); diff --git a/src/app/api/documents/inbound/[id]/chat/__tests__/route.test.ts b/src/app/api/documents/inbound/[id]/chat/__tests__/route.test.ts index c04152cc4..1cee38bac 100644 --- a/src/app/api/documents/inbound/[id]/chat/__tests__/route.test.ts +++ b/src/app/api/documents/inbound/[id]/chat/__tests__/route.test.ts @@ -421,6 +421,7 @@ describe("POST — consent / budget gating", () => { expect(res.status).toBe(403); const body = await res.json(); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "consent.ai.required", capability: "documentAi", reason: "consent_required", diff --git a/src/app/api/documents/inbound/[id]/extract/__tests__/route.test.ts b/src/app/api/documents/inbound/[id]/extract/__tests__/route.test.ts index a03e75fe6..1f143900a 100644 --- a/src/app/api/documents/inbound/[id]/extract/__tests__/route.test.ts +++ b/src/app/api/documents/inbound/[id]/extract/__tests__/route.test.ts @@ -371,6 +371,7 @@ describe("POST /api/documents/inbound/[id]/extract — the documentAi capability expect(res.status).toBe(403); const body = await res.json(); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "assistant.disabled.documentAi", capability: "documentAi", reason: "operator_disabled", diff --git a/src/app/api/documents/inbound/reindex/__tests__/route.test.ts b/src/app/api/documents/inbound/reindex/__tests__/route.test.ts index bcb3dc018..dcdaad6ec 100644 --- a/src/app/api/documents/inbound/reindex/__tests__/route.test.ts +++ b/src/app/api/documents/inbound/reindex/__tests__/route.test.ts @@ -137,6 +137,7 @@ describe("POST /api/documents/inbound/reindex — the documentAi capability", () expect(res.status).toBe(403); const body = await res.json(); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "assistant.disabled.documentAi", capability: "documentAi", reason: "operator_disabled", diff --git a/src/app/api/medications/[id]/intake/import/__tests__/route.test.ts b/src/app/api/medications/[id]/intake/import/__tests__/route.test.ts index a66164c05..cd905a742 100644 --- a/src/app/api/medications/[id]/intake/import/__tests__/route.test.ts +++ b/src/app/api/medications/[id]/intake/import/__tests__/route.test.ts @@ -344,6 +344,7 @@ describe("POST /api/medications/[id]/intake/import — durable kickoff", () => { await expect(res.json()).resolves.toEqual({ data: null, error: "Medication intake import already in progress", + meta: { requestId: expect.any(String) }, }); expect(prisma.medicationIntakeImportJob.create).not.toHaveBeenCalled(); expect(getGlobalBoss).not.toHaveBeenCalled(); diff --git a/src/app/api/medications/intake/dose-history-import/__tests__/route.test.ts b/src/app/api/medications/intake/dose-history-import/__tests__/route.test.ts index ce9e2e813..491f52dd5 100644 --- a/src/app/api/medications/intake/dose-history-import/__tests__/route.test.ts +++ b/src/app/api/medications/intake/dose-history-import/__tests__/route.test.ts @@ -232,6 +232,7 @@ describe("POST /api/medications/intake/dose-history-import", () => { expect(res.status).toBe(422); const body = await res.json(); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "missing_required_columns", detail: "Medication, Status", }); diff --git a/src/app/api/settings/__tests__/email-test-route.test.ts b/src/app/api/settings/__tests__/email-test-route.test.ts index 2bf5e0684..c54eec97a 100644 --- a/src/app/api/settings/__tests__/email-test-route.test.ts +++ b/src/app/api/settings/__tests__/email-test-route.test.ts @@ -86,7 +86,11 @@ describe("POST /api/settings/email/test", () => { expect(response.status).toBe(502); const json = await response.json(); - expect(json.meta).toEqual({ errorCode: failureCode, smtpCode }); + expect(json.meta).toEqual({ + requestId: expect.any(String), + errorCode: failureCode, + smtpCode, + }); expect(json.error).toContain(sentence); }, ); @@ -118,7 +122,7 @@ describe("POST /api/settings/email/test", () => { expect(response.status).toBe(500); const json = await response.json(); - expect(json.meta).toBeUndefined(); + expect(json.meta).toEqual({ requestId: expect.any(String) }); }); it("answers a delivered test with 200", async () => { diff --git a/src/app/api/settings/__tests__/private-origin-routes.test.ts b/src/app/api/settings/__tests__/private-origin-routes.test.ts index edcc96bd4..a7c46caf3 100644 --- a/src/app/api/settings/__tests__/private-origin-routes.test.ts +++ b/src/app/api/settings/__tests__/private-origin-routes.test.ts @@ -140,7 +140,10 @@ describe("PUT /api/settings/webhook — private targets", () => { expect(response.status).toBe(422); const json = await response.json(); expect(json.data).toBeNull(); - expect(json.meta).toEqual({ errorCode: "private_origin_not_approved" }); + expect(json.meta).toEqual({ + requestId: expect.any(String), + errorCode: "private_origin_not_approved", + }); expect(json.error).toContain("NOTIFICATION_PRIVATE_ORIGINS"); expect(prisma.notificationChannel.upsert).not.toHaveBeenCalled(); }); @@ -155,7 +158,10 @@ describe("PUT /api/settings/webhook — private targets", () => { expect(response.status).toBe(422); const json = await response.json(); - expect(json.meta).toEqual({ errorCode: "private_origin_not_approved" }); + expect(json.meta).toEqual({ + requestId: expect.any(String), + errorCode: "private_origin_not_approved", + }); expect(prisma.notificationChannel.upsert).not.toHaveBeenCalled(); }); @@ -181,7 +187,7 @@ describe("PUT /api/settings/webhook — private targets", () => { expect(response.status).toBe(422); const json = await response.json(); expect(json.error).toBe("Invalid data"); - expect(json.meta).toBeUndefined(); + expect(json.meta).toEqual({ requestId: expect.any(String) }); }); it("saves a listed loopback target and refuses an unlisted one with the listable code", async () => { @@ -223,7 +229,10 @@ describe("PUT /api/settings/webhook — private targets", () => { const response = await put("webhook", { url, enabled: true }); expect(response.status).toBe(422); const json = await response.json(); - expect(json.meta).toEqual({ errorCode: "private_origin_not_grantable" }); + expect(json.meta).toEqual({ + requestId: expect.any(String), + errorCode: "private_origin_not_grantable", + }); expect(json.error).toMatch(/no operator grant can open/); expect(json.error).not.toContain("NOTIFICATION_PRIVATE_ORIGINS"); expect(json.details.issues.length).toBeGreaterThan(0); @@ -262,7 +271,10 @@ describe("PUT /api/settings/ntfy — private servers", () => { expect(response.status).toBe(422); const json = await response.json(); - expect(json.meta).toEqual({ errorCode: "private_origin_not_approved" }); + expect(json.meta).toEqual({ + requestId: expect.any(String), + errorCode: "private_origin_not_approved", + }); expect(json.error).toContain("NOTIFICATION_PRIVATE_ORIGINS"); expect(prisma.notificationChannel.upsert).not.toHaveBeenCalled(); }); @@ -291,7 +303,10 @@ describe("PUT /api/settings/ntfy — private servers", () => { expect(response.status).toBe(422); const json = await response.json(); - expect(json.meta).toEqual({ errorCode: "private_origin_not_approved" }); + expect(json.meta).toEqual({ + requestId: expect.any(String), + errorCode: "private_origin_not_approved", + }); }); }); @@ -325,7 +340,10 @@ describe("POST /api/settings/{webhook,ntfy}/test — the refusal names itself", expect(response.status).toBe(422); const json = await response.json(); - expect(json.meta).toEqual({ errorCode: "private_origin_not_approved" }); + expect(json.meta).toEqual({ + requestId: expect.any(String), + errorCode: "private_origin_not_approved", + }); expect(json.error).toContain("NOTIFICATION_PRIVATE_ORIGINS"); }, ); @@ -347,7 +365,10 @@ describe("POST /api/settings/{webhook,ntfy}/test — the refusal names itself", expect(response.status).toBe(422); const json = await response.json(); - expect(json.meta).toEqual({ errorCode: "private_origin_not_grantable" }); + expect(json.meta).toEqual({ + requestId: expect.any(String), + errorCode: "private_origin_not_grantable", + }); expect(json.error).toMatch(/no operator grant can open/); expect(json.error).not.toContain("NOTIFICATION_PRIVATE_ORIGINS"); }, @@ -372,6 +393,7 @@ describe("POST /api/settings/{webhook,ntfy}/test — the refusal names itself", expect(response.status).toBe(502); const json = await response.json(); expect(json.meta).toEqual({ + requestId: expect.any(String), errorCode: "upstream_rejected", upstreamStatus: 400, upstreamBody: '{"error":"Bad Request","errorCode":400}', @@ -408,7 +430,11 @@ describe("POST /api/settings/{webhook,ntfy}/test — the refusal names itself", expect(response.status).toBe(502); const json = await response.json(); - expect(json.meta).toEqual({ errorCode: code, upstreamStatus: status }); + expect(json.meta).toEqual({ + requestId: expect.any(String), + errorCode: code, + upstreamStatus: status, + }); }, ); @@ -450,7 +476,7 @@ describe("POST /api/settings/{webhook,ntfy}/test — the refusal names itself", expect(response.status).toBe(500); const json = await response.json(); - expect(json.meta).toBeUndefined(); + expect(json.meta).toEqual({ requestId: expect.any(String) }); expect(emitIfSampledMock).toHaveBeenCalledWith( expect.objectContaining({ level: "error" }), ); diff --git a/src/lib/__tests__/acting-account-resolver.test.ts b/src/lib/__tests__/acting-account-resolver.test.ts index 6ed62b275..458243588 100644 --- a/src/lib/__tests__/acting-account-resolver.test.ts +++ b/src/lib/__tests__/acting-account-resolver.test.ts @@ -130,6 +130,7 @@ import { auditLog } from "@/lib/auth/audit"; import { emitIfSampled } from "@/lib/logging/transports"; import { prisma } from "@/lib/db"; import type { WideEvent } from "@/lib/logging/types"; +import { bodyWithoutRequestId } from "@/__tests__/helpers/error-envelope"; const OWNER = "owner-1"; const DELEGATE = "delegate-1"; @@ -604,7 +605,7 @@ describe("refusals do not enumerate", () => { const missing = await route(() => requireRecordAuth("read", "measurements"), )(); - const missingBody = await missing.text(); + const missingBody = await bodyWithoutRequestId(missing); vi.clearAllMocks(); headerJar.clear(); @@ -616,7 +617,7 @@ describe("refusals do not enumerate", () => { const present = await route(() => requireRecordAuth("read", "measurements"), )(); - const presentBody = await present.text(); + const presentBody = await bodyWithoutRequestId(present); expect(missing.status).toBe(present.status); // Bytes, not statuses. A difference of one word here is an account @@ -631,7 +632,7 @@ describe("refusals do not enumerate", () => { const revoked = await route(() => requireRecordAuth("read", "measurements"), )(); - const revokedBody = await revoked.text(); + const revokedBody = await bodyWithoutRequestId(revoked); vi.clearAllMocks(); headerJar.clear(); @@ -642,7 +643,7 @@ describe("refusals do not enumerate", () => { requireRecordAuth("read", "measurements"), )(); - expect(revokedBody).toBe(await never.text()); + expect(revokedBody).toBe(await bodyWithoutRequestId(never)); }); it("keeps the reason off the wire and on the audit row", async () => { @@ -790,7 +791,7 @@ describe("a scoped grant reaches only the sections it names", () => { const outOfScope = await route(() => requireRecordAuth("read", "measurements"), )(); - const outOfScopeBody = await outOfScope.text(); + const outOfScopeBody = await bodyWithoutRequestId(outOfScope); grantRows.length = 0; liveGrant({ access: "READ" }); @@ -799,7 +800,7 @@ describe("a scoped grant reaches only the sections it names", () => { )(); expect(outOfScope.status).toBe(insufficient.status); - expect(outOfScopeBody).toBe(await insufficient.text()); + expect(outOfScopeBody).toBe(await bodyWithoutRequestId(insufficient)); expect(outOfScopeBody).not.toContain("scope"); expect(outOfScopeBody).not.toContain("section"); }); @@ -954,7 +955,7 @@ describe("the guardian resolver gates on the marker, not the grant", () => { userRows.set(OWNER, user(OWNER, "USER", null)); liveGrant({ access: "MANAGE" }); const fenced = await route(() => requireGuardianAuth())(); - const fencedBody = await fenced.text(); + const fencedBody = await bodyWithoutRequestId(fenced); // Compared against the oldest refusal in the feature: no grant at all. The // two are as far apart in meaning as this feature gets — "you were never @@ -966,7 +967,7 @@ describe("the guardian resolver gates on the marker, not the grant", () => { )(); expect(fenced.status).toBe(insufficient.status); - expect(fencedBody).toBe(await insufficient.text()); + expect(fencedBody).toBe(await bodyWithoutRequestId(insufficient)); expect(fencedBody).not.toContain("guardian"); expect(fencedBody).not.toContain("managed"); }); diff --git a/src/lib/__tests__/ai-refusal-envelope.test.ts b/src/lib/__tests__/ai-refusal-envelope.test.ts index a21e8f390..5b72cb8c1 100644 --- a/src/lib/__tests__/ai-refusal-envelope.test.ts +++ b/src/lib/__tests__/ai-refusal-envelope.test.ts @@ -137,6 +137,7 @@ describe("apiHandler renders it", () => { expect(body.data).toBeNull(); expect(typeof body.error).toBe("string"); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "consent.ai.required", capability: "coach", reason: "consent_required", diff --git a/src/lib/__tests__/api-handler-error-request-id.test.ts b/src/lib/__tests__/api-handler-error-request-id.test.ts new file mode 100644 index 000000000..a76c73493 --- /dev/null +++ b/src/lib/__tests__/api-handler-error-request-id.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it, vi } from "vitest"; + +vi.mock("@/lib/db", () => ({ prisma: {} })); +vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn() })); +vi.mock("@/lib/auth/hmac", () => ({ hashToken: vi.fn() })); +vi.mock("@/lib/auth/audit", () => ({ + auditLog: vi.fn().mockResolvedValue(undefined), +})); +vi.mock("@/lib/logging/transports", () => ({ emitIfSampled: vi.fn() })); +vi.mock("@/lib/monitoring/glitchtip", () => ({ + sendGlitchtipEvent: vi.fn().mockResolvedValue(undefined), +})); +vi.mock("next/headers", () => ({ + headers: vi.fn(async () => ({ get: () => null })), + cookies: vi.fn(async () => ({ + get: () => undefined, + set: () => {}, + delete: () => {}, + })), +})); + +import { NextRequest, NextResponse } from "next/server"; +import { apiHandler, HttpError } from "@/lib/api-handler"; +import { apiError, apiSuccess, withErrorRequestId } from "@/lib/api-response"; + +const INCOMING = "3f9a2c1b-0000-4000-8000-000000000001"; + +function call( + handler: () => Promise, + headers: Record = {}, +) { + return apiHandler(handler)( + new NextRequest("http://localhost/api/probe", { headers }), + ); +} + +describe("meta.requestId on every error envelope", () => { + it("adds the request id to an apiError envelope, equal to the header", async () => { + const res = await call(async () => + apiError("Nope", 409, { errorCode: "probe.conflict" }), + ); + const body = await res.json(); + expect(res.status).toBe(409); + expect(body.meta.errorCode).toBe("probe.conflict"); + expect(body.meta.requestId).toBe(res.headers.get("x-request-id")); + expect(body.meta.requestId).toMatch(/^[A-Za-z0-9-]{8,64}$/); + }); + + it("adds it to an envelope without meta and to a hand-built one", async () => { + const plain = await call(async () => apiError("Not found", 404)); + expect((await plain.json()).meta).toEqual({ + requestId: plain.headers.get("x-request-id"), + }); + const hand = await call(async () => + NextResponse.json({ data: null, error: "Gone" }, { status: 410 }), + ); + expect((await hand.json()).meta.requestId).toBe( + hand.headers.get("x-request-id"), + ); + }); + + it("adds it to a thrown HttpError and to an unexpected throw (500)", async () => { + const thrown = await call(async () => { + throw new HttpError(403, "Forbidden"); + }); + expect((await thrown.json()).meta.requestId).toBe( + thrown.headers.get("x-request-id"), + ); + const crash = await call(async () => { + throw new Error("boom"); + }); + expect(crash.status).toBe(500); + expect((await crash.json()).meta.requestId).toBe( + crash.headers.get("x-request-id"), + ); + }); + + it("adopts a well-formed incoming x-request-id and replaces a malformed one", async () => { + const adopted = await call(async () => apiError("Nope", 400), { + "x-request-id": INCOMING, + }); + expect((await adopted.json()).meta.requestId).toBe(INCOMING); + expect(adopted.headers.get("x-request-id")).toBe(INCOMING); + + const forged = ''; + const replaced = await call(async () => apiError("Nope", 400), { + "x-request-id": forged, + }); + const id = (await replaced.json()).meta.requestId; + expect(id).not.toBe(forged); + expect(id).toMatch(/^[A-Za-z0-9-]{8,64}$/); + expect(replaced.headers.get("x-request-id")).toBe(id); + }); + + it("keeps status, headers and set-cookie on the rewritten response", async () => { + const res = await call(async () => { + const r = apiError("Slow down", 429, { + headers: { "Retry-After": "30" }, + }); + r.cookies.set("probe", "1"); + return r; + }); + expect(res.status).toBe(429); + expect(res.headers.get("Retry-After")).toBe("30"); + expect(res.headers.get("set-cookie")).toContain("probe=1"); + }); + + it("leaves a success, a non-envelope error and a non-JSON error untouched", async () => { + const ok = await call(async () => apiSuccess({ fine: true })); + expect(await ok.json()).toEqual({ data: { fine: true }, error: null }); + + const rpc = await call(async () => + NextResponse.json( + { jsonrpc: "2.0", error: { code: -32600, message: "bad" }, id: 1 }, + { status: 400 }, + ), + ); + expect(await rpc.json()).toEqual({ + jsonrpc: "2.0", + error: { code: -32600, message: "bad" }, + id: 1, + }); + + const text = await call( + async () => new Response("plain failure", { status: 502 }), + ); + expect(await text.text()).toBe("plain failure"); + }); + + it("never overwrites an id the handler set itself", async () => { + const res = await withErrorRequestId( + NextResponse.json( + { data: null, error: "x", meta: { requestId: "kept-by-handler" } }, + { status: 500 }, + ), + "ignored-0000", + ); + expect((await res.json()).meta.requestId).toBe("kept-by-handler"); + }); +}); diff --git a/src/lib/__tests__/api-handler-key-mismatch.test.ts b/src/lib/__tests__/api-handler-key-mismatch.test.ts index b4bbf5a63..906a33526 100644 --- a/src/lib/__tests__/api-handler-key-mismatch.test.ts +++ b/src/lib/__tests__/api-handler-key-mismatch.test.ts @@ -41,7 +41,10 @@ describe("apiHandler while the encryption key does not match", () => { expect(response.status).toBe(503); const body = await response.json(); expect(body.data).toBeNull(); - expect(body.meta).toEqual({ errorCode: "encryption.key_mismatch" }); + expect(body.meta).toEqual({ + requestId: expect.any(String), + errorCode: "encryption.key_mismatch", + }); expect(response.headers.get("Retry-After")).toBe("300"); expect(handler).not.toHaveBeenCalled(); }); diff --git a/src/lib/__tests__/auth-error-codes.test.ts b/src/lib/__tests__/auth-error-codes.test.ts index eb608b7e9..76cf3ee13 100644 --- a/src/lib/__tests__/auth-error-codes.test.ts +++ b/src/lib/__tests__/auth-error-codes.test.ts @@ -236,7 +236,11 @@ describe("auth failures carry a machine-readable errorCode", () => { )) as Response; expect(res.status).toBe(404); - expect(await res.json()).toEqual({ data: null, error: "Not found" }); + expect(await res.json()).toEqual({ + data: null, + error: "Not found", + meta: { requestId: expect.any(String) }, + }); }); it("keeps every code distinct and dot.case", () => { diff --git a/src/lib/api-handler.ts b/src/lib/api-handler.ts index c837aec0f..57a0f5c96 100644 --- a/src/lib/api-handler.ts +++ b/src/lib/api-handler.ts @@ -55,6 +55,7 @@ import { } from "./sharing/record-session-fence"; import { refuseOnKeyMismatch } from "./boot/key-mismatch-refusal"; import { acceptIncomingRequestId } from "./http/request-id"; +import { withErrorRequestId } from "./api-response"; import { capturedRateLimit, rateLimitResponseHeaders, @@ -363,7 +364,13 @@ export function apiHandler Promise>( /* logging must never crash the handler */ } } - const nr = response as NextResponse; + // Every error envelope names its request id in `meta.requestId`, so + // the id survives a proxy that strips the header (see + // `withErrorRequestId`). + const nr = (await withErrorRequestId( + response as Response, + evt.getRequestId(), + )) as NextResponse; nr.headers.set("x-request-id", evt.getRequestId()); if (isBypassRoute) applyBypassRouteHeaders(nr.headers); // v1.37.0 — echo the record context this response was actually served diff --git a/src/lib/api-response.ts b/src/lib/api-response.ts index 0f22c09d6..82762766f 100644 --- a/src/lib/api-response.ts +++ b/src/lib/api-response.ts @@ -301,6 +301,69 @@ export function apiError(message: string, status = 400, meta?: ErrorMeta) { return buildJsonErrorResponse({ data: null, error: message }, status, meta); } +/** An error body larger than this is not an envelope worth re-reading. */ +const ERROR_ENVELOPE_MAX_BYTES = 64 * 1024; + +function isPlainObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Put the request id into `meta.requestId` of an error envelope. + * + * Every 4xx and 5xx a route answers with the `{ data: null, error, meta? }` + * envelope carries the full request id beside the `x-request-id` header, so a + * client behind a proxy that strips headers can still show the id a person + * reads out to the operator, who finds the event in the admin log with it. + * + * Applied once, by `apiHandler`, to whatever the handler answered, so a route + * that builds its error with `apiError`, with `NextResponse.json` by hand or by + * throwing cannot be the one that forgets it. Anything that is not a JSON + * envelope (a redirect, a stream, a FHIR `OperationOutcome`, a body that does + * not parse) is returned untouched, and an id the handler already set wins. + */ +export async function withErrorRequestId( + response: Response, + requestId: string, +): Promise { + if (response.status < 400) return response; + const contentType = response.headers.get("content-type") ?? ""; + if (!contentType.toLowerCase().includes("application/json")) return response; + const declared = Number(response.headers.get("content-length") ?? "0"); + if (declared > ERROR_ENVELOPE_MAX_BYTES) return response; + + let body: unknown; + try { + const text = await response.clone().text(); + if (text.length === 0 || text.length > ERROR_ENVELOPE_MAX_BYTES) { + return response; + } + body = JSON.parse(text); + } catch { + return response; + } + // The envelope and nothing else: a JSON-RPC error (`/mcp`) or an RFC-shaped + // OAuth body has no `data: null` beside its `error`, and a member added to + // either would be one its own clients do not expect. + if ( + !isPlainObject(body) || + body.data !== null || + typeof body.error !== "string" + ) { + return response; + } + const meta = body.meta; + if (meta !== undefined && !isPlainObject(meta)) return response; + if (meta && typeof meta.requestId === "string") return response; + + const headers = new Headers(response.headers); + headers.delete("content-length"); + return new NextResponse( + JSON.stringify({ ...body, meta: { ...(meta ?? {}), requestId } }), + { status: response.status, statusText: response.statusText, headers }, + ); +} + /** * Read a request body as text, counting BYTES as they arrive and stopping at * `maxBytes`. A body that declares a larger `Content-Length` is refused before diff --git a/tests/integration/acting-account-resolver.test.ts b/tests/integration/acting-account-resolver.test.ts index 13ace25fb..0c61815a4 100644 --- a/tests/integration/acting-account-resolver.test.ts +++ b/tests/integration/acting-account-resolver.test.ts @@ -75,6 +75,7 @@ import { import { hashToken } from "@/lib/auth/hmac"; import { prisma } from "@/lib/db"; import { acceptGrant, inviteGrant, revokeGrant } from "@/lib/sharing/grants"; +import { bodyWithoutRequestId } from "@/__tests__/helpers/error-envelope"; let counter = 0; @@ -379,11 +380,11 @@ describe("acting-account resolver — refusals do not enumerate", () => { headerJar.set(ACCOUNT_SELECTOR_HEADER, "cmnosuchaccount000000000x"); const missing = await call(); - const missingBody = await missing.text(); + const missingBody = await bodyWithoutRequestId(missing); headerJar.set(ACCOUNT_SELECTOR_HEADER, stranger.id); const present = await call(); - const presentBody = await present.text(); + const presentBody = await bodyWithoutRequestId(present); expect(missing.status).toBe(403); expect(present.status).toBe(403); diff --git a/tests/integration/ai-extraction-capability.test.ts b/tests/integration/ai-extraction-capability.test.ts index a94cc4008..4a326b1cc 100644 --- a/tests/integration/ai-extraction-capability.test.ts +++ b/tests/integration/ai-extraction-capability.test.ts @@ -273,6 +273,7 @@ describe("reading a stored document — POST /api/documents/inbound/[id]/suggest expect(status).toBe(403); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "assistant.disabled.documentAi", capability: "documentAi", reason: "operator_disabled", @@ -303,6 +304,7 @@ describe("reading a stored document — POST /api/documents/inbound/[id]/suggest expect(status).toBe(403); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "consent.ai.required", capability: "documentAi", reason: "consent_required", @@ -336,6 +338,7 @@ describe("reading a stored document — POST /api/documents/inbound/[id]/suggest expect(status).toBe(422); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "documents.inbound.providerUnsupported", capability: "documentAi", reason: "no_provider", @@ -390,6 +393,7 @@ describe("scanning a lab report — POST /api/labs/ocr/extract", () => { expect(status).toBe(403); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "module.disabled", capability: "labsOcr", reason: "module_disabled", @@ -438,6 +442,7 @@ describe("turning medication text into a schedule — POST /api/medications/extr expect(status).toBe(403); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "assistant.disabled.documentAi", capability: "medicationExtract", reason: "operator_disabled", @@ -457,6 +462,7 @@ describe("turning medication text into a schedule — POST /api/medications/extr expect(status).toBe(503); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "ai.provider.none", capability: "medicationExtract", reason: "no_provider", diff --git a/tests/integration/encryption-key-check.test.ts b/tests/integration/encryption-key-check.test.ts index 965509974..51daa67cb 100644 --- a/tests/integration/encryption-key-check.test.ts +++ b/tests/integration/encryption-key-check.test.ts @@ -157,7 +157,10 @@ describe("boot encryption key check (real Postgres)", () => { ); expect(refused.status).toBe(503); const body = await refused.json(); - expect(body.meta).toEqual({ errorCode: "encryption.key_mismatch" }); + expect(body.meta).toEqual({ + requestId: expect.any(String), + errorCode: "encryption.key_mismatch", + }); const { GET: healthGet } = await import("@/app/api/health/route"); const health = await asRoute(healthGet)( @@ -625,6 +628,7 @@ describe("routes outside apiHandler refuse while the key does not match", () => ); expect(res.status).toBe(503); expect((await res.json()).meta).toEqual({ + requestId: expect.any(String), errorCode: "encryption.key_mismatch", }); }); diff --git a/tests/integration/login-insecure-transport.test.ts b/tests/integration/login-insecure-transport.test.ts index 58f495d0c..c23df31ba 100644 --- a/tests/integration/login-insecure-transport.test.ts +++ b/tests/integration/login-insecure-transport.test.ts @@ -139,6 +139,7 @@ describe("sign-in over plain http with Secure-only cookies (real Postgres)", () expect(res.status).toBe(409); const body = await res.json(); expect(body.meta).toEqual({ + requestId: expect.any(String), errorCode: "auth.session.insecure_transport", sessionCookieSecure: true, }); diff --git a/tests/integration/sharing-lifecycle.test.ts b/tests/integration/sharing-lifecycle.test.ts index a948ddc80..1aa9574a0 100644 --- a/tests/integration/sharing-lifecycle.test.ts +++ b/tests/integration/sharing-lifecycle.test.ts @@ -51,6 +51,7 @@ vi.mock("@/lib/db-compat", () => ({ import { apiHandler, requireRecordAuth } from "@/lib/api-handler"; import { hashToken } from "@/lib/auth/hmac"; import { prisma } from "@/lib/db"; +import { bodyWithoutRequestId } from "@/__tests__/helpers/error-envelope"; let counter = 0; @@ -771,7 +772,9 @@ describe("the switch endpoint", () => { const ungranting = await switchTo(stranger.id); expect(unknown.status).toBe(ungranting.status); - expect(await unknown.text()).toBe(await ungranting.text()); + expect(await bodyWithoutRequestId(unknown)).toBe( + await bodyWithoutRequestId(ungranting), + ); }); it("refuses over Bearer, where the carrier is the header", async () => { diff --git a/tests/integration/sharing-scope-fence.test.ts b/tests/integration/sharing-scope-fence.test.ts index 67b3beafe..f8d88f3e8 100644 --- a/tests/integration/sharing-scope-fence.test.ts +++ b/tests/integration/sharing-scope-fence.test.ts @@ -34,6 +34,7 @@ import { getPrismaClient, truncateAllTables, switchSessionTo } from "./setup"; import { SHARE_DOMAINS } from "@/lib/sharing/scope"; import type { ShareDomain } from "@/lib/sharing/scope"; +import { bodyWithoutRequestId } from "@/__tests__/helpers/error-envelope"; vi.mock("next/headers", async () => { const { cookieJar, headerJar } = await import("./mock-next-headers"); @@ -417,7 +418,7 @@ describe("the refusal does not distinguish itself", () => { const delegate = await makeUser("delegate"); await switchInto(owner.id, delegate.id, ["medications"]); const outOfScope = await PROBES.labs.call(); - const outOfScopeBody = await outOfScope.text(); + const outOfScopeBody = await bodyWithoutRequestId(outOfScope); // A stranger naming the same record. Different story, same answer. const stranger = await makeUser("stranger"); @@ -427,7 +428,7 @@ describe("the refusal does not distinguish itself", () => { const noGrant = await PROBES.labs.call(); expect(outOfScope.status).toBe(noGrant.status); - expect(outOfScopeBody).toBe(await noGrant.text()); + expect(outOfScopeBody).toBe(await bodyWithoutRequestId(noGrant)); expect(outOfScopeBody).not.toContain("scope"); // …and the operator's trail tells them apart, which is the half that has