diff --git a/backend/src/gateway-app.test.ts b/backend/src/gateway-app.test.ts index 674cc50f..db85eaf3 100644 --- a/backend/src/gateway-app.test.ts +++ b/backend/src/gateway-app.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -42,3 +42,32 @@ describe("gateway health", () => { expect(body.artifact_storage).toContain("ARTIFACT_STORAGE_DIR"); }); }); + +describe("gateway error answers", () => { + test("an unknown path is a JSON 404", async () => { + const response = await createGatewayApp().request("/api/provider-typo/v1/chat"); + + expect(response.status).toBe(404); + expect(response.headers.get("content-type")).toContain("application/json"); + expect(await response.json()).toEqual({ error: "not_found" }); + }); + + test("an error no route caught is a JSON 500, logged with method and path", async () => { + const logged = spyOn(console, "error").mockImplementation(() => {}); + try { + const app = createGatewayApp(); + app.get("/api/test-only-crash", () => { + throw new Error("test-only crash"); + }); + + const response = await app.request("/api/test-only-crash"); + + expect(response.status).toBe(500); + expect(response.headers.get("content-type")).toContain("application/json"); + expect(await response.json()).toEqual({ error: "internal_error" }); + expect(logged.mock.calls[0]?.[0]).toBe("[gateway] GET /api/test-only-crash failed:"); + } finally { + logged.mockRestore(); + } + }); +}); diff --git a/backend/src/gateway-app.ts b/backend/src/gateway-app.ts index 37c4ed98..f2809551 100644 --- a/backend/src/gateway-app.ts +++ b/backend/src/gateway-app.ts @@ -1,5 +1,6 @@ import { Hono, type Context } from "hono"; import { artifactStorageHealth } from "./artifacts/storage"; +import { installJsonErrorHandlers } from "./http-errors"; import { knowledgeMcpRoutes } from "./knowledge/gateway/mcp"; import { providerGatewayRoutes } from "./provider-gateway/routes"; import { currentReleaseFingerprint } from "./release"; @@ -11,6 +12,7 @@ import { currentReleaseFingerprint } from "./release"; */ export function createGatewayApp(): Hono { const app = new Hono(); + installJsonErrorHandlers(app, "gateway"); // Health includes the artifact store: the gateway is the process every // harness publishes through, so "listening" without a writable store is down. const health = async (c: Context) => { diff --git a/backend/src/http-errors.test.ts b/backend/src/http-errors.test.ts new file mode 100644 index 00000000..4f0b24ff --- /dev/null +++ b/backend/src/http-errors.test.ts @@ -0,0 +1,94 @@ +import { afterEach, describe, expect, spyOn, test } from "bun:test"; +import { Hono } from "hono"; +import { HTTPException } from "hono/http-exception"; +import { installJsonErrorHandlers } from "./http-errors"; + +let logged: ReturnType | null = null; + +afterEach(() => { + logged?.mockRestore(); + logged = null; +}); + +function app(): Hono { + const app = new Hono(); + installJsonErrorHandlers(app, "test"); + app.get("/api/ok", (c) => c.json({ ok: true })); + app.get("/api/boom", () => { + throw new Error("unexpected database state"); + }); + app.get("/api/teapot", () => { + throw new HTTPException(418, { message: "short and stout" }); + }); + // A mounted router with no handler of its own, the way index.ts mounts them. + const nested = new Hono(); + nested.post("/explode", () => { + throw new TypeError("cannot read properties of undefined"); + }); + app.route("/api/nested", nested); + return app; +} + +describe("installJsonErrorHandlers", () => { + test("answers an unknown path with a JSON 404", async () => { + const response = await app().request("/api/does-not-exist"); + + expect(response.status).toBe(404); + expect(response.headers.get("content-type")).toContain("application/json"); + expect(await response.json()).toEqual({ error: "not_found" }); + }); + + test("answers a thrown error with a JSON 500 and logs the method and path", async () => { + logged = spyOn(console, "error").mockImplementation(() => {}); + + const response = await app().request("/api/boom"); + + expect(response.status).toBe(500); + expect(response.headers.get("content-type")).toContain("application/json"); + expect(await response.json()).toEqual({ error: "internal_error" }); + expect(logged).toHaveBeenCalledTimes(1); + const [line, error] = logged.mock.calls[0] as [string, Error]; + expect(line).toBe("[test] GET /api/boom failed:"); + expect(error.message).toBe("unexpected database state"); + }); + + test("catches an error thrown inside a mounted router", async () => { + logged = spyOn(console, "error").mockImplementation(() => {}); + + const response = await app().request("/api/nested/explode", { method: "POST" }); + + expect(response.status).toBe(500); + expect(await response.json()).toEqual({ error: "internal_error" }); + expect(logged.mock.calls[0]?.[0]).toBe("[test] POST /api/nested/explode failed:"); + }); + + test("logs a path with the capability it carries scrubbed", async () => { + logged = spyOn(console, "error").mockImplementation(() => {}); + const crashing = new Hono(); + installJsonErrorHandlers(crashing, "test"); + crashing.get("/api/port-proxy/:threadId/view/:capability/*", () => { + throw new Error("proxy failed"); + }); + + const response = await crashing.request("/api/port-proxy/t1/view/v1.eyJjbGFpbXMiOnt9fQ.c2lnbmF0dXJl/index.html"); + + expect(response.status).toBe(500); + expect(logged.mock.calls[0]?.[0]).toBe("[test] GET /api/port-proxy/t1/view//index.html failed:"); + }); + + test("keeps the response an HTTPException carries", async () => { + logged = spyOn(console, "error").mockImplementation(() => {}); + + const response = await app().request("/api/teapot"); + + expect(response.status).toBe(418); + expect(await response.text()).toBe("short and stout"); + expect(logged).not.toHaveBeenCalled(); + }); + + test("leaves a route's own answer alone", async () => { + const response = await app().request("/api/ok"); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true }); + }); +}); diff --git a/backend/src/http-errors.ts b/backend/src/http-errors.ts new file mode 100644 index 00000000..b45a1fdd --- /dev/null +++ b/backend/src/http-errors.ts @@ -0,0 +1,25 @@ +import type { Env, Hono } from "hono"; +import { HTTPException } from "hono/http-exception"; +import { createSecretRedactor } from "./secrets/redact"; + +/** Some paths carry a credential (a preview view's signed capability): the + * logged path keeps its shape with the credential scrubbed. */ +const pathRedactor = createSecretRedactor([]); + +/** + * Give an app's last-resort answers the JSON shape every route already uses: + * an unknown path is `404 {error: "not_found"}` and an error no route caught + * is `500 {error: "internal_error"}`, logged with its method and path. Hono's + * defaults are plain text, which a client reading the body as JSON fails on a + * second time. An `HTTPException` (thrown by Hono middleware on purpose) keeps + * the response it carries. Sub-apps mounted with `route()` that set no handler + * of their own fall through to these. + */ +export function installJsonErrorHandlers(app: Hono, surface: string): void { + app.notFound((c) => c.json({ error: "not_found" }, 404)); + app.onError((error, c) => { + if (error instanceof HTTPException) return error.getResponse(); + console.error(`[${surface}] ${c.req.method} ${pathRedactor.text(c.req.path)} failed:`, error); + return c.json({ error: "internal_error" }, 500); + }); +} diff --git a/backend/src/index.ts b/backend/src/index.ts index 6b8deb3a..8cb82d61 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -9,6 +9,7 @@ import { internalArtifactChangeRoutes } from "./artifacts/internal-change-routes import { startEmailConnector } from "./connectors/email"; import { client, db } from "./db/client"; import type { AppEnv } from "./http"; +import { installJsonErrorHandlers } from "./http-errors"; import { allowDevOrg, connectorEmailConfig, @@ -272,6 +273,7 @@ if (learningReset > 0) console.log(`[boot] learning recovery — ${learningReset} stuck rows re-armed`); const app = new Hono(); +installJsonErrorHandlers(app, "api"); // CORS for the frontend, with credentials so cookie sessions flow when the // browser calls the backend directly (the Next dev proxy is same-origin). A diff --git a/backend/test/api-errors.test.ts b/backend/test/api-errors.test.ts new file mode 100644 index 00000000..ddbf559c --- /dev/null +++ b/backend/test/api-errors.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, test } from "bun:test"; +import { createOrgSession, fetchApi } from "./helpers"; + +// The backend app's last-resort answers, through the real app and auth adapter +// (src/http-errors.ts installed in src/index.ts). +describe("unknown API paths", () => { + test("a signed-in GET of a path no router serves answers a JSON 404", async () => { + const session = await createOrgSession("api-not-found"); + + for (const path of ["/api/does-not-exist", "/api/runs/abc/no-such-view"]) { + const response = await fetchApi(path, { cookies: session.cookies }); + expect(response.status).toBe(404); + expect(response.headers.get("content-type")).toContain("application/json"); + expect(await response.json()).toEqual({ error: "not_found" }); + } + }); +}); diff --git a/docs-site/docs/api/index.mdx b/docs-site/docs/api/index.mdx index d9da5f3e..79ecc03f 100644 --- a/docs-site/docs/api/index.mdx +++ b/docs-site/docs/api/index.mdx @@ -79,6 +79,10 @@ product reference. - **Server-owned fields.** Tenant identity and provenance (`org_id`, `user_id`, `origin`) are set server-side. `POST /api/runs` rejects a client-supplied `origin` with `400`. +- **JSON errors.** Errors are JSON with an `error` field. A path no route + serves is `404 {"error": "not_found"}`, and an error no route handled is + `500 {"error": "internal_error"}`, logged on the server with its method and + path. The sandbox gateway answers the same way. ## Streaming