import { Hono } from "hono"; import { describe, expect, test, vi } from "vitest"; import { createRequestIdMiddleware, type ApiRequestIdVariables, type RequestIdLogger } from "./request-id.js"; type TestEnv = { Variables: ApiRequestIdVariables; }; function createLogger(): Required { return { error: vi.fn(), info: vi.fn(), }; } function createTestApp(logger?: RequestIdLogger) { const app = new Hono(); app.use("*", createRequestIdMiddleware({ logger })); app.get("/request-id", (c) => c.json({ requestId: c.get("requestId") })); app.get("/boom", () => { throw new Error("boom"); }); app.onError((error, c) => c.json({ requestId: c.get("requestId"), message: error.message }, 500)); return app; } describe("createRequestIdMiddleware", () => { test("echoes a trusted incoming request ID in the response body and header", async () => { const logger = createLogger(); const app = createTestApp(logger); const response = await app.request("/request-id", { headers: { "x-request-id": "req_existing_123" }, }); await expect(response.json()).resolves.toEqual({ requestId: "req_existing_123" }); expect(response.headers.get("x-request-id")).toBe("req_existing_123"); expect(logger.info).toHaveBeenCalledWith( expect.objectContaining({ durationMs: expect.any(Number), method: "GET", path: "/request-id", requestId: "req_existing_123", status: 200, }), "API request completed" ); }); test("generates a non-empty request ID when the request omits the header", async () => { const app = createTestApp(); const response = await app.request("/request-id"); const body = (await response.json()) as { requestId: string }; expect(body.requestId).toEqual(expect.any(String)); expect(body.requestId).not.toHaveLength(0); expect(response.headers.get("x-request-id")).toBe(body.requestId); }); test.each([ ["blank", " "], ["oversized", "r".repeat(129)], ["DEL control character", "req\u007Fpoison"], ])("generates a safe request ID for a %s incoming header", async (_name, incomingRequestId) => { const app = createTestApp(); const request = new Request("http://localhost/request-id"); vi.spyOn(request.headers, "get").mockReturnValue(incomingRequestId); const response = await app.request(request); const body = (await response.json()) as { requestId: string }; expect(body.requestId).toEqual(expect.any(String)); expect(body.requestId).not.toBe(incomingRequestId.trim()); expect(response.headers.get("x-request-id")).toBe(body.requestId); }); test("makes the request ID available to downstream handlers", async () => { const app = createTestApp(); const response = await app.request("/request-id", { headers: { "x-request-id": "req_context_456" }, }); await expect(response.json()).resolves.toEqual({ requestId: "req_context_456" }); }); test("keeps generated response header parity when downstream returns JSON", async () => { const app = createTestApp(); const response = await app.request("/request-id"); const body = (await response.json()) as { requestId: string }; expect(response.headers.get("content-type")).toContain("application/json"); expect(response.headers.get("x-request-id")).toBe(body.requestId); }); test("emits a correlated error log and preserves response header parity when downstream throws", async () => { const logger = createLogger(); const app = new Hono(); app.use("*", createRequestIdMiddleware({ logger })); app.get("/boom", () => { throw new Error("boom"); }); app.onError((error, c) => c.json({ message: error.message }, 500)); const response = await app.request("/boom", { headers: { "x-request-id": "req_error_789" }, }); expect(response.status).toBe(500); expect(response.headers.get("x-request-id")).toBe("req_error_789"); expect(logger.error).toHaveBeenCalledWith( expect.objectContaining({ durationMs: expect.any(Number), error: expect.any(Error), method: "GET", path: "/boom", requestId: "req_error_789", status: 500, }), "API request failed" ); }); });