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

A NUL or control character in any query string or form field is a plain 400 at the edge, not a page #15373

Merged opened this

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

Merged

scout/forge:scout/15364-a-nul-or-control-character-in-any-query → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/15364-a-nul-or-control-character-in-any-query was merged into main as 86b0afa.

Review

Sign in to review this change.
27 files changed +442 −39
src/http/api.ts +4 −3
@@ -44,6 +44,7 @@ import { recordDrill } from "../core/domain_drills.ts";
4444 import { drillVerdict } from "../kernel/domain_drill.ts";
4545 import { DOMAINS } from "../kernel/domains.ts";
4646 import { BODY_CAPS, readBounded } from "./limits.ts";
47 import { FILE_TEXT } from "./parseable_request.ts";
4748 import { askCheck, askedWords } from "../checks/again.ts";
4849 import { nextUp, queueJson } from "../core/next_up.ts";
4950 import { notStartable } from "../crew/not_startable.ts";
@@ -2219,7 +2220,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
22192220 if (denied) return denied;
22202221 const repo = loadRepo(ctx);
22212222 if (!repo) return notFound();
2222 const input = await body(ctx.request);
2223 const input = await body(ctx.request, FILE_TEXT);
22232224 const rawFiles = Array.isArray(input.files) ? input.files : [];
22242225 const files = rawFiles
22252226 .filter(
@@ -2255,7 +2256,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
22552256 if (denied) return denied;
22562257 const repo = loadRepo(ctx);
22572258 if (!repo) return notFound();
2258 const input = await body(ctx.request);
2259 const input = await body(ctx.request, FILE_TEXT);
22592260
22602261 const files = (Array.isArray(input.files) ? input.files : [])
22612262 .filter(
@@ -3537,7 +3538,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
35373538 // repo the caller may not be able to see anyway.
35383539 const link = originForRepo(ctx.app.db, repo.id);
35393540 if (!link) return notFound();
3540 const input = await body(ctx.request);
3541 const input = await body(ctx.request, FILE_TEXT);
35413542 const result = await contribute(ctx.app, ctx.auth.user, {
35423543 originId: link.origin.id,
35433544 // The repo names its own upstream; a caller cannot redirect the write
src/http/api/boards.ts +4
@@ -18,6 +18,7 @@ import { boardsAdmin } from "../api.ts";
1818 import type { Handler } from "../context.ts";
1919 import { holds, weakEtag } from "../etag.ts";
2020 import { bodyCapFor, readBounded } from "../limits.ts";
21 import { refuseDirtyJson } from "../parseable_request.ts";
2122 import { apiError, json, notFound, requireAccount } from "../respond.ts";
2223 import type { Router } from "../router.ts";
2324
@@ -60,6 +61,7 @@ export function boardRoutes(router: Router<Handler>): void {
6061 } catch {
6162 return apiError("bad_json", 400, "the body must be a JSON query object");
6263 }
64 refuseDirtyJson(query);
6365 const answer = runQuery(ctx.app.db, query, { repoIds: "all" });
6466 return answer.ok
6567 ? json({ rows: answer.rows })
@@ -107,6 +109,7 @@ export function boardRoutes(router: Router<Handler>): void {
107109 } catch {
108110 return apiError("bad_json", 400, "the body must be a JSON object");
109111 }
112 refuseDirtyJson(input);
110113 const { op, slug, title, by } = input;
111114 const done =
112115 op === "pin" ? await pinPanel(ctx.app, ctx.auth.user, slug, title)
@@ -176,6 +179,7 @@ export function boardRoutes(router: Router<Handler>): void {
176179 } catch {
177180 return apiError("bad_json", 400, "the body must be a JSON board");
178181 }
182 refuseDirtyJson(input);
179183 const done = await writeBoard(ctx.app, ctx.auth.user, ctx.params.slug!, input);
180184 return done.ok ? json({ slug: ctx.params.slug, ...done.value }) : boardFailed(done.error);
181185 });
src/http/api/displays.ts +2
@@ -7,6 +7,7 @@ import { chooseBuilds, parseChoice } from "../../actions/displays.ts";
77 import type { Handler } from "../context.ts";
88 import { loadRepo } from "../api.ts";
99 import { bodyCapFor, readBounded } from "../limits.ts";
10 import { refuseDirtyJson } from "../parseable_request.ts";
1011 import { apiError, forbidden, json, notFound, requireScope } from "../respond.ts";
1112 import type { Router } from "../router.ts";
1213
@@ -25,6 +26,7 @@ export function displayRoutes(router: Router<Handler>): void {
2526 } catch {
2627 return apiError("bad_json", 400, "the body must be JSON: { \"builds\": [\"owner/name:label\"] }");
2728 }
29 refuseDirtyJson(input);
2830 const choice = parseChoice(input);
2931 if (!choice.ok) return apiError("invalid", 422, choice.error);
3032 const done = await chooseBuilds(ctx.app, ctx.auth.user, repo, choice.value.builds, choice.value.tip);
src/http/api/timers.ts +2
@@ -6,6 +6,7 @@
66 import { armFor, cancelFor, type TimerError } from "../../actions/timers.ts";
77 import type { Handler } from "../context.ts";
88 import { BODY_CAPS, readBounded } from "../limits.ts";
9 import { refuseDirtyJson } from "../parseable_request.ts";
910 import { apiError, json, unauthorized } from "../respond.ts";
1011 import type { Router } from "../router.ts";
1112 import { tokenSecret } from "../token_header.ts";
@@ -25,6 +26,7 @@ export function timersRoutes(router: Router<Handler>): void {
2526 } catch {
2627 return apiError("invalid", 422, "The body is JSON.");
2728 }
29 refuseDirtyJson(input);
2830 const armed = armFor(ctx.app, secret, input);
2931 if (!armed.ok) return apiError(armed.error.kind, STATUS[armed.error.kind], armed.error.message);
3032 return json({ timer: armed.value }, 201);
src/http/api/user.ts +2 −1
@@ -32,6 +32,7 @@ import type { Ctx, Handler } from "../context.ts";
3232 import { holds, weakEtag } from "../etag.ts";
3333 import { clientAddress } from "../peer.ts";
3434 import { apiError, body, json, notFound, publicProfile, publicUser, requireAccount, requireScope, respondAccess, str, tryAgain, unauthorized, WINDOW } from "../respond.ts";
35 import { FILE_TEXT } from "../parseable_request.ts";
3536 import type { Router } from "../router.ts";
3637 import { eventStream } from "../sse.ts";
3738 import { gateBlocked, hostOf } from "../../actions/ask_host.ts";
@@ -697,7 +698,7 @@ export function userRoutes(router: Router<Handler>): void {
697698 router.add("POST", `${BROWSE}/contribute`, async (ctx) => {
698699 const denied = requireAccount(ctx, { adminToken: true });
699700 if (denied) return denied;
700 const input = await body(ctx.request);
701 const input = await body(ctx.request, FILE_TEXT);
701702 const result = await contribute(ctx.app, ctx.auth.user, {
702703 originId: ctx.params.id!,
703704 fullName: `${ctx.params.owner!}/${ctx.params.name!}`,
src/http/mcp.ts +6 −1
@@ -27,6 +27,7 @@ import { running } from "../kernel/version.ts";
2727 import { bearerChallenge } from "./oauth.ts";
2828 import { BodyTooLarge, json } from "./respond.ts";
2929 import { bodyCapFor, readBounded } from "./limits.ts";
30 import { CONTROL_HINT, CONTROL_MESSAGE, dirtyJson, PATCH_TEXT } from "./parseable_request.ts";
3031 import { page, signInHref } from "../web/layout.ts";
3132 import { html } from "../web/html.ts";
3233 import type { Router } from "./router.ts";
@@ -681,7 +682,9 @@ function parseRpc(bytes: Uint8Array): unknown {
681682 * (-32601), and, for a stranger only, a tool it lacks (-32602; the issue does not name it, but a
682683 * call to a tool that does not exist cannot be helped by signing in). With a `challenge` the
683684 * -32700 and -32600 answer 401 and carry it; without, they answer 200 to a caller already let in.
684 * Undefined when the message is well formed and names something that exists.
685 * A control character in any string but a tool's `patch` or file `content` text is -32602 before
686 * any method runs, notification or call (#15364): the same gate `body()` keeps, said in
687 * JSON-RPC. Undefined when the message is well formed and names something that exists.
685688 */
686689 function rpcFault(value: unknown, challenge: Record<string, string> | undefined): Response | undefined {
687690 const fail = (code: number, message: string, id: unknown, status: number) =>
@@ -696,6 +699,8 @@ function rpcFault(value: unknown, challenge: Record<string, string> | undefined)
696699 const m = value as Record<string, unknown>;
697700 if (m["jsonrpc"] !== "2.0" || typeof m["method"] !== "string")
698701 return fail(-32600, "Invalid Request: not a JSON-RPC 2.0 request", m["id"], 401);
702 if (dirtyJson(m, PATCH_TEXT))
703 return fail(-32602, `Invalid params: ${CONTROL_MESSAGE("JSON field")}; ${CONTROL_HINT}`, m["id"], 200);
699704 if (m["id"] === undefined) return undefined;
700705 const method = m["method"];
701706 if (!RPC_METHODS.includes(method) && !method.startsWith("notifications/"))
src/http/offer_routes.ts +2 −1
@@ -17,6 +17,7 @@ import { canRead, getRepo } from "../core/repos.ts";
1717 import type { Handler } from "./context.ts";
1818 import { clientBucket } from "./peer.ts";
1919 import { apiError, boundedBody, json, notFound, str as bodyStr, tryAgain } from "./respond.ts";
20 import { PATCH_TEXT } from "./parseable_request.ts";
2021
2122 /** A full queue drains as people read offers; no clock says when, so a minute. */
2223 const QUEUE_RETRY = 60;
@@ -26,7 +27,7 @@ export const offerHandler: Handler = async (ctx) => {
2627 const found = getRepo(ctx.app.db, ctx.params.owner!, ctx.params.name!);
2728 const repo = found && canRead(ctx.app.db, found, ctx.auth.user) ? found : undefined;
2829 if (!repo) return notFound();
29 const input = await boundedBody(ctx.request, OFFER_REQUEST_MAX);
30 const input = await boundedBody(ctx.request, OFFER_REQUEST_MAX, PATCH_TEXT);
3031 if (input === "too_large") return apiError("patch_too_large", 422, OFFER_WORDS.patch_too_large);
3132 const filed = await fileOffer(
3233 ctx.app,
src/http/parseable_request.ts +108
@@ -1,3 +1,7 @@
1 import { apiError } from "./respond.ts";
2 import { leanPage } from "../web/lean_page.ts";
3 import { html } from "../web/html.ts";
4
15 /**
26 * A request whose URL cannot be parsed. The runtime builds `request.url`
37 * from the Host header, so a Host like `evil#x` yields a URL every later
@@ -36,3 +40,107 @@ export function answeringFor<S extends object>(server: S, rebuilt: Request, orig
3640 },
3741 });
3842 }
43
44 /*
45 * Control characters are refused at the edge (#15364). A NUL or another C0
46 * control (U+0000–U+0008, U+000B, U+000C, U+000E–U+001F) or DEL (U+007F) in
47 * a decoded path, query, form field or JSON string field gets a plain 400,
48 * never a page. Tab, newline and carriage return stay allowed: a multi-line
49 * field holds them. Only decoded strings are looked at. Raw bodies (git packs,
50 * uploads) are never read here.
51 */
52
53 /** Where the control character was: named in the refusal, the bytes never echoed. */
54 export type DirtyKind = "path" | "query string" | "form field" | "JSON field";
55
56 const CONTROL = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;
57 // A WHATWG URL percent-encodes every control in its path and query, and a
58 // single %0X, %1X or %7F byte is always that ASCII control: UTF-8 never encodes
59 // a wider character with one. So the encoded form is tested as it is, with no
60 // decoding.
61 const ENCODED_CONTROL = /%(?:0[0-8bc]|1[0-9a-f]|7f)/i;
62
63 /**
64 * Keys whose string value is a file's bytes or a diff, not a typed value: a
65 * form feed or an escape is part of a real text file, and the route judges
66 * it itself. A
67 * route names its own (`body(request, FILE_TEXT)`); no key is raw anywhere
68 * else, and an object or a list under one is looked at like any other.
69 */
70 export type RawText = ReadonlySet<string>;
71 export const NO_RAW_TEXT: RawText = new Set();
72 /** `files[].content` of an edit, a commit or a contribution. */
73 export const FILE_TEXT: RawText = new Set(["content"]);
74 /** An offer's or a pull's unified diff, and the files that may come with it. */
75 export const PATCH_TEXT: RawText = new Set(["patch", "content"]);
76
77 /** The part of a URL that holds a refused control character, if any. */
78 export function dirtyUrl(url: URL): DirtyKind | undefined {
79 if (ENCODED_CONTROL.test(url.pathname)) return "path";
80 if (url.search !== "" && ENCODED_CONTROL.test(url.search)) return "query string";
81 return undefined;
82 }
83
84 /**
85 * Whether any string inside a parsed JSON value, an object key included,
86 * holds one. Only a string value under a key in `raw` is not looked at.
87 */
88 export function dirtyJson(value: unknown, raw: RawText = NO_RAW_TEXT, depth = 0): boolean {
89 if (typeof value === "string") return CONTROL.test(value);
90 if (typeof value !== "object" || value === null || depth > 64) return false;
91 if (Array.isArray(value)) return value.some((v) => dirtyJson(v, raw, depth + 1));
92 for (const [key, v] of Object.entries(value)) {
93 if (CONTROL.test(key)) return true;
94 if (typeof v === "string" && raw.has(key)) continue;
95 if (dirtyJson(v, raw, depth + 1)) return true;
96 }
97 return false;
98 }
99
100 /**
101 * The one check every parsed JSON body goes through, `body()` and the routes
102 * that parse their own alike: throws `ControlInput`, which the server's door
103 * answers 400.
104 */
105 export function refuseDirtyJson<T>(value: T, raw: RawText = NO_RAW_TEXT): T {
106 if (dirtyJson(value, raw)) throw new ControlInput("JSON field");
107 return value;
108 }
109
110 /** Whether a submitted form's names or string values hold one. A file's bytes are never read. */
111 export function dirtyForm(form: { forEach(fn: (value: unknown, key: string) => void): void }): boolean {
112 let dirty = false;
113 form.forEach((value, key) => {
114 if (dirty) return;
115 if (CONTROL.test(key) || (typeof value === "string" && CONTROL.test(value))) dirty = true;
116 });
117 return dirty;
118 }
119
120 /** Thrown by a JSON body reader. The server's one door answers it with `controlRefusal`. */
121 export class ControlInput extends Error {
122 constructor(readonly kind: DirtyKind) {
123 super(`control character in ${kind}`);
124 }
125 }
126
127 export const CONTROL_MESSAGE = (kind: DirtyKind): string =>
128 `the ${kind} holds a control character (U+0000-U+001F or U+007F other than tab, newline and carriage return)`;
129 export const CONTROL_HINT = "remove the control character and send the request again";
130
131 /**
132 * The house 400. `/api` and `/mcp`, and anyone who ranks JSON above HTML, get
133 * `{error,message,hint}`. Anyone else gets a lean page that names the field
134 * kind.
135 */
136 export function controlRefusal(request: Request, pathname: string, kind: DirtyKind): Response {
137 const machine = pathname === "/api" || pathname.startsWith("/api/") || pathname === "/mcp" || pathname.startsWith("/mcp/");
138 const accept = request.headers.get("accept") ?? "";
139 const wantsJson = accept.includes("application/json") && !accept.includes("text/html");
140 if (machine || wantsJson || kind === "JSON field") return apiError("control_character", 400, CONTROL_MESSAGE(kind), CONTROL_HINT);
141 return leanPage(
142 "Bad request",
143 html`<h1>That request could not be read</h1><p class="muted">The ${kind} held a control character, which no page here accepts. Remove it and try again.</p><p><a href="/">Go home</a></p>`,
144 400,
145 );
146 }
src/http/respond.ts +8 −4
@@ -5,6 +5,7 @@
55 */
66
77 import { InvalidJson, objectOf } from "./json_body.ts";
8 import { NO_RAW_TEXT, refuseDirtyJson, type RawText } from "./parseable_request.ts";
89 import { bodyCapFor, readBounded } from "./limits.ts";
910 import { namesReader } from "./reader.ts";
1011 import { scopeAllows, type TokenScope } from "../core/tokens.ts";
@@ -482,12 +483,14 @@ export function respondAccess(error: string, status: number): Response {
482483 * \`STRANGER_MAX\` for anyone else (\`http/limits.ts\`) — a route reads its
483484 * body before it asks who is calling, so the cap cannot wait for that. Past
484485 * the cap it throws \`BodyTooLarge\` (answered 413) and the connection closes;
485 * malformed, it throws \`InvalidJson\` (answered 400 \`invalid_json\`).
486 * malformed, it throws \`InvalidJson\` (answered 400 \`invalid_json\`);
487 * a control character in a string throws \`ControlInput\` (400), except in a
488 * string under a key of \`raw\` (#15364).
486489 */
487 export async function body(request: Request): Promise<Record<string, unknown>> {
490 export async function body(request: Request, raw: RawText = NO_RAW_TEXT): Promise<Record<string, unknown>> {
488491 const bytes = await readBounded(request, bodyCapFor(request));
outdated

The JSON gate lives only in body() and boundedBody(). Routes that call JSON.parse on readBounded themselves (api/displays.ts, api/timers.ts, api/boards.ts) and /mcp are not covered, so box 1's gate before routing is not met for JSON. Cover them, or move the check to one shared parse.

489492 if (bytes === "too_large") throw new BodyTooLarge(bodyCapFor(request));
490 return objectOf(bytes);
493 return refuseDirtyJson(objectOf(bytes), raw);
491494 }
492495
493496 /**
@@ -524,9 +527,10 @@ export const bodyTooLarge = (error: BodyTooLarge): Response =>
524527 export async function boundedBody(
525528 request: Request,
526529 max: number,
530 raw: RawText = NO_RAW_TEXT,
527531 ): Promise<Record<string, unknown> | "too_large"> {
528532 const bytes = await readBounded(request, max);
529 return bytes === "too_large" ? "too_large" : objectOf(bytes);
533 return bytes === "too_large" ? "too_large" : refuseDirtyJson(objectOf(bytes), raw);
530534 }
531535
532536 export const str = (v: unknown): string => (typeof v === "string" ? v : "");
src/http/server.ts +6 −1
@@ -7,7 +7,7 @@
77
88 import { standingFragment } from "../web/pages/fork-standing.ts";
99 import { InvalidJson } from "./json_body.ts";
10 import { answeringFor, parseableRequest } from "./parseable_request.ts";
10 import { answeringFor, ControlInput, controlRefusal, dirtyUrl, parseableRequest } from "./parseable_request.ts";
1111 import { expireCookie } from "../auth/cookies.ts";
1212 import { checkText } from "./check_text.ts";
1313 import { noteOwnWrite } from "../flow/keep.ts";
@@ -2651,6 +2651,8 @@ export interface Servers {
26512651 function failure(app: App, error: unknown, request?: Request): Response {
26522652 if (error instanceof BodyTooLarge) return securityFloor(bodyTooLarge(error));
26532653 if (error instanceof InvalidJson) return securityFloor(invalidJson(error));
2654 if (error instanceof ControlInput && request !== undefined)
2655 return securityFloor(controlRefusal(request, new URL(request.url).pathname, error.kind));
26542656 if (isFullError(error)) {
26552657 if (noteFull(app.config.dataDir)) {
26562658 app.log.error("disk full: forge is read-only until space returns", { error: String(error) });
@@ -3379,6 +3381,9 @@ async function answer(
33793381 request: Request,
33803382 ): Promise<Response> {
33813383 const url = publicUrl(request, app.config.url);
3384 // A control character in the path or query is a plain 400 before any route (#15364).
3385 const dirty = dirtyUrl(url);
3386 if (dirty !== undefined) return controlRefusal(request, url.pathname, dirty);
33823387 // A doubled slash is the same page, not a second copy (#14374): GET and HEAD
33833388 // answer 308 to the path with each run of slashes collapsed, query kept. The
33843389 // Location is a path, never an origin, and starts with exactly one slash, so
src/web/form.ts +6 −1
@@ -14,6 +14,7 @@ import { scopeAllows, type TokenScope } from "../core/tokens.ts";
1414 import { isLocalPath } from "./flash.ts";
1515 import type { FieldOptions } from "./ui.ts";
1616 import { crossOrigin, type Ctx } from "../http/context.ts";
17 import { controlRefusal, dirtyForm } from "../http/parseable_request.ts";
1718
1819 export type Form = Awaited<ReturnType<Request["formData"]>>;
1920
@@ -46,13 +47,17 @@ export async function readForm(
4647 // at all — is an empty form, not a malformed one.
4748 if (type === null || bytes.byteLength === 0)
4849 return new FormData() as unknown as Form;
50 let form: Form;
4951 try {
50 return await new Response(bytes, {
52 form = await new Response(bytes, {
5153 headers: { "content-type": type },
5254 }).formData();
5355 } catch {
5456 return new Response("bad request", { status: 400 });
5557 }
58 // A name or string value with a control character in it is a plain 400 (#15364). Tab,
59 // newline and carriage return stay allowed. A file's bytes are never looked at.
60 return dirtyForm(form) ? controlRefusal(ctx.request, ctx.url.pathname, "form field") : form;
5661 }
5762
5863 /** A form field as a trimmed string, or "" when absent or a file. */
test/clean-input.test.ts added +224
@@ -0,0 +1,224 @@
1 // A control character in a path, query, form field or JSON field is a plain 400 at the edge
2 // (#15364).
3 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { createRepo } from "../src/actions/repos.ts";
9 import { createApp as insertApp } from "../src/core/apps.ts";
10 import { listIssues } from "../src/core/issues.ts";
11 import type { Repo } from "../src/core/repos.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { createToken } from "../src/core/tokens.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { dirtyForm, dirtyJson, dirtyUrl, FILE_TEXT, PATCH_TEXT } from "../src/http/parseable_request.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { promote } from "./helpers/members.ts";
18
19 const FLOOR = ["content-security-policy", "x-content-type-options", "referrer-policy"];
20
21 test("the refused set is C0 but tab, newline and carriage return, plus DEL", () => {
22 for (let c = 0; c < 0x20; c++) expect(dirtyJson({ a: String.fromCharCode(c) })).toBe(c !== 9 && c !== 10 && c !== 13);
23 expect(dirtyJson({ a: "\u007f" })).toBe(true);
24 expect(dirtyJson({ a: "plain words, é and 🌱" })).toBe(false);
25 // A file's text or a diff may hold a form feed or an escape, on the routes that name it raw.
26 expect(dirtyJson({ files: [{ path: "COPYING", content: "a\fb\u001b" }], patch: "\f" }, PATCH_TEXT)).toBe(false);
27 expect(dirtyJson({ files: [{ path: "a\u0000b", content: "x" }] }, FILE_TEXT)).toBe(true);
28 // No key is raw on a route that does not say so.
29 expect(dirtyJson({ content: "\f" })).toBe(true);
30 expect(dirtyJson({ patch: "\f" }, FILE_TEXT)).toBe(true);
31 // Only a string under a raw key is skipped: an object or a list under it is looked at.
32 expect(dirtyJson({ content: { x: "\u0000" } }, FILE_TEXT)).toBe(true);
33 expect(dirtyJson({ patch: ["\u0000"] }, PATCH_TEXT)).toBe(true);
34 expect(dirtyJson({ files: [{ path: "a", content: [{ y: "\u0001" }] }] }, FILE_TEXT)).toBe(true);
35 expect(dirtyUrl(new URL("http://x/a%00b"))).toBe("path");
36 expect(dirtyUrl(new URL("http://x/?q=%01"))).toBe("query string");
37 expect(dirtyUrl(new URL("http://x/?%7F=1"))).toBe("query string");
38 // An escaped percent is the text "%00", not a NUL; a newline in a query is allowed.
39 expect(dirtyUrl(new URL("http://x/a%2500?q=a%0Ab%09%0D"))).toBeUndefined();
40 expect(dirtyJson({ a: [{ b: "x\u0000" }] })).toBe(true);
41 expect(dirtyJson({ "k\u0001": 1 })).toBe(true);
42 expect(dirtyJson({ a: "line\nline\ttab" })).toBe(false);
43 const form = new FormData();
44 form.set("text", "one\r\ntwo");
45 expect(dirtyForm(form)).toBe(false);
46 form.set("t", "a\u000bb");
47 expect(dirtyForm(form)).toBe(true);
48 });
49
50 test("the URL check costs under 0.1 ms on a clean request", () => {
51 const url = new URL("http://x/alice/garden/issues?state=open&q=rain+gauge&page=2");
52 const n = 10_000;
53 const start = performance.now();
54 for (let i = 0; i < n; i++) dirtyUrl(url);
55 expect((performance.now() - start) / n).toBeLessThan(0.1);
56 });
57
58 describe("the edge refuses control characters", () => {
59 let dataDir: string;
60 let app: App;
61 let servers: Servers;
62 let cookie: string;
63 let token: string;
64 let adminToken: string;
65 let garden: Repo;
66
67 beforeAll(async () => {
68 dataDir = await mkdtemp(join(tmpdir(), "forge-clean-input-"));
69 app = createApp({ dataDir, port: 0 });
70 servers = await serve(app);
71 const r = await createUser(app.db, {
72 origin: "seed",
73 trusted: true,
74 username: "alice",
75 email: "[email protected]",
76 password: "a-good-passphrase",
77 adminIfFirst: true,
78 });
79 if (!r.ok) throw new Error(r.error);
80 promote(app.db, r.value);
81 cookie = `forge_session=${createSession(app.db, r.value.id).token}`;
82 token = createToken(app.db, r.value.id, "rw", "rw").token;
83 adminToken = createToken(app.db, r.value.id, "admin", "admin").token;
84 const g = await createRepo(app, r.value, { name: "garden", visibility: "public" });
85 if (!g.ok) throw new Error("repo");
86 garden = g.value;
87 insertApp(app.db, { repoId: garden.id, slug: "garden", access: "public" });
88 });
89
90 afterAll(async () => {
91 servers.stop();
92 await rm(dataDir, { recursive: true, force: true });
93 });
94
95 const floored = (res: Response) => {
96 for (const h of FLOOR) expect(res.headers.get(h)).not.toBeNull();
97 };
98
99 test("a page with a NUL in its query is a 400 page that names the field kind and echoes nothing", async () => {
100 for (const path of ["/?q=%00", "/explore?q=%00", "/search?q=a%00b", "/apps?q=%01", "/changelog?x=%00"]) {
101 const res = await fetch(`${servers.url}${path}`, { headers: { accept: "text/html" }, redirect: "manual" });
102 expect(res.status).toBe(400);
103 expect(res.headers.get("content-type")).toContain("text/html");
104 floored(res);
105 const text = await res.text();
106 expect(text).toContain("query string");
107 expect(text).not.toContain("\u0000");
108 expect(text).not.toContain("%00");
109 }
110 const path = await fetch(`${servers.url}/alice%00/garden`, { headers: { accept: "text/html" } });
111 expect(path.status).toBe(400);
112 expect(await path.text()).toContain("path");
113 // The same page, clean, still answers.
114 expect((await fetch(`${servers.url}/explore?q=rain`)).status).toBe(200);
115 });
116
117 test("an API list and /mcp answer the JSON envelope", async () => {
118 const res = await fetch(`${servers.url}/api/v1/repos?q=%00`, { headers: { accept: "text/html" } });
119 expect(res.status).toBe(400);
120 floored(res);
121 const body = (await res.json()) as Record<string, string>;
122 expect(body.error).toBe("control_character");
123 expect(body.message).toContain("query string");
124 expect(typeof body.hint).toBe("string");
125 const mcp = await fetch(`${servers.url}/mcp?x=%1f`, { method: "POST", body: "{}" });
126 expect(mcp.status).toBe(400);
127 expect(((await mcp.json()) as { error: string }).error).toBe("control_character");
128 });
129
130 test("a JSON field with a control character is refused, and nothing is written", async () => {
131 const before = listIssues(app.db, garden.id, { state: "open" }).length;
132 const res = await fetch(`${servers.url}/api/v1/repos/alice/garden/issues`, {
133 method: "POST",
134 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
135 body: JSON.stringify({ title: "rain\u0000gauge" }),
136 });
137 expect(res.status).toBe(400);
138 floored(res);
139 const body = (await res.json()) as Record<string, string>;
140 expect(body.error).toBe("control_character");
141 expect(body.message).toContain("JSON field");
142 expect(listIssues(app.db, garden.id, { state: "open" }).length).toBe(before);
143 });
144
145 test("a form POST with a control character is refused; a tell with newlines still posts", async () => {
146 const before = listIssues(app.db, garden.id, { state: "open" }).length;
147 const refused = await fetch(`${servers.url}/tell`, {
148 method: "POST",
149 headers: { cookie, origin: servers.url },
150 body: new URLSearchParams({ app: "alice/garden", text: "Add a\u0007 rain gauge" }),
151 redirect: "manual",
152 });
153 expect(refused.status).toBe(400);
154 floored(refused);
155 expect(await refused.text()).toContain("form field");
156 expect(listIssues(app.db, garden.id, { state: "open" }).length).toBe(before);
157 const posted = await fetch(`${servers.url}/tell`, {
158 method: "POST",
159 headers: { cookie, origin: servers.url },
160 body: new URLSearchParams({ app: "alice/garden", text: "Add a rain gauge\r\n\twith a\nsecond line" }),
161 redirect: "manual",
162 });
163 expect(posted.status).toBe(303);
164 expect(listIssues(app.db, garden.id, { state: "open" }).length).toBe(before + 1);
165 });
166
167 test("routes that parse their own JSON are gated too: timers, boards, displays and /mcp (in JSON-RPC)", async () => {
168 const auth = { authorization: `Bearer ${token}`, "content-type": "application/json" };
169 const timer = await fetch(`${servers.url}/api/v1/timers`, {
170 method: "POST",
171 headers: auth,
172 body: JSON.stringify({ key: "k", in: 60, body: "ring\u0000" }),
173 });
174 expect(timer.status).toBe(400);
175 floored(timer);
176 expect(((await timer.json()) as { error: string }).error).toBe("control_character");
177 const admin = { authorization: `Bearer ${adminToken}`, "content-type": "application/json" };
178 for (const [method, path, headers] of [
179 ["POST", "/api/v1/boards/query", admin],
180 ["POST", "/api/v1/boards/pins", admin],
181 ["PUT", "/api/v1/boards/rain", admin],
182 ["PUT", "/api/v1/repos/alice/garden/display/builds", auth],
183 ] as const) {
184 const res = await fetch(`${servers.url}${path}`, { method, headers, body: JSON.stringify({ title: "a\u0001" }) });
185 expect([path, res.status]).toEqual([path, 400]);
186 expect(((await res.json()) as { error: string }).error).toBe("control_character");
187 }
188 const rpc = (args: Record<string, unknown>) =>
189 fetch(`${servers.url}/mcp`, {
190 method: "POST",
191 headers: { ...auth, accept: "application/json, text/event-stream" },
192 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "offer", arguments: args } }),
193 });
194 // /mcp says it in JSON-RPC, so a client reads it as an answer to its call.
195 const code = async (res: Response) => ((await res.json()) as { error?: { code: number; message: string } }).error;
196 const dirty = await rpc({ repo: "alice/garden", title: "rain\u0000gauge" });
197 expect(dirty.status).toBe(200);
198 floored(dirty);
199 const said = await code(dirty);
200 expect(said?.code).toBe(-32602);
201 expect(said?.message).toContain("control character");
202 // A list under `patch` is looked at; a diff's own text is the tool's to judge.
203 expect((await code(await rpc({ repo: "alice/garden", patch: ["\u0000"] })))?.code).toBe(-32602);
204 expect((await code(await rpc({ repo: "alice/garden", title: "t", patch: "a\fb" })))?.code).not.toBe(-32602);
205 });
206
207 test("an edit's file text may hold a form feed; an object under `content` may not", async () => {
208 const post = (files: unknown) =>
209 fetch(`${servers.url}/api/v1/repos/alice/garden/contents`, {
210 method: "POST",
211 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
212 body: JSON.stringify({ branch: "main", message: "add", files }),
213 });
214 expect((await post([{ path: "a.txt", content: { x: "\u0000" } }])).status).toBe(400);
215 expect((await post([{ path: "COPYING", content: "page one\fpage two\n" }])).status).not.toBe(400);
216 // A key that is raw on one route is not raw on another.
217 const issue = await fetch(`${servers.url}/api/v1/repos/alice/garden/issues`, {
218 method: "POST",
219 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
220 body: JSON.stringify({ title: "t", content: "\f" }),
221 });
222 expect(issue.status).toBe(400);
223 });
224 });
test/crew-key.test.ts +4 −1
@@ -77,7 +77,10 @@ describe("adding the crew's key", () => {
7777 expect(keyShapeOk("sk-ant-api03-ab\u0000cd")).toBe(false);
7878 expect(keyShapeOk("é".repeat(KEY_MAX_BYTES / 2 + 1))).toBe(false);
7979 expect(keyShapeOk(GOOD)).toBe(true);
80 const res = await post(admin, `sk-ant-api03-ab\u0007cd`);
80 // A C0 control is refused at the edge (#15364); a newline reaches the shape check.
81 expect((await post(admin, `sk-ant-api03-ab\u0007cd`)).status).toBe(400);
82 expect(listSubscriptions(app.db)).toEqual([]);
83 const res = await post(admin, `sk-ant-api03-ab\ncd`);
8184 expect(res.status).toBe(303);
8285 expect(listSubscriptions(app.db)).toEqual([]);
8386 const flashed = await (await fetch(`${servers.url}/`, { headers: { cookie: `${admin}; ${(res.headers.getSetCookie()[0] ?? "").split(";")[0]}` } })).text();
test/disk-intake.test.ts +6 −3
@@ -128,11 +128,14 @@ test("the Disks screen is the owner's door, and says what the API stored", () =>
128128 expect(lines[1]).toContain("0.00 TB");
129129 });
130130
131 test("a cpu with a control character is refused; model and firmware reach the terminal without theirs", async () => {
132 expect((await put(admin, "rack4", { smartctl: smart(1), cpu: "EPYC\u001b]0;pwned\u0007", memoryBytes: 1 })).status).toBe(422);
131 test("a cpu with a control character is refused (C0 at the edge); model and firmware reach the terminal without theirs", async () => {
132 expect((await put(admin, "rack4", { smartctl: smart(1), cpu: "EPYC\u001b]0;pwned\u0007", memoryBytes: 1 })).status).toBe(400);
133133 expect((await put(admin, "rack4", { smartctl: smart(1), cpu: "EPYC\u009b2J", memoryBytes: 1 })).status).toBe(422);
134134 const evil = { ...smart(1), model_name: "Samsung\u001b[2J SSD", firmware_version: "5B2\u001b]52;c;eA==\u0007QGXA7" };
135 expect((await put(admin, "rack4", { smartctl: evil })).status).toBe(201);
135 // As an object its strings are looked at like any other (#15364); as smartctl's own JSON
136 // text the escapes are `\u001b`, not the byte, and the route strips them itself.
137 expect((await put(admin, "rack4", { smartctl: evil })).status).toBe(400);
138 expect((await put(admin, "rack4", { smartctl: JSON.stringify(evil) })).status).toBe(201);
136139 const lines = diskLines(diskSummary(app.db, "rack4"));
137140 expect(lines.join("\n")).not.toMatch(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/);
138141 expect(lines[1]).toContain("Samsung[2J SSD 5B2]52;c;eA==QGXA7");
test/drop.test.ts +3 −1
@@ -198,7 +198,9 @@ describe("the drop", () => {
198198 });
199199
200200 test("names are checked at the boundary and the folder holds at most FILES_MAX", async () => {
201 for (const bad of ["../x", "a/b", ".hidden", "", "x".repeat(101), "a\u0000b"]) expect((await put("paper", bad, "x")).status).toBe(422);
201 for (const bad of ["../x", "a/b", ".hidden", "", "x".repeat(101)]) expect((await put("paper", bad, "x")).status).toBe(422);
202 // A NUL in the name is refused at the edge, before the route (#15364).
203 expect((await put("paper", "a\u0000b", "x")).status).toBe(400);
202204 expect((await put("paper", "empty.txt", "")).status).toBe(422);
203205 expect(FILES_MAX).toBe(500);
204206 });
test/edits-security.test.ts +3 −1
@@ -196,7 +196,6 @@ describe("edits: refusals that must leave nothing behind", () => {
196196 ["a//b", "invalid_path"],
197197 ["a/", "invalid_path"],
198198 ["/abs", "invalid_path"],
199 ["a\u0000b", "invalid_path"],
200199 ["a\nb", "invalid_path"],
201200 [".git/config", "invalid_path"],
202201 ["sub/.GIT/hooks/pre-receive", "invalid_path"],
@@ -208,6 +207,9 @@ describe("edits: refusals that must leave nothing behind", () => {
208207 expect([path, r.status]).toEqual([path, 422]);
209208 expect([path, r.body.error]).toEqual([path, code]);
210209 }
210 // A NUL in a path is refused at the edge (#15364), before any object.
211 const nul = await edit({ files: [{ path: "a\u0000b", content: "pwned" }] });
212 expect([nul.status, nul.body.error]).toEqual([400, "control_character"]);
211213 expect(await objects()).toBe(before);
212214 expect(await refs()).not.toContain("refs/heads/stray");
213215 });
test/explore-pages-web.test.ts +3 −1
@@ -82,11 +82,13 @@ test("walking Next reads every row once; filters survive Next and Previous", asy
8282 test("a junk page shows the first, an out-of-range page the last, never an error", async () => {
8383 const first = await get("/explore?kind=app&owner=olive&sort=name");
8484 expect(first.html).toContain("Page 1 of 2");
85 for (const bad of ["abc", "0", "-3", "1.5", "%00", "9".repeat(5000), ""]) {
85 for (const bad of ["abc", "0", "-3", "1.5", "9".repeat(5000), ""]) {
8686 const res = await get(`/explore?kind=app&owner=olive&sort=name&page=${bad}`);
8787 expect(res.status).toBe(200);
8888 expect(rows(res.html)).toEqual(rows(first.html));
8989 }
90 // A NUL is the one page the edge refuses outright (#15364).
91 expect((await get("/explore?kind=app&owner=olive&sort=name&page=%00")).status).toBe(400);
9092 const last = await get("/explore?kind=app&owner=olive&sort=name&page=999");
9193 expect(last.status).toBe(200);
9294 expect(last.html).toContain("Page 2 of 2");
test/feed-share.test.ts +3 −1
@@ -106,7 +106,9 @@ describe("share note", () => {
106106 body: JSON.stringify(payload),
107107 });
108108 const item = emit();
109 for (const note of ["a".repeat(NOTE_MAX + 1), " ", "x\u0000y"]) {
109 // A NUL is refused at the edge before the route (#15364), still a 400.
110 expect((await post({ item, to: ["bob"], note: "x\u0000y" })).status).toBe(400);
111 for (const note of ["a".repeat(NOTE_MAX + 1), " "]) {
110112 const r = await post({ item, to: ["bob"], note });
111113 expect(r.status).toBe(400);
112114 expect(await r.text()).toContain("280");
test/keeper-heartbeat.test.ts +2 −2
@@ -81,8 +81,8 @@ describe("release heartbeat", () => {
8181 expect(lastBeat(app.db)).toEqual(before);
8282 });
8383
84 test("a reason carrying a control character is a 422", async () => {
85 expect((await post(admin, { outcome: "failed", reason: "red\u001b[2Jwiped" })).status).toBe(422);
84 test("a reason carrying a control character is refused: 400 at the edge for a C0, 422 for a newline", async () => {
85 expect((await post(admin, { outcome: "failed", reason: "red\u001b[2Jwiped" })).status).toBe(400);
8686 expect((await post(admin, { outcome: "failed", reason: "two\nlines" })).status).toBe(422);
8787 });
8888
test/parity.test.ts +5 −5
@@ -965,22 +965,22 @@ describe("parity: full control through actions and the API", () => {
965965 expect(res.json.error).toBe("invalid_cursor");
966966 }
967967
968 // A name with a control character pages on: its own cursor is accepted.
968 // A name with a tab in it pages on: its own cursor is accepted.
969969 const odd = await call("POST", "/api/v1/orgs/paging/teams", {
970970 token: aliceAdmin,
971 body: { name: "a\u0001b", permission: "read" },
971 body: { name: "a\tb", permission: "read" },
972972 });
973973 expect(odd.status).toBe(201);
974974 {
975975 const list = await call("GET", "/api/v1/orgs/paging/teams", { token: aliceAdmin });
976 const at = (list.json.items as Json[]).findIndex((t) => t.name === "a\u0001b");
976 const at = (list.json.items as Json[]).findIndex((t) => t.name === "a\tb");
977977 const page = await call("GET", `/api/v1/orgs/paging/teams?limit=${at + 1}`, {
978978 token: aliceAdmin,
979979 });
980 expect(page.json.next_cursor).toBe("a\u0001b");
980 expect(page.json.next_cursor).toBe("a\tb");
981981 const next = await call(
982982 "GET",
983 `/api/v1/orgs/paging/teams?cursor=${encodeURIComponent("a\u0001b")}`,
983 `/api/v1/orgs/paging/teams?cursor=${encodeURIComponent("a\tb")}`,
984984 { token: aliceAdmin },
985985 );
986986 expect(next.status).toBe(200);
test/redirect-targets.test.ts +15 −5
@@ -35,6 +35,9 @@ const HOSTILE = [
3535 "evil.example",
3636 ];
3737
38 // A NUL never reaches a door: the edge answers 400 first (#15364), proved below.
39 const AT_DOORS = HOSTILE.filter((h) => !h.includes("\u0000"));
40
3841 /** Deep links that must keep working, query string and all. */
3942 const GOOD = ["/kim/proj/issues?state=open&q=a%20b", "/settings/keys", "/oauth/authorize?client_id=c&state=s"];
4043
@@ -74,8 +77,15 @@ describe("every door that reads a return address", () => {
7477 redirect: "manual",
7578 });
7679
80 test("a next holding a NUL is a 400 at the edge on every door", async () => {
81 const nul = "/\u0000/evil.example";
82 expect((await signIn(nul)).status).toBe(400);
83 expect((await get(`/login?${q(nul)}`)).status).toBe(400);
84 expect((await get(`/signin?${q(nul)}`)).status).toBe(400);
85 });
86
7787 test("POST /signin lands a hostile next on / and a deep link on itself", async () => {
78 for (const bad of HOSTILE) {
88 for (const bad of AT_DOORS) {
7989 const res = await signIn(bad);
8090 expect([bad, res.status, res.headers.get("location")]).toEqual([bad, 303, "/"]);
8191 }
@@ -84,14 +94,14 @@ describe("every door that reads a return address", () => {
8494
8595 test("/login and /sign-in drop a hostile next and keep a deep link", async () => {
8696 for (const alias of ["/login", "/sign-in"]) {
87 for (const bad of HOSTILE) expect([bad, (await get(`${alias}?${q(bad)}`)).headers.get("location")]).toEqual([bad, "/signin"]);
97 for (const bad of AT_DOORS) expect([bad, (await get(`${alias}?${q(bad)}`)).headers.get("location")]).toEqual([bad, "/signin"]);
8898 for (const good of GOOD) expect((await get(`${alias}?${q(good)}`)).headers.get("location")).toBe(`/signin?${q(good)}`);
8999 }
90100 });
91101
92102 test("the sign-in and sign-up forms carry no hostile next anywhere on the page", async () => {
93103 for (const door of ["/signin", "/signup"]) {
94 for (const bad of HOSTILE) {
104 for (const bad of AT_DOORS) {
95105 const body = await (await get(`${door}?${q(bad)}`)).text();
96106 expect([door, bad, body.includes("evil.example")]).toEqual([door, bad, false]);
97107 }
@@ -101,7 +111,7 @@ describe("every door that reads a return address", () => {
101111 });
102112
103113 test("the OAuth consent page sends a signed-out person to sign in and back to itself only", async () => {
104 for (const bad of HOSTILE) {
114 for (const bad of AT_DOORS) {
105115 const res = await get(`/oauth/authorize?client_id=nobody&response_type=code&${new URLSearchParams({ redirect_uri: bad, next: bad })}`);
106116 const location = res.headers.get("location") ?? "";
107117 expect([bad, location.startsWith("/signin?next=%2Foauth%2Fauthorize")]).toEqual([bad, true]);
@@ -110,7 +120,7 @@ describe("every door that reads a return address", () => {
110120 });
111121
112122 test("the everyday-account switch sends a signed-out person to sign in, never off-site", async () => {
113 for (const bad of HOSTILE) {
123 for (const bad of AT_DOORS) {
114124 const res = await fetch(`${base}/settings/everyday/switch?${q(bad)}`, { method: "POST", headers: { origin: base }, redirect: "manual" });
115125 const location = res.headers.get("location") ?? "";
116126 expect([bad, location.startsWith("/signin?next=%2Fsettings%2Feveryday%2Fswitch")]).toEqual([bad, true]);
test/reports.test.ts +6 −2
@@ -154,9 +154,13 @@ describe("reports from outside", () => {
154154 });
155155
156156 test("control and direction-override characters never reach the stored text", async () => {
157 // A C0 control is refused whole at the edge (#15364); nothing is stored.
158 const before = count("report");
159 expect((await report("alice/game", { title: "bad\u0000title", body: "x" })).status).toBe(400);
160 expect(count("report")).toBe(before);
157161 const res = await report("alice/game", {
158 title: "bad\u0000 ‮title",
159 body: "line\u0007 one\nline two⁦",
162 title: "bad ‮title",
163 body: "line one\nline two⁦",
160164 page: "javascript:alert(1)",
161165 });
162166 expect(res.status).toBe(202);
test/search.test.ts +1 −1
@@ -391,7 +391,7 @@ describe("search: one query, four sources", () => {
391391 });
392392
393393 test("an empty or whitespace query costs nothing and finds nothing", async () => {
394 for (const q of ["", "%20%20", "%00"]) {
394 for (const q of ["", "%20%20"]) {
395395 const results = await find(`q=${q}`);
396396 expect(results.note).toContain("q is empty");
397397 expect({ ...results, note: undefined }).toEqual({
test/thoughts.test.ts +1 −1
@@ -54,7 +54,7 @@ describe("thoughts", () => {
5454 .get(id);
5555
5656 test("text comes back byte for byte", async () => {
57 for (const text of [" padded \t\n", "line one\r\nline two\n\n", "héllo 🌍 wide \u0000 é", "<b>&amp;</b>"]) {
57 for (const text of [" padded \t\n", "line one\r\nline two\n\n", "héllo 🌍 wide é", "<b>&amp;</b>"]) {
5858 const res = await post(text);
5959 expect(res.status).toBe(201);
6060 const { id } = (await res.json()) as { id: string };
test/username-refusals.test.ts +11 −1
@@ -17,7 +17,6 @@ const UNSAFE: [string, string][] = [
1717 ["dot-dot", ".."],
1818 ["a slash", "a/b"],
1919 ["markup", "<b>"],
20 ["a NUL", "al\u0000ice"],
2120 ["200 characters", "a".repeat(200)],
2221 ];
2322 const RESERVED = ["settings", "api"];
@@ -79,6 +78,17 @@ describe("username refusals at sign-up", () => {
7978 });
8079 }
8180
81 test("a NUL is refused at the edge on both doors and makes no user (#15364)", async () => {
82 const before = users();
83 const viaApi = await api("al\u0000ice");
84 expect(viaApi.status).toBe(400);
85 expect(((await viaApi.json()) as { error: string }).error).toBe("control_character");
86 const viaPage = await form("al\u0000ice");
87 expect(viaPage.status).toBe(400);
88 expect(viaPage.headers.get("set-cookie")).toBeNull();
89 expect(users()).toBe(before);
90 });
91
8292 for (const name of RESERVED) {
8393 test(`the API refuses the reserved word ${name} and makes no user`, async () => {
8494 const before = users();
test/web-apps.test.ts +3 −1
@@ -218,7 +218,9 @@ describe("apps, runs and the crew on the web", () => {
218218 expect(escaped).not.toContain("<img src=x");
219219 expect(escaped).toContain("&lt;script&gt;alert(1)");
220220
221 for (const bad of ["x".repeat(MAX_STARTER_LENGTH + 1), "a\u0000b", " "]) {
221 // A NUL never reaches the page: the edge answers 400 (#15364).
222 expect((await web(alice, `/apps/new?description=${encodeURIComponent("a\u0000b")}`)).status).toBe(400);
223 for (const bad of ["x".repeat(MAX_STARTER_LENGTH + 1), " "]) {
222224 const ignored = await (
223225 await web(alice, `/apps/new?description=${encodeURIComponent(bad)}`)
224226 ).text();
test/web-ui.test.ts +2 −1
@@ -484,10 +484,11 @@ describe("web ui", () => {
484484 "--upload-pack=touch",
485485 "..%2F..%2Fetc",
486486 "main..other",
487 "%00main",
488487 ]) {
489488 expect((await fetch(`${base}/mel/proj/tree/${bad}`)).status).toBe(404);
490489 }
490 // A NUL is refused at the edge before the route reads it (#15364).
491 expect((await fetch(`${base}/mel/proj/tree/%00main`)).status).toBe(400);
491492 // The commits page falls back to the default branch instead of passing a
492493 // hostile ?ref= to git.
493494 const commits = await fetch(`${base}/mel/proj/commits?ref=--output%3Dx`);

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs