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

A file holding a private key shows no part of the key on any view of the Source tab, and a hostile file cannot stall the page #15824

Merged opened this

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

Merged

torque/forge:torque/15811-a-file-holding-a-private-key-shows-no-pa → main 0 commits fork

  • Merged. torque/15811-a-file-holding-a-private-key-shows-no-pa was merged into main as 2917693.

Review

Sign in to review this change.
9 files changed +208 −15
docs/features/file-cert-sbom-wasm.md +1 −1
@@ -4,7 +4,7 @@ row: A PEM certificate, a CycloneDX or SPDX SBOM and a WebAssembly module open a
44 ---
55 # A certificate, a bill of materials and a WebAssembly module open as facts
66
7 - **`.pem`, `.crt`, `.cer`** with a `-----BEGIN` line: subject, issuer, not-before and not-after with `valid`, `expired` or `not yet valid`, and the subject alternative names (50 a certificate, 10 certificates). Parsed by the runtime's `crypto.X509Certificate`. A file with any PRIVATE KEY block says "This file holds a private key" and draws nothing of it, not even a certificate beside it. (The Source tab is still the file as pushed.)
7 - **`.pem`, `.crt`, `.cer`** with a `-----BEGIN` line: subject, issuer, not-before and not-after with `valid`, `expired` or `not yet valid`, and the subject alternative names (50 a certificate, 10 certificates). Parsed by the runtime's `crypto.X509Certificate`. A file holding a private key says "This file holds a private key" and draws nothing of it, not even a certificate beside it, on the Source tab either; see [private-key-files.md](private-key-files.md).
88 - **`.json` with a `bomFormat` or `spdxVersion` key** in its first 4 KB: a table of name, version and licence, 1,000 rows with the count of the rest. Other JSON keeps its view.
99 - **`.wasm`** (head `\0asm`): version, imports (module, name, kind) and exports (name, kind), 200 each with the count of the rest.
1010
docs/features/private-key-files.md added +13
@@ -0,0 +1,13 @@
1 ---
2 topic: Files in the browser
3 row: A file holding a private key shows a notice, not the key
4 ---
5 # A file holding a private key
6
7 A file that carries a PEM private-key header or footer (`-----BEGIN … PRIVATE KEY-----` or `-----END … PRIVATE KEY-----`: plain, RSA, EC, DSA, OpenSSH, PGP, encrypted) is never drawn. The check runs once, where the Source tab reads the blob, before a renderer or the long-file tail is chosen, so a key in a `.md`, a `.json` (line breaks written `\n`), a `.csv`, the tail of an oversized log, or the hex head of a binary is withheld alike. A README holding one is not drawn under the tree.
8
9 - **What shows:** the empty state (`empty`, the component the binary and too-large files use) titled *Private key*, with the shared sentence `PRIVATE_KEY_NOTICE` and a Download button and a View raw link beside it. Raw and Download return the file as pushed.
10 - **Quoted headers:** source that only quotes a header (a secret scanner, say) is withheld too; that is accepted, Raw shows it.
11 - **Speed:** the detector finds each `PRIVATE KEY` with `indexOf` and reads only the 51 characters before it with a fixed, bounded pattern, so a hostile file costs one pass (`test/blob-private-key.test.ts` times 200 escaped lines under 50 ms).
12 - **Terminal:** the workspace and its facts view show the same sentence as the file's only line.
13 - **Code:** `src/core/private_key.ts` holds the one detector and sentence; `web/render/cert.ts`, `web/pages/repo.ts` and the terminal import it.
src/core/private_key.ts added +51
@@ -0,0 +1,51 @@
1 /**
2 * The one place the forge decides a file holds a private key, and the one sentence it says instead
3 * of drawing it. The page (`web/pages/repo.ts`), the certificate renderer (`web/render/cert.ts`)
4 * and the terminal (`tui/screens/workspace.ts`, `workspace_facts.ts`) all import these, so they
5 * cannot disagree on a file.
6 *
7 * A file holds a key when it carries a PEM `BEGIN … PRIVATE KEY` header (plain, RSA, EC, DSA,
8 * OpenSSH, PGP, encrypted), or an `END … PRIVATE KEY` footer: the tail of a long file can start
9 * mid-key, and a JSON service-account file writes its line breaks as `\n`, which a header test
10 * does not care about. A source file that only quotes a header is withheld too; Raw still shows it
11 * (#15811 accepts that).
12 *
13 * The scan has no backtracking to speak of: `indexOf` finds each "PRIVATE KEY" (linear in the
14 * text), and a fixed regex reads only the WINDOW characters before it, so a hostile file costs one
15 * pass however its lines are built (#15811: the old pattern doubled per escaped line).
16 */
17
18 /** The one sentence the page and the terminal show in place of a private key's body. */
19 export const PRIVATE_KEY_NOTICE = "This file holds a private key. The forge does not draw it.";
20
21 const NEEDLE = "PRIVATE KEY";
22 /** "-----BEGIN " is 11 characters; a label word before PRIVATE KEY is at most 40 more. */
23 const WINDOW = 51;
24 /**
25 * The header or footer, anchored to end where the needle starts. Bounded: at most 40 label chars.
26 */
27 const HEADER = /-----(?:BEGIN|END) [A-Z0-9 ]{0,40}$/;
28
29 /**
30 * Whether a text (or its bytes, read as Latin-1 so no decode of the whole is needed) holds a key.
31 */
32 export function holdsPrivateKey(body: Uint8Array | string): boolean {
33 if (typeof body === "string") {
34 for (let at = body.indexOf(NEEDLE); at !== -1; at = body.indexOf(NEEDLE, at + 1))
35 if (HEADER.test(body.slice(Math.max(0, at - WINDOW), at))) return true;
36 return false;
37 }
38 const bytes = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
39 for (let at = bytes.indexOf(NEEDLE); at !== -1; at = bytes.indexOf(NEEDLE, at + 1))
40 if (HEADER.test(bytes.toString("latin1", Math.max(0, at - WINDOW), at))) return true;
41 return false;
42 }
43
44 /** Whether any bytes the page could draw of a file (its body, head or tail) hold a private key. */
45 export function blobHoldsPrivateKey(blob: {
46 readonly body?: Uint8Array;
47 readonly head?: Uint8Array;
48 readonly tail?: Uint8Array;
49 }): boolean {
50 return [blob.body, blob.head, blob.tail].some((b) => b !== undefined && holdsPrivateKey(b));
51 }
src/tui/screens/workspace.ts +3 −1
@@ -59,6 +59,7 @@ import { isModelPath, modelFacts } from "../../web/render/model-facts.ts";
5959 import { measureTyped, unitFor } from "../../web/render/measure.ts";
6060 import type { RepoFacts, RepoSource } from "../../view/source.ts";
6161 import { detectLanguage, highlightLines } from "../../web/highlight.ts";
62 import { holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../core/private_key.ts";
6263 import { MAX_COLUMNS, parseCsv, type Table } from "../../text/csv.ts";
6364 import { isNumericColumn, sortRows } from "../../text/csv-sort.ts";
6465 import { parseGeoJson, propertyRows } from "../../web/render/geojson.ts";
@@ -344,7 +345,8 @@ export function buildLines(
344345 // A terminal log carries escapes; the viewer shows its text, never drives
345346 // the terminal or prints "[31m" as if it were the log.
346347 const clean = isLogPath(path) && text.includes("\x1b") ? stripAnsi(text) : text;
347 const body = clean.replace(/\n$/, "");
348 // A private key's body is never drawn: one notice line stands in, as on the page.
349 const body = holdsPrivateKey(clean) ? PRIVATE_KEY_NOTICE : clean.replace(/\n$/, "");
348350 const plain = body.split("\n").map((l) => expandTabs(l));
349351 // The first line is handed to the detector too: a `#!/usr/bin/env python3`
350352 // with no extension, a `.zshrc`, a vim modeline. The name is the strong
src/tui/screens/workspace_facts.ts +3 −2
@@ -9,7 +9,8 @@
99 */
1010
1111 import { fileKind, HEAD_BYTES, RENDER_CAP } from "../../web/render/kinds.ts";
12 import { holdsPrivateKey, readCerts, SAN_CAP } from "../../web/render/cert.ts";
12 import { holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../core/private_key.ts";
13 import { readCerts, SAN_CAP } from "../../web/render/cert.ts";
1314 import { COMPONENT_CAP, parseSbom } from "../../web/render/sbom.ts";
1415 import { parseWasm } from "../../web/render/wasm.ts";
1516 import type { Table } from "../../text/csv.ts";
@@ -23,7 +24,7 @@ export function factsView(path: string, body: Uint8Array, now: number = Date.now
2324 return `This file is over ${RENDER_CAP[kind] / 1_000_000} MB, too large to open here. Download it instead.`;
2425 if (kind === "cert") {
2526 const text = new TextDecoder().decode(body);
26 if (holdsPrivateKey(text)) return "This file holds a private key. The forge does not draw it.";
27 if (holdsPrivateKey(text)) return PRIVATE_KEY_NOTICE;
2728 const { certs, total, bad } = readCerts(text, now);
2829 if (certs.length === 0) return "This file holds no certificate the forge can read.";
2930 const rows = certs.map((c) => [c.subject, c.issuer, `${c.notAfter} (${c.state})`, c.names.slice(0, SAN_CAP).join(", ")]);
src/web/pages/repo.ts +20 −2
@@ -89,6 +89,7 @@ import {
8989 pageHead,
9090 } from "../chrome.ts";
9191 import { codeJs, liveRegionsJs } from "../client.ts";
92 import { blobHoldsPrivateKey, holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../core/private_key.ts";
9293 import { countLines, highlightPrefix } from "../code.ts";
9394 import { tailOf, tailSentence } from "../log_tail.ts";
9495 import { latestWave } from "../../story/waves.ts";
@@ -733,6 +734,7 @@ export async function readmeFor(
733734 const blob = await source.blob(ref, at);
734735 if (!blob.ok || blob.value.kind !== "text") return html``;
735736 if (blob.value.size > MAX_RENDER_BYTES) return html``;
737 if (holdsPrivateKey(blob.value.body)) return html``;
736738 const full = new TextDecoder().decode(blob.value.body);
737739 const cut = whole === undefined ? null : cutAtBlock(full, README_HOME_BYTES);
738740 const text = cut ?? full;
@@ -772,6 +774,17 @@ function tooLargeParts(path: string, size: number, head: Uint8Array | undefined,
772774 return undrawable(path, { size, ...(head !== undefined ? { head } : {}) }, fileSize) ?? { ...fallback, reason: "Over the render cap. Download it instead." };
773775 }
774776
777 /** The notice that stands where a private key's body would be drawn. */
778 function withheldKey(base: string, ref: string, path: string): Html {
779 return empty({
780 icon: "alert",
781 title: "Private key",
782 note: PRIVATE_KEY_NOTICE,
783 action: html`${btn("Download", { href: downloadHref(base, ref, path), variant: "primary", icon: "download" })}
784 ${btn("View raw", { href: `${base}/raw/${encodeURIComponent(ref)}/${path}`, variant: "outline" })}`,
785 });
786 }
787
775788 /** One file, in each of the three states a source can hand one back in. */
776789 export function blobBody(
777790 base: string,
@@ -1285,7 +1298,10 @@ export function renderBlob(
12851298 const base = scope.base;
12861299 const encoded = encodeURIComponent(o.ref);
12871300 const blob = o.blob;
1288 const renderer = blobRenderer(scope, o.path, blob);
1301 // The one key check for this read, before a renderer or the too-large tail is chosen: a key is
1302 // never drawn, whatever the file's type (#15811). Of a binary file only the hex head is drawn.
1303 const withheld = blobHoldsPrivateKey(blob.kind === "binary" ? { body: blob.body.subarray(0, HEX_BYTES) } : blob);
1304 const renderer = withheld ? undefined : blobRenderer(scope, o.path, blob);
12891305 const view: BlobView = renderer ? (o.view ?? "rendered") : "source";
12901306 const drawn =
12911307 view === "rendered" && renderer
@@ -1309,7 +1325,9 @@ export function renderBlob(
13091325 : undefined;
13101326 const fellBack = drawn?.fallback;
13111327 const { content, lines, summary } =
1312 drawn !== undefined && fellBack === undefined
1328 withheld
1329 ? { content: withheldKey(base, o.ref, o.path), lines: 0, summary: undefined }
1330 : drawn !== undefined && fellBack === undefined
13131331 ? drawn
13141332 : {
13151333 ...blobBody(base, o.ref, o.path, blob, o.highlighted, o.all, o.rows, fellBack ?? overCap(o.path, blob)),
src/web/render/cert.ts +6 −8
@@ -1,14 +1,15 @@
11 /**
22 * A PEM certificate (`.pem`, `.crt`, `.cer`) as its facts: subject, issuer, the validity window
33 * with a plain word when it has run out, and the subject alternative names. Parsing is the
4 * runtime's own `crypto.X509Certificate`; no dependency. A file with a PRIVATE KEY block of any
5 * kind is never drawn: it says it holds a private key and nothing else, and no byte of the file is
6 * read into the page. At most `CERT_CAP` certificates and `SAN_CAP` names are drawn, and the page
7 * says how many were left out. Every string is escaped.
4 * runtime's own `crypto.X509Certificate`; no dependency. A file holding a private key
5 * (`holdsPrivateKey` in `core/private_key.ts`) is never drawn: it says it holds a private key and
6 * nothing else, and no byte of the file is read into the page. At most `CERT_CAP` certificates and
7 * `SAN_CAP` names are drawn, and the page says how many were left out. Every string is escaped.
88 */
99
1010 import { X509Certificate } from "node:crypto";
1111 import { escapeHtml, html, raw } from "../html.ts";
12 import { holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../core/private_key.ts";
1213 import { fileSize } from "../ui.ts";
1314 import type { Rendered, RenderInput } from "./renderers.ts";
1415
@@ -25,9 +26,6 @@ export interface CertFacts {
2526 readonly names: readonly string[];
2627 }
2728
28 /** Whether the text opens any PRIVATE KEY block (RSA, EC, encrypted or plain). */
29 export const holdsPrivateKey = (text: string): boolean => /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/.test(text);
30
3129 /** The one line a distinguished name makes: `CN=a, O=b`. */
3230 const oneLine = (dn: string): string => dn.split("\n").join(", ");
3331
@@ -59,7 +57,7 @@ export function cert(input: RenderInput, now: number = Date.now()): Rendered {
5957 return {
6058 lines: 0,
6159 summary: `${fileSize(input.size)} · holds a private key`,
62 content: html`<p><strong>This file holds a private key.</strong></p><p class="muted small">The forge does not draw it. Keep it out of a repository, and replace it if it was ever pushed.</p>`,
60 content: html`<p><strong>${PRIVATE_KEY_NOTICE}</strong></p><p class="muted small">Keep it out of a repository, and replace it if it was ever pushed.</p>`,
6361 };
6462 const { certs, total, bad } = readCerts(text, now);
6563 if (certs.length === 0) return { content: html``, lines: 0, fallback: "This file holds no certificate the forge can read." };
test/blob-private-key.test.ts added +109
@@ -0,0 +1,109 @@
1 import { expect, test } from "bun:test";
2 import type { TreeEntry } from "../src/git/read.ts";
3 import type { Blob, RepoSource } from "../src/view/source.ts";
4 import { readmeFor, renderBlob } from "../src/web/pages/repo.ts";
5
6 // Spelled in pieces so this file does not trip the tree and secret scans.
7 const D = "-".repeat(5);
8 const pem = (kind: string, body = "SECRETBODY123" + "Ab0+".repeat(8)) => `${D}BEGIN ${kind}PRIVATE KEY${D}\n${body}\n${D}END ${kind}PRIVATE KEY${D}\n`;
9 const asText = (s: string) => ({ kind: "text" as const, body: new TextEncoder().encode(s), size: s.length });
10 const scope = { base: "/o/r", facts: { name: "r" }, caps: { write: false }, kind: "local" } as unknown as import("../src/web/scope.ts").RepoScope;
11 const page = (path: string, blob: Blob) =>
12 String(renderBlob(scope, { refs: { branches: ["main"], tags: [] }, ref: "main", path, blob }));
13 const draw = (path: string, s: string) => page(path, asText(s));
14
15 test("a private key's body is not drawn; a notice stands in", () => {
16 for (const kind of ["", "RSA ", "EC ", "OPENSSH ", "ENCRYPTED "]) {
17 const out = draw("k.pem", pem(kind));
18 expect(out).toContain("This file holds a private key");
19 expect(out).not.toContain("SECRETBODY123");
20 expect(out).toContain("Download");
21 expect(out).toContain('href="/o/r/raw/main/k.pem"');
22 expect(out).toContain("View raw");
23 }
24 });
25
26 test("source that quotes a header or footer is withheld too; Raw shows it (accepted in #15811)", () => {
27 const header = `${D}BEGIN PRIVATE KEY${D}`;
28 for (const text of [`const OPEN = "${header}";\nconst x = 1;\n`, `const CLOSE = "${D}END RSA PRIVATE KEY${D}";\n`]) {
29 expect(draw("scan.ts", text)).toContain("This file holds a private key");
30 }
31 // Words that are not a PEM header are drawn.
32 expect(draw("a.md", "Never push a PRIVATE KEY.\n")).toContain("Never push a PRIVATE KEY.");
33 expect(draw("a.txt", "BEGIN PRIVATE KEY without dashes\n")).toContain("without dashes");
34 });
35
36 // No clock (#7824): the old pattern doubled per escaped line, so 10,000 of them never finish
37 // inside the test's timeout; one linear pass answers them at once.
38 test("a BEGIN header and 10,000 escaped-JSON lines with no END are judged, and judged right", async () => {
39 const { holdsPrivateKey } = await import("../src/core/private_key.ts");
40 const hostile = `{"k": "${D}BEGIN PRIVATE KEY${D}\\n${"a b\\n".repeat(10_000)}"}`;
41 const noKey = `{"k": "${"a b\\n".repeat(10_000)}PRIVATE KEY"}`;
42 expect(holdsPrivateKey(hostile)).toBe(true);
43 expect(holdsPrivateKey(new TextEncoder().encode(hostile))).toBe(true);
44 expect(holdsPrivateKey(noKey)).toBe(false);
45 expect(holdsPrivateKey(new TextEncoder().encode(noKey))).toBe(false);
46 });
47
48 test("bytes and text agree, and a key behind a long label or deep in a large file is found", async () => {
49 const { holdsPrivateKey } = await import("../src/core/private_key.ts");
50 const deep = "x".repeat(2_000_000) + pem("ENCRYPTED ");
51 expect(holdsPrivateKey(deep)).toBe(true);
52 expect(holdsPrivateKey(new TextEncoder().encode(deep).subarray(1_000_000))).toBe(true);
53 expect(holdsPrivateKey(pem("PGP ").replace("KEY" + D, "KEY BLOCK" + D))).toBe(true);
54 expect(holdsPrivateKey("x".repeat(2_000_000))).toBe(false);
55 });
56
57 test("a binary file whose drawn hex head holds a key header shows the notice, not the hex", () => {
58 const bytes = new Uint8Array([0, 1, 2, ...new TextEncoder().encode(pem(""))]);
59 const out = page("k.bin", { kind: "binary", body: bytes, size: bytes.length });
60 expect(out).toContain("This file holds a private key");
61 expect(out).not.toContain("hexdump");
62 });
63
64 test("the page, the certificate renderer and the terminal share one sentence and one detector", async () => {
65 const { PRIVATE_KEY_NOTICE, holdsPrivateKey } = await import("../src/core/private_key.ts");
66 const { factsView } = await import("../src/tui/screens/workspace_facts.ts");
67 expect(factsView("k.pem", new TextEncoder().encode(pem("")))).toBe(PRIVATE_KEY_NOTICE);
68 expect(holdsPrivateKey(pem("ENCRYPTED "))).toBe(true);
69 expect(holdsPrivateKey(`{"private_key": "${pem("").replaceAll("\n", "\\n")}"}`)).toBe(true);
70 });
71
72 test("a key after other text is still withheld; ordinary text is drawn", () => {
73 expect(draw("x.txt", "hi\n" + pem(""))).not.toContain("SECRETBODY123");
74 expect(draw("x.txt", "hello world")).toContain("hello");
75 });
76
77 test("the terminal's file rows show the notice, not the key", async () => {
78 const { buildLines } = await import("../src/tui/screens/workspace.ts");
79 const { PRIVATE_KEY_NOTICE } = await import("../src/core/private_key.ts");
80 const built = buildLines(pem(""), "k.pem", (await import("../src/tui/ui/theme.ts")).theme("dark").c);
81 expect(built.plain).toEqual([PRIVATE_KEY_NOTICE]);
82 });
83
84
85 test("every renderer is skipped for a key: .md, .json and .csv draw the notice, not the body", () => {
86 for (const [path, text] of [
87 ["notes.md", `# Title\n\n${pem("")}`],
88 ["data.json", `{"k": "${pem("").replaceAll("\n", "\\n")}"}`],
89 ["data.csv", `a,b\n1,"${pem("")}"\n`],
90 ] as const) {
91 const out = page(path, { kind: "text", body: new TextEncoder().encode(text), size: text.length });
92 expect(out).toContain("This file holds a private key");
93 expect(out).not.toContain("SECRETBODY123");
94 }
95 });
96
97 test("the tail of an oversized file that holds a key is not drawn", () => {
98 const tail = new TextEncoder().encode(`partial line\nSECRETBODY123\n${D}END PRIVATE KEY${D}\n`);
99 const out = page("big.log", { kind: "too_large", size: 9_000_000, tail });
100 expect(out).toContain("This file holds a private key");
101 expect(out).not.toContain("SECRETBODY123");
102 });
103
104 test("a README holding a key is not drawn", async () => {
105 const text = `# Hi\n\n${pem("")}`;
106 const source = { where: { kind: "local", repo: { id: "r" } }, blob: async () => ({ ok: true, value: { kind: "text", body: new TextEncoder().encode(text), size: text.length } }) } as unknown as RepoSource;
107 const entry: TreeEntry = { mode: "100644", type: "blob", oid: "c".repeat(40), size: 1, name: "README.md" };
108 expect(String(await readmeFor(source, "main", [entry], ""))).not.toContain("SECRETBODY123");
109 });
test/render-cert.test.ts +2 −1
@@ -2,7 +2,8 @@ import { describe, expect, test } from "bun:test";
22 import { rendererFor } from "../src/web/render/renderers.ts";
33 import type { Blob } from "../src/view/source.ts";
44 import { CERT } from "./cert-fixture.ts";
5 import { cert, holdsPrivateKey } from "../src/web/render/cert.ts";
5 import { cert } from "../src/web/render/cert.ts";
6 import { holdsPrivateKey } from "../src/core/private_key.ts";
67 import { fileKind } from "../src/web/render/kinds.ts";
78 import type { RenderInput } from "../src/web/render/renderers.ts";
89

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs