Public: anyone can read this; the crew can change it.
One table test pins every renderer's byte cap and its hostile-input answer #15732
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/15720-one-table-test-pins-every-renderer-s-byt → main 0 commits fork 1 thread · 1 unresolved
20 files
changed +576
−27
docs/features/config-form.md +9 −1
| @@ -101,7 +101,15 @@ and the two hashes. | ||
| 101 | 101 | Hostile input is bounded before it is walked: a file over 256 KB is never |
| 102 | 102 | parsed (page and save both check the size first), YAML aliases and merge |
| 103 | 103 | keys share a 2,000-value budget, and nesting deeper than 64 is refused in |
| 104 | YAML and TOML alike. | |
| 104 | YAML and TOML alike. YAML is counted before the parser sees it | |
| 105 | (`yamlTooLarge`), since the vendored parser costs some 25 µs a line: more | |
| 106 | than 6,000 items (three times `MAX_FIELDS`; an item is a line of block | |
| 107 | structure or a value in a flow list), more than 20,000 lines of any sort, | |
| 108 | or flow brackets or dashes nested past 64 are refused at once. Text inside | |
| 109 | quotes, block scalars (`|`, `>`) and comments is not counted, so a long | |
| 110 | list written inside a string costs nothing. What a person loses: a file | |
| 111 | past those caps is not a form; it keeps its source view, and the page | |
| 112 | says which cap it met. A key written twice is refused at its line and column. | |
| 105 | 113 | |
| 106 | 114 | ## Saving |
| 107 | 115 |
docs/features/gpx.md +1
| @@ -10,4 +10,5 @@ Open a `.gpx` file in a repository and see the route drawn as an outline, with i | ||
| 10 | 10 | - **Terminal:** the workspace opens a `.gpx` as a Fact / Value table (`src/tui/screens/workspace.ts`, sharing `parseGpx` and `gpxFacts`); `s` flips to the source. The status line reads `4 facts`. |
| 11 | 11 | - Distance is the haversine sum, climb the sum of rises. No map tiles, no network. |
| 12 | 12 | - Beyond 20,000 points (`POINT_CAP`) the outline is thinned evenly, ends kept; the count stays true. |
| 13 | - The scan stops after 100,000 tags (`TOKEN_CAP`) or 25,000 points (`READ_POINT_CAP`): the first part is drawn, with a line under it saying the file goes on and that distance and climb count only that part; the terminal adds a "Read: first part only" fact. What a person loses: a track point written with `<ele>` and `<time>` is about nine tags, so a recorded track past some 11,000 points is drawn, measured and counted as its first part only. | |
| 13 | 14 | - A file that is not readable GPX shows as source, with a one-line reason on the web. DOCTYPE entities are never expanded; all text is escaped. |
docs/features/kml.md +2 −1
| @@ -7,8 +7,9 @@ row: KML maps (.kml) as a placemark table | ||
| 7 | 7 | Open a `.kml` file in a repository and see its placemarks as a table: name, description, longitude, latitude. |
| 8 | 8 | |
| 9 | 9 | - **Web:** the blob page renders a table on the server (`src/web/render/kml.ts`, sharing gpx's tag scanner). The table sits in the `.gj-table` region: focusable, labelled "Placemarks", and it scrolls sideways inside the column (`overflow-x: auto; max-width: 100%`), so it never widens a 360px phone page; long words wrap. `?view=source`, Raw and Download work as for any file. |
| 10 | - **Terminal:** the workspace opens a `.kml` as a Name / Description / Longitude / Latitude table (`src/tui/screens/kml.ts`, same parser); `s` flips to the source, and the status line counts the rows left out. | |
| 10 | - **Terminal:** the workspace opens a `.kml` as a Name / Description / Longitude / Latitude table (`src/tui/screens/kml.ts`, same parser); `s` flips to the source, and the status line counts the rows left out. A file the scan stopped reading opens on a "(file goes on)" row: "first part only: at least N placemarks". | |
| 11 | 11 | - At most 500 placemarks are listed (`PLACEMARK_CAP`); the rest are counted in a "Showing the first 500 of N placemarks." line. |
| 12 | - The scan stops after 100,000 tags (`TOKEN_CAP`, shared with GPX): the count reads "at least N placemarks" and a line says only the first part was listed. What a person loses: placemarks past those tags (some 20,000 short ones, fewer with long descriptions or polygons) are neither listed nor counted. | |
| 12 | 13 | - Descriptions are text, never markup: tags are shown, not applied. The web clips a description at 300 characters, the terminal at 80 (whitespace folded). |
| 13 | 14 | - **Only the first coordinate of a placemark is shown.** A Point shows its position; a LineString or Polygon shows its first vertex only, and nothing in the table says more follows. A placemark with no readable coordinate leaves both cells empty. Altitude is ignored. |
| 14 | 15 | - A file that is not well-formed KML (tags that do not nest, a root other than `kml`, no placemark) keeps the source view, with a one-line reason on the web. DOCTYPE entities are never expanded; all text is escaped. |
docs/features/timeline-cut-list.md +1
| @@ -16,6 +16,7 @@ Open a `.otio` (OpenTimelineIO), `.edl` (CMX3600 edit decision list) or `.fcpxml | ||
| 16 | 16 | ## Limits |
| 17 | 17 | |
| 18 | 18 | - **1 MB is the render cap.** A larger file is shown as its source, never drawn. |
| 19 | - **Final Cut and Kdenlive read at most 100,000 tags and 10,000 clips** (`TOKEN_CAP`, `READ_CLIP_CAP`). Past either the file keeps its source, with "it is too long to read here": its total length needs every clip. | |
| 19 | 20 | - A file that is cut off, is not a Timeline, or has no events also keeps its source, with the reason above it. |
| 20 | 21 | - **Frame rate.** An `.otio` carries its own rates. An `.edl` is read at the rate its header names (`FRAME RATE: 25`); with none, the page says it assumed one: 30 fps for a list marked `FCM: DROP FRAME`, 24 otherwise. |
| 21 | 22 | - **Drop-frame.** Timecode is counted by nominal frames, so a drop-frame duration can be a frame or two off the editor's own figure. Treat totals as a guide, not a conform. |
src/tui/screens/kml.ts +12 −1
| @@ -10,10 +10,21 @@ export function isKmlPath(path: string): boolean { | ||
| 10 | 10 | return /\.kml$/i.test(path); |
| 11 | 11 | } |
| 12 | 12 | |
| 13 | /** | |
| 14 | * The first row of a table the scan stopped reading, so it is on screen when the file opens | |
| 15 | * (`cut`): the page's "at least N placemarks" and its note under the table, short enough for the | |
| 16 | * terminal's cells. | |
| 17 | */ | |
| 18 | export const kmlCutRow = (total: number): string[] => ["(file goes on)", `first part only: at least ${total.toLocaleString("en")} placemarks`, "", ""]; | |
| 19 | ||
| 13 | 20 | /** The placemark table of a KML file; null when it is not KML. */ |
| 14 | 21 | export function kmlTable(source: string): Table | null { |
| 15 | 22 | const parsed = parseKml(source); |
| 16 | 23 | if (parsed === undefined) return null; |
| 17 | 24 | const rows = parsed.placemarks.map((p) => [p.name, p.description.replace(/\s+/g, " ").slice(0, 80), String(p.lon ?? ""), String(p.lat ?? "")]); |
| 18 | return { header: ["Name", "Description", "Longitude", "Latitude"], rows, more: parsed.total - rows.length, delimiter: ",", columns: 4 }; | |
| 25 | const more = parsed.total - rows.length; | |
| 26 | if (parsed.cut !== true) return { header: ["Name", "Description", "Longitude", "Latitude"], rows, more, delimiter: ",", columns: 4 }; | |
| 27 | // The note row takes one of the counted rows, so the status line's count stays the total read. | |
| 28 | rows.unshift(kmlCutRow(parsed.total)); | |
| 29 | return { header: ["Name", "Description", "Longitude", "Latitude"], rows, more: Math.max(0, more - 1), delimiter: ",", columns: 4 }; | |
| 19 | 30 | } |
src/tui/screens/workspace.ts +2
| @@ -501,6 +501,8 @@ function gpxTable(source: string, path: string): Table | null { | ||
| 501 | 501 | const parsed = parseGpx(source); |
| 502 | 502 | if (parsed === undefined) return null; |
| 503 | 503 | const rows = gpxFacts(parsed, path); |
| 504 | // A track the scan stopped reading says so (the page's `CUT_NOTE`, short enough for a cell). | |
| 505 | if (parsed.cut === true) rows.push(["Read", "first part only"]); | |
| 504 | 506 | return { header: ["Fact", "Value"], rows, more: 0, delimiter: ",", columns: 2 }; |
| 505 | 507 | } |
| 506 | 508 |
src/web/render/compose.ts +3
| @@ -11,6 +11,7 @@ import { escapeHtml, html, raw } from "../html.ts"; | ||
| 11 | 11 | import { fileSize } from "../ui.ts"; |
| 12 | 12 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 13 | 13 | import { parseAllDocuments } from "./vendor/yaml.mjs"; |
| 14 | import { yamlTooLarge } from "./yaml-config.ts"; | |
| 14 | 15 | |
| 15 | 16 | export const SERVICE_CAP = 100; |
| 16 | 17 | export const LIST_CAP = 50; |
| @@ -61,6 +62,8 @@ function buildOf(v: unknown): string { | ||
| 61 | 62 | } |
| 62 | 63 | |
| 63 | 64 | export function parseCompose(source: string): Compose { |
| 65 | const large = yamlTooLarge(source); | |
| 66 | if (large !== undefined) return { error: `it is too large to read here (${large})` }; | |
| 64 | 67 | const docs = parseAllDocuments(source, { maxAliasCount: 100 }); |
| 65 | 68 | const doc = docs[0]; |
| 66 | 69 | if (doc === undefined || docs.length > 1) return { error: "it is not one YAML document" }; |
src/web/render/fcpxml.ts +21 −5
| @@ -14,8 +14,8 @@ | ||
| 14 | 14 | */ |
| 15 | 15 | |
| 16 | 16 | import { html } from "../html.ts"; |
| 17 | import { TAG, attr, decode, local } from "./gpx.ts"; | |
| 18 | import { drawTimeline, timecode, type Cut, type Timeline } from "./timeline-table.ts"; | |
| 17 | import { TAG, TOKEN_CAP, attr, decode, local } from "./gpx.ts"; | |
| 18 | import { drawTimeline, READ_CLIP_CAP, timecode, TOO_LONG, type Cut, type Timeline } from "./timeline-table.ts"; | |
| 19 | 19 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 20 | 20 | |
| 21 | 21 | export type Parsed = { readonly timeline: Timeline } | { readonly error: string }; |
| @@ -42,8 +42,17 @@ export function parseFcpxml(text: string): Parsed { | ||
| 42 | 42 | let seqFormat = ""; |
| 43 | 43 | let sawRoot = false; |
| 44 | 44 | let spines = 0; |
| 45 | let tokens = 0; | |
| 46 | let read = 0; | |
| 47 | // How many `spine` and clip elements are open: counted, so no tag walks the whole stack (a file | |
| 48 | // of 60,000 nested clips took seconds when each one did). | |
| 49 | let inSpine = 0; | |
| 50 | let inClip = 0; | |
| 45 | 51 | try { |
| 46 | 52 | for (const m of text.replace(/^/, "").matchAll(TAG)) { |
| 53 | // Bounded as gpx.ts is: past either cap the file is not read on | |
| 54 | // (test/render-hostile.test.ts). | |
| 55 | if (++tokens > TOKEN_CAP) return { error: TOO_LONG }; | |
| 47 | 56 | const [, , closing, rawTag, attrs, selfClose, chars] = m; |
| 48 | 57 | if (chars !== undefined) { |
| 49 | 58 | if (stack.length === 0 && chars.trim() !== "") throw new Error("text outside root"); |
| @@ -53,6 +62,8 @@ export function parseFcpxml(text: string): Parsed { | ||
| 53 | 62 | const tag = local(rawTag); |
| 54 | 63 | if (closing === "/") { |
| 55 | 64 | if (stack.pop() !== tag) throw new Error("mismatch"); |
| 65 | if (tag === "spine") inSpine--; | |
| 66 | else if (tag === "asset-clip" || tag === "clip") inClip--; | |
| 56 | 67 | continue; |
| 57 | 68 | } |
| 58 | 69 | if (stack.length === 0) { |
| @@ -72,8 +83,9 @@ export function parseFcpxml(text: string): Parsed { | ||
| 72 | 83 | seqFormat = attr(a, "format") ?? ""; |
| 73 | 84 | } else if (tag === "spine") { |
| 74 | 85 | spines++; |
| 75 | } else if ((tag === "asset-clip" || tag === "clip") && stack.includes("spine")) { | |
| 86 | } else if ((tag === "asset-clip" || tag === "clip") && inSpine > 0) { | |
| 76 | 87 | const lane = (attr(a, "lane") ?? "0").trim(); |
| 88 | if (++read > READ_CLIP_CAP) return { error: TOO_LONG }; | |
| 77 | 89 | clips.push({ |
| 78 | 90 | lane: /^-?\d{1,3}$/.test(lane) ? String(Number(lane)) : "0", |
| 79 | 91 | name: decode(attr(a, "name") ?? ""), |
| @@ -81,10 +93,14 @@ export function parseFcpxml(text: string): Parsed { | ||
| 81 | 93 | start: seconds(attr(a, "start")) ?? 0, |
| 82 | 94 | duration: seconds(attr(a, "duration")) ?? 0, |
| 83 | 95 | offset: seconds(attr(a, "offset")) ?? 0, |
| 84 | primary: !stack.some((t) => t === "asset-clip" || t === "clip"), | |
| 96 | primary: inClip === 0, | |
| 85 | 97 | }); |
| 86 | 98 | } |
| 87 | if (selfClose !== "/") stack.push(tag); | |
| 99 | if (selfClose !== "/") { | |
| 100 | stack.push(tag); | |
| 101 | if (tag === "spine") inSpine++; | |
| 102 | else if (tag === "asset-clip" || tag === "clip") inClip++; | |
| 103 | } | |
| 88 | 104 | } |
| 89 | 105 | } catch { |
| 90 | 106 | return { error: "it is not well-formed XML" }; |
src/web/render/gpx.ts +34 −5
| @@ -18,6 +18,17 @@ import type { Rendered, RenderInput } from "./renderers.ts"; | ||
| 18 | 18 | /** Points drawn; more than this are thinned evenly across the whole track. */ |
| 19 | 19 | export const POINT_CAP = 20_000; |
| 20 | 20 | |
| 21 | /** | |
| 22 | * Tokens (`TAG` matches: a tag, a text run, a comment) the scanner reads before it stops. A token | |
| 23 | * costs about 1.5 µs and a point about 4 µs, so a 5 MB file of nothing but `<a>` or `<trkpt/>` | |
| 24 | * would take most of a second; at these caps the scan stays under about 150 ms, and what was read | |
| 25 | * is drawn with a note that the file goes on (`cut`). A track that writes `<ele>` and `<time>` per | |
| 26 | * point spends about nine tokens a point, so some 11,000 points are read. | |
| 27 | */ | |
| 28 | export const TOKEN_CAP = 100_000; | |
| 29 | /** Points the scanner reads before it stops: more than `POINT_CAP` draws. */ | |
| 30 | export const READ_POINT_CAP = 25_000; | |
| 31 | ||
| 21 | 32 | export interface Point { |
| 22 | 33 | readonly lat: number; |
| 23 | 34 | readonly lon: number; |
| @@ -30,6 +41,8 @@ export interface Line { | ||
| 30 | 41 | export interface Gpx { |
| 31 | 42 | readonly lines: Line[]; |
| 32 | 43 | readonly count: number; |
| 44 | /** The scan stopped at `TOKEN_CAP`: the lines and count are the file's first part. */ | |
| 45 | readonly cut?: true; | |
| 33 | 46 | } |
| 34 | 47 | |
| 35 | 48 | const ENTITIES: Readonly<Record<string, string>> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" }; |
| @@ -44,8 +57,13 @@ export const decode = (s: string): string => | ||
| 44 | 57 | export const TAG = /<!--[\s\S]*?-->|<!DOCTYPE[^[>]*(?:\[[\s\S]*?\])?\s*>|<!\[CDATA\[([\s\S]*?)\]\]>|<[?!][^>]*>|<(\/?)([A-Za-z_][\w:.-]*)((?:"[^"]*"|'[^']*'|[^>"'])*?)(\/?)>|([^<]+)/g; |
| 45 | 58 | const ATTR = /([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g; |
| 46 | 59 | |
| 60 | /** | |
| 61 | * The first attribute of that name in a tag's attribute text; an `exec` loop, not `matchAll`'s | |
| 62 | * iterator, which cost most of a point's parse. | |
| 63 | */ | |
| 47 | 64 | export const attr = (src: string, name: string): string | undefined => { |
| 48 | for (const m of src.matchAll(ATTR)) if (m[1] === name) return m[2] ?? m[3]; | |
| 65 | ATTR.lastIndex = 0; | |
| 66 | for (let m = ATTR.exec(src); m !== null; m = ATTR.exec(src)) if (m[1] === name) return m[2] ?? m[3]; | |
| 49 | 67 | return undefined; |
| 50 | 68 | }; |
| 51 | 69 | export const local = (tag: string): string => tag.slice(tag.indexOf(":") + 1).toLowerCase(); |
| @@ -65,6 +83,8 @@ export function parseGpx(source: string): Gpx | undefined { | ||
| 65 | 83 | let text = ""; |
| 66 | 84 | let sawRoot = false; |
| 67 | 85 | let count = 0; |
| 86 | let tokens = 0; | |
| 87 | let cut = false; | |
| 68 | 88 | |
| 69 | 89 | const open = (tag: string, attrs: string): void => { |
| 70 | 90 | if (stack.length === 0) { |
| @@ -90,7 +110,7 @@ export function parseGpx(source: string): Gpx | undefined { | ||
| 90 | 110 | if (tag === "name" && (parent === "trk" || parent === "rte") && name === "") name = decode(text.trim()); |
| 91 | 111 | if ((tag === "trkpt" || tag === "rtept") && current !== undefined && seg !== undefined) { |
| 92 | 112 | seg.push(current); |
| 93 | count++; | |
| 113 | if (++count >= READ_POINT_CAP) cut = true; | |
| 94 | 114 | current = undefined; |
| 95 | 115 | } |
| 96 | 116 | if (tag === "trkseg" || tag === "rte") seg = undefined; |
| @@ -99,6 +119,10 @@ export function parseGpx(source: string): Gpx | undefined { | ||
| 99 | 119 | |
| 100 | 120 | try { |
| 101 | 121 | for (const m of source.replace(/^/, "").matchAll(TAG)) { |
| 122 | if (cut || ++tokens > TOKEN_CAP) { | |
| 123 | cut = true; | |
| 124 | break; | |
| 125 | } | |
| 102 | 126 | const [, cdata, closing, rawTag, attrs, selfClose, chars] = m; |
| 103 | 127 | if (cdata !== undefined) text += cdata; |
| 104 | 128 | else if (chars !== undefined) { |
| @@ -120,8 +144,9 @@ export function parseGpx(source: string): Gpx | undefined { | ||
| 120 | 144 | } catch { |
| 121 | 145 | return undefined; |
| 122 | 146 | } |
| 123 | if (!sawRoot || stack.length > 0 || count === 0) return undefined; | |
| 124 | return { lines: lines.filter((l) => l.points.length > 0), count }; | |
| 147 | if (!sawRoot || (stack.length > 0 && !cut) || count === 0) return undefined; | |
| 148 | const drawn = lines.filter((l) => l.points.length > 0); | |
| 149 | return cut ? { lines: drawn, count, cut } : { lines: drawn, count }; | |
| 125 | 150 | } |
| 126 | 151 | |
| 127 | 152 | /** Keep at most `cap` points of a list, evenly spaced, first and last included. */ |
| @@ -212,6 +237,9 @@ export function gpxFacts(parsed: Gpx, path: string): [string, string][] { | ||
| 212 | 237 | ]; |
| 213 | 238 | } |
| 214 | 239 | |
| 240 | /** Said under a track the scan stopped reading (`Gpx.cut`). */ | |
| 241 | export const CUT_NOTE = `The file goes on past the ${TOKEN_CAP.toLocaleString("en")} tags or ${READ_POINT_CAP.toLocaleString("en")} points the page reads: this is its first part, and the distance and climb count only that.`; | |
| 242 | ||
| 215 | 243 | export function gpx(input: RenderInput): Rendered { |
| 216 | 244 | const parsed = parseGpx(new TextDecoder().decode(input.body)); |
| 217 | 245 | if (parsed === undefined) |
| @@ -223,11 +251,12 @@ export function gpx(input: RenderInput): Rendered { | ||
| 223 | 251 | const content = html`<figure class="gpx-view"> |
| 224 | 252 | <svg viewBox="0 0 ${width} ${height}" role="img" aria-label="Route of ${title}" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${raw(d)}</svg> |
| 225 | 253 | <dl class="status-rows">${facts.map(([k, v]) => html`<div class="status-row"><dt>${k}</dt><dd>${v}</dd></div>`)}</dl> |
| 254 | ${parsed.cut === true ? html`<p class="muted small">${CUT_NOTE}</p>` : null} | |
| 226 | 255 | </figure>`; |
| 227 | 256 | const { distance, gain } = gpxStats(parsed); |
| 228 | 257 | return { |
| 229 | 258 | content, |
| 230 | 259 | lines: 0, |
| 231 | summary: `${km(distance)} km · ${Math.round(gain)} m climb · ${fileSize(input.size)}`, | |
| 260 | summary: `${parsed.cut === true ? "first part: " : ""}${km(distance)} km · ${Math.round(gain)} m climb · ${fileSize(input.size)}`, | |
| 232 | 261 | }; |
| 233 | 262 | } |
src/web/render/kdenlive.ts +8 −2
| @@ -17,8 +17,8 @@ | ||
| 17 | 17 | */ |
| 18 | 18 | |
| 19 | 19 | import { html } from "../html.ts"; |
| 20 | import { TAG, attr, decode, local } from "./gpx.ts"; | |
| 21 | import { drawTimeline, timecode, type Cut, type Timeline } from "./timeline-table.ts"; | |
| 20 | import { TAG, TOKEN_CAP, attr, decode, local } from "./gpx.ts"; | |
| 21 | import { drawTimeline, READ_CLIP_CAP, timecode, TOO_LONG, type Cut, type Timeline } from "./timeline-table.ts"; | |
| 22 | 22 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 23 | 23 | |
| 24 | 24 | export type Parsed = { readonly timeline: Timeline } | { readonly error: string }; |
| @@ -49,8 +49,13 @@ export function parseKdenlive(text: string): Parsed { | ||
| 49 | 49 | let num = 25; |
| 50 | 50 | let den = 1; |
| 51 | 51 | let sawRoot = false; |
| 52 | let tokens = 0; | |
| 53 | let read = 0; | |
| 52 | 54 | try { |
| 53 | 55 | for (const m of text.replace(/^/, "").matchAll(TAG)) { |
| 56 | // Bounded as gpx.ts is: past either cap the file is not read on | |
| 57 | // (test/render-hostile.test.ts). | |
| 58 | if (++tokens > TOKEN_CAP) return { error: TOO_LONG }; | |
| 54 | 59 | const [, , closing, rawTag, attrs, selfClose, chars] = m; |
| 55 | 60 | if (chars !== undefined) { |
| 56 | 61 | const top = stack[stack.length - 1]; |
| @@ -99,6 +104,7 @@ export function parseKdenlive(text: string): Parsed { | ||
| 99 | 104 | } else if (tag === "playlist") { |
| 100 | 105 | playlists.push({ id, name: "", entries: [] }); |
| 101 | 106 | } else if (tag === "entry" && parent === "playlist") { |
| 107 | if (++read > READ_CLIP_CAP) return { error: TOO_LONG }; | |
| 102 | 108 | playlists[playlists.length - 1]!.entries.push({ |
| 103 | 109 | producer: attr(a, "producer") ?? "", |
| 104 | 110 | in: attr(a, "in") ?? "0", |
src/web/render/kml.ts +18 −6
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | 13 | import { html } from "../html.ts"; |
| 14 | import { TAG, decode, local } from "./gpx.ts"; | |
| 14 | import { TAG, TOKEN_CAP, decode, local } from "./gpx.ts"; | |
| 15 | 15 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 16 | 16 | |
| 17 | 17 | /** Placemarks listed; more are counted and left out. */ |
| @@ -28,8 +28,10 @@ export interface Placemark { | ||
| 28 | 28 | export interface Kml { |
| 29 | 29 | /** The first PLACEMARK_CAP. */ |
| 30 | 30 | readonly placemarks: Placemark[]; |
| 31 | /** All of them in the file. */ | |
| 31 | /** All of them in the file, or in the part read when `cut`. */ | |
| 32 | 32 | readonly total: number; |
| 33 | /** The scan stopped at `TOKEN_CAP` (gpx.ts): the file holds more than was read. */ | |
| 34 | readonly cut?: true; | |
| 33 | 35 | } |
| 34 | 36 | |
| 35 | 37 | /** First "lon,lat[,alt]" tuple of a coordinates text, when it is in range. */ |
| @@ -49,6 +51,8 @@ export function parseKml(source: string): Kml | undefined { | ||
| 49 | 51 | let total = 0; |
| 50 | 52 | let sawRoot = false; |
| 51 | 53 | let text = ""; |
| 54 | let tokens = 0; | |
| 55 | let cut = false; | |
| 52 | 56 | let cur: { name: string; description: string; at?: { lon: number; lat: number } | undefined } | undefined; |
| 53 | 57 | |
| 54 | 58 | const close = (tag: string): void => { |
| @@ -74,6 +78,10 @@ export function parseKml(source: string): Kml | undefined { | ||
| 74 | 78 | |
| 75 | 79 | try { |
| 76 | 80 | for (const m of source.replace(/^/, "").matchAll(TAG)) { |
| 81 | if (++tokens > TOKEN_CAP) { | |
| 82 | cut = true; | |
| 83 | break; | |
| 84 | } | |
| 77 | 85 | const [, cdata, closing, rawTag, , selfClose, chars] = m; |
| 78 | 86 | if (cdata !== undefined) text += cdata.replace(/&/g, "&").replace(/</g, "<"); |
| 79 | 87 | else if (chars !== undefined) { |
| @@ -95,8 +103,8 @@ export function parseKml(source: string): Kml | undefined { | ||
| 95 | 103 | } catch { |
| 96 | 104 | return undefined; |
| 97 | 105 | } |
| 98 | if (!sawRoot || stack.length > 0 || total === 0) return undefined; | |
| 99 | return { placemarks, total }; | |
| 106 | if (!sawRoot || (stack.length > 0 && !cut) || total === 0) return undefined; | |
| 107 | return cut ? { placemarks, total, cut } : { placemarks, total }; | |
| 100 | 108 | } |
| 101 | 109 | |
| 102 | 110 | const clip = (s: string): string => (s.length > TEXT_CAP ? `${s.slice(0, TEXT_CAP)}…` : s); |
| @@ -106,11 +114,15 @@ export function kml(input: RenderInput): Rendered { | ||
| 106 | 114 | const parsed = parseKml(new TextDecoder().decode(input.body)); |
| 107 | 115 | if (parsed === undefined) return { content: html``, lines: 0, fallback: "This file is not a readable KML map." }; |
| 108 | 116 | const { placemarks, total } = parsed; |
| 109 | const label = `${total.toLocaleString("en")} placemark${total === 1 ? "" : "s"}`; | |
| 110 | const note = | |
| 117 | const label = `${parsed.cut === true ? "at least " : ""}${total.toLocaleString("en")} placemark${total === 1 ? "" : "s"}`; | |
| 118 | const showing = | |
| 111 | 119 | total > placemarks.length |
| 112 | 120 | ? html`<p class="muted small">Showing the first ${PLACEMARK_CAP.toLocaleString("en")} of ${label}.</p>` |
| 113 | 121 | : html``; |
| 122 | const note = | |
| 123 | parsed.cut === true | |
| 124 | ? html`${showing}<p class="muted small">The file goes on past the ${TOKEN_CAP.toLocaleString("en")} tags the page reads, so only its first part is listed.</p>` | |
| 125 | : showing; | |
| 114 | 126 | const content = html`<div class="gj-table" tabindex="0" role="region" aria-label="Placemarks"><table> |
| 115 | 127 | <caption class="sr-only">${label}</caption> |
| 116 | 128 | <thead><tr><th scope="col">Name</th><th scope="col">Description</th><th scope="col">Longitude</th><th scope="col">Latitude</th></tr></thead> |
src/web/render/timeline-table.ts +9
| @@ -6,12 +6,21 @@ | ||
| 6 | 6 | |
| 7 | 7 | import { html, type Html } from "../html.ts"; |
| 8 | 8 | import { fileSize } from "../ui.ts"; |
| 9 | import { TOKEN_CAP } from "./gpx.ts"; | |
| 9 | 10 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 10 | 11 | |
| 11 | 12 | /** Tracks and rows drawn, whatever the file holds. */ |
| 12 | 13 | export const TRACK_CAP = 50; |
| 13 | 14 | export const ROW_CAP = 500; |
| 14 | 15 | |
| 16 | /** | |
| 17 | * Clips an XML timeline (fcpxml.ts, kdenlive.ts) reads at most: each costs some microseconds, and a | |
| 18 | * 1 MB file can hold tens of thousands. Past it, or past the tag scanner's `TOKEN_CAP`, the file | |
| 19 | * is not drawn (`TOO_LONG`): its total length needs every clip. | |
| 20 | */ | |
| 21 | export const READ_CLIP_CAP = 10_000; | |
| 22 | export const TOO_LONG = `it is too long to read here (more than ${TOKEN_CAP.toLocaleString("en")} tags or ${READ_CLIP_CAP.toLocaleString("en")} clips)`; | |
| 23 | ||
| 15 | 24 | export interface Cut { |
| 16 | 25 | readonly name: string; |
| 17 | 26 | readonly source: string; |
src/web/render/vendor/yaml.d.mts +2
| @@ -4,6 +4,8 @@ export interface Node { | ||
| 4 | 4 | /** Comment lines above the node. */ |
| 5 | 5 | commentBefore?: string | null; |
| 6 | 6 | comment?: string | null; |
| 7 | /** Offsets into the source: start, end of the value, end of the node. */ | |
| 8 | range?: [number, number, number] | null; | |
| 7 | 9 | } |
| 8 | 10 | export interface Scalar extends Node { |
| 9 | 11 | value: unknown; |
src/web/render/workflow.ts +3
| @@ -12,6 +12,7 @@ import { escapeHtml, html, raw } from "../html.ts"; | ||
| 12 | 12 | import { fileSize } from "../ui.ts"; |
| 13 | 13 | import type { Rendered, RenderInput } from "./renderers.ts"; |
| 14 | 14 | import { parseAllDocuments } from "./vendor/yaml.mjs"; |
| 15 | import { yamlTooLarge } from "./yaml-config.ts"; | |
| 15 | 16 | |
| 16 | 17 | export const JOB_CAP = 100; |
| 17 | 18 | export const STEP_CAP = 200; |
| @@ -76,6 +77,8 @@ function stepOf(raw: unknown): Step { | ||
| 76 | 77 | } |
| 77 | 78 | |
| 78 | 79 | export function parseWorkflow(source: string): Workflow { |
| 80 | const large = yamlTooLarge(source); | |
| 81 | if (large !== undefined) return { error: `it is too large to read here (${large})` }; | |
| 79 | 82 | const docs = parseAllDocuments(source, { maxAliasCount: 100 }); |
| 80 | 83 | const doc = docs[0]; |
| 81 | 84 | if (doc === undefined || docs.length > 1) return { error: "it is not one YAML document" }; |
src/web/render/yaml-config.ts +121 −3
| @@ -21,7 +21,116 @@ export type YamlParsed = | ||
| 21 | 21 | |
| 22 | 22 | const MAX_DEPTH = 64; |
| 23 | 23 | |
| 24 | class Unsupported extends Error {} | |
| 24 | /** | |
| 25 | * The most items a YAML text may hold before it is handed to the parser. An item is a line of | |
| 26 | * block structure (not blank, not a comment, not inside a quoted or block scalar) or a value in a | |
| 27 | * flow collection (`[a, b]` is two: the bracket and the comma). The form draws at most | |
| 28 | * `MAX_FIELDS` (2,000) values, and each costs at most its own line and its parent's, so three | |
| 29 | * times that (pinned in test/config-yaml-toml.test.ts; a literal, since config-form.ts imports | |
| 30 | * this module) is never reached by a file the form could hold. The vendored parser costs some | |
| 31 | * 25 µs a line, so the cap bounds a parse near 150 ms, where 50,000 `key: value` lines (under the | |
| 32 | * 1 MB config cap) would take over a second. | |
| 33 | */ | |
| 34 | export const YAML_ITEM_CAP = 6_000; | |
| 35 | /** | |
| 36 | * Lines of any sort, comments, blanks and scalar text too: the parser spends some 9 µs on a | |
| 37 | * comment line, so 20,000 cost under 200 ms. | |
| 38 | */ | |
| 39 | export const YAML_LINE_CAP = 20_000; | |
| 40 | ||
| 41 | const SPACE = 32; | |
| 42 | const TAB = 9; | |
| 43 | const CR = 13; | |
| 44 | const blank = (c: number): boolean => c === SPACE || c === TAB || c === CR || Number.isNaN(c); | |
| 45 | ||
| 46 | /** | |
| 47 | * Why a YAML text is not handed to the parser, or undefined: more than `YAML_ITEM_CAP` items or | |
| 48 | * `YAML_LINE_CAP` lines, or flow brackets (`[[[[`) or a run of dashes (`- - - -`) nested past | |
| 49 | * `MAX_DEPTH`, which the parser would recurse into for seconds. One pass, line by line: text | |
| 50 | * inside quotes (`"…"`, `'…'`), a block scalar (`|`, `>`) or a comment is skipped, so a long | |
| 51 | * flow list written inside a string never counts as structure. | |
| 52 | */ | |
| 53 | export function yamlTooLarge(text: string): string | undefined { | |
| 54 | let items = 0; | |
| 55 | let lines = 0; | |
| 56 | /** Open flow brackets, carried across lines. */ | |
| 57 | let depth = 0; | |
| 58 | /** The open quote (34 or 39) of a scalar that runs on to the next line, or 0. */ | |
| 59 | let quote = 0; | |
| 60 | /** The indent of the line that opened a block scalar; its text is every line indented more. */ | |
| 61 | let block = -1; | |
| 62 | for (let start = 0; start <= text.length; ) { | |
| 63 | let end = text.indexOf("\n", start); | |
| 64 | if (end === -1) end = text.length; | |
| 65 | if (++lines > YAML_LINE_CAP) return `more than ${YAML_LINE_CAP.toLocaleString("en")} lines`; | |
| 66 | let i = start; | |
| 67 | while (i < end && (text.charCodeAt(i) === SPACE || text.charCodeAt(i) === TAB)) i++; | |
| 68 | const indent = i - start; | |
| 69 | const empty = i === end || (i === end - 1 && text.charCodeAt(i) === CR); | |
| 70 | const next = end + 1; | |
| 71 | if (block >= 0) { | |
| 72 | if (empty || indent > block) { | |
| 73 | start = next; | |
| 74 | continue; | |
| 75 | } | |
| 76 | block = -1; | |
| 77 | } | |
| 78 | if (quote === 0 && (empty || text.charCodeAt(i) === 35)) { | |
| 79 | start = next; | |
| 80 | continue; | |
| 81 | } | |
| 82 | if (quote === 0 && depth === 0 && ++items > YAML_ITEM_CAP) return `more than ${YAML_ITEM_CAP.toLocaleString("en")} items`; | |
| 83 | let dashes = 0; | |
| 84 | /** At a place a new scalar or collection may begin. */ | |
| 85 | let token = quote === 0; | |
| 86 | for (; i < end; i++) { | |
| 87 | const c = text.charCodeAt(i); | |
| 88 | if (quote === 34) { | |
| 89 | if (c === 92) i++; | |
| 90 | else if (c === 34) quote = 0; | |
| 91 | continue; | |
| 92 | } | |
| 93 | if (quote === 39) { | |
| 94 | if (c === 39 && text.charCodeAt(i + 1) === 39) i++; | |
| 95 | else if (c === 39) quote = 0; | |
| 96 | continue; | |
| 97 | } | |
| 98 | if (c === SPACE || c === TAB) continue; | |
| 99 | if (c === 35 && blank(text.charCodeAt(i - 1))) break; | |
| 100 | if (token && (c === 34 || c === 39)) { | |
| 101 | quote = c; | |
| 102 | token = false; | |
| 103 | } else if ((c === 91 || c === 123) && (token || depth > 0)) { | |
| 104 | if (++depth > MAX_DEPTH) return "values nested too deeply"; | |
| 105 | if (++items > YAML_ITEM_CAP) return `more than ${YAML_ITEM_CAP.toLocaleString("en")} items`; | |
| 106 | token = true; | |
| 107 | } else if ((c === 93 || c === 125) && depth > 0) { | |
| 108 | depth--; | |
| 109 | token = false; | |
| 110 | } else if (c === 44 && depth > 0) { | |
| 111 | if (++items > YAML_ITEM_CAP) return `more than ${YAML_ITEM_CAP.toLocaleString("en")} items`; | |
| 112 | token = true; | |
| 113 | } else if (token && depth === 0 && (c === 45 || c === 63) && blank(text.charCodeAt(i + 1))) { | |
| 114 | // `- ` opens a sequence entry, `? ` a complex key; a run of them nests one level each. | |
| 115 | if (++dashes > MAX_DEPTH) return "values nested too deeply"; | |
| 116 | } else if (c === 58 && (blank(text.charCodeAt(i + 1)) || (depth > 0 && text.charCodeAt(i + 1) === 44))) token = true; | |
| 117 | else if (token && depth === 0 && (c === 124 || c === 62)) { | |
| 118 | // `key: |` or `- >-`: the lines indented past this one are the scalar's text. | |
| 119 | block = indent; | |
| 120 | break; | |
| 121 | } else token = false; | |
| 122 | } | |
| 123 | start = next; | |
| 124 | } | |
| 125 | return undefined; | |
| 126 | } | |
| 127 | ||
| 128 | class Unsupported extends Error { | |
| 129 | /** Where in the text the problem is, when one place is (a key written twice). */ | |
| 130 | constructor(message: string, readonly at?: number) { | |
| 131 | super(message); | |
| 132 | } | |
| 133 | } | |
| 25 | 134 | |
| 26 | 135 | const docKey = (i: number): string => `Document ${i + 1}`; |
| 27 | 136 | |
| @@ -43,9 +152,13 @@ function toJson(doc: Document, node: unknown, depth: number, budget: { left: num | ||
| 43 | 152 | } |
| 44 | 153 | if (isMap(node)) { |
| 45 | 154 | const entries: (readonly [string, Json])[] = []; |
| 155 | // The parser's own check of each key against every key before it is quadratic; a set is not. | |
| 156 | const seen = new Set<string>(); | |
| 46 | 157 | for (const pair of node.items) { |
| 47 | 158 | if (!isScalar(pair.key) || typeof pair.key.value !== "string") |
| 48 | 159 | throw new Unsupported("a key that is not plain text"); |
| 160 | if (seen.has(pair.key.value)) throw new Unsupported(`the key ${JSON.stringify(pair.key.value)} twice`, pair.key.range?.[0]); | |
| 161 | seen.add(pair.key.value); | |
| 49 | 162 | entries.push([pair.key.value, toJson(doc, pair.value, depth + 1, budget)]); |
| 50 | 163 | } |
| 51 | 164 | return { t: "object", entries }; |
| @@ -66,7 +179,9 @@ function firstError(docs: readonly Document[]): ParseError | undefined { | ||
| 66 | 179 | } |
| 67 | 180 | |
| 68 | 181 | export function parseYaml(text: string): YamlParsed { |
| 69 | const docs = parseAllDocuments(text, { prettyErrors: true }); | |
| 182 | const large = yamlTooLarge(text); | |
| 183 | if (large !== undefined) return { ok: false, error: { message: `The form cannot hold ${large}`, line: 1, column: 1 } }; | |
| 184 | const docs = parseAllDocuments(text, { prettyErrors: true, uniqueKeys: false }); | |
| 70 | 185 | const error = firstError(docs); |
| 71 | 186 | if (error !== undefined) return { ok: false, error }; |
| 72 | 187 | try { |
| @@ -76,7 +191,10 @@ export function parseYaml(text: string): YamlParsed { | ||
| 76 | 191 | return { ok: true, value: { t: "object", entries: values.map((v, i) => [docKey(i), v] as const) } }; |
| 77 | 192 | } catch (e) { |
| 78 | 193 | if (!(e instanceof Unsupported)) throw e; |
| 79 | return { ok: false, error: { message: `The form cannot hold ${e.message}`, line: 1, column: 1 } }; | |
| 194 | const before = e.at === undefined ? "" : text.slice(0, e.at); | |
| 195 | const line = before.split("\n").length; | |
| 196 | const column = before.length - before.lastIndexOf("\n"); | |
| 197 | return { ok: false, error: { message: `The form cannot hold ${e.message}`, line, column } }; | |
| 80 | 198 | } |
| 81 | 199 | } |
| 82 | 200 |
test/config-yaml-toml.test.ts +52 −1
| @@ -5,7 +5,8 @@ | ||
| 5 | 5 | |
| 6 | 6 | import { describe, expect, test } from "bun:test"; |
| 7 | 7 | import { formatOf, isFormConfig, languageOf, parseConfig, writeConfig } from "../src/web/render/config-format.ts"; |
| 8 | import { configFields } from "../src/web/render/config-form.ts"; | |
| 8 | import { configFields, MAX_FIELDS } from "../src/web/render/config-form.ts"; | |
| 9 | import { YAML_ITEM_CAP, YAML_LINE_CAP, yamlTooLarge } from "../src/web/render/yaml-config.ts"; | |
| 9 | 10 | import { getAt, updateAt, type Json } from "../src/web/render/json-doc.ts"; |
| 10 | 11 | import { findSchema, schemaRefusal } from "../src/web/render/json-schema.ts"; |
| 11 | 12 | import { rendererFor } from "../src/web/render/renderers.ts"; |
| @@ -267,3 +268,53 @@ describe("the vendored bundles say what they are", () => { | ||
| 267 | 268 | expect(doc).toContain(`\`toml-patch.mjs\` sha256 \`${sha(toml)}\``); |
| 268 | 269 | }); |
| 269 | 270 | }); |
| 271 | ||
| 272 | describe("YAML read in bounded time (#15720)", () => { | |
| 273 | test("a key written twice is refused at its line and column, by the form's own check", () => { | |
| 274 | const parsed = parseConfig("a.yaml", "a: 1\nb: 2\n # note\nb: 3\n"); | |
| 275 | expect(parsed.ok).toBe(false); | |
| 276 | if (parsed.ok) return; | |
| 277 | expect(parsed.error).toEqual({ message: 'The form cannot hold the key "b" twice', line: 4, column: 1 }); | |
| 278 | }); | |
| 279 | ||
| 280 | test("a key written twice inside a nested map names that line", () => { | |
| 281 | const parsed = parseConfig("a.yaml", "top:\n x: 1\n x: 2\n"); | |
| 282 | expect(parsed.ok ? undefined : parsed.error).toEqual({ message: 'The form cannot hold the key "x" twice', line: 3, column: 3 }); | |
| 283 | }); | |
| 284 | ||
| 285 | test("a file past the item cap is refused before it is parsed; comments and blanks do not count", () => { | |
| 286 | const keys = (n: number): string => Array.from({ length: n }, (_, i) => `k${i}: v`).join("\n"); | |
| 287 | expect(parseConfig("a.yaml", keys(YAML_ITEM_CAP + 1)).ok).toBe(false); | |
| 288 | expect(yamlTooLarge(keys(YAML_ITEM_CAP))).toBeUndefined(); | |
| 289 | const commented = Array.from({ length: 1_000 }, (_, i) => `# c${i}\n\nk${i}: v`).join("\n"); | |
| 290 | expect(parseConfig("a.yaml", commented).ok).toBe(true); | |
| 291 | }); | |
| 292 | ||
| 293 | test("the item cap is three times the form's MAX_FIELDS, so a form-sized file is never refused", () => { | |
| 294 | expect(YAML_ITEM_CAP).toBe(3 * MAX_FIELDS); | |
| 295 | // MAX_FIELDS values as a list of maps, each value on its own line under a parent line. | |
| 296 | const people = Array.from({ length: MAX_FIELDS / 2 }, (_, i) => ` - name: p${i}\n age: ${i}`).join("\n"); | |
| 297 | expect(yamlTooLarge(`people:\n${people}\n`)).toBeUndefined(); | |
| 298 | expect(parseConfig("a.yaml", `people:\n${people}\n`).ok).toBe(true); | |
| 299 | }); | |
| 300 | ||
| 301 | test("brackets, commas and dashes inside quoted and block scalars are text, not structure", () => { | |
| 302 | const flow = `[${"1, ".repeat(YAML_ITEM_CAP)}1]`; | |
| 303 | const deep = "[".repeat(200); | |
| 304 | expect(yamlTooLarge(`a: "${flow}"\nb: '${deep} it''s'\n`)).toBeUndefined(); | |
| 305 | expect(yamlTooLarge(`a: "${flow.slice(0, 40)}\n ${flow}"\n`)).toBeUndefined(); | |
| 306 | expect(yamlTooLarge(`script: |\n ${flow}\n ${deep}\n\n - - - -\nnext: >-\n ${deep}\nlast: 1\n`)).toBeUndefined(); | |
| 307 | expect(yamlTooLarge(`a: x # ${flow}\n`)).toBeUndefined(); | |
| 308 | expect(yamlTooLarge("url: http://h/a[0],b{1}\n")).toBeUndefined(); | |
| 309 | }); | |
| 310 | ||
| 311 | test("real flow structure past the caps is still refused", () => { | |
| 312 | expect(yamlTooLarge(`a: [${"1, ".repeat(YAML_ITEM_CAP)}1]\n`)).toMatch(/more than 6,000 items/); | |
| 313 | expect(yamlTooLarge(`a: ${"[".repeat(65)}${"]".repeat(65)}\n`)).toBe("values nested too deeply"); | |
| 314 | expect(yamlTooLarge(`a: [\n${"[".repeat(65)}\n]\n`)).toBe("values nested too deeply"); | |
| 315 | expect(yamlTooLarge(`${"- ".repeat(65)}x\n`)).toBe("values nested too deeply"); | |
| 316 | // After a block scalar ends, the file is read as structure again. | |
| 317 | expect(yamlTooLarge(`a: |\n text\nb: ${"[".repeat(65)}\n`)).toBe("values nested too deeply"); | |
| 318 | expect(yamlTooLarge("# a\n".repeat(YAML_LINE_CAP + 1))).toMatch(/more than 20,000 lines/); | |
| 319 | }); | |
| 320 | }); |
test/render-gpx.test.ts +4 −2
| @@ -58,10 +58,12 @@ describe("gpx", () => { | ||
| 58 | 58 | }); |
| 59 | 59 | |
| 60 | 60 | test("more than 20,000 points are thinned evenly, ends kept", () => { |
| 61 | // Under READ_POINT_CAP (25,000), past which the scan stops: every point is read, then thinned. | |
| 61 | 62 | let pts = ""; |
| 62 | for (let i = 0; i < 30_000; i++) pts += `<trkpt lat="${(i / 30_000).toFixed(6)}" lon="0"/>`; | |
| 63 | for (let i = 0; i < 24_000; i++) pts += `<trkpt lat="${(i / 24_000).toFixed(6)}" lon="0"/>`; | |
| 63 | 64 | const g = parseGpx(`<gpx><trk><trkseg>${pts}</trkseg></trk></gpx>`)!; |
| 64 | expect(g.count).toBe(30_000); | |
| 65 | expect(g.count).toBe(24_000); | |
| 66 | expect(g.cut).toBeUndefined(); | |
| 65 | 67 | const path = outline(g).paths[0]!; |
| 66 | 68 | expect(path.split("L").length).toBeLessThanOrEqual(20_000); |
| 67 | 69 | expect(path.split("L").length).toBeGreaterThan(19_000); |
test/render-hostile.test.ts added +217
| @@ -0,0 +1,217 @@ | ||
| 1 | /** | |
| 2 | * One table for every renderer's byte cap and its answer to a hostile file (#15720). | |
| 3 | * | |
| 4 | * First the registry: every kind `RENDERERS` draws has a positive cap in `RENDER_CAP` (a kind | |
| 5 | * without one fails by name), and a file one byte over that cap, named so its kind is read from | |
| 6 | * the name alone, is never handed to the renderer: the page offers Download instead. | |
| 7 | * | |
| 8 | * Then the bombs: archive, JSON, YAML, XML and CSV files shaped to stall a parser (a gzip that | |
| 9 | * inflates past the archive reader's cap, nesting hundreds of thousands deep, a 5 MB single line, | |
| 10 | * half a million cells in one record, entity expansion). Each goes through `rendererFor` as the | |
| 11 | * blob page sends it and must return, never throw, with its answer: the "too large", "too deep" | |
| 12 | * or "too long" reason, or the cut it made, checked as data where the renderer exposes it (the | |
| 13 | * GPX and KML `cut` flag, the CSV column count, the YAML item cap). | |
| 14 | * | |
| 15 | * The caps are what these assertions hold; time is only a guard against a cap that stopped | |
| 16 | * working, so it is wall clock, per case, at `GUARD_MS`: some ten times the slowest case here | |
| 17 | * (the gzip bomb inflates `GUNZIP_CAP`, about 130 ms on a quiet box), so a loaded check box does | |
| 18 | * not flake it. Bodies are built before the clock starts. | |
| 19 | * | |
| 20 | * SVG is listed for the claim that the page never parses it (it is drawn by the browser, from the | |
| 21 | * media route, in an <img>): that pins the route, and is not a bomb check on any renderer. | |
| 22 | * | |
| 23 | * test/fuzz-renderers.test.ts holds that no input throws or smuggles markup; this file holds caps | |
| 24 | * and time, and does not repeat that. | |
| 25 | */ | |
| 26 | import { describe, expect, test } from "bun:test"; | |
| 27 | import { gzipSync } from "node:zlib"; | |
| 28 | import { RENDERERS, rendererFor } from "../src/web/render/renderers.ts"; | |
| 29 | import { kindByName, kindMatches, RENDER_CAP, type FileKind } from "../src/web/render/kinds.ts"; | |
| 30 | import { GUNZIP_CAP, ENTRY_CAP } from "../src/web/render/archive.ts"; | |
| 31 | import { CUT_NOTE, parseGpx, READ_POINT_CAP, TOKEN_CAP } from "../src/web/render/gpx.ts"; | |
| 32 | import { parseKml } from "../src/web/render/kml.ts"; | |
| 33 | import { TOO_LONG } from "../src/web/render/timeline-table.ts"; | |
| 34 | import { YAML_ITEM_CAP, YAML_LINE_CAP } from "../src/web/render/yaml-config.ts"; | |
| 35 | import { COLUMN_CAP } from "../src/web/render/csv.ts"; | |
| 36 | import type { Blob } from "../src/view/source.ts"; | |
| 37 | import { zip } from "./helpers/zip.ts"; | |
| 38 | ||
| 39 | /** The most wall-clock time one hostile render may take, in milliseconds: a guard, not a budget. */ | |
| 40 | const GUARD_MS = 2_000; | |
| 41 | const MB = 1_000_000; | |
| 42 | const enc = (s: string): Uint8Array => new TextEncoder().encode(s); | |
| 43 | ||
| 44 | describe("every renderer has a byte cap", () => { | |
| 45 | const drawn = Object.keys(RENDERERS) as FileKind[]; | |
| 46 | ||
| 47 | test("the registry draws kinds", () => { | |
| 48 | expect(drawn.length).toBeGreaterThan(40); | |
| 49 | }); | |
| 50 | ||
| 51 | for (const kind of drawn) | |
| 52 | test(`${kind} has a positive cap in RENDER_CAP`, () => { | |
| 53 | const cap = RENDER_CAP[kind] as number | undefined; | |
| 54 | expect(cap, `RENDER_CAP has no entry for "${kind}"`).toBeDefined(); | |
| 55 | expect(Number.isFinite(cap) && cap! > 0, `RENDER_CAP.${kind} is ${cap}`).toBe(true); | |
| 56 | }); | |
| 57 | ||
| 58 | // A name the registry reads as the kind by itself: an extension (`.gpx`) or an exact name | |
| 59 | // (`Dockerfile`). Kinds told only by their bytes (a JUnit root, a DXF head) have none. | |
| 60 | const named = (kind: FileKind): string | undefined => | |
| 61 | kindMatches(kind) | |
| 62 | .map((m) => (m.startsWith(".") ? `file${m}` : m)) | |
| 63 | .find((path) => !/[*\s<]/.test(path) && kindByName(path) === kind); | |
| 64 | ||
| 65 | const checked = drawn.filter((kind) => named(kind) !== undefined); | |
| 66 | test("most drawn kinds can be named for the over-cap check", () => { | |
| 67 | expect(checked.length).toBeGreaterThan(drawn.length - 8); | |
| 68 | }); | |
| 69 | for (const kind of checked) | |
| 70 | test(`a ${kind} file one byte over its cap is not drawn`, () => { | |
| 71 | const path = named(kind)!; | |
| 72 | const over: Blob = { kind: "too_large", size: RENDER_CAP[kind] + 1 }; | |
| 73 | expect(rendererFor(path, over)).toBeUndefined(); | |
| 74 | }); | |
| 75 | }); | |
| 76 | ||
| 77 | interface Bomb { | |
| 78 | readonly path: string; | |
| 79 | readonly body: () => Uint8Array; | |
| 80 | /** The answer the page gives, in its fallback reason or its drawn HTML. */ | |
| 81 | readonly says: RegExp; | |
| 82 | /** Set for a body the page reads only a prefix of (a big table or JSON file). */ | |
| 83 | readonly size?: number; | |
| 84 | /** The cap, checked as data on the body the renderer was given. */ | |
| 85 | readonly holds?: (text: string) => void; | |
| 86 | } | |
| 87 | ||
| 88 | /** Cells in the one-record CSV: 1 MB of `a,`. */ | |
| 89 | const CELLS = 500_000; | |
| 90 | ||
| 91 | const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); | |
| 92 | ||
| 93 | const nested = (n: number, open: string, close: string, root = ""): string => | |
| 94 | `${root === "" ? "" : `<${root}>`}${open.repeat(n)}${close.repeat(n)}${root === "" ? "" : `</${root}>`}`; | |
| 95 | const flatYaml = (n: number): string => Array.from({ length: n }, (_, i) => `k${i}: v`).join("\n"); | |
| 96 | ||
| 97 | /** Concatenated gzip members of 1 MiB of zeros each (1 KiB packed): past `GUNZIP_CAP` unpacked. */ | |
| 98 | function gzipBomb(): Uint8Array { | |
| 99 | const one = gzipSync(new Uint8Array(1024 * 1024), { level: 9 }); | |
| 100 | const members = GUNZIP_CAP / (1024 * 1024) + 2; | |
| 101 | const out = new Uint8Array(one.length * members); | |
| 102 | for (let i = 0; i < members; i++) out.set(one, i * one.length); | |
| 103 | return out; | |
| 104 | } | |
| 105 | ||
| 106 | /** Files the bomb shapes take, by kind family. Each is a few MB at most, under its kind's cap. */ | |
| 107 | const BOMBS: readonly Bomb[] = [ | |
| 108 | // Archives: nothing is unpacked but a gzip, and that under GUNZIP_CAP. | |
| 109 | { path: "bomb.tar.gz", body: gzipBomb, says: /unpacks to more than/ }, | |
| 110 | { path: "claims.zip", body: () => zip({ "a.bin": new Uint8Array(1024) }, 0xfffffffe), says: /archive-view/ }, | |
| 111 | { | |
| 112 | path: "many.zip", | |
| 113 | body: () => zip(Object.fromEntries(Array.from({ length: ENTRY_CAP + 500 }, (_, i) => [`f${i}`, ""]))), | |
| 114 | says: /500 more entries are not listed/, | |
| 115 | }, | |
| 116 | // JSON: nesting deeper than any parser here recurses, and a 1 MB string. | |
| 117 | { path: "deep.json", body: () => enc(nested(400_000, "[", "]")), says: /Nested too deeply/ }, | |
| 118 | { path: "deep-object.json", body: () => enc(`${'{"a":'.repeat(150_000)}1${"}".repeat(150_000)}`), says: /Nested too deeply/ }, | |
| 119 | { path: "line.json", body: () => enc(`"${"x".repeat(MB - 10)}"`), says: /config-form/ }, | |
| 120 | { | |
| 121 | path: "big.json", | |
| 122 | body: () => enc("[".repeat(4 * MB)), | |
| 123 | size: 50 * MB, | |
| 124 | says: /not parsed/, | |
| 125 | }, | |
| 126 | ...["a.ipynb", "a.har", "a.geojson", "a.excalidraw", "a.sarif", "a.otio", "openapi.json"].map( | |
| 127 | (path): Bomb => ({ path, body: () => enc(nested(400_000, "[", "]")), says: /\bno\b|\bnot\b|Nested too deeply/i }), | |
| 128 | ), | |
| 129 | // YAML is read by a parser that costs microseconds a token: it is counted before it is parsed. | |
| 130 | { path: "deep.yaml", body: () => enc(nested(400_000, "[", "]")), says: /nested too deeply/ }, | |
| 131 | { path: "dashes.yaml", body: () => enc(`${"- ".repeat(400_000)}x`), says: /nested too deeply/ }, | |
| 132 | { path: "flat.yaml", body: () => enc(flatYaml(50_000)), says: new RegExp(`more than ${YAML_ITEM_CAP.toLocaleString("en")} items`) }, | |
| 133 | { | |
| 134 | path: "comments.yaml", | |
| 135 | body: () => enc(Array.from({ length: 90_000 }, (_, i) => `# ${i}`).join("\n")), | |
| 136 | says: new RegExp(`more than ${YAML_LINE_CAP.toLocaleString("en")} lines`), | |
| 137 | }, | |
| 138 | { path: ".github/workflows/ci.yml", body: () => enc(flatYaml(50_000)), says: /too large to read here/ }, | |
| 139 | { path: "compose.yaml", body: () => enc(flatYaml(50_000)), says: /too large to read here/ }, | |
| 140 | // XML: deep nesting, a 5 MB text, the billion laughs (never expanded) and long flat files. | |
| 141 | { path: "deep.xml", body: () => enc(nested(400_000, "<a>", "</a>", "r")), says: /more elements not shown/ }, | |
| 142 | { path: "line.xml", body: () => enc(`<r>${"x".repeat(5 * MB - 20)}</r>`), says: /xml-tree/ }, | |
| 143 | { path: "laughs.xml", body: () => enc(laughs("r")), says: /&l10;|xml-tree/ }, | |
| 144 | { path: "a.gpx", body: () => enc(nested(400_000, "<a>", "</a>", "gpx")), says: /not a readable GPX/ }, | |
| 145 | { | |
| 146 | path: "points.gpx", | |
| 147 | body: () => enc(`<gpx><trk><trkseg>\n${'<trkpt lat="1.5" lon="2.5"/>\n'.repeat(READ_POINT_CAP * 4)}</trkseg></trk></gpx>`), | |
| 148 | says: new RegExp(CUT_NOTE.slice(0, 40)), | |
| 149 | holds: (text) => { | |
| 150 | const read = parseGpx(text)!; | |
| 151 | expect(read.cut).toBe(true); | |
| 152 | expect(read.count).toBeLessThanOrEqual(READ_POINT_CAP); | |
| 153 | }, | |
| 154 | }, | |
| 155 | { path: "a.kml", body: () => enc(nested(400_000, "<a>", "</a>", "kml")), says: /not a readable KML/ }, | |
| 156 | { | |
| 157 | path: "places.kml", | |
| 158 | body: () => enc(`<kml><Document>\n${"<Placemark><name>a</name></Placemark>\n".repeat(TOKEN_CAP)}</Document></kml>`), | |
| 159 | says: /at least .* placemarks/, | |
| 160 | holds: (text) => expect(parseKml(text)?.cut).toBe(true), | |
| 161 | }, | |
| 162 | { path: "a.rss", body: () => enc(nested(400_000, "<a>", "</a>", "rss")), says: /nest too deeply/ }, | |
| 163 | { path: "a.opml", body: () => enc(nested(400_000, "<a>", "</a>", "opml")), says: /nest too deeply/ }, | |
| 164 | { path: "TEST-a.xml", body: () => enc(nested(400_000, "<a>", "</a>", "testsuites")), says: /nest too deeply/ }, | |
| 165 | { path: "a.drawio", body: () => enc(nested(120_000, "<a>", "</a>", "mxfile")), says: /not a draw\.io file/ }, | |
| 166 | { path: "a.fcpxml", body: () => enc(nested(60_000, "<clip>", "</clip>", "fcpxml")), says: new RegExp(escape(TOO_LONG)) }, | |
| 167 | { | |
| 168 | path: "clips.fcpxml", | |
| 169 | body: () => enc(`<fcpxml><spine>${'<clip name="a" duration="1s"/>'.repeat(30_000)}</spine></fcpxml>`), | |
| 170 | says: new RegExp(escape(TOO_LONG)), | |
| 171 | }, | |
| 172 | { path: "a.kdenlive", body: () => enc(nested(120_000, "<a>", "</a>", "mlt")), says: new RegExp(escape(TOO_LONG)) }, | |
| 173 | // CSV: one record of half a million cells (all counted, `COLUMN_CAP` kept), a quote never | |
| 174 | // closed, a 10 MB JSON line. | |
| 175 | { path: "line.csv", body: () => enc("a,".repeat(CELLS - 1)), says: new RegExp(`Showing ${COLUMN_CAP} of ${CELLS.toLocaleString()} columns`) }, | |
| 176 | { path: "line.tsv", body: () => enc("a\t".repeat(CELLS - 1)), says: new RegExp(`Showing ${COLUMN_CAP} of ${CELLS.toLocaleString()} columns`) }, | |
| 177 | { path: "quote.csv", body: () => enc(`"${"x".repeat(10 * MB - 2)}`), says: /never closed/ }, | |
| 178 | { path: "line.jsonl", body: () => enc(`{"a":"${"x".repeat(10 * MB - 20)}"}`), says: /csv-view/ }, | |
| 179 | // SVG is drawn by the browser from the media route, in an <img>: the page never parses it. This | |
| 180 | // pins that route; it checks no SVG parser, since the forge has none. | |
| 181 | { path: "laughs.svg", body: () => enc(laughs("svg")), says: /imgview/ }, | |
| 182 | { path: "deep.svg", body: () => enc(nested(400_000, "<g>", "</g>", "svg")), says: /imgview/ }, | |
| 183 | ]; | |
| 184 | ||
| 185 | /** Ten levels of ten entity references each: 10^10 "ha" if anything expanded them. */ | |
| 186 | function laughs(root: string): string { | |
| 187 | const entities = Array.from({ length: 10 }, (_, i) => `<!ENTITY l${i + 1} "${`&l${i};`.repeat(10)}">`).join(""); | |
| 188 | return `<?xml version="1.0"?><!DOCTYPE l [<!ENTITY l0 "ha">${entities}]><${root} xmlns="http://www.w3.org/2000/svg"><text>&l10;</text></${root}>`; | |
| 189 | } | |
| 190 | ||
| 191 | describe("a hostile file renders its answer, and the cap holds", () => { | |
| 192 | for (const bomb of BOMBS) | |
| 193 | test(bomb.path, () => { | |
| 194 | const body = bomb.body(); | |
| 195 | const size = bomb.size ?? body.length; | |
| 196 | const blob: Blob = { kind: "text", body, size, ...(bomb.size === undefined ? {} : { partial: true }) }; | |
| 197 | const chosen = rendererFor(bomb.path, blob); | |
| 198 | expect(chosen, `${bomb.path}: no renderer, or ${body.length} bytes is over its cap`).toBeDefined(); | |
| 199 | const input = { | |
| 200 | path: bomb.path, | |
| 201 | size, | |
| 202 | body: chosen!.body, | |
| 203 | media: `/o/r/media/main/${bomb.path}`, | |
| 204 | download: `/o/r/raw/main/${bomb.path}`, | |
| 205 | ...(bomb.size === undefined ? {} : { partial: true }), | |
| 206 | }; | |
| 207 | const start = performance.now(); | |
| 208 | const out = chosen!.render(input); | |
| 209 | const ms = performance.now() - start; | |
| 210 | const said = `${out.fallback ?? ""} ${String(out.content)}`; | |
| 211 | expect(said).toMatch(bomb.says); | |
| 212 | bomb.holds?.(new TextDecoder().decode(chosen!.body)); | |
| 213 | // The answer does not outgrow the file: nothing expanded. A view may echo the text, escaped. | |
| 214 | expect(String(out.content).length).toBeLessThan(3 * body.length + 65_536); | |
| 215 | expect(ms, `${bomb.path} took ${ms.toFixed(0)} ms`).toBeLessThan(GUARD_MS); | |
| 216 | }); | |
| 217 | }); |
test/render-kml.test.ts +19
| @@ -1,6 +1,8 @@ | ||
| 1 | 1 | /** KML files as a placemark table: a good file, a malformed one, a hostile entity. */ |
| 2 | 2 | import { describe, expect, test } from "bun:test"; |
| 3 | 3 | import { kml, parseKml, PLACEMARK_CAP } from "../src/web/render/kml.ts"; |
| 4 | import { TOKEN_CAP } from "../src/web/render/gpx.ts"; | |
| 5 | import { kmlCutRow, kmlTable } from "../src/tui/screens/kml.ts"; | |
| 4 | 6 | import { fileKind } from "../src/web/render/kinds.ts"; |
| 5 | 7 | import { RENDERERS } from "../src/web/render/renderers.ts"; |
| 6 | 8 | |
| @@ -51,3 +53,20 @@ describe("kml", () => { | ||
| 51 | 53 | expect(out).toContain("&b; &a; &lol;"); |
| 52 | 54 | }); |
| 53 | 55 | }); |
| 56 | ||
| 57 | describe("kml in the terminal, cut by the scan (#15720)", () => { | |
| 58 | test("a file past TOKEN_CAP tags leads with a row saying so; the row count stays the total read", () => { | |
| 59 | const parsed = parseKml(`<kml><Document>${"<Placemark><name>a</name></Placemark>".repeat(TOKEN_CAP)}</Document></kml>`); | |
| 60 | expect(parsed?.cut).toBe(true); | |
| 61 | const table = kmlTable(`<kml><Document>${"<Placemark><name>a</name></Placemark>".repeat(TOKEN_CAP)}</Document></kml>`)!; | |
| 62 | expect(table.rows[0]).toEqual(kmlCutRow(parsed!.total)); | |
| 63 | expect(table.rows[0]![1]).toContain("at least"); | |
| 64 | expect(table.rows.length + table.more).toBe(parsed!.total); | |
| 65 | }); | |
| 66 | ||
| 67 | test("a whole file has no such row", () => { | |
| 68 | const table = kmlTable("<kml><Placemark><name>Harbour</name></Placemark></kml>")!; | |
| 69 | expect(table.rows).toEqual([["Harbour", "", "", ""]]); | |
| 70 | expect(table.more).toBe(0); | |
| 71 | }); | |
| 72 | }); |
test/tui-workspace-formats.test.ts +38
| @@ -12,6 +12,7 @@ import type { App as Forge } from "../src/app.ts"; | ||
| 12 | 12 | import type { User } from "../src/core/users.ts"; |
| 13 | 13 | import { quietLogs } from "./helpers/globals.ts"; |
| 14 | 14 | import { workspaceFixture, type Fixture } from "./helpers/tui-workspace.ts"; |
| 15 | import { READ_POINT_CAP, TOKEN_CAP } from "../src/web/render/gpx.ts"; | |
| 15 | 16 | |
| 16 | 17 | quietLogs(); |
| 17 | 18 | |
| @@ -438,6 +439,43 @@ describe("the terminal workspace, by file type", () => { | ||
| 438 | 439 | } |
| 439 | 440 | }); |
| 440 | 441 | |
| 442 | test("a .gpx longer than the scan reads says, as a fact, that only its first part was read", async () => { | |
| 443 | const made = await createRepo(forge, alice, { name: "long-tracks", visibility: "public", description: "routes" }); | |
| 444 | if (!made.ok) throw new Error("repo failed"); | |
| 445 | const points = '<trkpt lat="10" lon="20"/>'.repeat(READ_POINT_CAP + 10); | |
| 446 | await commitToBranch(forge, alice, made.value, { | |
| 447 | message: "seed", | |
| 448 | files: [{ path: "long.gpx", content: `<gpx><trk><trkseg>${points}</trkseg></trk></gpx>` }], | |
| 449 | }); | |
| 450 | const h = boot(); | |
| 451 | try { | |
| 452 | await h.settle(); | |
| 453 | await open(h, "long-tracks"); | |
| 454 | await openFile(h, "long.gpx"); | |
| 455 | expect(h.text()).toContain("5 facts"); | |
| 456 | expect(h.text()).toContain("first part only"); | |
| 457 | } finally { | |
| 458 | h.stop(); | |
| 459 | } | |
| 460 | }); | |
| 461 | ||
| 462 | test("a .kml longer than the scan reads opens on a row saying only its first part was read", async () => { | |
| 463 | const made = await createRepo(forge, alice, { name: "long-places", visibility: "public", description: "places" }); | |
| 464 | if (!made.ok) throw new Error("repo failed"); | |
| 465 | // 600 placemarks, then past TOKEN_CAP tags of four bytes each: some 400 KB. | |
| 466 | const marks = `${"<Placemark/>".repeat(600)}${"<a/>".repeat(TOKEN_CAP)}`; | |
| 467 | await commitToBranch(forge, alice, made.value, { message: "seed", files: [{ path: "long.kml", content: `<kml><Document>${marks}</Document></kml>` }] }); | |
| 468 | const h = boot(); | |
| 469 | try { | |
| 470 | await h.settle(); | |
| 471 | await open(h, "long-places"); | |
| 472 | await openFile(h, "long.kml"); | |
| 473 | expect(h.text()).toContain("(file goes on)"); | |
| 474 | } finally { | |
| 475 | h.stop(); | |
| 476 | } | |
| 477 | }); | |
| 478 | ||
| 441 | 479 | test("a .kml opens as its placemarks, sharing the web parser, and s flips to the source", async () => { |
| 442 | 480 | const made = await createRepo(forge, alice, { name: "maps", visibility: "public", description: "places" }); |
| 443 | 481 | if (!made.ok) throw new Error("repo failed"); |
new above
offline
Time budget on process-wide CPU at 250 ms is too tight next to the 130 ms gzip bomb on a loaded gate; see the body.