Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 30 additions & 1 deletion backend/src/gateway-app.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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();
}
});
});
2 changes: 2 additions & 0 deletions backend/src/gateway-app.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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) => {
Expand Down
94 changes: 94 additions & 0 deletions backend/src/http-errors.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof spyOn> | 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/<redacted>/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 });
});
});
25 changes: 25 additions & 0 deletions backend/src/http-errors.ts
Original file line number Diff line number Diff line change
@@ -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<E extends Env>(app: Hono<E>, 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);
});
}
2 changes: 2 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -272,6 +273,7 @@ if (learningReset > 0)
console.log(`[boot] learning recovery — ${learningReset} stuck rows re-armed`);

const app = new Hono<AppEnv>();
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
Expand Down
17 changes: 17 additions & 0 deletions backend/test/api-errors.test.ts
Original file line number Diff line number Diff line change
@@ -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" });
}
});
});
4 changes: 4 additions & 0 deletions docs-site/docs/api/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading