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

A push that adds a secret-shaped line is flagged before it lands #17066

Merged opened this

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

Merged

mason/forge:mason/17048-a-push-that-adds-a-secret-shaped-line-is → main 0 commits fork 3 threads · 3 unresolved

  • Merged. mason/17048-a-push-that-adds-a-secret-shaped-line-is was merged into main as 068c207.

Review

Sign in to review this change.
17 files changed +802 −67
docs/features/code-scanning.md +9 −4
@@ -7,8 +7,11 @@ row: Code scanning
77 Every push to a repository is scanned (`src/checks/scan.ts`, run from the
88 post-receive hook, off git's answer):
99
10 - **Secrets** in the files the push changed: AWS, GitHub, Slack and Stripe
11 live keys, and private key blocks. High, except in tests and fixtures
10 - **Secrets** in the lines the push added: AWS, GitHub, Slack and Stripe
11 live keys, private key blocks, the forge's own tokens, and random-looking
12 values given to `*_KEY` / `*_SECRET` names; a line holding
13 `forge:allow-secret` is left alone. An open pull and /maintenance flag
14 them ([secret-shaped pushes](pushed-secrets.md)). High, except in tests and fixtures
1215 (`test/`, `*.test.ts`, `fixtures/`), which quote fakes on purpose: medium there.
1316 - **Advisories** in each changed `package.json`: a pin whose lowest admitted
1417 version is below the fix of an advisory the forge keeps
@@ -20,8 +23,10 @@ the default branch's whole tree gets both, plus **static analysis**: `eval`,
2023 value, in source files outside tests. Static findings are medium.
2124
2225 A finding is recorded once per fingerprint (rule, path and a hash of the
23 match). The matched text is never stored or shown: pages, logs and comments
24 name the rule, the file and the line.
26 match); a pushed secret is also noted against each branch it was pushed to,
27 and is read in the lines that push added, not the whole file. The matched text is never stored or shown: pages, logs and comments
28 name the rule, the file and the line, and a secret's line with the secret
29 masked to its vendor prefix (`AKIA••••`).
2530
2631 A pass is bounded: at most 5 000 files, each at most 512 KiB, read in one
2732 `git cat-file --batch` (a push of many refs costs one `diff-tree` and one
docs/features/pushed-secrets.md added +46
@@ -0,0 +1,46 @@
1 ---
2 topic: Ship and undo
3 row: Secret-shaped pushes flagged on the pull
4 ---
5 # Secret-shaped pushes flagged on the pull
6
7 A push that brings a line shaped like a secret is flagged before it lands (#17048). The push
8 pass of [code scanning](code-scanning.md) reads only the lines the push added: each changed file
9 is compared with its text before the push, and a line the file already held, kept or moved, is
10 not the push's. Each match is recorded once as a finding, and noted against every branch it was
11 pushed to, so the same secret pushed to a second branch flags that pull too. What is shown is a
12 masked excerpt: the line, with the secret cut to the part that is not secret (`AKIA••••`,
13 `forge_••••`, `API_SECRET = "••••"`). The secret itself is never stored or shown.
14
15 ## What is caught
16
17 `secretMatches` in `src/checks/scan_rules.ts`, a pure function of the lines a push added:
18
19 - AWS access key ids, GitHub, Slack and Stripe live tokens, and private key blocks.
20 - The forge's own credentials: `forge_…`, `forge_runner_…`, `forge_job_…` and `fgb_…` tokens.
21 - A random-looking value (20+ characters, letters and digits, 3.5+ bits a character) given to a
22 name ending in `_KEY` or `_SECRET`. A reference (`process.env.API_KEY`, `${API_KEY}`), a
23 placeholder (`FORGE_TOKEN`, `changeme`) or a `PUBLIC_KEY` is not.
24
25 A line that is not a secret takes `forge:allow-secret` anywhere in it (a comment), and nothing on
26 that line is flagged.
27
28 ## Where it shows
29
30 High secrets only, on the pull and the board alike: a test or fixture (`test/`, `*.test.ts`,
31 `fixtures/`) quotes fakes on purpose, so its matches are medium and listed on the findings page
32 alone.
33
34 - **The pull.** An open pull whose head branch was pushed a secret shows it under its checks
35 line (`src/web/pages/pull.ts`): one sentence with how many and a link to the findings page,
36 then each one's rule, file, line and masked excerpt as a row that opens the file on the line. The terminal's pull screen (`src/tui/screens/pull.ts`) shows the same
37 on a `secrets:` row. A fork's pull reads the fork's findings, for someone who may read the fork.
38 - **/maintenance.** The forge's open secrets, every repository, newest first, with
39 "N secret-shaped pushes" in the needs-you line (`src/web/pages/maintenance.ts`); the terminal's
40 Maintenance screen (`src/tui/screens/maintenance.ts`) lists them under what needs you.
41
42 ## Clearing it
43
44 Taking the line out of the branch does not take it out of the history, so the flag stays until a
45 person with write access accepts the finding with a reason on `/:owner/:name/findings` (or in
46 the terminal's Findings screen): say it was rotated, or why it never was a secret.
src/checks/pushed_secrets.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * A push that brings a secret-shaped line is flagged before it lands (#17048): on the pull whose
3 * head branch it was pushed to, and on /maintenance. The push pass records each finding with its
4 * ref and a masked excerpt (`scan.ts`, `scan_rules.ts`); this reads them back as plain data and
5 * words the page, the terminal and the board share. A secret stays flagged until a person accepts
6 * it on the findings page: taking it out of the tip does not take it out of the history, so the
7 * acceptance is where someone says it was rotated, or never was one.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { canRead, getRepoById, type Repo } from "../core/repos.ts";
12 import type { User } from "../core/users.ts";
13 import { openSecretsAll, openSecretsOn, type FindingRow, type ForgeSecret } from "./scan_store.ts";
14
15 export interface PulledSecrets {
16 readonly rows: readonly FindingRow[];
17 /**
18 * The head repository's path (`/owner/name`): its findings page accepts each, its files show
19 * them.
20 */
21 readonly findingsBase: string;
22 }
23
24 /**
25 * The open secrets pushed to a pull's head branch, read in the head repository (a fork's pull
26 * reads the fork's), or null when there are none or `viewer` may not read that repository.
27 * `base` is the pull's own repository, which its reader has already been let into: a same-repo
28 * pull costs the one indexed read.
29 */
30 export function pullSecrets(
31 db: Database,
32 base: Repo,
33 pull: { readonly headRepoId: string; readonly headBranch: string },
34 viewer: User | undefined,
35 ): PulledSecrets | null {
36 const head = pull.headRepoId === base.id ? base : getRepoById(db, pull.headRepoId);
37 if (head === undefined || (head !== base && !canRead(db, head, viewer))) return null;
38 const rows = openSecretsOn(db, head.id, `refs/heads/${pull.headBranch}`);
39 if (rows.length === 0) return null;
40 return { rows, findingsBase: `/${head.ownerName}/${head.name}` };
41 }
42
43 /** "1 secret-shaped line was pushed here" / "3 secret-shaped lines were pushed here". */
44 export const secretsWords = (n: number): string =>
45 n === 1 ? "1 secret-shaped line was pushed here" : `${String(n)} secret-shaped lines were pushed here`;
46
47 /** One finding as a line: the rule, where, and the masked excerpt. Never the secret. */
48 export const secretLine = (f: Pick<FindingRow, "rule" | "path" | "line" | "excerpt">): string =>
49 `${f.rule} in ${f.path}${f.line > 0 ? `:${String(f.line)}` : ""}${f.excerpt === "" ? "" : `: ${f.excerpt}`}`;
50
51 /** What clears the flag, said the same on the pull, the board and in the terminal. */
52 export const CLEAR_WORDS =
53 "Take it out and rotate it, then accept it on the findings page with a reason; a line that is not a secret takes `forge:allow-secret`.";
54
55 /** The forge's open high secrets for /maintenance and its terminal screen. */
56 export function forgeSecrets(db: Database): { rows: readonly ForgeSecret[]; more: number } {
57 const { rows, total } = openSecretsAll(db);
58 return { rows, more: Math.max(0, total - rows.length) };
59 }
60
61 /** The board's secrets as terminal lines, led by a blank line; nothing when none. */
62 export function secretPushLines(db: Database): string[] {
63 const { rows, more } = forgeSecrets(db);
64 if (rows.length === 0) return [];
65 return [
66 "",
67 "Secret-shaped pushes (open until accepted):",
68 ...rows.map((f) => `${f.repo}: ${secretLine(f)}`),
69 ...(more > 0 ? [`And ${String(more)} more, not listed.`] : []),
70 CLEAR_WORDS,
71 ];
72 }
src/checks/scan.ts +54 −20
@@ -28,6 +28,11 @@ interface Read {
2828 skipped: number;
2929 }
3030
31 /** `batchReplies`' answer: the texts, and the requests whose blob was over MAX_BYTES. */
32 interface Replies extends Read {
33 readonly big: Set<string>;
34 }
35
3136 /**
3237 * A name holding a newline would split its `cat-file --batch` request in two
3338 * and shift every later reply onto the wrong file: never asked for, counted
@@ -41,7 +46,11 @@ const askable = (path: string): boolean => !path.includes("\n") && !path.include
4146 * reply could not be parsed (`batchReplies`), so a caller that must not pass
4247 * on silence (the hold) can tell.
4348 */
44 async function readFiles(dir: string, wanted: readonly { readonly oid: string; readonly path: string }[]): Promise<Read | null> {
49 async function readFiles(
50 dir: string,
51 wanted: readonly { readonly oid: string; readonly path: string }[],
52 priors: readonly { readonly oid: string; readonly path: string }[] = [],
53 ): Promise<Read | null> {
4554 const out: Read = { texts: new Map(), skipped: 0 };
4655 const asked = wanted.filter((w) => askable(w.path));
4756 out.skipped = wanted.length - asked.length;
@@ -51,11 +60,17 @@ async function readFiles(dir: string, wanted: readonly { readonly oid: string; r
5160 }
5261 if (asked.length === 0) return out;
5362 const requests = asked.map((w) => `${w.oid}:${w.path}`);
54 const raw = await runGitRaw(["cat-file", "--batch"], { cwd: dir, stdin: requests.map((r) => `${r}\n`).join(""), timeoutMs: 60_000 });
63 // A file's text before the push rides the same `cat-file`, after the files themselves, and only
64 // for a file that is asked: one left out is read whole, never counted as left out twice.
65 const kept = new Set(asked.map((w) => w.path));
66 const before = priors.filter((p) => kept.has(p.path)).map((p) => `${p.oid}:${p.path}`);
67 const all = [...requests, ...before];
68 const raw = await runGitRaw(["cat-file", "--batch"], { cwd: dir, stdin: all.map((r) => `${r}\n`).join(""), timeoutMs: 60_000 });
5569 if (!raw.ok) return null;
56 const replies = batchReplies(raw.value, requests);
70 const replies = batchReplies(raw.value, all);
5771 if (replies === null) return null;
58 out.skipped += replies.skipped;
72 // A file is left out when its own blob is too big; a prior too big only makes it read whole.
73 out.skipped += requests.filter((r) => replies.big.has(r)).length;
5974 for (const [request, text] of replies.texts) out.texts.set(request, text);
6075 return out;
6176 }
@@ -76,8 +91,8 @@ const UNANSWERED = / (?:missing|ambiguous)$/;
7691 * misread would put one file's text under another's name, so the scan fails
7792 * rather than guess.
7893 */
79 export function batchReplies(bytes: Uint8Array, requests: readonly string[]): Read | null {
80 const out: Read = { texts: new Map(), skipped: 0 };
94 export function batchReplies(bytes: Uint8Array, requests: readonly string[]): Replies | null {
95 const out: Replies = { texts: new Map(), skipped: 0, big: new Set() };
8196 const decoder = new TextDecoder();
8297 let at = 0;
8398 for (const request of requests) {
@@ -97,7 +112,10 @@ export function batchReplies(bytes: Uint8Array, requests: readonly string[]): Re
97112 at += size + 1;
98113 if (found[1] !== "blob") continue;
99114 if (size <= MAX_BYTES) out.texts.set(request, decoder.decode(body));
100 else out.skipped++;
115 else {
116 out.skipped++;
117 out.big.add(request);
118 }
101119 }
102120 return at === bytes.length ? out : null;
103121 }
@@ -142,7 +160,7 @@ function filesOf(read: Read | null, oid: string, paths: readonly string[]): Map<
142160 return files;
143161 }
144162
145 const askScan = workerAsker<{ files: [string, string][]; withStatic: boolean }, Finding[]>(new URL("./scan_worker.ts", import.meta.url).href);
163 const askScan = workerAsker<{ files: [string, string][]; withStatic: boolean; before: [string, string][] }, Finding[]>(new URL("./scan_worker.ts", import.meta.url).href);
146164
147165 /** Text crosses to the worker by copy, this much an ask: a whole tree's would hold the thread. */
148166 const BATCH_CHARS = 1_000_000;
@@ -155,35 +173,46 @@ export const scanWorker = { force: false };
155173 * patterns on every line of every file read, which held the serving thread
156174 * for the whole of a push's or a tree's text (2.7% of its samples on
157175 * production, 2026-11-14). The same findings in the same order; scanned here
158 * when the worker fails, so a scan is never lost to it.
176 * when the worker fails, so a scan is never lost to it. `before` is each
177 * file's text before the push, which crosses with its file.
159178 */
160 export async function findingsOff(files: ReadonlyMap<string, string>, withStatic: boolean): Promise<Finding[]> {
161 if (files.size === 0 || (!scanWorker.force && process.env["NODE_ENV"] === "test")) return findingsIn(files, withStatic);
179 export async function findingsOff(
180 files: ReadonlyMap<string, string>,
181 withStatic: boolean,
182 before: ReadonlyMap<string, string> = new Map(),
183 ): Promise<Finding[]> {
184 if (files.size === 0 || (!scanWorker.force && process.env["NODE_ENV"] === "test")) return findingsIn(files, withStatic, before);
162185 try {
163186 const out: Finding[] = [];
164187 let batch: [string, string][] = [];
188 let prior: [string, string][] = [];
165189 let chars = 0;
166190 for (const file of files) {
167191 batch.push(file);
168 chars += file[1].length;
192 const was = before.get(file[0]);
193 if (was !== undefined) prior.push([file[0], was]);
194 chars += file[1].length + (was?.length ?? 0);
169195 if (chars < BATCH_CHARS) continue;
170 out.push(...(await askScan({ files: batch, withStatic })));
196 out.push(...(await askScan({ files: batch, withStatic, before: prior })));
171197 batch = [];
198 prior = [];
172199 chars = 0;
173200 }
174 if (batch.length > 0) out.push(...(await askScan({ files: batch, withStatic })));
201 if (batch.length > 0) out.push(...(await askScan({ files: batch, withStatic, before: prior })));
175202 return out;
176203 } catch {
177 return findingsIn(files, withStatic);
204 return findingsIn(files, withStatic, before);
178205 }
179206 }
180207
181208 /**
182209 * The push pass: returns how many findings were new. Never throws for a ref
183210 * it cannot read. Bounded work however many refs a push names: one
184 * `diff-tree` and one `cat-file` for them all, at most MAX_FILES files. A new
185 * branch is compared with the default branch's tip; only a push with no
186 * default branch yet lists whole trees.
211 * `diff-tree` and one `cat-file` for them all, at most MAX_FILES files and
212 * each one's text before the push. A new branch is compared with the default
213 * branch's tip; only a push with no default branch yet lists whole trees.
outdated

Medium-high: this records whole-file matches with u.ref, so a secret already in a touched file is flagged on this pull, and a secret first seen on another branch (fingerprint dedupe, first ref wins) is silent here. Scan only the lines this push added and let each ref carry its own finding.

214 * Secrets are read in the lines the push added (#17048), and each is
215 * recorded against the ref it was pushed to, so its pull is flagged.
187216 */
188217 export async function scanPush(
189218 app: App,
@@ -199,18 +228,23 @@ export async function scanPush(
199228 if (r.ok && OID.test(r.value)) tip = r.value;
200229 }
201230 const paths: string[][] = live.map(() => []);
231 const bases: (string | undefined)[] = live.map(() => undefined);
202232 const pairs: { base: string; oid: string; at: number }[] = [];
203233 for (const [i, u] of live.entries()) {
204234 const base = ZERO.test(u.oldOid) ? tip : u.oldOid;
235 bases[i] = base;
205236 if (base === undefined) paths[i] = await listTree(dir, u.newOid);
206237 else if (base !== u.newOid) pairs.push({ base, oid: u.newOid, at: i });
207238 }
208239 const changed = await listChangedMany(dir, pairs);
209240 for (const [j, p] of pairs.entries()) paths[p.at] = changed[j]!;
210 const read = await readFiles(dir, live.flatMap((u, i) => paths[i]!.map((path) => ({ oid: u.newOid, path }))));
241 // A file new to the branch has no text before: `cat-file` says missing, and every line is added.
242 const priors = live.flatMap((_, i) => (bases[i] === undefined ? [] : paths[i]!.map((path) => ({ oid: bases[i]!, path }))));
243 const read = await readFiles(dir, live.flatMap((u, i) => paths[i]!.map((path) => ({ oid: u.newOid, path }))), priors);
211244 let fresh = 0;
212245 for (const [i, u] of live.entries()) {
213 fresh += recordFindings(app.db, repo.id, u.newOid, await findingsOff(filesOf(read, u.newOid, paths[i]!), false));
246 const before = bases[i] === undefined ? new Map<string, string>() : filesOf(read, bases[i]!, paths[i]!);
247 fresh += recordFindings(app.db, repo.id, u.newOid, await findingsOff(filesOf(read, u.newOid, paths[i]!), false, before), u.ref);
214248 }
215249 const total = live.reduce((n, _, i) => n + paths[i]!.length, 0);
216250 noteScanRun(app.db, repo.id, "push", live.at(-1)!.newOid, read === null ? total : read.skipped);
src/checks/scan_rules.ts +167 −21
@@ -4,7 +4,8 @@
44 * `advisory` (a package.json pin a known advisory names) and `static` (a
55 * pattern that turns text into code). A finding never carries the matched
66 * text: the secret is hashed into the fingerprint and dropped, so a page,
7 * a log or a comment that prints a finding cannot print the secret.
7 * a log or a comment that prints a finding cannot print the secret; a
8 * secret's excerpt is its line with the match masked to its vendor prefix.
89 */
910
1011 import { createHash } from "node:crypto";
@@ -22,18 +23,139 @@ export interface Finding {
2223 readonly line: number;
2324 /** Stable across pushes for the same thing in the same file: rule, path and a hash of the match. */
2425 readonly fingerprint: string;
26 /** A secret's line with the secret masked (`secretMatches`); empty for every other kind. */
27 readonly excerpt: string;
2528 }
2629
2730 const hash = (s: string): string => createHash("sha256").update(s).digest("hex").slice(0, 24);
2831
29 const SECRETS: readonly { rule: string; re: RegExp }[] = [
30 { rule: "AWS access key", re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g },
31 { rule: "GitHub token", re: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/g },
32 { rule: "Slack token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g },
33 { rule: "Stripe live key", re: /\b[sr]k_live_[0-9A-Za-z]{24,}\b/g },
34 { rule: "Private key", re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----/g },
32 /**
33 * The secret shapes, few and anchored (#17048): each names the part of a match
34 * that is not secret (`shown`: a vendor prefix, a key block's header), so an
35 * excerpt can say what was found without saying the value. `check` turns
36 * down a match that only looks like one: an identifier, a placeholder.
37 */
38 interface SecretRule {
39 readonly rule: string;
40 readonly re: RegExp;
41 /** The start of a match that may be shown; the rest is masked. */
42 readonly shown: RegExp;
43 readonly check?: (match: RegExpMatchArray) => boolean;
44 }
45
46 /**
47 * Bits per character of `s`: a random token is near 4 or more, a word or a placeholder well under.
48 */
49 export function entropy(s: string): number {
50 const seen = new Map<string, number>();
51 for (const c of s) seen.set(c, (seen.get(c) ?? 0) + 1);
52 let bits = 0;
53 for (const n of seen.values()) bits -= (n / s.length) * Math.log2(n / s.length);
54 return bits;
55 }
56
57 /**
58 * A value that reads as random: long, letters and digits mixed, and at least 3.5 bits a character.
59 */
60 const randomLooking = (v: string): boolean => v.length >= 20 && /\d/.test(v) && /[A-Za-z]/.test(v) && entropy(v) >= 3.5;
61
62 const SECRETS: readonly SecretRule[] = [
63 { rule: "AWS access key", re: /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, shown: /^.{4}/ },
64 { rule: "GitHub token", re: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/g, shown: /^.{4}/ },
65 { rule: "Slack token", re: /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g, shown: /^.{5}/ },
66 { rule: "Stripe live key", re: /\b[sr]k_live_[0-9A-Za-z]{24,}\b/g, shown: /^.{8}/ },
67 { rule: "Private key", re: /-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----/g, shown: /^.*/ },
68 // The forge's own credentials: `forge_` (an API token, `core/tokens.ts`), a runner's and a
69 // job's, and a game box's `fgb_`, each 43 characters of base64url (`kernel/id.ts`, `secret`).
70 {
71 rule: "Forge token",
72 re: /\b(?:forge_(?:runner_|job_)?|fgb_)[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g,
73 shown: /^(?:forge_(?:runner_|job_)?|fgb_)/,
74 check: (m) => randomLooking(m[0].slice(m[0].length - 43)),
75 },
76 // A random-looking value given to a name ending in _KEY or _SECRET: `API_SECRET = "…"`,
77 // `aws_secret_key: …`. A value read from elsewhere (`process.env.X`, `${X}`) has a character
78 // the value may not hold, so it never matches.
79 {
80 rule: "Key or secret assignment",
81 re: /\b[A-Za-z0-9_]*(?:_KEY|_SECRET)["']?\s*[:=]\s*["'`]?([A-Za-z0-9+/=_-]{20,})(?![A-Za-z0-9+/=_.$-])/gi,
82 shown: /^[^:=]*[:=]\s*["'`]?/,
83 // A public key is said to be shared: `PUBLIC_KEY`, `STRIPE_PUBLISHABLE_KEY`.
84 check: (m) => randomLooking(m[1] ?? "") && !/publi/i.test(m[0].slice(0, m[0].search(/[:=]/))),
85 },
3586 ];
3687
88 /** A line holding this is never a finding: the one-line way to say a match is not a secret. */
89 export const ALLOW_MARKER = "forge:allow-secret";
90
91 /** What stands for the masked part of a match: fixed, so its length says nothing either. */
92 export const MASK = "••••";
93 /** An excerpt is at most this many characters of its line. */
94 export const EXCERPT_CHARS = 120;
95
96 /** A line a push brought: its file, its 1-based number there, and its text. */
97 export interface AddedLine {
98 readonly path: string;
99 readonly line: number;
100 readonly text: string;
101 }
102
103 /** One secret-shaped match: where, by which rule, the line masked, and the hash of the match. */
104 export interface SecretMatch {
105 readonly rule: string;
106 readonly path: string;
107 readonly line: number;
108 readonly excerpt: string;
109 /** The matched text, for the fingerprint only: never stored or shown. */
110 readonly match: string;
111 }
112
113 /** `line` with every match masked to its shown part, cut to `EXCERPT_CHARS` around the first. */
114 function excerptOf(line: string, matches: readonly { index: number; text: string; shown: string }[]): string {
115 let out = "";
116 let at = 0;
117 let first = -1;
118 for (const m of [...matches].sort((a, b) => a.index - b.index)) {
119 if (m.index < at) continue;
120 out += line.slice(at, m.index);
121 if (first < 0) first = out.length;
122 out += m.shown === m.text ? m.text : m.shown + MASK;
123 at = m.index + m.text.length;
124 }
125 out += line.slice(at);
126 const lead = out.length - out.trimStart().length;
127 out = out.trim();
128 first = Math.max(0, first - lead);
129 if (out.length <= EXCERPT_CHARS) return out;
130 const start = Math.max(0, Math.min(first - 40, out.length - EXCERPT_CHARS));
131 return `${start > 0 ? "…" : ""}${out.slice(start, start + EXCERPT_CHARS)}${start + EXCERPT_CHARS < out.length ? "…" : ""}`;
132 }
133
134 /**
135 * The secret-shaped matches in `added`, pure: lines in, matches out, in line order. A line with
136 * `ALLOW_MARKER` gives none. Each match's excerpt masks every match on its line.
137 */
138 export function secretMatches(added: readonly AddedLine[]): SecretMatch[] {
139 const out: SecretMatch[] = [];
140 for (const a of added) {
141 if (a.text.includes(ALLOW_MARKER)) continue;
142 const found: { rule: string; index: number; text: string; shown: string }[] = [];
143 for (const { rule, re, shown, check } of SECRETS) {
144 for (const m of a.text.matchAll(re)) {
145 if (check !== undefined && !check(m)) continue;
146 // One finding for one stretch of text: an earlier rule's match wins
147 // (`AWS_SECRET_KEY = "AKIA…"`).
148 if (found.some((f) => m.index < f.index + f.text.length && f.index < m.index + m[0].length)) continue;
149 found.push({ rule, index: m.index, text: m[0], shown: shown.exec(m[0])?.[0] ?? "" });
150 }
151 }
152 if (found.length === 0) continue;
153 const excerpt = excerptOf(a.text, found);
154 for (const f of found) out.push({ rule: f.rule, path: a.path, line: a.line, excerpt, match: f.text });
155 }
156 return out;
157 }
158
37159 /** Lines of `text` with their 1-based numbers; a file with a NUL is binary and has none. */
38160 function lines(text: string): string[] {
39161 return text.includes("\0") ? [] : text.split("\n");
@@ -42,19 +164,40 @@ function lines(text: string): string[] {
42164 /** Tests and fixtures quote fake credentials on purpose: what they hold is still shown, as medium, and holds nothing. */
43165 export const TEST_PATH = /(?:^|\/)(?:test|tests|__tests__|fixtures?)\/|\.test\.[cm]?[jt]sx?$/;
44166
45 export function secretFindings(path: string, text: string): Finding[] {
46 const severity: Severity = TEST_PATH.test(path) ? "medium" : "high";
47 const out: Finding[] = [];
48 lines(text).forEach((l, i) => {
49 for (const { rule, re } of SECRETS) {
50 for (const m of l.matchAll(re)) {
51 out.push({ kind: "secret", severity, rule, path, line: i + 1, fingerprint: hash(`secret\0${rule}\0${path}\0${m[0]}`) });
52 }
53 }
167 /**
168 * The lines of `after` a change added, with their numbers in `after`: each line whose text `before`
169 * did not hold as many times, so a line kept, moved or copied from elsewhere in the file is not
170 * added. Pure. With no `before` (a new file, a whole tree), every line is added.
outdated

secretFindings reads every line as added, so pre-existing lines count as pushed. Issue box 1 says a diff's added lines; pass the real added lines from the push diff.

171 */
172 export function addedLines(path: string, after: string, before?: string): AddedLine[] {
173 const had = new Map<string, number>();
174 for (const l of before === undefined ? [] : lines(before)) had.set(l, (had.get(l) ?? 0) + 1);
175 const out: AddedLine[] = [];
176 lines(after).forEach((text, i) => {
177 const n = had.get(text) ?? 0;
178 if (n > 0) had.set(text, n - 1);
179 else out.push({ path, line: i + 1, text });
54180 });
55181 return out;
56182 }
57183
184 /**
185 * A file's secrets, in the lines it added since `before` (`addedLines`): a push is flagged for what
186 * it brought, not for what the file already held (#17048). With no `before`, every line.
187 */
188 export function secretFindings(path: string, text: string, before?: string): Finding[] {
189 const severity: Severity = TEST_PATH.test(path) ? "medium" : "high";
190 return secretMatches(addedLines(path, text, before)).map((m) => ({
191 kind: "secret",
192 severity,
193 rule: m.rule,
194 path,
195 line: m.line,
196 fingerprint: hash(`secret\0${m.rule}\0${path}\0${m.match}`),
197 excerpt: m.excerpt,
198 }));
199 }
200
58201 /** Known advisories, kept here and read without the network: a package, the first fixed version, and its severity. */
59202 export const ADVISORIES: readonly { name: string; fixed: string; severity: Severity; id: string }[] = [
60203 { name: "lodash", fixed: "4.17.21", severity: "high", id: "GHSA-35jh-r3h4-6jhm" },
@@ -106,7 +249,7 @@ export function advisoryFindings(path: string, text: string): Finding[] {
106249 for (const a of ADVISORIES) {
107250 if (a.name !== name || !versionBelow(floor, a.fixed)) continue;
108251 const rule = `${name} < ${a.fixed} (${a.id})`;
109 out.push({ kind: "advisory", severity: a.severity, rule, path, line: 0, fingerprint: hash(`advisory\0${a.id}\0${path}`) });
252 out.push({ kind: "advisory", severity: a.severity, rule, path, line: 0, fingerprint: hash(`advisory\0${a.id}\0${path}`), excerpt: "" });
110253 }
111254 }
112255 }
@@ -129,17 +272,20 @@ export function staticFindings(path: string, text: string): Finding[] {
129272 const code = l.trimStart();
130273 if (code.startsWith("//") || code.startsWith("*")) return;
131274 for (const { rule, re } of STATIC) {
132 if (re.test(l)) out.push({ kind: "static", severity: "medium", rule, path, line: i + 1, fingerprint: hash(`static\0${rule}\0${path}\0${l.trim()}`) });
275 if (re.test(l)) out.push({ kind: "static", severity: "medium", rule, path, line: i + 1, fingerprint: hash(`static\0${rule}\0${path}\0${l.trim()}`), excerpt: "" });
133276 }
134277 });
135278 return out;
136279 }
137280
138 /** Every rule's findings over `files` (path to text): secrets, advisories, static if asked. */
139 export function findingsIn(files: ReadonlyMap<string, string>, withStatic: boolean): Finding[] {
281 /**
282 * Every rule's findings over `files` (path to text): secrets, advisories, static if asked. A path
283 * in `before` (its text before the push) has its secrets read in the lines the push added only.
284 */
285 export function findingsIn(files: ReadonlyMap<string, string>, withStatic: boolean, before?: ReadonlyMap<string, string>): Finding[] {
140286 const out: Finding[] = [];
141287 for (const [path, text] of files) {
142 out.push(...secretFindings(path, text), ...advisoryFindings(path, text));
288 out.push(...secretFindings(path, text, before?.get(path)), ...advisoryFindings(path, text));
143289 if (withStatic) out.push(...staticFindings(path, text));
144290 }
145291 return out;
src/checks/scan_store.ts +66 −7
@@ -17,6 +17,8 @@ export interface FindingRow {
1717 readonly oid: string;
1818 /** The hash of rule, path and match: how a later read knows it again. Never the match. */
1919 readonly fingerprint: string;
20 /** A secret's line with the secret masked; empty for other kinds and older rows. */
21 readonly excerpt: string;
2022 readonly foundAt: string;
2123 /** Who accepted it, by username, with why and when; null while open. */
2224 readonly accepted: { readonly by: string; readonly reason: string; readonly at: string } | null;
@@ -31,29 +33,42 @@ interface Raw {
3133 line: number;
3234 oid: string;
3335 fingerprint: string;
36 excerpt: string;
3437 found_at: string;
3538 accepted_reason: string | null;
3639 accepted_at: string | null;
3740 username: string | null;
3841 }
3942
40 const SELECT = `SELECT f.id, f.kind, f.severity, f.rule, f.path, f.line, f.oid, f.fingerprint, f.found_at, f.accepted_reason, f.accepted_at, u.username
43 const SELECT = `SELECT f.id, f.kind, f.severity, f.rule, f.path, f.line, f.oid, f.fingerprint, f.excerpt, f.found_at, f.accepted_reason, f.accepted_at, u.username
4144 FROM scan_finding f LEFT JOIN user u ON u.id = f.accepted_by`;
4245
4346 const shape = (r: Raw): FindingRow => ({
44 id: r.id, kind: r.kind, severity: r.severity, rule: r.rule, path: r.path, line: r.line, oid: r.oid, fingerprint: r.fingerprint, foundAt: r.found_at,
47 id: r.id, kind: r.kind, severity: r.severity, rule: r.rule, path: r.path, line: r.line, oid: r.oid, fingerprint: r.fingerprint, excerpt: r.excerpt, foundAt: r.found_at,
4548 accepted: r.accepted_at === null ? null : { by: r.username ?? "someone removed", reason: r.accepted_reason ?? "", at: r.accepted_at },
4649 });
4750
48 /** Record what a pass found at `oid`; a fingerprint already recorded is left as it stands. Returns how many were new. */
49 export function recordFindings(db: Database, repoId: string, oid: string, findings: readonly Finding[], at = new Date().toISOString()): number {
51 /**
52 * Record what a pass found at `oid`; a fingerprint already recorded is left as it stands. A push
53 * names the `ref` it went to: each secret is then noted against that ref too (#17048), once per
54 * ref, so a secret first pushed elsewhere still flags this branch's pull. Returns how many
55 * findings were new.
56 */
57 export function recordFindings(db: Database, repoId: string, oid: string, findings: readonly Finding[], ref = "", at = new Date().toISOString()): number {
5058 const insert = db.query(
51 `INSERT OR IGNORE INTO scan_finding (repo_id, fingerprint, kind, severity, rule, path, line, oid, found_at)
52 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
59 `INSERT OR IGNORE INTO scan_finding (repo_id, fingerprint, kind, severity, rule, path, line, oid, found_at, excerpt)
60 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)`,
61 );
62 const onRef = db.query(
63 `INSERT OR IGNORE INTO scan_finding_ref (repo_id, ref, finding_id, oid, line, excerpt)
64 SELECT ?1, ?2, id, ?4, ?5, ?6 FROM scan_finding WHERE repo_id = ?1 AND fingerprint = ?3`,
5365 );
5466 let fresh = 0;
5567 db.transaction(() => {
56 for (const f of findings) fresh += insert.run(repoId, f.fingerprint, f.kind, f.severity, f.rule, f.path, f.line, oid, at).changes;
68 for (const f of findings) {
69 fresh += insert.run(repoId, f.fingerprint, f.kind, f.severity, f.rule, f.path, f.line, oid, at, f.excerpt).changes;
70 if (ref !== "" && f.kind === "secret") onRef.run(repoId, ref, f.fingerprint, oid, f.line, f.excerpt);
71 }
5772 })();
5873 return fresh;
5974 }
@@ -84,6 +99,50 @@ export function getFinding(db: Database, repoId: string, id: number): FindingRow
8499 return r ? shape(r) : undefined;
85100 }
86101
102 /** Open secrets a pull or the board lists: past this they are counted, not listed. */
103 export const SECRET_ROWS = 20;
104
105 /**
106 * The open high secrets pushes to `ref` brought, oldest first: what its pull is flagged with
107 * (#17048), each at the commit and line it was pushed to there. High only, as on /maintenance: a
108 * test or fixture quotes a fake on purpose (medium), which the findings page still lists.
109 */
110 export function openSecretsOn(db: Database, repoId: string, ref: string, limit = SECRET_ROWS): FindingRow[] {
111 return db
112 .query<Raw, [string, string, number]>(
113 `SELECT f.id, f.kind, f.severity, f.rule, f.path, r.line, r.oid, f.fingerprint, r.excerpt, f.found_at, f.accepted_reason, f.accepted_at, NULL AS username
114 FROM scan_finding_ref r JOIN scan_finding f ON f.id = r.finding_id
115 WHERE r.repo_id = ?1 AND r.ref = ?2 AND f.kind = 'secret' AND f.severity = 'high' AND f.accepted_at IS NULL
116 ORDER BY f.id LIMIT ?3`,
117 )
118 .all(repoId, ref, limit)
119 .map(shape);
120 }
121
122 /** An open secret anywhere on the forge, with the repository it is in: a row of /maintenance. */
123 export interface ForgeSecret extends FindingRow {
124 readonly repoId: string;
125 readonly repo: string;
126 }
127
128 /**
129 * The forge's open high secrets, newest first, at most `limit`, and how many in all (#17048). Read
130 * through the partial index of open secrets, which acceptance empties: never the whole table.
131 */
132 export function openSecretsAll(db: Database, limit = SECRET_ROWS): { rows: ForgeSecret[]; total: number } {
133 const rows = db
134 .query<Raw & { repo_id: string; repo: string; total: number }, [number]>(
135 `SELECT f.id, f.kind, f.severity, f.rule, f.path, f.line, f.oid, f.fingerprint, f.excerpt, f.found_at,
136 f.accepted_reason, f.accepted_at, NULL AS username, f.repo_id, u.username || '/' || r.name AS repo, COUNT(*) OVER () AS total
137 FROM scan_finding f INDEXED BY scan_finding_open_secret
138 JOIN repo r ON r.id = f.repo_id JOIN user u ON u.id = r.owner_id
139 WHERE f.kind = 'secret' AND f.accepted_at IS NULL AND f.severity = 'high'
140 ORDER BY f.id DESC LIMIT ?1`,
141 )
142 .all(limit);
143 return { rows: rows.map((r) => ({ ...shape(r), repoId: r.repo_id, repo: r.repo })), total: rows[0]?.total ?? 0 };
144 }
145
87146 /** The open high findings: each holds a release of this repository. */
88147 export function openHigh(db: Database, repoId: string): FindingRow[] {
89148 return db
src/checks/scan_worker.ts +3 −1
@@ -3,4 +3,6 @@
33 import { answerAsks } from "../kernel/worker_ask.ts";
44 import { findingsIn, type Finding } from "./scan_rules.ts";
55
6 answerAsks<{ files: [string, string][]; withStatic: boolean }, Finding[]>("scan", (ask) => findingsIn(new Map(ask.files), ask.withStatic));
6 answerAsks<{ files: [string, string][]; withStatic: boolean; before: [string, string][] }, Finding[]>("scan", (ask) =>
7 findingsIn(new Map(ask.files), ask.withStatic, new Map(ask.before)),
8 );
src/core/migration-pins/20261201140000-scan-finding-excerpt.pin added +1
@@ -0,0 +1,1 @@
1 8538330de106a61fa22db52b19565a65e0ab8f96aa80994dcb1b40d55fa6c187
src/core/migrations/20261201140000-scan-finding-excerpt.ts added +22
@@ -0,0 +1,22 @@
1 // A secret-shaped push is flagged on its pull and on /maintenance (#17048). A finding keeps a
2 // secret's line with the secret masked (`excerpt`, `secretMatches` in `checks/scan_rules.ts`),
3 // never the secret. `scan_finding_ref` is each branch or tag a push brought a secret to, with the
4 // commit, line and excerpt there: one finding (one acceptance) per secret, one row per ref, so the
5 // same secret pushed to a second branch flags that branch's pull too. A pull's read walks its key
6 // by repository and ref; the partial index holds only the open secrets, which a person's
7 // acceptance takes out, and /maintenance reads it whole. Additive: rows recorded before keep an
8 // empty excerpt and no ref.
9 export default `
10 ALTER TABLE scan_finding ADD COLUMN excerpt TEXT NOT NULL DEFAULT '';
11 CREATE TABLE scan_finding_ref (
12 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
13 ref TEXT NOT NULL,
14 finding_id INTEGER NOT NULL REFERENCES scan_finding(id) ON DELETE CASCADE,
15 oid TEXT NOT NULL,
16 line INTEGER NOT NULL,
17 excerpt TEXT NOT NULL,
18 PRIMARY KEY (repo_id, ref, finding_id)
19 ) WITHOUT ROWID;
20 CREATE INDEX scan_finding_ref_finding ON scan_finding_ref(finding_id);
21 CREATE INDEX scan_finding_open_secret ON scan_finding(repo_id) WHERE kind = 'secret' AND accepted_at IS NULL;
22 `;
src/generated/migrations.ts +2
@@ -447,6 +447,7 @@ import m442 from "../core/migrations/20261201120000-first-change-forge.ts";
447447 import m443 from "../core/migrations/20261201121000-repo-check-slots.ts";
448448 import m444 from "../core/migrations/20261201130000-finding-touched.ts";
449449 import m445 from "../core/migrations/20261201130000-game-box-boot.ts";
450 import m446 from "../core/migrations/20261201140000-scan-finding-excerpt.ts";
450451
451452 /** Each migration file's name and its default export, in name order. */
452453 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -896,4 +897,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
896897 ["20261201121000-repo-check-slots.ts", m443],
897898 ["20261201130000-finding-touched.ts", m444],
898899 ["20261201130000-game-box-boot.ts", m445],
900 ["20261201140000-scan-finding-excerpt.ts", m446],
899901 ];
src/tui/screens/maintenance.ts +5 −2
@@ -12,6 +12,7 @@ import { diskLine, diskSentence } from "../../maintenance/disk_line.ts";
1212 import { readDisk } from "../../kernel/disk_reading.ts";
1313 import { filedText } from "../../maintenance/filed.ts";
1414 import { autoClosedCauses, findingLines, reopenFinding } from "../../maintenance/findings.ts";
15 import { secretPushLines } from "../../checks/pushed_secrets.ts";
1516 import { LEVEL_WORDS, nextLevel, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts";
1617 import { dutyStates } from "../../maintain/pause.ts";
1718 import { duties, quietLine, splitDuties } from "../../maintenance/duties.ts";
@@ -66,6 +67,8 @@ export function maintenanceLines(f: Session, standby?: Standby, level?: Level):
6667 const stalled = step === undefined || level === "fyi" || f.user?.isAdmin !== true || f.user.kind === "agent" ? [] : [...wrap(`Stalled: ${step.step} ${step.says} (a asks if still wanted)`, INNER), ""];
6768 // The last restore drill in words, as on the page; the calm view leaves it out.
6869 const drill = level === "fyi" ? [] : [...wrap(drillLine(lastDrill(f.app.db)), INNER), ""];
70 // Secret-shaped pushes (#17048), as on the page: each waits on a person to accept it.
71 const secrets = secretPushLines(f.app.db).flatMap((l) => wrap(l, INNER));
6972 const findings = findingLines(f.app.db).flatMap((l) => wrap(l, INNER));
7073 // Findings quieted (#14557): numbered, so `b` can bring one back; when each is back.
7174 const hidden = quieted(f.app.db).flatMap((q, i) => wrap(`${String(i + 1)}. quieted until ${when(q.until)}: ${q.label}`, INNER));
@@ -79,14 +82,14 @@ export function maintenanceLines(f: Session, standby?: Standby, level?: Level):
7982 // here.
8083 const disk = diskLine((f.app.config.disk ?? readDisk)(f.app.config.dataDir));
8184 const diskText = disk === null ? [] : [...wrap(diskSentence(disk), INNER), ""];
82 if (level === undefined) return [...diskText, ...stalled, ...drill, ...lead, "", ...facts, ...checks, "", ...dutyText(loud), ...paused, ...quietText, ...findings, ...hiddenText, ...effectText];
85 if (level === undefined) return [...diskText, ...stalled, ...drill, ...lead, "", ...facts, ...checks, "", ...dutyText(loud), ...paused, ...secrets, ...quietText, ...findings, ...hiddenText, ...effectText];
8386 // The same split as the page, by the same rule (maintenance/level.ts): what waits on a person,
8487 // and what is only to read.
8588 const needs = stateLevel(s.phase) === "needs-you" || returnLevel(last?.healthy) === "needs-you";
8689 const overdue = loud.filter((d) => d.overdue);
8790 const out =
8891 level === "needs-you"
89 ? [...(disk?.low === true ? diskText : []), ...stalled, ...drill, ...(needs ? [...lead, "", ...facts, ...checks, ""] : []), ...dutyText(overdue), ...paused]
92 ? [...(disk?.low === true ? diskText : []), ...stalled, ...drill, ...(needs ? [...lead, "", ...facts, ...checks, ""] : []), ...dutyText(overdue), ...paused, ...secrets]
9093 : [...(disk?.low === false ? diskText : []), ...(needs ? [] : [...lead, "", ...facts, ...checks, ""]), ...dutyText(loud.filter((d) => !d.overdue)), ...quietText, ...findings, ...hiddenText, ...effectText];
9194 return out.length === 0 ? [level === "needs-you" ? "Nothing here needs you." : "Nothing here to read."] : out;
9295 }
src/tui/screens/pull.ts +11 −1
@@ -64,6 +64,7 @@ import { pullReviewScreen, setStepsPrompt } from "./pull_review.ts";
6464 import { combinedView, combinedWords, type CombinedView } from "../../core/combined_view.ts";
6565 import { previewEnv } from "../../apps/data.ts";
6666 import { findingsWords, pullPreviewFindings } from "../../core/preview_findings.ts";
67 import { pullSecrets, secretLine, secretsWords } from "../../checks/pushed_secrets.ts";
6768 import {
6869 type EnvState,
6970 type EnvStatus, envsFor } from "../../apps/runtime.ts";
@@ -372,6 +373,10 @@ export function pullScreen(
372373 let strangerLine = "";
373374 /** The offer's status link, for a writer only (`offerStatusLinkFor`, #15988); empty otherwise. */
374375 let statusLink = "";
376 /**
377 * The secret-shaped lines pushed to an open pull's head branch, as the page flags them (#17048).
378 */
379 let secretText = "";
375380 /** `h` is a person's key: an agent's hold is refused by the action, so it is not offered. */
376381 const mayHold = (): boolean =>
377382 mayWrite() && f.user?.kind === "user" && issueRow !== undefined;
@@ -425,6 +430,8 @@ export function pullScreen(
425430 return base === undefined ? undefined : wallOf(dir, base, facts.headOid);
426431 })()
427432 : undefined;
433 const pushed = row === undefined || settings === undefined || row.state !== "open" ? null : pullSecrets(f.db, settings, row, f.user);
434 secretText = pushed === null ? "" : `${secretsWords(pushed.rows.length)}: rotate each, then accept it at ${pushed.findingsBase}/findings. ${pushed.rows.map(secretLine).join("; ")}`;
428435 strangerLine =
429436 repo !== undefined && row !== undefined && row.state === "open" && row.mergedAt === null && isStrangerPull(f.db, repo, row)
430437 ? strangerNext(repo, await strangerGuard(f.app, repo, row))
@@ -1342,7 +1349,7 @@ export function pullScreen(
13421349 (checksLine === "" ? 0 : 1) +
13431350 (originCheckText === "" ? 0 : 1) +
13441351 teams.length;
1345 const [strip, head, nextRow, linkRow, previewRow, boxRow, tabRow, body, comp] = split(
1352 const [strip, head, nextRow, linkRow, secretRow, previewRow, boxRow, tabRow, body, comp] = split(
13461353 area,
13471354 "v",
13481355 [
@@ -1350,6 +1357,7 @@ export function pullScreen(
13501357 len(3),
13511358 len(strangerLine === "" ? 0 : 1),
13521359 len(statusLink === "" ? 0 : 1),
1360 len(secretText === "" ? 0 : 1),
13531361 len(isApp ? 1 : 0),
13541362 len(boxH),
13551363 len(2),
@@ -1412,6 +1420,8 @@ export function pullScreen(
14121420 s.text(nextRow!.x, nextRow!.y, truncate(`next: ${strangerLine}`, nextRow!.w), style(c.mutedFg, c.bg), nextRow!.x + nextRow!.w);
14131421 if (statusLink !== "" && linkRow!.h > 0)
14141422 s.text(linkRow!.x, linkRow!.y, truncate(`status link: ${statusLink}`, linkRow!.w), style(c.mutedFg, c.bg), linkRow!.x + linkRow!.w);
1423 if (secretText !== "" && secretRow!.h > 0)
1424 s.text(secretRow!.x, secretRow!.y, truncate(`secrets: ${secretText}`, secretRow!.w), style(c.danger, c.bg), secretRow!.x + secretRow!.w);
14151425 if (isApp && previewRow!.h > 0)
14161426 drawPreviewLine(s, previewRow!, c, preview);
14171427 drawMergeBox(s, boxRow!, c, issue, facts, view.summary(), mirrored(), {
src/web/pages/findings.ts +25 −6
@@ -1,6 +1,7 @@
11 /**
22 * Findings (#9593): `/:owner/:name/findings` lists what code scanning found
3 * in a repository — the rule, the file and line, never the matched text —
3 * in a repository — the rule, the file and line, a secret's line with the
4 * secret masked, never the matched text —
45 * open high findings first, each of which holds a release. A person with
56 * write access accepts one with a reason; who, why and when show on it.
67 * Reached from the flows view's "Code scanning" line. Server-rendered, no script.
@@ -9,6 +10,7 @@
910 import { acceptFinding, REASON_MAX, REASON_MIN } from "../../actions/scan_accept.ts";
1011 import { emptyNote } from "../empty_words.ts";
1112 import { lastScan, listFindings, type FindingRow } from "../../checks/scan_store.ts";
13 import { secretsWords, type PulledSecrets } from "../../checks/pushed_secrets.ts";
1214 import { canWrite } from "../../core/repos.ts";
1315 import type { Ctx } from "../../http/context.ts";
1416 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -16,7 +18,7 @@ import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, repoHeader, repo
1618 import { field as formField, readForm } from "../form.ts";
1719 import { html, type Html } from "../html.ts";
1820 import { flashTo, page } from "../layout.ts";
19 import { badge, btn, field, row, time } from "../ui.ts";
21 import { badge, btn, field, row, rowList, time } from "../ui.ts";
2022
2123 /** When a pass last ran, and whether it read everything: a partial pass says how many files it left out. */
2224 export function passWords(run: { at: string; skipped: number } | null): Html {
@@ -27,14 +29,18 @@ export function passWords(run: { at: string; skipped: number } | null): Html {
2729
2830 const where = (f: FindingRow): string => `${f.path}${f.line > 0 ? `:${f.line}` : ""}`;
2931
32 /**
33 * A finding has no page of its own: a row opens the file at the commit that found it, on the line.
34 */
35 const findingHref = (base: string, f: FindingRow): string =>
36 `${base}/blob/${f.oid}/${f.path.split("/").map(encodeURIComponent).join("/")}${f.line > 0 ? `#L${f.line}` : ""}`;
37
3038 function findingRow(f: FindingRow, base: string, writer: boolean): Html {
3139 const tone = f.accepted !== null ? "default" : f.severity === "high" ? "danger" : "attn";
3240 const meta = f.accepted !== null
3341 ? html`${where(f)} · accepted by ${f.accepted.by} ${time(f.accepted.at)}: ${f.accepted.reason}`
34 : html`${where(f)} · ${f.kind} · found ${time(f.foundAt)} at ${f.oid.slice(0, 12)}`;
35 // A finding has no page of its own: a row opens the file at the commit that found it, on the line.
36 const href = `${base}/blob/${f.oid}/${f.path.split("/").map(encodeURIComponent).join("/")}${f.line > 0 ? `#L${f.line}` : ""}`;
37 const line = row({ href, nav: true, title: html`${f.rule}`, meta, trail: badge(f.accepted !== null ? "accepted" : f.severity, { tone }) });
42 : html`${where(f)} · ${f.kind} · found ${time(f.foundAt)} at ${f.oid.slice(0, 12)}${f.excerpt === "" ? "" : html` · <code>${f.excerpt}</code>`}`;
43 const line = row({ href: findingHref(base, f), nav: true, title: html`${f.rule}`, meta, trail: badge(f.accepted !== null ? "accepted" : f.severity, { tone }) });
3844 if (f.accepted !== null || !writer) return line;
3945 return html`${line}
4046 <form method="post" action="${base}/findings/${String(f.id)}/accept" class="mt">
@@ -43,6 +49,19 @@ function findingRow(f: FindingRow, base: string, writer: boolean): Html {
4349 </form>`;
4450 }
4551
52 /**
53 * A pull's flag (#17048): one sentence that says how many and where they are cleared, then each
54 * masked line as a row that opens its file on the line. Under the pull's checks line; nothing when
55 * there are none.
56 */
57 export function pushedSecretsNote(found: PulledSecrets | null): Html {
58 if (found === null) return html``;
59 return html`<div id="pull-secrets" class="mt" data-secrets="${String(found.rows.length)}">
60 <p>${badge("secret", { tone: "danger" })} <strong>${secretsWords(found.rows.length)}</strong>: rotate each, then <a href="${found.findingsBase}/findings">accept it on the findings page</a>.</p>
61 ${rowList(found.rows.map((f) => row({ href: findingHref(found.findingsBase, f), title: html`${f.rule}`, meta: html`${where(f)} · <code>${f.excerpt}</code>` })), { label: "Secret-shaped lines" })}
62 </div>`;
63 }
64
4665 // GET /:owner/:name/findings
4766 export function findingsPage(ctx: Ctx): Response {
4867 const repo = loadRepo(ctx);
src/web/pages/maintenance.ts +20 −2
@@ -13,6 +13,7 @@ import { duties, quietLine, splitDuties } from "../../maintenance/duties.ts";
1313 import { LEVELS, LEVEL_WORDS, dutiesLevel, levelOf, returnLevel, stateLevel, type Level } from "../../maintenance/level.ts";
1414 import { findingRows, findingsJson, reopenFinding, rowWords } from "../../maintenance/findings.ts";
1515 import { NOTHING_FILED, filedPieces } from "../../maintenance/filed.ts";
16 import { CLEAR_WORDS, forgeSecrets, secretLine } from "../../checks/pushed_secrets.ts";
1617 import { drillLine } from "../../maintenance/drill_line.ts";
1718 import { lastDrill } from "../../snapshot/drills.ts";
1819 import { stalledStep } from "../../maintenance/stalled.ts";
@@ -68,6 +69,20 @@ export function findingsFold(db: Parameters<typeof findingRows>[0], now: number
6869 )}${more > 0 ? statusRow(`And ${String(more)} more`, html`<span class="muted">older causes, not listed</span>`) : html``}</dl>`);
6970 }
7071
72 /**
73 * The forge's open secret-shaped pushes (#17048), one row per finding with its repository and its
74 * masked line, each linked to the findings page that accepts it; nothing when none. Always open:
75 * a pushed secret waits on a person.
76 */
77 export function secretsFold({ rows, more }: ReturnType<typeof forgeSecrets>): Html {
78 if (rows.length === 0) return html``;
79 return fold("maintenance-secrets", "Secret-shaped pushes", String(rows.length + more), true,
80 html`<dl id="maintenance-secrets-rows" class="status-rows">${rows.map(
81 (f) => statusRow(f.repo, html`<code data-secret="${String(f.id)}">${secretLine(f)}</code> <a href="/${f.repo}/findings">Findings</a>`),
82 )}${more > 0 ? statusRow(`And ${String(more)} more`, html`<span class="muted">not listed</span>`) : html``}</dl>
83 <p class="muted small">${CLEAR_WORDS}</p>`);
84 }
85
7186 /** A loud duty's row: what it found with each issue or pull it filed linked, or "nothing filed". */
7287 function foundWords(ctx: Ctx, d: { detail: string; found: string; lastRun: string }): Html {
7388 if (d.lastRun === "never" || d.found === "not finished") return html`${d.detail}`;
@@ -77,13 +92,14 @@ function foundWords(ctx: Ctx, d: { detail: string; found: string; lastRun: strin
7792 }
7893
7994 /** What waits on a person, in words; empty when nothing does. Plain data in, plain data out. */
80 export function needsYou(o: { phase: string; healthy?: boolean; overdue: number; paused: number; stale: number }): string[] {
95 export function needsYou(o: { phase: string; healthy?: boolean; overdue: number; paused: number; stale: number; secrets?: number }): string[] {
8196 const out: string[] = [];
8297 if (o.phase !== "idle") out.push("maintenance is on");
8398 if (o.healthy === false) out.push("the last return failed a check");
8499 if (o.overdue > 0) out.push(plural(o.overdue, "duty overdue", "duties overdue"));
85100 if (o.paused > 0) out.push(plural(o.paused, "duty paused", "duties paused"));
86101 if (o.stale > 0) out.push(plural(o.stale, "stale pull", "stale pulls"));
102 if ((o.secrets ?? 0) > 0) out.push(plural(o.secrets ?? 0, "secret-shaped push", "secret-shaped pushes"));
87103 return out;
88104 }
89105
@@ -136,7 +152,8 @@ async function maintenanceAnswer(ctx: Ctx): Promise<Response> {
136152 const overdue = ran.filter((d) => d.overdue).length;
137153 const dismissable = states.filter((d) => !d.paused && dismissed.get(d.name)?.active !== true).map((d) => d.name);
138154 const paused = states.filter((d) => d.paused).length;
139 const waiting = needsYou({ phase: s.phase, ...(s.healthy === undefined ? {} : { healthy: s.healthy }), overdue, paused, stale });
155 const secrets = forgeSecrets(ctx.app.db);
156 const waiting = needsYou({ phase: s.phase, ...(s.healthy === undefined ? {} : { healthy: s.healthy }), overdue, paused, stale, secrets: secrets.rows.length + secrets.more });
140157 const idle = s.phase === "idle";
141158 const drill = lastDrill(ctx.app.db);
142159 const statusLine = waiting.length === 0
@@ -165,6 +182,7 @@ async function maintenanceAnswer(ctx: Ctx): Promise<Response> {
165182 <input type="text" name="reason" required maxlength="${String(REASON_MAX)}" autocomplete="off" placeholder="Why (kept)" aria-label="Why dismiss it for ${String(DISMISS_DAYS)} days">${btn(`Dismiss ${String(DISMISS_DAYS)} days`, { variant: "outline" })}
166183 </form>`}`)],
167184 ["fyi", fold("maintenance-budgets", "Budgets", String(states.length), false, html`<dl class="status-rows">${budgetRows(ctx.app, states.map((d) => d.name))}</dl>`)],
185 ["needs-you", secretsFold(secrets)],
168186 ["fyi", findingsFold(ctx.app.db)],
169187 ["fyi", writePauseFold(ctx.app.db)],
170188 ["needs-you", stale > 0
src/web/pages/pull.ts +4 −1
@@ -129,6 +129,8 @@ import {
129129 } from "./thread.ts";
130130 import { previewEnv } from "../../apps/data.ts";
131131 import { specFindings } from "./pull-spec.ts";
132 import { pushedSecretsNote } from "./findings.ts";
133 import { pullSecrets } from "../../checks/pushed_secrets.ts";
132134 import { pullPreviewFindings } from "../../core/preview_findings.ts";
133135 import { crewActivityCard } from "./runs.ts";
134136 import { holdCard } from "../studio/hold.ts";
@@ -530,7 +532,8 @@ function pullChecksLine(
530532 main.says === ""
531533 ? html``
532534 : html`<p class="muted small">${main.waiting ? "" : icon("x")}${main.says}</p>`;
533 return html`${originCheckLine(ctx, repo, pull)}${header}${line}${red}${found === null ? "" : specFindings(found)}`;
535 const secrets = pull.state === "open" ? pushedSecretsNote(pullSecrets(ctx.app.db, repo, pull, ctx.auth.user)) : "";
536 return html`${originCheckLine(ctx, repo, pull)}${header}${line}${red}${found === null ? "" : specFindings(found)}${secrets}`;
534537 }
535538
536539 /**
test/pull-budget.test.ts +5 −2
@@ -28,8 +28,11 @@ quietLogs();
2828 * machine has to be slow every time to fail it: 4 ms of headroom over the floor.
2929 */
3030 const BUDGET_MS = budget.medianMs;
31 /** The statements one warm request runs. A new query fails the test; raise it on purpose. */
32 const STATEMENTS = 110;
31 /**
32 * The statements one warm request runs. A new query fails the test; raise it on purpose. 111: the
33 * open secrets pushed to the head branch (#17048, `openSecretsOn`, one read of a partial index).
34 */
35 const STATEMENTS = 111;
3336 const RUNS = 30;
3437
3538 let dataDir: string;
test/secret_scan.test.ts added +290
@@ -0,0 +1,290 @@
1 /**

Add tests that fail without the change: forge_job_ shape, a pull from a fork the viewer cannot read returns null, the terminal pull 'secrets:' row and Maintenance lines, needsYou counting secrets, and a second branch pushing the same secret being flagged.

2 * A push that adds a secret-shaped line is flagged before it lands (#17048): the pure matcher
3 * (`secretMatches` in `src/checks/scan_rules.ts`) catches each shape, leaves placeholders and
4 * lines marked `forge:allow-secret` alone, and masks the excerpt; a branch push that carries one
5 * flags its open pull (page and terminal words) and /maintenance until a person accepts it. The
6 * fake secrets are built at run time, so this file is not itself a finding.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { acceptFinding } from "../src/actions/scan_accept.ts";
13 import { openPull } from "../src/actions/pulls.ts";
14 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
15 import { createApp, type App } from "../src/app.ts";
16 import { pullSecrets, secretPushLines } from "../src/checks/pushed_secrets.ts";
17 import { scanPush } from "../src/checks/scan.ts";
18 import { ALLOW_MARKER, MASK, addedLines, secretFindings, secretMatches, type AddedLine } from "../src/checks/scan_rules.ts";
19 import { listFindings, openSecretsOn } from "../src/checks/scan_store.ts";
20 import type { Repo } from "../src/core/repos.ts";
21 import { createToken } from "../src/core/tokens.ts";
22 import { createUser, type User } from "../src/core/users.ts";
23 import { serve, type Servers } from "../src/http/server.ts";
24 import { createForgeApp } from "../src/tui/forge.ts";
25 import { maintenanceLines } from "../src/tui/screens/maintenance.ts";
26 import { pullScreen } from "../src/tui/screens/pull.ts";
27 import { local } from "../src/tui/screens/where.ts";
28 import { headlessTerminal } from "../src/tui/term/terminal.ts";
29 import { needsYou } from "../src/web/pages/maintenance.ts";
30 import { quietLogs } from "./helpers/globals.ts";
31 import { promote } from "./helpers/members.ts";
32 import { settleApp } from "./helpers/tui.ts";
33 import { openMaintenance } from "./helpers/tui-maintenance.ts";
34
35 quietLogs();
36
37 /** A base64url run of `n` random characters: what a real token's tail looks like. */
38 const random = (n: number): string => Buffer.from(crypto.getRandomValues(new Uint8Array(n))).toString("base64url").slice(0, n);
39 /**
40 * Random, with a digit and a letter for sure, so the shape check never turns one down by chance.
41 */
42 const randomMixed = (n: number): string => `a1${random(n - 2)}`;
43
44 const AWS = "AKIA" + "QX7Z".repeat(4);
45 const SHAPES: { rule: string; value: string; shown: string }[] = [
46 { rule: "AWS access key", value: AWS, shown: "AKIA" },
47 { rule: "GitHub token", value: "gh" + "p_" + "Ab3d".repeat(9), shown: "ghp_" },
48 { rule: "Slack token", value: "xo" + "xb-" + "1234567890-abcdef", shown: "xoxb-" },
49 { rule: "Stripe live key", value: "sk" + "_live_" + "Zx9Q".repeat(6), shown: "sk_live_" },
50 { rule: "Forge token", value: "forge_" + randomMixed(43), shown: "forge_" },
51 { rule: "Forge token", value: "forge_runner_" + randomMixed(43), shown: "forge_runner_" },
52 { rule: "Forge token", value: "forge_job_" + randomMixed(43), shown: "forge_job_" },
53 { rule: "Forge token", value: "fgb_" + randomMixed(43), shown: "fgb_" },
54 ];
55 const PEM = "-----BEGIN " + "OPENSSH PRIVATE KEY-----";
56 const ASSIGNED = "a8Fk2LqP9xZr4TmW7vBn3Yc";
57
58 const at = (text: string, path = "src/config.ts"): AddedLine => ({ path, line: 7, text });
59
60 describe("the matcher", () => {
61 test("catches each shape, with its rule and line, and masks the excerpt", () => {
62 for (const s of SHAPES) {
63 const found = secretMatches([at(`const value = "${s.value}";`)]);
64 expect(found.map((f) => [f.rule, f.path, f.line])).toEqual([[s.rule, "src/config.ts", 7]]);
65 expect(found[0]!.excerpt).toBe(`const value = "${s.shown}${MASK}";`);
66 expect(found[0]!.excerpt).not.toContain(s.value.slice(s.shown.length));
67 }
68 expect(secretMatches([at(PEM)]).map((f) => [f.rule, f.excerpt])).toEqual([["Private key", PEM]]);
69 });
70
71 test("catches a random value given to a *_KEY or *_SECRET name, the value masked", () => {
72 for (const line of [`API_SECRET = "${ASSIGNED}"`, `aws_secret_access_key: ${ASSIGNED}/K7MDENG`, `export SIGNING_KEY=${ASSIGNED}`]) {
73 const found = secretMatches([at(line)]);
74 expect(found.map((f) => f.rule)).toEqual(["Key or secret assignment"]);
75 expect(found[0]!.excerpt).not.toContain(ASSIGNED);
76 expect(found[0]!.excerpt).toContain(MASK);
77 }
78 expect(secretMatches([at(`API_SECRET = "${ASSIGNED}"`)])[0]!.excerpt).toBe(`API_SECRET = "${MASK}"`);
79 });
80
81 test("leaves placeholders, references and public keys alone", () => {
82 for (const line of [
83 "FORGE_TOKEN",
84 "export FORGE_TOKEN=$FORGE_TOKEN",
85 'curl -H "authorization: Bearer $FORGE_TOKEN"',
86 "const API_KEY = process.env.API_KEY;",
87 'API_KEY="${API_KEY}"',
88 "API_KEY=changeme_placeholder_value",
89 "SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxx",
90 `PUBLIC_KEY = "${ASSIGNED}"`,
91 "const forge_telemetry_reads_total_by_route_and_reader = 1;",
92 "AKIA is a prefix",
93 ])
94 expect(secretMatches([at(line)])).toEqual([]);
95 });
96
97 test("a line with the allow marker gives nothing; the next line still does", () => {
98 const found = secretMatches([at(`const k = "${AWS}"; // ${ALLOW_MARKER}`), { path: "a.ts", line: 8, text: `const k = "${AWS}";` }]);
99 expect(found.map((f) => [f.path, f.line])).toEqual([["a.ts", 8]]);
100 });
101
102 test("one stretch of text is one finding, and every match on a line is masked in its excerpt", () => {
103 expect(secretMatches([at(`AWS_SECRET_KEY = "${AWS}"`)]).map((f) => f.rule)).toEqual(["AWS access key"]);
104 const two = secretMatches([at(`a = "${AWS}"; b = "${SHAPES[1]!.value}"`)]);
105 expect(two.length).toBe(2);
106 for (const f of two) expect(f.excerpt).toBe(`a = "AKIA${MASK}"; b = "ghp_${MASK}"`);
107 });
108
109 test("a long line is cut around the match, which stays masked", () => {
110 const found = secretMatches([at(`${"x ".repeat(200)}k = "${AWS}" ${"y ".repeat(200)}`)]);
111 expect(found[0]!.excerpt.length).toBeLessThanOrEqual(122);
112 expect(found[0]!.excerpt).toContain(`AKIA${MASK}`);
113 });
114
115 test("a changed file's added lines are those its text before did not hold, numbered as after", () => {
116 const before = "a\nb\nc\n";
117 expect(addedLines("f.ts", "a\nNEW\nb\nc\n", before)).toEqual([{ path: "f.ts", line: 2, text: "NEW" }]);
118 // A line moved is not added; a second copy of a line is.
119 expect(addedLines("f.ts", "c\na\nb\nb\n", before).map((l) => [l.line, l.text])).toEqual([[4, "b"]]);
120 expect(addedLines("f.ts", "x\n").map((l) => l.text)).toEqual(["x", ""]);
121 expect(addedLines("f.bin", "x\0y", before)).toEqual([]);
122 });
123
124 test("a file's secrets are read in its added lines when its text before is known", () => {
125 const old = `const k = "${AWS}";\n`;
126 expect(secretFindings("deploy.ts", `${old}const name = "vault";\n`, old)).toEqual([]);
127 expect(secretFindings("deploy.ts", `const name = "vault";\n${old}`, "").map((f) => f.line)).toEqual([2]);
128 });
129
130 test("a file's findings carry the excerpt, never the match", () => {
131 const [f] = secretFindings("deploy.ts", `\nconst k = "${AWS}";\n`);
132 expect(f).toMatchObject({ kind: "secret", severity: "high", line: 2, excerpt: `const k = "AKIA${MASK}";` });
133 expect(JSON.stringify(f)).not.toContain(AWS);
134 });
135 });
136
137 let dataDir: string;
138 let app: App;
139 let servers: Servers;
140 let alice: User;
141 let repo: Repo;
142 let auth: string;
143
144 const ok = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
145 if (!r.ok) throw new Error(JSON.stringify(r.error));
146 return r.value;
147 };
148
149 beforeAll(async () => {
150 dataDir = await mkdtemp(join(tmpdir(), "forge-secret-scan-"));
151 app = createApp({ dataDir, port: 0 });
152 servers = await serve(app);
153 alice = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }));
154 repo = ok(await createRepo(app, alice, { name: "vault", visibility: "public" }));
155 ok(await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "# vault\n" }] }));
156 auth = `Bearer ${createToken(app.db, alice.id, "t", "rw").token}`;
157 }, 30_000);
158
159 afterAll(async () => {
160 servers.stop();
161 app.close();
162 await rm(dataDir, { recursive: true, force: true });
163 });
164
165 describe("a push with a secret-shaped line", () => {
166 test("flags its pull and /maintenance, masked, until a person accepts it", async () => {
167 const leak = ok(await commitToBranch(app, alice, repo, {
168 branch: "leak",
169 message: "Configure",
170 files: [{ path: "src/config.ts", content: `export const API_SECRET = "${ASSIGNED}";\nexport const name = "vault"; // ${ALLOW_MARKER}\n` }],
171 }));
172 const pull = ok(await openPull(app, alice, repo, { title: "Configure", body: "", baseBranch: "main", headBranch: "leak" }));
173 expect(pullSecrets(app.db, repo, pull, alice)).toBeNull();
174 await scanPush(app, repo, [{ ref: "refs/heads/leak", oldOid: "0".repeat(40), newOid: leak.commitOid }]);
175
176 const flagged = pullSecrets(app.db, repo, pull, alice);
177 expect(flagged?.findingsBase).toBe("/alice/vault");
178 expect(flagged?.rows.map((f) => [f.rule, f.path, f.line, f.oid])).toEqual([["Key or secret assignment", "src/config.ts", 1, leak.commitOid]]);
179
180 const page = await (await fetch(`${servers.url}/alice/vault/pulls/${pull.number}`, { headers: { authorization: auth } })).text();
181 expect(page).toContain('id="pull-secrets"');
182 expect(page).toContain("1 secret-shaped line was pushed here");
183 expect(page).toContain(`API_SECRET = &quot;${MASK}&quot;`);
184 expect(page).not.toContain(ASSIGNED);
185
186 const board = await (await fetch(`${servers.url}/maintenance`, { headers: { authorization: auth } })).text();
187 expect(board).toContain('id="maintenance-secrets"');
188 expect(board).toContain("1 secret-shaped push");
189 expect(board).not.toContain(ASSIGNED);
190 expect(secretPushLines(app.db).join("\n")).toContain(`alice/vault: Key or secret assignment in src/config.ts:1: export const API_SECRET = "${MASK}";`);
191
192 const findings = await (await fetch(`${servers.url}/alice/vault/findings`, { headers: { authorization: auth } })).text();
193 expect(findings).not.toContain(ASSIGNED);
194
195 // Accepted with a reason, the flag is gone from the pull, the board and the terminal.
196 expect(acceptFinding(app, repo, alice, flagged!.rows[0]!.id, "Rotated: the old value is revoked")).toEqual({ ok: true });
197 expect(openSecretsOn(app.db, repo.id, "refs/heads/leak")).toEqual([]);
198 expect(pullSecrets(app.db, repo, pull, alice)).toBeNull();
199 expect(secretPushLines(app.db)).toEqual([]);
200 const after = await (await fetch(`${servers.url}/alice/vault/pulls/${pull.number}`, { headers: { authorization: auth } })).text();
201 expect(after).not.toContain('id="pull-secrets"');
202 }, 30_000);
203 });
204
205 /** Commits `files` to a new `branch` off main, runs the push pass on it, and opens its pull. */
206 async function pushAndOpen(branch: string, files: { path: string; content: string }[], into: Repo = repo, who: User = alice) {
207 const made = ok(await commitToBranch(app, who, into, { branch, message: branch, files }));
208 await scanPush(app, into, [{ ref: `refs/heads/${branch}`, oldOid: "0".repeat(40), newOid: made.commitOid }]);
209 return made;
210 }
211
212 describe("what a push brought, and where it is flagged", () => {
213 test("a secret the file already held is not this push's: touching the file flags nothing", async () => {
214 // On main, never scanned: the old whole-file read would have charged it to the branch below.
215 ok(await commitToBranch(app, alice, repo, { message: "Keys", files: [{ path: "src/keys.ts", content: `export const k = "${AWS}";\n` }] }));
216 await pushAndOpen("touch", [{ path: "src/keys.ts", content: `export const k = "${AWS}";\nexport const two = 2;\n` }]);
217 const pull = ok(await openPull(app, alice, repo, { title: "Touch", body: "", baseBranch: "main", headBranch: "touch" }));
218 expect(pullSecrets(app.db, repo, pull, alice)).toBeNull();
219 }, 30_000);
220
221 test("a test's fake is medium: listed on the findings page, never on the pull", async () => {
222 await pushAndOpen("fake", [{ path: "test/fake.test.ts", content: `const k = "${AWS}";\n` }]);
223 const pull = ok(await openPull(app, alice, repo, { title: "Fake", body: "", baseBranch: "main", headBranch: "fake" }));
224 expect(listFindings(app.db, repo.id).filter((f) => f.path === "test/fake.test.ts").map((f) => f.severity)).toEqual(["medium"]);
225 expect(pullSecrets(app.db, repo, pull, alice)).toBeNull();
226 }, 30_000);
227
228 test("the same secret pushed to two branches flags both pulls, as one finding; both terminal doors show it", async () => {
229 const line = `export const DEPLOY_SECRET = "${ASSIGNED}9Q";\n`;
230 const a = await pushAndOpen("one", [{ path: "deploy/env.ts", content: line }]);
231 const b = await pushAndOpen("two", [{ path: "deploy/env.ts", content: `// deploy\n${line}` }]);
232 const one = ok(await openPull(app, alice, repo, { title: "One", body: "", baseBranch: "main", headBranch: "one" }));
233 const two = ok(await openPull(app, alice, repo, { title: "Two", body: "", baseBranch: "main", headBranch: "two" }));
234 expect(listFindings(app.db, repo.id).filter((f) => f.path === "deploy/env.ts").length).toBe(1);
235 expect(pullSecrets(app.db, repo, one, alice)?.rows.map((f) => [f.oid, f.line])).toEqual([[a.commitOid, 1]]);
236 expect(pullSecrets(app.db, repo, two, alice)?.rows.map((f) => [f.oid, f.line])).toEqual([[b.commitOid, 2]]);
237
238 // The terminal's pull screen carries the same flag on its `secrets:` row.
239 const { app: tui, session } = createForgeApp(
240 app,
241 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: alice },
242 { terminal: headlessTerminal(200, 44), exitHooks: false },
243 );
244 tui.start();
245 try {
246 tui.ctx.push(pullScreen(session, tui.ctx, local(session, repo), two.number));
247 await settleApp(tui);
248 const text = tui.screen.toText();
249 expect(text).toContain("secrets: 1 secret-shaped line was pushed here: rotate each, then accept it at /alice/vault/findings.");
250 expect(text).not.toContain(ASSIGNED);
251 } finally {
252 tui.stop();
253 }
254
255 // The terminal's Maintenance screen lists it under what needs you.
256 const m = await openMaintenance(app, alice);
257 try {
258 // Joined and unwrapped: the screen wraps a long line at its width.
259 const needs = maintenanceLines(m.session, undefined, "needs-you").join(" ").replace(/\s+/g, " ");
260 expect(needs).toContain("Secret-shaped pushes (open until accepted):");
261 expect(needs).toContain(`alice/vault: Key or secret assignment in deploy/env.ts:1: export const DEPLOY_SECRET = "${MASK}";`);
262 expect(maintenanceLines(m.session).join("\n")).toContain("Secret-shaped pushes (open until accepted):");
263 expect(needs).not.toContain(ASSIGNED);
264 } finally {
265 m.tui.stop();
266 }
267 }, 30_000);
268
269 test("a fork's pull reads the fork's findings, for a viewer who may read the fork only", async () => {
270 const bob = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }));
271 const carol = ok(await createUser(app.db, { origin: "seed", trusted: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" }));
272 promote(app.db, bob);
273 const hidden = ok(await createRepo(app, bob, { name: "hidden", visibility: "private" }));
274 ok(await commitToBranch(app, bob, hidden, { message: "Start", files: [{ path: "README.md", content: "# hidden\n" }] }));
275 await pushAndOpen("leak", [{ path: "src/env.ts", content: `export const TOKEN_SECRET = "${ASSIGNED}7Z";\n` }], hidden, bob);
276 const pull = { headRepoId: hidden.id, headBranch: "leak" };
277 expect(pullSecrets(app.db, repo, pull, bob)?.findingsBase).toBe("/bob/hidden");
278 expect(pullSecrets(app.db, repo, pull, carol)).toBeNull();
279 expect(pullSecrets(app.db, repo, pull, undefined)).toBeNull();
280 }, 30_000);
281 });
282
283 describe("what needs you", () => {
284 test("counts secret-shaped pushes, and says nothing of none", () => {
285 const calm = { phase: "idle", overdue: 0, paused: 0, stale: 0 };
286 expect(needsYou({ ...calm, secrets: 1 })).toEqual(["1 secret-shaped push"]);
287 expect(needsYou({ ...calm, secrets: 3 })).toEqual(["3 secret-shaped pushes"]);
288 expect(needsYou({ ...calm, secrets: 0 })).toEqual([]);
289 });
290 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs