feat(api): carry the request id in meta.requestId on every error envelope

This commit is contained in:
Marc-André Bombeck committed 2026-10-15 22:05:06 +02:00
1 parent f75a2fe343
commit 2fd62cc115
22 files changed
+336 -30

No files matched your search

+35
View File
@@ -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<string, unknown>) };
const meta = record.meta;
if (typeof meta === "object" && meta !== null && !Array.isArray(meta)) {
const rest = { ...(meta as Record<string, unknown>) };
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<string> {
return withoutRequestId(await res.text());
}
@@ -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);
@@ -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",
@@ -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",
@@ -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",
@@ -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();
@@ -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",
});
@@ -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 () => {
@@ -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" }),
);
@@ -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");
});
@@ -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",
@@ -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<Response>,
headers: Record<string, string> = {},
) {
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 = '<script>"x"</script>';
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");
});
});
@@ -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();
});
+5 -1
View File
@@ -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", () => {
+8 -1
View File
@@ -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<T extends (...args: any[]) => Promise<Response>>(
/* 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
+63
View File
@@ -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<string, unknown> {
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<Response> {
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
@@ -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);
@@ -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",
@@ -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",
});
});
@@ -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,
});
+4 -1
View File
@@ -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 () => {
@@ -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