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
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15364-a-nul-or-control-character-in-any-query → main 0 commits fork 2 threads · 2 unresolved
27 files
changed +442
−39
src/http/api.ts +4 −3
| @@ -44,6 +44,7 @@ import { recordDrill } from "../core/domain_drills.ts"; | ||
| 44 | 44 | import { drillVerdict } from "../kernel/domain_drill.ts"; |
| 45 | 45 | import { DOMAINS } from "../kernel/domains.ts"; |
| 46 | 46 | import { BODY_CAPS, readBounded } from "./limits.ts"; |
| 47 | import { FILE_TEXT } from "./parseable_request.ts"; | |
| 47 | 48 | import { askCheck, askedWords } from "../checks/again.ts"; |
| 48 | 49 | import { nextUp, queueJson } from "../core/next_up.ts"; |
| 49 | 50 | import { notStartable } from "../crew/not_startable.ts"; |
| @@ -2219,7 +2220,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 2219 | 2220 | if (denied) return denied; |
| 2220 | 2221 | const repo = loadRepo(ctx); |
| 2221 | 2222 | if (!repo) return notFound(); |
| 2222 | const input = await body(ctx.request); | |
| 2223 | const input = await body(ctx.request, FILE_TEXT); | |
| 2223 | 2224 | const rawFiles = Array.isArray(input.files) ? input.files : []; |
| 2224 | 2225 | const files = rawFiles |
| 2225 | 2226 | .filter( |
| @@ -2255,7 +2256,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 2255 | 2256 | if (denied) return denied; |
| 2256 | 2257 | const repo = loadRepo(ctx); |
| 2257 | 2258 | if (!repo) return notFound(); |
| 2258 | const input = await body(ctx.request); | |
| 2259 | const input = await body(ctx.request, FILE_TEXT); | |
| 2259 | 2260 | |
| 2260 | 2261 | const files = (Array.isArray(input.files) ? input.files : []) |
| 2261 | 2262 | .filter( |
| @@ -3537,7 +3538,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo | ||
| 3537 | 3538 | // repo the caller may not be able to see anyway. |
| 3538 | 3539 | const link = originForRepo(ctx.app.db, repo.id); |
| 3539 | 3540 | if (!link) return notFound(); |
| 3540 | const input = await body(ctx.request); | |
| 3541 | const input = await body(ctx.request, FILE_TEXT); | |
| 3541 | 3542 | const result = await contribute(ctx.app, ctx.auth.user, { |
| 3542 | 3543 | originId: link.origin.id, |
| 3543 | 3544 | // 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"; | ||
| 18 | 18 | import type { Handler } from "../context.ts"; |
| 19 | 19 | import { holds, weakEtag } from "../etag.ts"; |
| 20 | 20 | import { bodyCapFor, readBounded } from "../limits.ts"; |
| 21 | import { refuseDirtyJson } from "../parseable_request.ts"; | |
| 21 | 22 | import { apiError, json, notFound, requireAccount } from "../respond.ts"; |
| 22 | 23 | import type { Router } from "../router.ts"; |
| 23 | 24 | |
| @@ -60,6 +61,7 @@ export function boardRoutes(router: Router<Handler>): void { | ||
| 60 | 61 | } catch { |
| 61 | 62 | return apiError("bad_json", 400, "the body must be a JSON query object"); |
| 62 | 63 | } |
| 64 | refuseDirtyJson(query); | |
| 63 | 65 | const answer = runQuery(ctx.app.db, query, { repoIds: "all" }); |
| 64 | 66 | return answer.ok |
| 65 | 67 | ? json({ rows: answer.rows }) |
| @@ -107,6 +109,7 @@ export function boardRoutes(router: Router<Handler>): void { | ||
| 107 | 109 | } catch { |
| 108 | 110 | return apiError("bad_json", 400, "the body must be a JSON object"); |
| 109 | 111 | } |
| 112 | refuseDirtyJson(input); | |
| 110 | 113 | const { op, slug, title, by } = input; |
| 111 | 114 | const done = |
| 112 | 115 | op === "pin" ? await pinPanel(ctx.app, ctx.auth.user, slug, title) |
| @@ -176,6 +179,7 @@ export function boardRoutes(router: Router<Handler>): void { | ||
| 176 | 179 | } catch { |
| 177 | 180 | return apiError("bad_json", 400, "the body must be a JSON board"); |
| 178 | 181 | } |
| 182 | refuseDirtyJson(input); | |
| 179 | 183 | const done = await writeBoard(ctx.app, ctx.auth.user, ctx.params.slug!, input); |
| 180 | 184 | return done.ok ? json({ slug: ctx.params.slug, ...done.value }) : boardFailed(done.error); |
| 181 | 185 | }); |
src/http/api/displays.ts +2
| @@ -7,6 +7,7 @@ import { chooseBuilds, parseChoice } from "../../actions/displays.ts"; | ||
| 7 | 7 | import type { Handler } from "../context.ts"; |
| 8 | 8 | import { loadRepo } from "../api.ts"; |
| 9 | 9 | import { bodyCapFor, readBounded } from "../limits.ts"; |
| 10 | import { refuseDirtyJson } from "../parseable_request.ts"; | |
| 10 | 11 | import { apiError, forbidden, json, notFound, requireScope } from "../respond.ts"; |
| 11 | 12 | import type { Router } from "../router.ts"; |
| 12 | 13 | |
| @@ -25,6 +26,7 @@ export function displayRoutes(router: Router<Handler>): void { | ||
| 25 | 26 | } catch { |
| 26 | 27 | return apiError("bad_json", 400, "the body must be JSON: { \"builds\": [\"owner/name:label\"] }"); |
| 27 | 28 | } |
| 29 | refuseDirtyJson(input); | |
| 28 | 30 | const choice = parseChoice(input); |
| 29 | 31 | if (!choice.ok) return apiError("invalid", 422, choice.error); |
| 30 | 32 | 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 @@ | ||
| 6 | 6 | import { armFor, cancelFor, type TimerError } from "../../actions/timers.ts"; |
| 7 | 7 | import type { Handler } from "../context.ts"; |
| 8 | 8 | import { BODY_CAPS, readBounded } from "../limits.ts"; |
| 9 | import { refuseDirtyJson } from "../parseable_request.ts"; | |
| 9 | 10 | import { apiError, json, unauthorized } from "../respond.ts"; |
| 10 | 11 | import type { Router } from "../router.ts"; |
| 11 | 12 | import { tokenSecret } from "../token_header.ts"; |
| @@ -25,6 +26,7 @@ export function timersRoutes(router: Router<Handler>): void { | ||
| 25 | 26 | } catch { |
| 26 | 27 | return apiError("invalid", 422, "The body is JSON."); |
| 27 | 28 | } |
| 29 | refuseDirtyJson(input); | |
| 28 | 30 | const armed = armFor(ctx.app, secret, input); |
| 29 | 31 | if (!armed.ok) return apiError(armed.error.kind, STATUS[armed.error.kind], armed.error.message); |
| 30 | 32 | return json({ timer: armed.value }, 201); |
src/http/api/user.ts +2 −1
| @@ -32,6 +32,7 @@ import type { Ctx, Handler } from "../context.ts"; | ||
| 32 | 32 | import { holds, weakEtag } from "../etag.ts"; |
| 33 | 33 | import { clientAddress } from "../peer.ts"; |
| 34 | 34 | 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"; | |
| 35 | 36 | import type { Router } from "../router.ts"; |
| 36 | 37 | import { eventStream } from "../sse.ts"; |
| 37 | 38 | import { gateBlocked, hostOf } from "../../actions/ask_host.ts"; |
| @@ -697,7 +698,7 @@ export function userRoutes(router: Router<Handler>): void { | ||
| 697 | 698 | router.add("POST", `${BROWSE}/contribute`, async (ctx) => { |
| 698 | 699 | const denied = requireAccount(ctx, { adminToken: true }); |
| 699 | 700 | if (denied) return denied; |
| 700 | const input = await body(ctx.request); | |
| 701 | const input = await body(ctx.request, FILE_TEXT); | |
| 701 | 702 | const result = await contribute(ctx.app, ctx.auth.user, { |
| 702 | 703 | originId: ctx.params.id!, |
| 703 | 704 | fullName: `${ctx.params.owner!}/${ctx.params.name!}`, |
src/http/mcp.ts +6 −1
| @@ -27,6 +27,7 @@ import { running } from "../kernel/version.ts"; | ||
| 27 | 27 | import { bearerChallenge } from "./oauth.ts"; |
| 28 | 28 | import { BodyTooLarge, json } from "./respond.ts"; |
| 29 | 29 | import { bodyCapFor, readBounded } from "./limits.ts"; |
| 30 | import { CONTROL_HINT, CONTROL_MESSAGE, dirtyJson, PATCH_TEXT } from "./parseable_request.ts"; | |
| 30 | 31 | import { page, signInHref } from "../web/layout.ts"; |
| 31 | 32 | import { html } from "../web/html.ts"; |
| 32 | 33 | import type { Router } from "./router.ts"; |
| @@ -681,7 +682,9 @@ function parseRpc(bytes: Uint8Array): unknown { | ||
| 681 | 682 | * (-32601), and, for a stranger only, a tool it lacks (-32602; the issue does not name it, but a |
| 682 | 683 | * call to a tool that does not exist cannot be helped by signing in). With a `challenge` the |
| 683 | 684 | * -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. | |
| 685 | 688 | */ |
| 686 | 689 | function rpcFault(value: unknown, challenge: Record<string, string> | undefined): Response | undefined { |
| 687 | 690 | const fail = (code: number, message: string, id: unknown, status: number) => |
| @@ -696,6 +699,8 @@ function rpcFault(value: unknown, challenge: Record<string, string> | undefined) | ||
| 696 | 699 | const m = value as Record<string, unknown>; |
| 697 | 700 | if (m["jsonrpc"] !== "2.0" || typeof m["method"] !== "string") |
| 698 | 701 | 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); | |
| 699 | 704 | if (m["id"] === undefined) return undefined; |
| 700 | 705 | const method = m["method"]; |
| 701 | 706 | 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"; | ||
| 17 | 17 | import type { Handler } from "./context.ts"; |
| 18 | 18 | import { clientBucket } from "./peer.ts"; |
| 19 | 19 | import { apiError, boundedBody, json, notFound, str as bodyStr, tryAgain } from "./respond.ts"; |
| 20 | import { PATCH_TEXT } from "./parseable_request.ts"; | |
| 20 | 21 | |
| 21 | 22 | /** A full queue drains as people read offers; no clock says when, so a minute. */ |
| 22 | 23 | const QUEUE_RETRY = 60; |
| @@ -26,7 +27,7 @@ export const offerHandler: Handler = async (ctx) => { | ||
| 26 | 27 | const found = getRepo(ctx.app.db, ctx.params.owner!, ctx.params.name!); |
| 27 | 28 | const repo = found && canRead(ctx.app.db, found, ctx.auth.user) ? found : undefined; |
| 28 | 29 | 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); | |
| 30 | 31 | if (input === "too_large") return apiError("patch_too_large", 422, OFFER_WORDS.patch_too_large); |
| 31 | 32 | const filed = await fileOffer( |
| 32 | 33 | 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 | ||
| 1 | 5 | /** |
| 2 | 6 | * A request whose URL cannot be parsed. The runtime builds `request.url` |
| 3 | 7 | * 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 | ||
| 36 | 40 | }, |
| 37 | 41 | }); |
| 38 | 42 | } |
| 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 @@ | ||
| 5 | 5 | */ |
| 6 | 6 | |
| 7 | 7 | import { InvalidJson, objectOf } from "./json_body.ts"; |
| 8 | import { NO_RAW_TEXT, refuseDirtyJson, type RawText } from "./parseable_request.ts"; | |
| 8 | 9 | import { bodyCapFor, readBounded } from "./limits.ts"; |
| 9 | 10 | import { namesReader } from "./reader.ts"; |
| 10 | 11 | import { scopeAllows, type TokenScope } from "../core/tokens.ts"; |
| @@ -482,12 +483,14 @@ export function respondAccess(error: string, status: number): Response { | ||
| 482 | 483 | * \`STRANGER_MAX\` for anyone else (\`http/limits.ts\`) — a route reads its |
| 483 | 484 | * body before it asks who is calling, so the cap cannot wait for that. Past |
| 484 | 485 | * 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). | |
| 486 | 489 | */ |
| 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>> { | |
| 488 | 491 | const bytes = await readBounded(request, bodyCapFor(request)); |
| 489 | 492 | if (bytes === "too_large") throw new BodyTooLarge(bodyCapFor(request)); |
| 490 | return objectOf(bytes); | |
| 493 | return refuseDirtyJson(objectOf(bytes), raw); | |
| 491 | 494 | } |
| 492 | 495 | |
| 493 | 496 | /** |
| @@ -524,9 +527,10 @@ export const bodyTooLarge = (error: BodyTooLarge): Response => | ||
| 524 | 527 | export async function boundedBody( |
| 525 | 528 | request: Request, |
| 526 | 529 | max: number, |
| 530 | raw: RawText = NO_RAW_TEXT, | |
| 527 | 531 | ): Promise<Record<string, unknown> | "too_large"> { |
| 528 | 532 | 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); | |
| 530 | 534 | } |
| 531 | 535 | |
| 532 | 536 | export const str = (v: unknown): string => (typeof v === "string" ? v : ""); |
src/http/server.ts +6 −1
| @@ -7,7 +7,7 @@ | ||
| 7 | 7 | |
| 8 | 8 | import { standingFragment } from "../web/pages/fork-standing.ts"; |
| 9 | 9 | 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"; | |
| 11 | 11 | import { expireCookie } from "../auth/cookies.ts"; |
| 12 | 12 | import { checkText } from "./check_text.ts"; |
| 13 | 13 | import { noteOwnWrite } from "../flow/keep.ts"; |
| @@ -2651,6 +2651,8 @@ export interface Servers { | ||
| 2651 | 2651 | function failure(app: App, error: unknown, request?: Request): Response { |
| 2652 | 2652 | if (error instanceof BodyTooLarge) return securityFloor(bodyTooLarge(error)); |
| 2653 | 2653 | 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)); | |
| 2654 | 2656 | if (isFullError(error)) { |
| 2655 | 2657 | if (noteFull(app.config.dataDir)) { |
| 2656 | 2658 | app.log.error("disk full: forge is read-only until space returns", { error: String(error) }); |
| @@ -3379,6 +3381,9 @@ async function answer( | ||
| 3379 | 3381 | request: Request, |
| 3380 | 3382 | ): Promise<Response> { |
| 3381 | 3383 | 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); | |
| 3382 | 3387 | // A doubled slash is the same page, not a second copy (#14374): GET and HEAD |
| 3383 | 3388 | // answer 308 to the path with each run of slashes collapsed, query kept. The |
| 3384 | 3389 | // 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"; | ||
| 14 | 14 | import { isLocalPath } from "./flash.ts"; |
| 15 | 15 | import type { FieldOptions } from "./ui.ts"; |
| 16 | 16 | import { crossOrigin, type Ctx } from "../http/context.ts"; |
| 17 | import { controlRefusal, dirtyForm } from "../http/parseable_request.ts"; | |
| 17 | 18 | |
| 18 | 19 | export type Form = Awaited<ReturnType<Request["formData"]>>; |
| 19 | 20 | |
| @@ -46,13 +47,17 @@ export async function readForm( | ||
| 46 | 47 | // at all — is an empty form, not a malformed one. |
| 47 | 48 | if (type === null || bytes.byteLength === 0) |
| 48 | 49 | return new FormData() as unknown as Form; |
| 50 | let form: Form; | |
| 49 | 51 | try { |
| 50 | return await new Response(bytes, { | |
| 52 | form = await new Response(bytes, { | |
| 51 | 53 | headers: { "content-type": type }, |
| 52 | 54 | }).formData(); |
| 53 | 55 | } catch { |
| 54 | 56 | return new Response("bad request", { status: 400 }); |
| 55 | 57 | } |
| 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; | |
| 56 | 61 | } |
| 57 | 62 | |
| 58 | 63 | /** 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", () => { | ||
| 77 | 77 | expect(keyShapeOk("sk-ant-api03-ab\u0000cd")).toBe(false); |
| 78 | 78 | expect(keyShapeOk("é".repeat(KEY_MAX_BYTES / 2 + 1))).toBe(false); |
| 79 | 79 | 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`); | |
| 81 | 84 | expect(res.status).toBe(303); |
| 82 | 85 | expect(listSubscriptions(app.db)).toEqual([]); |
| 83 | 86 | 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", () => | ||
| 128 | 128 | expect(lines[1]).toContain("0.00 TB"); |
| 129 | 129 | }); |
| 130 | 130 | |
| 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); | |
| 133 | 133 | expect((await put(admin, "rack4", { smartctl: smart(1), cpu: "EPYC\u009b2J", memoryBytes: 1 })).status).toBe(422); |
| 134 | 134 | 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); | |
| 136 | 139 | const lines = diskLines(diskSummary(app.db, "rack4")); |
| 137 | 140 | expect(lines.join("\n")).not.toMatch(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f]/); |
| 138 | 141 | 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", () => { | ||
| 198 | 198 | }); |
| 199 | 199 | |
| 200 | 200 | 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); | |
| 202 | 204 | expect((await put("paper", "empty.txt", "")).status).toBe(422); |
| 203 | 205 | expect(FILES_MAX).toBe(500); |
| 204 | 206 | }); |
test/edits-security.test.ts +3 −1
| @@ -196,7 +196,6 @@ describe("edits: refusals that must leave nothing behind", () => { | ||
| 196 | 196 | ["a//b", "invalid_path"], |
| 197 | 197 | ["a/", "invalid_path"], |
| 198 | 198 | ["/abs", "invalid_path"], |
| 199 | ["a\u0000b", "invalid_path"], | |
| 200 | 199 | ["a\nb", "invalid_path"], |
| 201 | 200 | [".git/config", "invalid_path"], |
| 202 | 201 | ["sub/.GIT/hooks/pre-receive", "invalid_path"], |
| @@ -208,6 +207,9 @@ describe("edits: refusals that must leave nothing behind", () => { | ||
| 208 | 207 | expect([path, r.status]).toEqual([path, 422]); |
| 209 | 208 | expect([path, r.body.error]).toEqual([path, code]); |
| 210 | 209 | } |
| 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"]); | |
| 211 | 213 | expect(await objects()).toBe(before); |
| 212 | 214 | expect(await refs()).not.toContain("refs/heads/stray"); |
| 213 | 215 | }); |
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 | ||
| 82 | 82 | test("a junk page shows the first, an out-of-range page the last, never an error", async () => { |
| 83 | 83 | const first = await get("/explore?kind=app&owner=olive&sort=name"); |
| 84 | 84 | 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), ""]) { | |
| 86 | 86 | const res = await get(`/explore?kind=app&owner=olive&sort=name&page=${bad}`); |
| 87 | 87 | expect(res.status).toBe(200); |
| 88 | 88 | expect(rows(res.html)).toEqual(rows(first.html)); |
| 89 | 89 | } |
| 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); | |
| 90 | 92 | const last = await get("/explore?kind=app&owner=olive&sort=name&page=999"); |
| 91 | 93 | expect(last.status).toBe(200); |
| 92 | 94 | expect(last.html).toContain("Page 2 of 2"); |
test/keeper-heartbeat.test.ts +2 −2
| @@ -81,8 +81,8 @@ describe("release heartbeat", () => { | ||
| 81 | 81 | expect(lastBeat(app.db)).toEqual(before); |
| 82 | 82 | }); |
| 83 | 83 | |
| 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); | |
| 86 | 86 | expect((await post(admin, { outcome: "failed", reason: "two\nlines" })).status).toBe(422); |
| 87 | 87 | }); |
| 88 | 88 |
test/parity.test.ts +5 −5
| @@ -965,22 +965,22 @@ describe("parity: full control through actions and the API", () => { | ||
| 965 | 965 | expect(res.json.error).toBe("invalid_cursor"); |
| 966 | 966 | } |
| 967 | 967 | |
| 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. | |
| 969 | 969 | const odd = await call("POST", "/api/v1/orgs/paging/teams", { |
| 970 | 970 | token: aliceAdmin, |
| 971 | body: { name: "a\u0001b", permission: "read" }, | |
| 971 | body: { name: "a\tb", permission: "read" }, | |
| 972 | 972 | }); |
| 973 | 973 | expect(odd.status).toBe(201); |
| 974 | 974 | { |
| 975 | 975 | 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"); | |
| 977 | 977 | const page = await call("GET", `/api/v1/orgs/paging/teams?limit=${at + 1}`, { |
| 978 | 978 | token: aliceAdmin, |
| 979 | 979 | }); |
| 980 | expect(page.json.next_cursor).toBe("a\u0001b"); | |
| 980 | expect(page.json.next_cursor).toBe("a\tb"); | |
| 981 | 981 | const next = await call( |
| 982 | 982 | "GET", |
| 983 | `/api/v1/orgs/paging/teams?cursor=${encodeURIComponent("a\u0001b")}`, | |
| 983 | `/api/v1/orgs/paging/teams?cursor=${encodeURIComponent("a\tb")}`, | |
| 984 | 984 | { token: aliceAdmin }, |
| 985 | 985 | ); |
| 986 | 986 | expect(next.status).toBe(200); |
test/redirect-targets.test.ts +15 −5
| @@ -35,6 +35,9 @@ const HOSTILE = [ | ||
| 35 | 35 | "evil.example", |
| 36 | 36 | ]; |
| 37 | 37 | |
| 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 | ||
| 38 | 41 | /** Deep links that must keep working, query string and all. */ |
| 39 | 42 | const GOOD = ["/kim/proj/issues?state=open&q=a%20b", "/settings/keys", "/oauth/authorize?client_id=c&state=s"]; |
| 40 | 43 | |
| @@ -74,8 +77,15 @@ describe("every door that reads a return address", () => { | ||
| 74 | 77 | redirect: "manual", |
| 75 | 78 | }); |
| 76 | 79 | |
| 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 | ||
| 77 | 87 | 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) { | |
| 79 | 89 | const res = await signIn(bad); |
| 80 | 90 | expect([bad, res.status, res.headers.get("location")]).toEqual([bad, 303, "/"]); |
| 81 | 91 | } |
| @@ -84,14 +94,14 @@ describe("every door that reads a return address", () => { | ||
| 84 | 94 | |
| 85 | 95 | test("/login and /sign-in drop a hostile next and keep a deep link", async () => { |
| 86 | 96 | 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"]); | |
| 88 | 98 | for (const good of GOOD) expect((await get(`${alias}?${q(good)}`)).headers.get("location")).toBe(`/signin?${q(good)}`); |
| 89 | 99 | } |
| 90 | 100 | }); |
| 91 | 101 | |
| 92 | 102 | test("the sign-in and sign-up forms carry no hostile next anywhere on the page", async () => { |
| 93 | 103 | for (const door of ["/signin", "/signup"]) { |
| 94 | for (const bad of HOSTILE) { | |
| 104 | for (const bad of AT_DOORS) { | |
| 95 | 105 | const body = await (await get(`${door}?${q(bad)}`)).text(); |
| 96 | 106 | expect([door, bad, body.includes("evil.example")]).toEqual([door, bad, false]); |
| 97 | 107 | } |
| @@ -101,7 +111,7 @@ describe("every door that reads a return address", () => { | ||
| 101 | 111 | }); |
| 102 | 112 | |
| 103 | 113 | 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) { | |
| 105 | 115 | const res = await get(`/oauth/authorize?client_id=nobody&response_type=code&${new URLSearchParams({ redirect_uri: bad, next: bad })}`); |
| 106 | 116 | const location = res.headers.get("location") ?? ""; |
| 107 | 117 | expect([bad, location.startsWith("/signin?next=%2Foauth%2Fauthorize")]).toEqual([bad, true]); |
| @@ -110,7 +120,7 @@ describe("every door that reads a return address", () => { | ||
| 110 | 120 | }); |
| 111 | 121 | |
| 112 | 122 | 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) { | |
| 114 | 124 | const res = await fetch(`${base}/settings/everyday/switch?${q(bad)}`, { method: "POST", headers: { origin: base }, redirect: "manual" }); |
| 115 | 125 | const location = res.headers.get("location") ?? ""; |
| 116 | 126 | 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", () => { | ||
| 154 | 154 | }); |
| 155 | 155 | |
| 156 | 156 | 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); | |
| 157 | 161 | 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", | |
| 160 | 164 | page: "javascript:alert(1)", |
| 161 | 165 | }); |
| 162 | 166 | expect(res.status).toBe(202); |
test/search.test.ts +1 −1
| @@ -391,7 +391,7 @@ describe("search: one query, four sources", () => { | ||
| 391 | 391 | }); |
| 392 | 392 | |
| 393 | 393 | 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"]) { | |
| 395 | 395 | const results = await find(`q=${q}`); |
| 396 | 396 | expect(results.note).toContain("q is empty"); |
| 397 | 397 | expect({ ...results, note: undefined }).toEqual({ |
test/thoughts.test.ts +1 −1
| @@ -54,7 +54,7 @@ describe("thoughts", () => { | ||
| 54 | 54 | .get(id); |
| 55 | 55 | |
| 56 | 56 | 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>&</b>"]) { | |
| 57 | for (const text of [" padded \t\n", "line one\r\nline two\n\n", "héllo 🌍 wide é", "<b>&</b>"]) { | |
| 58 | 58 | const res = await post(text); |
| 59 | 59 | expect(res.status).toBe(201); |
| 60 | 60 | const { id } = (await res.json()) as { id: string }; |
test/username-refusals.test.ts +11 −1
| @@ -17,7 +17,6 @@ const UNSAFE: [string, string][] = [ | ||
| 17 | 17 | ["dot-dot", ".."], |
| 18 | 18 | ["a slash", "a/b"], |
| 19 | 19 | ["markup", "<b>"], |
| 20 | ["a NUL", "al\u0000ice"], | |
| 21 | 20 | ["200 characters", "a".repeat(200)], |
| 22 | 21 | ]; |
| 23 | 22 | const RESERVED = ["settings", "api"]; |
| @@ -79,6 +78,17 @@ describe("username refusals at sign-up", () => { | ||
| 79 | 78 | }); |
| 80 | 79 | } |
| 81 | 80 | |
| 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 | ||
| 82 | 92 | for (const name of RESERVED) { |
| 83 | 93 | test(`the API refuses the reserved word ${name} and makes no user`, async () => { |
| 84 | 94 | const before = users(); |
test/web-apps.test.ts +3 −1
| @@ -218,7 +218,9 @@ describe("apps, runs and the crew on the web", () => { | ||
| 218 | 218 | expect(escaped).not.toContain("<img src=x"); |
| 219 | 219 | expect(escaped).toContain("<script>alert(1)"); |
| 220 | 220 | |
| 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), " "]) { | |
| 222 | 224 | const ignored = await ( |
| 223 | 225 | await web(alice, `/apps/new?description=${encodeURIComponent(bad)}`) |
| 224 | 226 | ).text(); |
test/web-ui.test.ts +2 −1
| @@ -484,10 +484,11 @@ describe("web ui", () => { | ||
| 484 | 484 | "--upload-pack=touch", |
| 485 | 485 | "..%2F..%2Fetc", |
| 486 | 486 | "main..other", |
| 487 | "%00main", | |
| 488 | 487 | ]) { |
| 489 | 488 | expect((await fetch(`${base}/mel/proj/tree/${bad}`)).status).toBe(404); |
| 490 | 489 | } |
| 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); | |
| 491 | 492 | // The commits page falls back to the default branch instead of passing a |
| 492 | 493 | // hostile ?ref= to git. |
| 493 | 494 | const commits = await fetch(`${base}/mel/proj/commits?ref=--output%3Dx`); |
new above
offline
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.