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

The Source tab shows a private key file's body as pushed #15756

Closed opened this
Closed without merging

scout/forge:scout/15738-the-source-tab-shows-a-private-key-file → main 10 commits fork 8 threads · 8 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +162 −9
docs/features/private-key-files.md added +11
@@ -0,0 +1,11 @@
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 text file with a PEM private-key block (plain, RSA, EC, OpenSSH, PGP or encrypted) is not drawn as source. A block is a `BEGIN … PRIVATE KEY` or `END … PRIVATE KEY` line next to base64 key text, so source that only quotes a header is still drawn. The Source view shows the shared notice (`PRIVATE_KEY_NOTICE`) with a Download button and a View raw link.
outdated

Says "with Download and Raw links"; the page renders only Download. Make the docs match, and name the shared notice once rather than quoting the sentence in two places.

8
9 - **Terminal:** the workspace and its facts view show the same notice as the file's only line.
10 - **Left out:** a "show anyway" toggle; Raw and Download still return the file as pushed. Binary files are unchanged.
11 - **Code:** `src/text/private_key.ts`, the one detector and sentence; `web/render/cert.ts`, `web/pages/repo.ts` and the terminal import it.
src/text/private_key.ts added +41
@@ -0,0 +1,41 @@
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
outdated

Duplicates holdsPrivateKey in src/web/render/cert.ts (and the notice in workspace_facts.ts). Keep one detector and one sentence; have cert.ts and the facts view import it.

5 * cannot disagree on a file.
outdated

Second detector for the same fact: cert.ts:29 (holdsPrivateKey) and scan_rules.ts:34 already define one. The regexes differ (this one also matches END, cert.ts only BEGIN), so the page and the terminal facts view will disagree on the same file. Keep one, in this module, and import it in cert.ts and workspace_facts.ts. Also decide what happens to a source file that merely quotes a header: it is now withheld with no way to view it except Raw.

6 *
7 * A header alone is not a key: source that quotes a BEGIN or END header in a string is drawn. A key
8 * is a header next to base64 key text — a BEGIN line followed (after any `Proc-Type:` style
9 * headers) by a base64 line, or a base64 line followed by an END line, which is how a log's tail
10 * reads when it begins mid-key, or a BEGIN line and its END line on lines of their own with lines
11 * between. A line break may be a real one or a JSON `\n`, so a key inside a service-account JSON
12 * file is caught too.
13 */
14
15 /** The one sentence the page and the terminal show in place of a private key's body. */
16 export const PRIVATE_KEY_NOTICE = "This file holds a private key. The forge does not draw it.";
17
18 const D = "-----";
19 const LABEL = `(?:[A-Z0-9]+ )*PRIVATE KEY(?: BLOCK)?${D}`;
20 const BREAK = String.raw`(?:\r?\n|(?:\\r)?\\n)`;
21 const B64 = "[A-Za-z0-9+/=]";
22 const OPENS = new RegExp(`${D}BEGIN ${LABEL}${BREAK}(?:[A-Za-z-]+: [^\\n\\\\]*${BREAK})*${BREAK}?${B64}{16,}`);
23 const CLOSES = new RegExp(`(?:^|${BREAK})${B64}{4,}${BREAK}${D}END ${LABEL}`);
24 const WHOLE = new RegExp(`${D}BEGIN ${LABEL}${BREAK}(?:.*?${BREAK})+?${D}END ${LABEL}`);

Blocker. (?:.?BREAK)+? is ambiguous: with a JSON \\n the . can eat the backslash and the n, or BREAK can. When no END follows, the engine tries every split. I measured a BEGIN header then a b\\n repeated: 20 repeats 3 ms, 22 repeats 13 ms, so it doubles per line; around 40 lines it hangs the process for minutes. One pushed file (a BEGIN header and a long escaped-JSON body with no END) stalls the page for every viewer. Fix: do it without a nested lazy loop, e.g. match the BEGIN header, then check text.indexOf(END_HEADER, start) (or a non-backtracking [^]? once) within a byte cap. Add a test with 200 escaped lines and no END that must finish fast.

25
26 /**
27 * Whether a text file carries a PEM private-key block (plain, RSA, EC, OpenSSH, PGP or encrypted).
28 */
29 export function holdsPrivateKey(body: Uint8Array | string): boolean {
30 const text = typeof body === "string" ? body : new TextDecoder().decode(body);
31 return OPENS.test(text) || CLOSES.test(text) || WHOLE.test(text);
32 }
33
34 /** Whether any bytes the page could draw of a file (its body, head or tail) hold a private key. */
35 export function blobHoldsPrivateKey(blob: {
36 readonly body?: Uint8Array;
37 readonly head?: Uint8Array;
38 readonly tail?: Uint8Array;
39 }): boolean {
40 return [blob.body, blob.head, blob.tail].some((b) => b !== undefined && holdsPrivateKey(b));
41 }
src/tui/screens/workspace.ts +3 −1
@@ -58,6 +58,7 @@ import { hexdump, HEX_BYTES } from "../../web/render/hexdump.ts";
5858 import { isModelPath, modelFacts } from "../../web/render/model-facts.ts";
5959 import type { RepoFacts, RepoSource } from "../../view/source.ts";
6060 import { detectLanguage, highlightLines } from "../../web/highlight.ts";
61 import { holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../text/private_key.ts";
6162 import { MAX_COLUMNS, parseCsv, type Table } from "../../text/csv.ts";
6263 import { isNumericColumn, sortRows } from "../../text/csv-sort.ts";
6364 import { parseGeoJson, propertyRows } from "../../web/render/geojson.ts";
@@ -343,7 +344,8 @@ export function buildLines(
343344 // A terminal log carries escapes; the viewer shows its text, never drives
344345 // the terminal or prints "[31m" as if it were the log.
345346 const clean = isLogPath(path) && text.includes("\x1b") ? stripAnsi(text) : text;
346 const body = clean.replace(/\n$/, "");
347 // A private key's body is never drawn: one notice line stands in, as on the page.
outdated

The terminal now has two sentences: this one and workspace_facts.ts:26 ("The forge does not draw it."). Use the single shared constant in both places, and plain words per docs/WRITING.md.

348 const body = holdsPrivateKey(clean) ? PRIVATE_KEY_NOTICE : clean.replace(/\n$/, "");
347349 const plain = body.split("\n").map((l) => expandTabs(l));
348350 // The first line is handed to the detector too: a `#!/usr/bin/env python3`
349351 // 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 "../../text/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 +15 −1
@@ -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 "../../text/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 {

Principle 1 and the stated behaviour: the notice offers only a Download button, while the docs and the pull say Download and Raw links. Add Raw as a link or correct the docs. Keep the sentence identical with the terminal's.

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,
@@ -784,6 +797,7 @@ export function blobBody(
784797 why?: string,
785798 ): { content: Html; lines: number } {
786799 const encoded = encodeURIComponent(ref);
800 if (blob.kind !== "binary" && blobHoldsPrivateKey(blob)) return { lines: 0, content: withheldKey(base, ref, path) };
787801 if (blob.kind === "binary" && why === undefined) {
788802 const head = blob.body.subarray(0, HEX_BYTES);
789803 const shown = Math.min(head.length, blob.size);
@@ -1285,7 +1299,7 @@ export function renderBlob(
12851299 const base = scope.base;
12861300 const encoded = encodeURIComponent(o.ref);
12871301 const blob = o.blob;
1288 const renderer = blobRenderer(scope, o.path, blob);
1302 const renderer = blobHoldsPrivateKey(blob) ? undefined : blobRenderer(scope, o.path, blob);
12891303 const view: BlobView = renderer ? (o.view ?? "rendered") : "source";
12901304 const drawn =
12911305 view === "rendered" && renderer
src/web/render/cert.ts +2 −4
@@ -9,6 +9,7 @@
99
1010 import { X509Certificate } from "node:crypto";
1111 import { escapeHtml, html, raw } from "../html.ts";
12 import { holdsPrivateKey, PRIVATE_KEY_NOTICE } from "../../text/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 +85
@@ -0,0 +1,85 @@
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 { blobBody, 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 draw = (path: string, s: string) => String(blobBody("/a/app", "main", path, asText(s)).content);
11
12 test("a private key's body is not drawn; a notice stands in", () => {
13 for (const kind of ["", "RSA ", "EC ", "OPENSSH ", "ENCRYPTED "]) {
14 const out = draw("k.pem", pem(kind));
15 expect(out).toContain("This file holds a private key");
16 expect(out).not.toContain("SECRETBODY123");
17 expect(out).toContain("Download");
18 expect(out).toContain('href="/a/app/raw/main/k.pem"');
19 expect(out).toContain("View raw");
20 }
21 });
22
23 test("source that only quotes a header is drawn, not withheld", () => {
24 const header = `${D}BEGIN PRIVATE KEY${D}`;
25 for (const text of [
26 `const OPEN = "${header}";\nconst x = 1;\n`,
27 `if (line === "${header}") return true;\n`,
28 `look for:\n${header}\nand stop.\n`,
29 `const CLOSE = "${D}END PRIVATE KEY${D}";\n`,
30 ]) {
31 const out = draw("scan.ts", text);
32 expect(out).not.toContain("This file holds a private key");
33 expect(out).toContain("PRIVATE");
34 }
35 });
36
37 test("the page, the certificate renderer and the terminal share one sentence and one detector", async () => {
38 const { PRIVATE_KEY_NOTICE, holdsPrivateKey } = await import("../src/text/private_key.ts");
39 const { factsView } = await import("../src/tui/screens/workspace_facts.ts");
40 expect(factsView("k.pem", new TextEncoder().encode(pem("")))).toBe(PRIVATE_KEY_NOTICE);
41 expect(holdsPrivateKey(pem("ENCRYPTED "))).toBe(true);
42 expect(holdsPrivateKey(`{"private_key": "${pem("").replaceAll("\n", "\\n")}"}`)).toBe(true);
43 });
44
45 test("a key after other text is still withheld; ordinary text is drawn", () => {
46 expect(draw("x.txt", "hi\n" + pem(""))).not.toContain("SECRETBODY123");
47 expect(draw("x.txt", "hello world")).toContain("hello");
48 });
49
50 test("the terminal's file rows show the notice, not the key", async () => {
51 const { buildLines } = await import("../src/tui/screens/workspace.ts");
52 const { PRIVATE_KEY_NOTICE } = await import("../src/text/private_key.ts");
53 const built = buildLines(pem(""), "k.pem", (await import("../src/tui/ui/theme.ts")).theme("dark").c);
54 expect(built.plain).toEqual([PRIVATE_KEY_NOTICE]);
55 });
56
57 const scope = { base: "/o/r", facts: { name: "r" }, caps: { write: false }, kind: "local" } as unknown as import("../src/web/scope.ts").RepoScope;
58 const page = (path: string, blob: Blob) =>
59 String(renderBlob(scope, { refs: { branches: ["main"], tags: [] }, ref: "main", path, blob }));
60
61 test("every renderer is skipped for a key: .md, .json and .csv draw the notice, not the body", () => {
62 for (const [path, text] of [
63 ["notes.md", `# Title\n\n${pem("")}`],
64 ["data.json", `{"k": "${pem("").replaceAll("\n", "\\n")}"}`],
65 ["data.csv", `a,b\n1,"${pem("")}"\n`],
66 ] as const) {
67 const out = page(path, { kind: "text", body: new TextEncoder().encode(text), size: text.length });
68 expect(out).toContain("This file holds a private key");
69 expect(out).not.toContain("SECRETBODY123");
70 }
71 });
72
73 test("the tail of an oversized file that holds a key is not drawn", () => {
74 const tail = new TextEncoder().encode(`partial line\nSECRETBODY123\n${D}END PRIVATE KEY${D}\n`);
75 const out = page("big.log", { kind: "too_large", size: 9_000_000, tail });
76 expect(out).toContain("This file holds a private key");
77 expect(out).not.toContain("SECRETBODY123");
78 });
79
80 test("a README holding a key is not drawn", async () => {
81 const text = `# Hi\n\n${pem("")}`;
82 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;
83 const entry: TreeEntry = { mode: "100644", type: "blob", oid: "c".repeat(40), size: 1, name: "README.md" };
84 expect(String(await readmeFor(source, "main", [entry], ""))).not.toContain("SECRETBODY123");
85 });
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/text/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