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

A JSON body that is not valid or has an unknown field is refused with a 400 that names the field, on every write route that uses json_body #16060

Merged opened this

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

Merged

mason/forge:mason/16043-a-json-body-that-is-not-valid-or-has-an → main 0 commits fork

  • Merged. mason/16043-a-json-body-that-is-not-valid-or-has-an was merged into main as f324950.

Review

Sign in to review this change.
6 files changed +322 −5
AGENTS.md +2
@@ -42,6 +42,8 @@ The check queue hands work to a runner through `src/checks/runner.ts` (#13652, R
4242
4343 `src/release/running_check.ts`: `settled`, per forge, the full check's settled verdict (`ok` or `failed`) on the running commit, the one the public changelog answer states (#15514); one entry, replaced when the commit changes, gone on restart.
4444
45 `src/http/json_body.ts`: `sent`, the JSON object a body reader (`body`, `boundedBody`) handed the route, per request in a WeakMap (an idempotent replay notes it on the original, `carrySent`), read by the server's door to name the field a bare-code 422 refused (`namedRefusal` in `src/http/named_refusal.ts`, #16043); gone with the request. `src/http/named_refusal.ts`: `DECLARED_BODIES`, the contract's write routes that declare a body as a matcher, built once at load; bounded by the contract.
46
4547 `src/core/transfer.ts`: the old owner/name pairs a transfer left behind (`repo_redirect`), held per database after the first request reads them and dropped by `transferRepo`, so a request under a path nothing moved from costs no statement (#569).
4648
4749 `src/http/mcp/load.ts`: `loading`, the one import of the MCP server and its tool index (#12521), started by the first request that needs the tools; when it settles it hands the list to /llms.txt (`setMcpTools`) and the cards (`setCardTools`), so a reader of those lists awaits `loadMcp()` first. A failed import is dropped and tried again; gone on restart.
src/http/json_body.ts +21
@@ -135,3 +135,24 @@ export function objectOf(bytes: Uint8Array): Record<string, unknown> {
135135 ? (value as Record<string, unknown>)
136136 : {};
137137 }
138
139 /**
140 * The object a body reader handed the route, noted per request (#16043), so a
141 * bare-code 422 can be named for the field the body got wrong
142 * (`named_refusal.ts`).
143 */
144 const sent = new WeakMap<Request, Record<string, unknown>>();
145 const rootOf = new WeakMap<Request, Request>();
146
147 /** Note the object a body reader handed the route for `request`. */
148 export function noteSent(request: Request, value: Record<string, unknown>): void {
149 sent.set(rootOf.get(request) ?? request, value);
150 }
151
152 /** A request rebuilt from another (an idempotent replay) notes its body on the original. */
153 export function carrySent(from: Request, to: Request): void {
154 rootOf.set(to, rootOf.get(from) ?? from);
155 }
156
157 /** The object noted for `request`, if a body reader ran. */
158 export const sentFor = (request: Request): Record<string, unknown> | undefined => sent.get(request);
src/http/named_refusal.ts added +142
@@ -0,0 +1,142 @@
1 /**
2 * A bare-code 422 on a JSON write, named for the field the body got wrong
3 * (#16043). A route that answers 422 with only a code (`empty_title`,
4 * `invalid`) left the caller to guess which field it meant, though the hint
5 * says "the message names it". The server's door (`namedRefusal`) fills a
6 * message in from the route's declared body in the contract, and only where
7 * the field is plausibly the cause:
8 *
9 * - a declared field sent as the wrong JSON type, or
10 * - an undeclared field that is a near-miss of a declared field the body left
11 * out (`titel` for `title`).
12 *
13 * An extra field beside a declared one is never blamed: `{"title":"",
14 * "bogus":1}` was refused for the empty title, not for `bogus`. Only a 422
15 * without a message is touched, so success paths and a route's own words are
16 * kept. The matcher is built once, when the server loads, as `cursor_lists.ts`
17 * builds its own.
18 */
19
20 import { readsJsonBody, ROUTES } from "../contract/openapi.ts";
21 import { sentFor } from "./json_body.ts";
22 import { Router } from "./router.ts";
23
24 type Declared = Readonly<Record<string, string>>;
25
26 /** The JSON type of a value, in the contract's words. */
27 const kindOf = (v: unknown): string =>
28 v === null ? "null" : Array.isArray(v) ? "array" : typeof v === "number" ? (Number.isInteger(v) ? "integer" : "number") : typeof v;
29
30 const WORDS: Readonly<Record<string, string>> = {
31 string: "a string",
32 integer: "a number",
33 number: "a number",
34 boolean: "true or false",
35 array: "an array",
36 object: "an object",
37 null: "null",
38 };
39
40 /**
41 * Whether `v` fits the contract's type word: undefined for a word that is
42 * prose (`"small, medium or large"`), which is not judged. Null fits anything,
43 * as routes read it as left out; digits in a string fit an integer, as
44 * `schema.int` reads them.
45 */
46 function fits(declared: string, v: unknown): boolean | undefined {
47 const type = declared.endsWith("?") ? declared.slice(0, -1) : declared;
48 if (WORDS[type] === undefined || type === "null") return undefined;
49 if (v === null) return true;
50 const kind = kindOf(v);
51 if (kind === type || (type === "number" && kind === "integer")) return true;
52 return type === "integer" && typeof v === "string" && /^-?\d+$/.test(v.trim());
53 }
54
55 const named = (field: string): string => JSON.stringify(field.length > 64 ? `${field.slice(0, 64)}…` : field);
56
57 /** A key folded for comparison: case, `_` and `-` do not count. */
58 const folded = (k: string): string => k.toLowerCase().replace(/[_-]/g, "");
59
60 /** Edit distance with adjacent swaps as one edit, given up past 2. */
61 function distance(a: string, b: string): number {
62 if (Math.abs(a.length - b.length) > 2) return 3;
63 const d: number[][] = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array<number>(b.length).fill(0)]);
64 for (let j = 1; j <= b.length; j++) d[0]![j] = j;
65 for (let i = 1; i <= a.length; i++)
66 for (let j = 1; j <= b.length; j++) {
67 const cost = a[i - 1] === b[j - 1] ? 0 : 1;
68 let v = Math.min(d[i - 1]![j]! + 1, d[i]![j - 1]! + 1, d[i - 1]![j - 1]! + cost);
69 if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) v = Math.min(v, d[i - 2]![j - 2]! + 1);
70 d[i]![j] = v;
71 }
72 return d[a.length]![b.length]!;
73 }
74
75 /**
76 * Whether `sent` reads as a misspelling of `meant`: one edit for a short key, two for a longer one.
77 */
78 export function nearMiss(sent: string, meant: string): boolean {
79 const a = folded(sent);
80 const b = folded(meant);
81 return distance(a, b) <= (b.length <= 4 ? 1 : 2);
82 }
83
84 /**
85 * Words naming the field a body got wrong against the route's declared
86 * fields: a wrongly typed one first, then an undeclared one that is a
87 * near-miss of a declared field the body left out; undefined otherwise.
88 */
89 export function fieldAmiss(body: Record<string, unknown>, declared: Declared): string | undefined {
90 for (const [field, type] of Object.entries(declared)) {
91 if (!Object.hasOwn(body, field)) continue;
92 if (fits(type, body[field]) === false)
93 return `field ${named(field)} is ${WORDS[kindOf(body[field])]}; this route takes ${WORDS[type.replace(/\?$/, "")]}`;
94 }
95 const missing = Object.keys(declared).filter((f) => !Object.hasOwn(body, f));
96 for (const key of Object.keys(body)) {
97 if (Object.hasOwn(declared, key)) continue;
98 const meant = missing.find((f) => nearMiss(key, f));
99 if (meant !== undefined) return `field ${named(key)} is not one this route reads; did you mean ${named(meant)}?`;
100 }
101 return undefined;
102 }
103
104 /**
105 * The contract's write routes that declare a body, fewest parameters first, so a literal path wins.
106 */
107 const DECLARED_BODIES: Router<Declared> = (() => {
108 const matcher = new Router<Declared>();
109 const params = (p: string) => (p.match(/\{/g) ?? []).length;
110 for (const r of [...ROUTES].sort((a, b) => params(a.path) - params(b.path)))
111 if (readsJsonBody(r)) matcher.add(r.method.toUpperCase(), r.path.replace(/\{([^}]+)\}/g, ":$1"), r.body!);
112 return matcher;
113 })();
114
115 /**
116 * A 422 the route answered without a message, given one that names the field
117 * the body got wrong; any other answer is returned as it came. The cheap
118 * checks run first, so only a 422 on a contract route whose body was read is
119 * parsed.
120 */
121 export async function namedRefusal(request: Request, response: Response): Promise<Response> {
122 if (response.status !== 422) return response;
123 const body = sentFor(request);
124 if (body === undefined || !(response.headers.get("content-type") ?? "").startsWith("application/json")) return response;
125 const declared = DECLARED_BODIES.match(request.method, new URL(request.url).pathname)?.handler;
126 if (declared === undefined) return response;
127 const message = fieldAmiss(body, declared);
128 if (message === undefined) return response;
129 let data: unknown;
130 try {
131 data = await response.clone().json();
132 } catch {
133 return response;
134 }
135 if (typeof data !== "object" || data === null || Array.isArray(data)) return response;
136 const refusal = data as Record<string, unknown>;
137 if (typeof refusal.message === "string" && refusal.message.trim() !== "") return response;
138 const headers = new Headers(response.headers);
139 headers.delete("content-length");
140 const { error, ...rest } = refusal;
141 return new Response(JSON.stringify({ error, message, ...rest }), { status: 422, statusText: response.statusText, headers });
142 }
src/http/respond.ts +8 −3
@@ -4,7 +4,7 @@
44 * before it reaches an action.
55 */
66
7 import { InvalidJson, objectOf } from "./json_body.ts";
7 import { InvalidJson, noteSent, objectOf } from "./json_body.ts";
88 import { NO_RAW_TEXT, refuseDirtyJson, type RawText } from "./parseable_request.ts";
99 import { bodyCapFor, readBounded } from "./limits.ts";
1010 import { namesReader } from "./reader.ts";
@@ -490,7 +490,9 @@ export function respondAccess(error: string, status: number): Response {
490490 export async function body(request: Request, raw: RawText = NO_RAW_TEXT): Promise<Record<string, unknown>> {
491491 const bytes = await readBounded(request, bodyCapFor(request));
492492 if (bytes === "too_large") throw new BodyTooLarge(bodyCapFor(request));
493 return refuseDirtyJson(objectOf(bytes), raw);
493 const value = refuseDirtyJson(objectOf(bytes), raw);
494 noteSent(request, value);
495 return value;
494496 }
495497
496498 /**
@@ -530,7 +532,10 @@ export async function boundedBody(
530532 raw: RawText = NO_RAW_TEXT,
531533 ): Promise<Record<string, unknown> | "too_large"> {
532534 const bytes = await readBounded(request, max);
533 return bytes === "too_large" ? "too_large" : refuseDirtyJson(objectOf(bytes), raw);
535 if (bytes === "too_large") return "too_large";
536 const value = refuseDirtyJson(objectOf(bytes), raw);
537 noteSent(request, value);
538 return value;
534539 }
535540
536541 export const str = (v: unknown): string => (typeof v === "string" ? v : "");
src/http/server.ts +5 −2
@@ -7,7 +7,8 @@
77
88 import { outsiderStatusPage } from "./offer_routes.ts";
99 import { standingFragment } from "../web/pages/fork-standing.ts";
10 import { InvalidJson } from "./json_body.ts";
10 import { carrySent, InvalidJson } from "./json_body.ts";
11 import { namedRefusal } from "./named_refusal.ts";
1112 import { answeringFor, ControlInput, controlRefusal, dirtyUrl, parseableRequest } from "./parseable_request.ts";
1213 import { expireCookie } from "../auth/cookies.ts";
1314 import { checkText } from "./check_text.ts";
@@ -2281,6 +2282,7 @@ export async function withIdempotency(
22812282 carryPeer(request, again);
22822283 carryNotes(request, again);
22832284 carryCaller(request, again);
2285 carrySent(request, again);
22842286 return again;
22852287 };
22862288
@@ -2794,7 +2796,8 @@ export async function serve(app: App, options: { warm?: { families?: readonly Fa
27942796 const onAbort = () => gone.resolve("gone");
27952797 if (request.signal.aborted) onAbort();
27962798 else request.signal.addEventListener("abort", onAbort, { once: true });
2797 const work = run().then(
2799 // A bare-code 422 on a JSON write is named for the field the body got wrong.
2800 const work = run().then((answer) => namedRefusal(request, answer)).then(
27982801 async (response) => {
27992802 const compressing = performance.now();
28002803 if (response.status === 401 && !response.headers.has("www-authenticate")) {
test/json-body-refusals.test.ts added +144
@@ -0,0 +1,144 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { createRepo } from "../src/core/repos.ts";
7 import { createSession } from "../src/core/sessions.ts";
8 import { createToken } from "../src/core/tokens.ts";
9 import { noteSent } from "../src/http/json_body.ts";
10 import { fieldAmiss, namedRefusal, nearMiss } from "../src/http/named_refusal.ts";
11 import { serve, type Servers } from "../src/http/server.ts";
12 import { seedAdmin } from "./helpers/admin.ts";
13
14 // #16043: a body the write routes cannot use is refused in words that say
15 // what was wrong with it. Malformed JSON is a 400 `invalid_json` naming the
16 // byte offset (pinned: it held since #14269); a 422 the route answers with a
17 // bare code gains a message naming the field sent as the wrong type, or an
18 // undeclared field that is a near-miss of a declared one left out. An extra
19 // field beside a declared one is never blamed. Success paths are not touched.
20 let dataDir = "";
21 let app: App, servers: Servers;
22 let cookie = "";
23 let token = "";
24
25 beforeAll(async () => {
26 dataDir = await mkdtemp(join(tmpdir(), "forge-json-refusals-"));
27 app = createApp({ dataDir, port: 0 });
28 servers = await serve(app);
29 const admin = await seedAdmin(app, { username: "ada", email: "[email protected]", password: "correct-horse-battery" });
30 if (!admin.ok) throw new Error(admin.error);
31 const made = await createRepo(app.db, app.reposRoot, { ownerId: admin.value.id, name: "notes", visibility: "public" });
32 if (!made.ok) throw new Error(String(made.error));
33 cookie = `forge_session=${createSession(app.db, admin.value.id).token}`;
34 token = createToken(app.db, admin.value.id, "t", "rw").token;
35 }, 30_000);
36
37 afterAll(async () => {
38 servers?.stop();
39 app?.close();
40 await rm(dataDir, { recursive: true, force: true });
41 });
42
43 const post = (path: string, body: string) =>
44 fetch(`${servers.url}${path}`, { method: "POST", headers: { "content-type": "application/json", cookie }, body });
45
46 type Refusal = { error: string; message?: string; hint?: string };
47
48 const ROUTES = [
49 { path: "/api/v1/repos/ada/notes/issues", field: "title", code: "empty_title" },
50 { path: "/api/v1/repos/ada/notes/labels", field: "name", code: "invalid" },
51 { path: "/api/v1/repos", field: "name", code: "invalid_name" },
52 ] as const;
53
54 describe.each(ROUTES)("POST $path", ({ path, field, code }) => {
55 test("malformed JSON is a 400 invalid_json naming the byte offset", async () => {
56 const res = await post(path, `{"${field}":"x",}`);
57 expect(res.status).toBe(400);
58 const got = (await res.json()) as Refusal;
59 expect(got.error).toBe("invalid_json");
60 expect(got.message).toContain(`at byte ${field.length + 8}`);
61 });
62
63 test("a wrongly typed field is named in the refusal", async () => {
64 const res = await post(path, JSON.stringify({ [field]: 5 }));
65 expect(res.status).toBe(422);
66 const got = (await res.json()) as Refusal;
67 expect(got.error).toBe(code);
68 expect(got.message).toBe(`field "${field}" is a number; this route takes a string`);
69 expect(got.hint).toContain("the message names");
70 });
71
72 test("a near-miss of a field left out is named in the refusal", async () => {
73 const res = await post(path, JSON.stringify({ [`${field}x`]: "notes" }));
74 expect(res.status).toBe(422);
75 const got = (await res.json()) as Refusal;
76 expect(got.error).toBe(code);
77 expect(got.message).toBe(`field "${field}x" is not one this route reads; did you mean "${field}"?`);
78 });
79
80 test("an extra field is not blamed when a declared field is the cause", async () => {
81 const res = await post(path, JSON.stringify({ [field]: "", bogus: 1 }));
82 expect(res.status).toBe(422);
83 const got = (await res.json()) as Refusal;
84 expect(got.error).toBe(code);
85 expect(got.message ?? "").not.toContain("bogus");
86 });
87
88 test.each(["[1]", '"x"', "5", "null"])("a body that is not an object (%s) is refused without a named field", async (text) => {
89 const res = await post(path, text);
90 expect(res.status).toBe(422);
91 const got = (await res.json()) as Refusal;
92 expect(got.error).toBe(code);
93 expect(got.message ?? "").not.toContain("field");
94 });
95 });
96
97 test("a body that succeeds today still succeeds, extra fields and all", async () => {
98 const res = await post("/api/v1/repos/ada/notes/issues", JSON.stringify({ title: "kept", bogus: 1 }));
99 expect(res.status).toBe(201);
100 expect(((await res.json()) as { title: string }).title).toBe("kept");
101 });
102
103 test("a token's idempotent write is refused in the same words", async () => {
104 const res = await fetch(`${servers.url}/api/v1/repos/ada/notes/issues`, {
105 method: "POST",
106 headers: { "content-type": "application/json", authorization: `Bearer ${token}`, "idempotency-key": "k-16043" },
107 body: JSON.stringify({ titel: "x" }),
108 });
109 expect(res.status).toBe(422);
110 expect(((await res.json()) as Refusal).message).toBe('field "titel" is not one this route reads; did you mean "title"?');
111 });
112
113 test("no field is named when every field sent is declared and fits", async () => {
114 const res = await post("/api/v1/repos/ada/notes/labels", JSON.stringify({ name: "x", color: "nothex" }));
115 expect(res.status).toBe(422);
116 expect(((await res.json()) as Refusal).message).toBeUndefined();
117 });
118
119 test("fieldAmiss judges only the types it knows", () => {
120 expect(fieldAmiss({ n: "5" }, { n: "integer" })).toBeUndefined();
121 expect(fieldAmiss({ n: null }, { n: "string" })).toBeUndefined();
122 expect(fieldAmiss({ n: "big" }, { n: "small, medium or large" })).toBeUndefined();
123 expect(fieldAmiss({ n: 1.5 }, { n: "number" })).toBeUndefined();
124 expect(fieldAmiss({ n: [1] }, { n: "boolean?" })).toBe('field "n" is an array; this route takes true or false');
125 expect(fieldAmiss({ "<b>": 1 }, {})).toBeUndefined();
126 expect(fieldAmiss({ "<title>": 1 }, { title: "string" })).toBe('field "<title>" is not one this route reads; did you mean "title"?');
127 });
128
129 test("an undeclared field is named only as a near-miss of a field left out", () => {
130 expect(fieldAmiss({ title: "", bogus: 1 }, { title: "string", body: "string" })).toBeUndefined();
131 expect(fieldAmiss({ title: "", Titel: "x" }, { title: "string" })).toBeUndefined();
132 expect(fieldAmiss({ Titel: "x" }, { title: "string" })).toBe('field "Titel" is not one this route reads; did you mean "title"?');
133 expect(nearMiss("full_name", "fullName")).toBe(true);
134 expect(nearMiss("bogus", "body")).toBe(false);
135 expect(nearMiss("nme", "name")).toBe(true);
136 expect(nearMiss("id", "name")).toBe(false);
137 });
138
139 test("a 422 on a route not in the contract is returned untouched", async () => {
140 const request = new Request("http://forge.local/not/in/the/contract", { method: "POST" });
141 noteSent(request, { titel: 5 });
142 const response = Response.json({ error: "invalid" }, { status: 422 });
143 expect(await namedRefusal(request, response)).toBe(response);
144 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs