Public: anyone can read this; the crew can change it.

No request answers with a stack trace: an error boundary, HEAD, and a content-type checked at the door #28

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/tempo:scout/20-no-request-answers-with-a-stack-trace-an → main 1 commit fork

  • Merged. scout/20-no-request-answers-with-a-stack-trace-an was merged into main as bbdb4f1.

Review

Sign in to review this change.
3 files changed +121 −11
src/routes.ts +35 −2
@@ -25,6 +25,18 @@ const html = (body: string, status = 200): Response =>
2525 const json = (body: unknown, status = 200): Response =>
2626 new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
2727 const bad = (message: string): Response => new Response(message, { status: 400 });
28 const methodNotAllowed = (allow: string): Response => new Response("method not allowed", { status: 405, headers: { allow } });
29
30 // Thrown by form() and caught once, at the door, so a handler never has to
31 // check for it itself.
32 class HttpError extends Error {
33 constructor(
34 public status: number,
35 message: string,
36 ) {
37 super(message);
38 }
39 }
2840
2941 // A plain form submit expects a redirect back to the board; the board's
3042 // own script asks for JSON (Accept: application/json) so it can update
@@ -47,15 +59,35 @@ function cleanText(value: FormDataEntryValue | null, max: number): string | null
4759 return text === "" ? null : text;
4860 }
4961
62 // A missing content-type is left alone: it parses as an empty form today
63 // (a bare `curl -X POST` with no body), and neither the board script nor a
64 // browser form ever omits it, so nothing real relies on rejecting it too.
65 function checkFormContentType(request: Request): void {
66 const type = request.headers.get("content-type");
67 if (type === null) return;
68 if (type.startsWith("application/x-www-form-urlencoded") || type.startsWith("multipart/form-data")) return;
69 throw new HttpError(415, "expected a form body");
70 }
5071 async function form(request: Request): Promise<FormData> {
72 checkFormContentType(request);
5173 return request.formData();
5274 }
5375
5476 export async function route(request: Request, url: URL, env: string, who: Who): Promise<Response | undefined> {
77 try {
78 return await dispatch(request, url, env, who);
79 } catch (err) {
80 if (err instanceof HttpError) return new Response(err.message, { status: err.status });
81 throw err;
82 }
83 }
84
85 async function dispatch(request: Request, url: URL, env: string, who: Who): Promise<Response | undefined> {
5586 const method = request.method;
5687 const parts = url.pathname.split("/").filter(Boolean);
5788
58 if (method === "GET" && parts.length === 0) {
89 if (parts.length === 0) {
90 if (method !== "GET") return methodNotAllowed("GET, HEAD");
5991 const boards = who.role === "anon" ? [] : db.listBoardsByOwner(who.id);
6092 return html(landingPage(env, who, boards));
6193 }
@@ -82,7 +114,8 @@ export async function route(request: Request, url: URL, env: string, who: Who):
82114 const boardId = parts[1];
83115 if (!BOARD_ID.test(boardId)) return undefined;
84116
85 if (method === "GET" && parts.length === 2) {
117 if (parts.length === 2) {
118 if (method !== "GET") return methodNotAllowed("GET, HEAD");
86119 const board = db.getBoard(boardId);
87120 if (!board) return new Response("board not found", { status: 404 });
88121 const columns = db.listColumns(boardId);
src/server.test.ts +54
@@ -347,6 +347,60 @@ test("the MCP server lists its tools and calls add_card as JSON-RPC", async () =
347347 expect(missing.error.code).toBe(-32602);
348348 });
349349
350 test("a POST with the wrong content-type is refused before formData() runs, and the server keeps answering", async () => {
351 const response = await fetch(base + "/boards", {
352 method: "POST",
353 headers: { "content-type": "application/json" },
354 body: "{}",
355 });
356 expect(response.status).toBe(415);
357
358 const next = await fetch(base + "/");
359 expect(next.status).toBe(200);
360 });
361
362 test("a body that throws inside formData() anyway gets a plain 500 with the floor, never a stack trace", async () => {
363 const response = await fetch(base + "/boards", {
364 method: "POST",
365 headers: { "content-type": "multipart/form-data; boundary=broken" },
366 body: "not actually multipart",
367 });
368 expect(response.status).toBe(500);
369 const body = await response.text();
370 expect(body).not.toContain("BunError");
371 expect(body).not.toContain("/");
372 expect(response.headers.get("content-security-policy")).toContain("default-src 'self'");
373 expect(response.headers.get("x-content-type-options")).toBe("nosniff");
374
375 const next = await fetch(base + "/");
376 expect(next.status).toBe(200);
377 });
378
379 test("HEAD matches GET's status and content-length with an empty body", async () => {
380 const id = await newBoard();
381 const boardPage = await (await fetch(base + `/b/${id}`)).text();
382 const [, staticSrc] = boardPage.match(/<script src="(\/static\/board[^"]+)"/)!;
383
384 for (const path of ["/", `/b/${id}`, staticSrc, "/nope"]) {
385 const get = await fetch(base + path);
386 const head = await fetch(base + path, { method: "HEAD" });
387 expect(head.status).toBe(get.status);
388 expect(head.headers.get("content-length")).toBe(get.headers.get("content-length"));
389 expect(await head.text()).toBe("");
390 }
391 });
392
393 test("a method the app does not implement on / or /b/<id> gets 405 with Allow", async () => {
394 const put = await fetch(base + "/", { method: "PUT" });
395 expect(put.status).toBe(405);
396 expect(put.headers.get("allow")).toBe("GET, HEAD");
397
398 const id = await newBoard();
399 const deleted = await fetch(base + `/b/${id}`, { method: "DELETE" });
400 expect(deleted.status).toBe(405);
401 expect(deleted.headers.get("allow")).toBe("GET, HEAD");
402 });
403
350404 test("list_boards over MCP only ever shows the caller's own boards", async () => {
351405 await fetch(base + "/boards", {
352406 method: "POST",
src/server.ts +32 −9
@@ -50,22 +50,45 @@ export const server = Bun.serve({
5050 // A connection silent for a minute is dropped; /b/:id/events heartbeats
5151 // every 25 seconds (src/live.ts) to stay well inside that.
5252 idleTimeout: 60,
53 // Never Bun's source-listing error page, in production or in a preview.
54 development: false,
5355 async fetch(request) {
5456 const url = new URL(request.url);
5557 if (request.method === "POST" && !sameOrigin(request)) return withFloor(new Response("forbidden", { status: 403 }));
5658
57 const routed = await route(request, url, env, who(request, identityKey));
58 if (routed) return withFloor(routed);
59 // A HEAD answers exactly like the matching GET, minus the body: route
60 // and serve as GET, then strip the body but keep status and headers.
61 const isHead = request.method === "HEAD";
62 const routingRequest = isHead ? new Request(request, { method: "GET" }) : request;
5963
60 // Files under ./static are served as they are, cached for a year: name
61 // them by content (board.<hash>.js) and a change is a new name, never a
62 // stale cache. The path is confined to the directory.
63 if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) {
64 const routed = await route(routingRequest, url, env, who(request, identityKey));
65 let response: Response;
66 if (routed) {
67 response = withFloor(routed);
68 } else if (url.pathname.startsWith("/static/") && !url.pathname.includes("..")) {
69 // Files under ./static are served as they are, cached for a year: name
70 // them by content (board.<hash>.js) and a change is a new name, never a
71 // stale cache. The path is confined to the directory.
6472 const file = Bun.file(join(import.meta.dir, "..", url.pathname.slice(1)));
65 if (await file.exists())
66 return withFloor(new Response(file, { headers: { "cache-control": "public, max-age=31536000, immutable" } }));
73 response = (await file.exists())
74 ? withFloor(new Response(file, { headers: { "cache-control": "public, max-age=31536000, immutable" } }))
75 : withFloor(new Response("not found", { status: 404 }));
76 } else {
77 response = withFloor(new Response("not found", { status: 404 }));
6778 }
68 return withFloor(new Response("not found", { status: 404 }));
79
80 if (!isHead) return response;
81 const body = await response.arrayBuffer();
82 const headers = new Headers(response.headers);
83 headers.set("content-length", String(body.byteLength));
84 return new Response(null, { status: response.status, headers });
85 },
86 // A thrown error (a malformed request body, anything unexpected) never
87 // reaches the caller as Bun's HTML error page or a stack trace: log it
88 // here, answer with a plain 500 that still carries the security floor.
89 error(err) {
90 console.error(err);
91 return withFloor(new Response("internal error", { status: 500 }));
6992 },
7093 });
7194

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs