import { Hono } from "hono"; import { HTTPException } from "hono/http-exception"; import { afterEach, describe, expect, test, vi } from "vitest"; import type { ErrorReporter } from "@hivegrid/error-reporter"; import { apiLogger } from "../logger.js"; import { apiError, createErrorHandler, createNotFoundHandler, normalizeErrorStatus, type ApiErrorEnv } from "./error-envelope.js"; type TestEnv = ApiErrorEnv; function createTestApp(requestId = "req_error_test", reporter?: ErrorReporter) { const app = new Hono(); app.use("*", async (c, next) => { c.set("requestId", requestId); await next(); }); app.notFound(createNotFoundHandler()); app.onError(createErrorHandler({ reporter })); return app; } afterEach(() => { vi.restoreAllMocks(); }); describe("error envelope middleware", () => { test("returns a request-ID-correlated not-found envelope", async () => { const app = createTestApp("req_missing_route"); const response = await app.request("/missing"); expect(response.status).toBe(404); await expect(response.json()).resolves.toEqual({ error: { code: "not_found", message: "Endpoint not found.", requestId: "req_missing_route", }, }); }); test("normalizes HTTPException statuses into public http_error envelopes", async () => { const app = createTestApp("req_http_exception"); app.get("/teapot", () => { throw new HTTPException(418, { message: "Short and stout." }); }); const response = await app.request("/teapot"); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: { code: "http_error", message: "Request failed.", params: { status: 418 }, requestId: "req_http_exception", }, }); }); test("redacts unhandled error details while logging request ID and reporting sanitized context once", async () => { const reporter: ErrorReporter = { report: vi.fn() }; const app = createTestApp("req_unhandled_secret", reporter); const error = new Error("postgres://user:secret@db.local/app token=fake-secret stack trace"); Object.assign(error, { connectionString: "postgres://user:secret@db.local/app", token: "fake-secret", }); const loggerError = vi.spyOn(apiLogger, "error").mockImplementation(() => undefined); app.get("/boom", () => { throw error; }); const response = await app.request("/boom?token=fake-secret", { headers: { authorization: "Bearer fake-secret", cookie: "session=fake-secret", }, }); const responseText = await response.text(); expect(response.status).toBe(500); expect(responseText).not.toContain("fake-secret"); expect(responseText).not.toContain("postgres://"); expect(responseText).not.toContain("stack trace"); expect(JSON.parse(responseText)).toEqual({ error: { code: "internal_error", message: "Internal server error.", requestId: "req_unhandled_secret", }, }); expect(loggerError).toHaveBeenCalledWith( { requestId: "req_unhandled_secret", error, }, "Unhandled API error", ); expect(loggerError.mock.calls[0]?.[0]).not.toEqual( expect.objectContaining({ body: expect.anything(), headers: expect.anything(), token: expect.anything(), }), ); expect(reporter.report).toHaveBeenCalledTimes(1); expect(reporter.report).toHaveBeenCalledWith( expect.objectContaining({ component: "api", operation: "http.unhandled_error", severity: "error", requestId: "req_unhandled_secret", method: "GET", path: "/boom", status: 500, error: expect.objectContaining({ errorName: "Error", token: "[Redacted]", connectionString: "[Redacted]", }), }), ); const serializedReport = JSON.stringify(vi.mocked(reporter.report).mock.calls); expect(serializedReport).not.toContain("fake-secret"); expect(serializedReport).not.toContain("postgres://"); expect(serializedReport).not.toContain("authorization"); expect(serializedReport).not.toContain("cookie"); expect(serializedReport).not.toContain("body"); }); test("swallows reporter failures without changing the 500 envelope", async () => { const reporter: ErrorReporter = { async report() { throw new Error("reporter transport failed"); }, }; const app = createTestApp("req_reporter_failure", reporter); app.get("/reporter-failure", () => { throw new Error("database token=fake-secret failed"); }); const response = await app.request("/reporter-failure"); expect(response.status).toBe(500); await expect(response.json()).resolves.toEqual({ error: { code: "internal_error", message: "Internal server error.", requestId: "req_reporter_failure", }, }); }); test("includes the current context request ID in direct error envelopes", async () => { const app = createTestApp("req_direct_envelope"); app.get("/direct", (c) => apiError(c, 403, "forbidden", "Forbidden.")); const response = await app.request("/direct"); expect(response.status).toBe(403); await expect(response.json()).resolves.toEqual({ error: { code: "forbidden", message: "Forbidden.", requestId: "req_direct_envelope", }, }); }); }); describe("normalizeErrorStatus", () => { test("keeps supported public statuses and buckets unsupported statuses", () => { expect(normalizeErrorStatus(401)).toBe(401); expect(normalizeErrorStatus(403)).toBe(403); expect(normalizeErrorStatus(404)).toBe(404); expect(normalizeErrorStatus(418)).toBe(400); expect(normalizeErrorStatus(503)).toBe(500); }); });