diff --git a/bin/gstack-review-plan b/bin/gstack-review-plan index efe200ebc..7ffb503b7 100755 --- a/bin/gstack-review-plan +++ b/bin/gstack-review-plan @@ -31,7 +31,7 @@ import { resultLine } from '../lib/result-codes'; import { gateOutcomeLine } from '../lib/gate-outcomes'; import { runScriptSync } from '../lib/script-invocation'; import { baseNote } from '../lib/gate-diff/git'; -import { collectCommit, collectLive, reviewPlanTimeoutMs } from '../lib/review-collect'; +import { collectCommit, collectLive, consumerScanCap, reviewPlanTimeoutMs } from '../lib/review-collect'; import { excludeLines, fallbackLine, reviewExclude, type Exclusion } from '../lib/review-exclude'; import { isUnavailable } from '../lib/ship-policy'; import { reviewPolicy } from '../lib/ship-policy-review'; @@ -317,6 +317,7 @@ function main(): number { const out = [`REVIEW_CLASS: ${plan.class} (${plan.reasons.slice(0, 3).join('; ') || 'no signals'})`, reviewDepthLine(plan), `GATE_SCAN: ${gateTagged === null ? 'unavailable' : `tagged=${gateTagged}`} head=${head}`, `REVIEW_BASE: ${ref} ${baseSha.slice(0, 12)}`, `TARGETED: classes=${classList(targeted.classes)} rules=${targeted.rules} brief=${brief} targeted_patch_id=${patch}${targeted.reasons.length ? ` reasons=${targeted.reasons.join('; ')}` : ''}`]; out.push(...excludeLines(exclusion, base), readersLine(readers)); + if (collected.consumed === 'all' && collected.mergeBase) out.push(`CONSUMER_SCAN: skipped: more than ${consumerScanCap()} data files changed, so each counts as code for review depth; fix: set GSTACK_REVIEW_CONSUMER_SCAN_CAP above that count, or move the data into its own PR (review_exclude_paths still leaves matched files out of the readers' diffs)`); out.push(`REVIEW_MODE: ${plan.mode} panel=${review.panel} reader_model=${review.reader_model} platform=${review.platform}`); if (declared.length) out.push(`RISK_DECLARED: classes=${plan.declared.join(',')} detected=${plan.detected.join(',') || 'none'}`); if (platform) out.push(platform.ok ? `PLATFORM_REVIEW: ${platform.review.id} reviewer=${platform.review.reviewer} head=${platform.review.head}` : `PLATFORM_REVIEW: none (${platform.reason})`); diff --git a/changelog.d/review-scan-cap-and-hash-manifests.md b/changelog.d/review-scan-cap-and-hash-manifests.md new file mode 100644 index 000000000..3219fa47a --- /dev/null +++ b/changelog.d/review-scan-cap-and-hash-manifests.md @@ -0,0 +1 @@ +**A results PR whose `pins.sha256` lists its data now gets `review_exclude_paths`, and large data PRs can raise the consumer-scan cap.** On harness-evals #538 the exclusion kept all 2,140 matched receipts in review and /ship refused a 13.3 MB diff: the name scan ran `git grep -o` with 2,140 paths, which ran past its 120-second bound, and even a finished scan would have counted the hash manifest that lists them as code. The scan now lists matching files with `git grep -l` and reads each one (the #538 plan took 48 s instead of 163 s and left all 2,140 out), and a hash or pin manifest (every line a hex digest and a path) keeps nothing and no longer reads as money, auth or data for review depth; a manifest with any other line is read as before, and its lines still count for secrets. `GSTACK_REVIEW_CONSUMER_SCAN_CAP` raises the 2,000-file consumer-scan cap, and a tripped cap prints a `CONSUMER_SCAN:` line naming both remedies. docs/ship-policy.md#review-exclude-paths, docs/review-policy.md. (HARN-64) diff --git a/docs/review-policy.md b/docs/review-policy.md index 3069fd363..f1fce311d 100644 --- a/docs/review-policy.md +++ b/docs/review-policy.md @@ -415,7 +415,14 @@ function but a same-file `url(#id)`, which closes `@import`, `image-set()`, `href` a same-file `#` reference or an inline raster image, no event handler and no entity declaration, and no DOCTYPE but a bare `` or W3C's own SVG DTD, read after character references are decoded. A ``, comment that only an HTML parser ends early, quoted `>` or Unicode space can hide CSS. A non-ASCII character in an element or attribute name, such as a `gé:` prefix, keeps the SVG code too (GST-940); anything else, a script or `foreignObject` included, keeps it code. More than -2,000 data paths keep every one code; a `git grep` failure is `consumer_scan_failed` +2,000 data paths keep every one code (`GSTACK_REVIEW_CONSUMER_SCAN_CAP` raises the count, a whole +number; an empty, zero, negative or non-numeric value keeps 2,000), and the plan then prints a +`CONSUMER_SCAN: skipped:` line naming both ways out: raise the cap or move the data into its own PR. +The cap is read from the environment, not recorded in the receipt, so a raised cap must also be set +wherever depth is recomputed (`gstack-ship-receipt carry` and the merge queue); without it they read +2,000, find a deeper depth than the receipt's and refuse it (`RECEIPT_CARRY_REFUSED`). +The cap counts files before `review_exclude_paths` applies, because the exclusion's own name scan reads +the depth this scan decides, and it changes only depth: excluded files still stay out of the readers' diffs; a `git grep` failure is `consumer_scan_failed` and fails the depth closed. The scan first lists the files that contain a candidate's extension and then searches only those, docs files left out, so a large data tree costs one cheap pass. Each scan gets one 120-second deadline, set in milliseconds with diff --git a/docs/ship-policy.md b/docs/ship-policy.md index f2dac9c3d..f16a01c5c 100644 --- a/docs/ship-policy.md +++ b/docs/ship-policy.md @@ -1526,8 +1526,13 @@ harness that writes the receipts names it) keeps nothing: the plan prints an informational `REVIEW_EXCLUDE_REFERENCE:` line naming the code that reads the folder. A data file never keeps another file: a results manifest such as `docs/receipts-manifest.json` lists every receipt by full path, and it is -content, not a program that reads them. The name scan is an uncapped `git grep -F -f` of the candidates' -paths over the consumer files alone (the head's and the merge base's trees filtered to code and tests and written into a +content, not a program that reads them. A hash or pin manifest names nothing either (HARN-64: +harness-evals #538's `pins.sha256` listed all 2,140 receipts): a file whose every non-blank line is a +hex digest of 32 to 128 characters, one or two spaces, an optional `*` and a path made only of letters, +digits and `. / _ - + @ ~`, as `sha256sum` writes it. Any other line, code or prose, makes it a consumer +again, and its lines still count for the secret risk class. The name scan is an uncapped `git grep -F -l -f` of the candidates' +paths, which lists the consumer files holding any of them, followed by a read of each such file +(`git grep -o` with thousands of paths ran past its 120-second bound on #538), over the consumer files alone (the head's and the merge base's trees filtered to code and tests and written into a scratch index that one `git grep` per tree reads), never the data under the patterns, so its cost follows the code a results PR can be read by and not the receipts it adds (GST-1435), and its git calls stay the same however many files the tree holds (GST-1442); it is not the collector's capped consumer scan. diff --git a/lib/review-collect.ts b/lib/review-collect.ts index c75fc75d1..b61465ce8 100644 --- a/lib/review-collect.ts +++ b/lib/review-collect.ts @@ -149,15 +149,16 @@ export const CONSUMER_SCAN_PATHSPEC_BYTES = 16_000; /** Output bytes one consumer grep may return across all its calls, the buffer the single whole-tree call had; past it the scan fails closed. */ export const CONSUMER_SCAN_OUTPUT_BYTES = 256 * 1024 * 1024; -export function reviewPlanTimeoutMs(): number { - const v = Number(process.env.GSTACK_REVIEW_PLAN_TIMEOUT_MS); - return Number.isFinite(v) && v >= 1 ? Math.floor(v) : REVIEW_PLAN_TIMEOUT_MS; +/** A whole number of at least 1 from the environment variable `name`, rounded down; anything else (unset, empty, zero, negative, not a number) is `fallback`. */ +function positiveEnv(name: string, fallback: number): number { + const v = Number(process.env[name]); + return Number.isFinite(v) && v >= 1 ? Math.floor(v) : fallback; } -export function consumerScanTimeoutMs(): number { - const v = Number(process.env.GSTACK_CONSUMER_SCAN_TIMEOUT_MS); - return Number.isFinite(v) && v >= 1 ? Math.floor(v) : CONSUMER_SCAN_TIMEOUT_MS; -} +export const reviewPlanTimeoutMs = (): number => positiveEnv('GSTACK_REVIEW_PLAN_TIMEOUT_MS', REVIEW_PLAN_TIMEOUT_MS); +export const consumerScanTimeoutMs = (): number => positiveEnv('GSTACK_CONSUMER_SCAN_TIMEOUT_MS', CONSUMER_SCAN_TIMEOUT_MS); +/** CONSUMER_SCAN_CAP, or GSTACK_REVIEW_CONSUMER_SCAN_CAP: more data candidates than this skip the scan and count every one as consumed (code). */ +export const consumerScanCap = (): number => positiveEnv('GSTACK_REVIEW_CONSUMER_SCAN_CAP', CONSUMER_SCAN_CAP); export type GrepFailure = { timedOut: boolean; status: number | null; err: string }; @@ -208,7 +209,7 @@ export function grepConsumers(root: string, patterns: readonly string[], rev: st */ export function scanConsumers(root: string, paths: readonly string[], revs: readonly string[], live: boolean, classRoot: string | readonly string[], errors: DepthError[], timeoutMs = consumerScanTimeoutMs()): string[] | 'all' { const candidates = [...new Set(paths)].filter(p => dataCandidate(p, classRoot) || svgCandidate(p, classRoot)).sort(); - if (candidates.length > CONSUMER_SCAN_CAP) return 'all'; + if (candidates.length > consumerScanCap()) return 'all'; const deadline = Date.now() + timeoutMs; const base = (p: string) => p.slice(p.lastIndexOf('/') + 1); const read = (file: string) => !scratch(file) && classifyPath(file, classRoot) !== 'docs'; diff --git a/lib/review-exclude.ts b/lib/review-exclude.ts index 2a9981a33..c3996bcf5 100644 --- a/lib/review-exclude.ts +++ b/lib/review-exclude.ts @@ -39,7 +39,7 @@ import { lineTags, swallowsAcrossLines, tagHunk } from './gate-diff/tags'; import { DATA_PATH, classifyPath, isAgentProse, isDataConfig, isGatePath, type PathLines } from './review-depth'; import { scan } from './redact-engine'; import { shannonEntropy } from './redact-patterns'; -import { KEY_NAME, RESULTS_TREE, SECRET_LINE, secretPath } from './review-risk'; +import { KEY_NAME, RESULTS_TREE, SECRET_LINE, hashManifest, secretPath } from './review-risk'; import { secretExcerpt } from './review-secret-excerpt'; import { cmpVersion, parseVersion } from './version-source'; import { REVIEW_EXCLUDE_KEY_VERSION, SHIP_POLICY_PATH, isUnavailable, policyUnavailableLine } from './ship-policy'; @@ -374,12 +374,15 @@ const consumer = (i: Scope, f: string, candidates: ReadonlySet, mode?: s || (!!i.declared?.has(f) && (!!i.keptDeclared?.has(f) || mode === '100755' || mode === '120000'))); /** - * An uncapped `git grep -F -o -f` of fixed strings at the head (or the working tree) and `revs`: string -> the consumer files + * An uncapped search for fixed strings at the head (or the working tree) and `revs`: string -> the consumer files * holding it; null when git could not list a tree, a consumer's name did not survive UTF-8 decoding, or git could not build * the scratch index or grep it (a timeout included). Each tree's file list is filtered to consumers first, so the data under * the patterns is never read (GST-1435: a whole-tree grep for 4,354 candidate paths through 30 MB of receipts ran 278 s), and * the consumers go into a scratch index that one git grep reads, so the git calls stay fixed however many files there are - * (GST-1442: 363 chunked greps over a 192k-file tree ran 132 s). On a live tree, an entry git reads from its blob + * (GST-1442: 363 chunked greps over a 192k-file tree ran 132 s). `git grep -l` lists the consumers holding any string, and + * only those are read and searched here: git's -o grew with the number of strings (HARN-64: 2,140 candidate paths in one + * 464 KB pins.sha256 ran past git's 120 s bound, so every candidate stayed in review). A consumer that is a hash or pin + * manifest (every line a digest and a path, lib/review-risk.ts) names files without reading them, so it keeps none. On a live tree, an entry git reads from its blob * (skip-worktree or assume-unchanged) goes into a second index grepped with --cached, as git grep itself would read it. */ function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet, revs: readonly string[]): Map> | null { @@ -409,14 +412,28 @@ function grepFixed(i: Scope, strings: readonly string[], candidates: ReadonlySet if (!entries.length) continue; const env = { ...process.env, GIT_INDEX_FILE: path.join(dir, `index-${n++}`) }; if (!git(i.root, ['update-index', '-z', '--index-info'], entries.join('\0') + '\0', env).ok) return null; - const r = git(i.root, ['grep', ...flags, '-I', '-F', '-o', '--null', '--no-line-number', '--no-column', '--no-color', '-f', list], undefined, env); - if (r.status !== 0 && r.status !== 1) return null; - for (const line of r.out.split('\n')) { - const parts = line.split('\0'); - const file = parts[0]; - const match = parts.length > 1 ? parts[parts.length - 1] : undefined; - if (!file || !match) continue; - (found.get(match) ?? found.set(match, new Set()).get(match)!).add(file); + const hits = git(i.root, ['grep', ...flags, '-I', '-F', '-l', '-z', '--no-color', '-f', list], undefined, env); + if (hits.status !== 0 && hits.status !== 1) return null; + const files = hits.out.split('\0').filter(Boolean); + const bodies = new Map(); + if (flags.length && files.length) { + const shas = new Map(entries.map(e => [e.slice(e.indexOf('\t') + 1), e.slice(0, e.indexOf('\t')).split(' ')[1]!])); + const want = files.map(f => shas.get(f)); + if (want.some(s => !s)) return null; + const b = spawnSync('git', ['cat-file', '--batch'], { cwd: i.root, input: want.join('\n') + '\n', timeout: 120_000, maxBuffer: MAX_BUFFER }); + if (b.status !== 0 || !b.stdout) return null; + let at = 0; + for (const f of files) { + const nl = b.stdout.indexOf(10, at); + const size = Number(b.stdout.subarray(at, nl).toString().split(' ')[2]); + if (nl < 0 || !Number.isInteger(size)) return null; + bodies.set(f, b.stdout.subarray(nl + 1, nl + 1 + size).toString('utf8')); + at = nl + 2 + size; + } + } else for (const f of files) try { bodies.set(f, fs.readFileSync(path.join(i.root, f), 'utf8')); } catch { return null; } + for (const [file, body] of bodies) { + if (hashManifest(body.split('\n'))) continue; + for (const s of strings) if (body.includes(s)) (found.get(s) ?? found.set(s, new Set()).get(s)!).add(file); } } } diff --git a/lib/review-risk.ts b/lib/review-risk.ts index 27870b5ec..0d7fd31a2 100644 --- a/lib/review-risk.ts +++ b/lib/review-risk.ts @@ -171,6 +171,16 @@ export const DOC_SECRET_LINE = [ /\b(?:mcp|auth|config|credentials?|tokens?|secrets?|keys?|login)\s+(?:get|show|print|view|cat|token)\b/i, /\b(?:get|show|print|cat)\s+(?:\S+[ ./-])?(?:tokens?|auth|credentials?|secrets?|api[_-]?keys?|bearer)\b/i, ]; +/** + * One line of a hash or pin manifest as sha256sum writes it (HARN-64: a preregistration's pins.sha256): an md5 to sha512 hex + * digest, one or two spaces, an optional binary-mode star and a path made only of letters, digits and . / _ - + @ ~ (no + * quote, =, $, bracket or semicolon, so no call or assignment fits). A file whose changed lines are all this names files and + * nothing else, so its lines carry no money, security, data or eval class (the secret line check still reads them); any other + * line keeps the whole file read as before. + */ +export const HASH_MANIFEST_LINE = /^[0-9a-f]{32,128} {1,2}\*?[\w./+@~-]+$/i; +export const hashManifest = (lines: readonly string[]) => lines.some(l => l.trim()) && lines.every(l => !l.trim() || HASH_MANIFEST_LINE.test(l.trim())); + /** Whether a path or line's tokens name money: a metering or charge word (a cost word too, for a path), or a pair. */ const pairs = (t: readonly string[], list: typeof MONEY_PAIRS) => list.some(([w, beside]) => t.includes(w) && t.some(x => beside.includes(x))); const namesMoney = (t: readonly string[], words: readonly string[]) => t.some(x => words.includes(x)) || pairs(t, MONEY_PAIRS); @@ -180,7 +190,7 @@ export const RISK_RULES = createHash('sha256').update(JSON.stringify({ RISK_CLASSES, MONEY_PATH_TOKENS, AUTH_PATH_TOKENS, AUTH_PATH_PREFIXES, KEY_NAME, SECURITY_PATH_TOKENS, DATA_PATH_TOKENS, EVAL_PATH_TOKENS, MONEY_LINE_TOKENS, MONEY_PAIRS, SPEND_PAIRS, REPORTED_COST_WORDS, MONEY_USD_WORDS, SECRET_SCAN, - patterns: Object.entries({ PROSE_PATH: [PROSE_PATH], DOC_SECRET_LINE, CONFIG_DATA_PATH: [CONFIG_DATA_PATH], STATS_SCRIPT: [STATS_SCRIPT], MONEY_LINE, PAID_MONEY_LINE, USD_COMPARE, RESULTS_TREE: [RESULTS_TREE], PRICE_USD_KEY: [PRICE_USD_KEY], PRICE_KEY_EXEMPT: [PRICE_KEY_EXEMPT], SECRET_LINE, SECRET_PATH: [SECRET_PATH], TOKEN_PATH: [TOKEN_PATH], TOKEN_SOURCE: [TOKEN_SOURCE], SECURITY_LINE, SECURITY_JOINED, DATA_LINE, SVG_PATH: [SVG_PATH], SVG_ACTIVE, SWIFT_PATH: [SWIFT_PATH], SWIFT_TEST_PATH: [SWIFT_TEST_PATH], SWIFT_SECURITY_LINE, SWIFT_DATA_LINE }).map(([k, v]) => [k, v.map(r => '/' + r.source + '/' + r.flags)]), + patterns: Object.entries({ HASH_MANIFEST_LINE: [HASH_MANIFEST_LINE], PROSE_PATH: [PROSE_PATH], DOC_SECRET_LINE, CONFIG_DATA_PATH: [CONFIG_DATA_PATH], STATS_SCRIPT: [STATS_SCRIPT], MONEY_LINE, PAID_MONEY_LINE, USD_COMPARE, RESULTS_TREE: [RESULTS_TREE], PRICE_USD_KEY: [PRICE_USD_KEY], PRICE_KEY_EXEMPT: [PRICE_KEY_EXEMPT], SECRET_LINE, SECRET_PATH: [SECRET_PATH], TOKEN_PATH: [TOKEN_PATH], TOKEN_SOURCE: [TOKEN_SOURCE], SECURITY_LINE, SECURITY_JOINED, DATA_LINE, SVG_PATH: [SVG_PATH], SVG_ACTIVE, SWIFT_PATH: [SWIFT_PATH], SWIFT_TEST_PATH: [SWIFT_TEST_PATH], SWIFT_SECURITY_LINE, SWIFT_DATA_LINE }).map(([k, v]) => [k, v.map(r => '/' + r.source + '/' + r.flags)]), })).digest('hex').slice(0, 16); export const tokens = (p: string) => p.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase().split(/[^a-z0-9]+/).filter(Boolean); @@ -221,8 +231,10 @@ export function matchRisk(i: RiskInput): Map { if (t.some(x => DATA_PATH_TOKENS.includes(x))) hit('data', 'data path: ' + p); if (!config && t.some(x => EVAL_PATH_TOKENS.includes(x))) hit('eval', 'eval scorer path: ' + p); if (SVG_PATH.test(p) && [i.added?.[p], i.removed?.[p]].some(l => l && svgActive(l.join('\n')))) hit('security', 'active SVG lines: ' + p); + const manifest = hashManifest([...(i.added?.[p] ?? []), ...(i.removed?.[p] ?? [])]); for (const line of [...(i.added?.[p] ?? []), ...(i.removed?.[p] ?? [])]) { if (!why.has('secret') && SECRET_LINE.some(r => r.test(line))) hit('secret', 'secret line: ' + p); + if (manifest) continue; if (!why.has('money') && pathOnly && (PAID_MONEY_LINE.some(r => r.test(line)) || (!PRICE_KEY_EXEMPT.test(p) && MONEY_USD.some(r => r.test(line)) && PRICE_USD_KEY.test(line)))) hit('money', 'spend cap, paid call or price key: ' + p); if (pathOnly) continue; if (!why.has('money') && (PAID_MONEY_LINE.some(r => r.test(line)) || (money && (usdMoney(line) || namesMoney(tokens(line), MONEY_LINE_TOKENS) || (!prose && pairs(tokens(line), SPEND_PAIRS)))))) hit('money', 'money line: ' + p); @@ -231,6 +243,7 @@ export function matchRisk(i: RiskInput): Map { if (swift && !why.has('security') && SWIFT_SECURITY_LINE.some(r => r.test(line))) hit('security', 'Swift permission request: ' + p); if (swift && !why.has('data') && SWIFT_DATA_LINE.some(r => r.test(line))) hit('data', 'Swift user-data line: ' + p); } + if (manifest) continue; if (!why.has('security') && [i.added?.[p], i.removed?.[p]].some(l => l && SECURITY_JOINED.some(r => r.test(l.join('\n'))))) hit('security', 'security lines: ' + p); if (swift && !why.has('security') && [i.added?.[p], i.removed?.[p]].some(l => l && SWIFT_SECURITY_LINE.some(r => r.test(l.join('\n'))))) hit('security', 'Swift permission request lines: ' + p); if (swift && !why.has('data') && [i.added?.[p], i.removed?.[p]].some(l => l && SWIFT_DATA_LINE.some(r => r.test(l.join('\n'))))) hit('data', 'Swift user-data lines: ' + p); diff --git a/test/fixtures/review-pins/files/lib/review-risk.ts.json b/test/fixtures/review-pins/files/lib/review-risk.ts.json index db763b592..3c159bb5e 100644 --- a/test/fixtures/review-pins/files/lib/review-risk.ts.json +++ b/test/fixtures/review-pins/files/lib/review-risk.ts.json @@ -1 +1 @@ -{"sha":"1bf74fcb384978ba30b36f02959a8e30c1f8feb9bbb549a99fbd9ff70496c80d","replay":"GST-3052"} +{"sha":"ea3575e908579e55829ae44e02736457b396447363bf0261f3aad54fab342c67","replay":"HARN-64"} diff --git a/test/fixtures/review-pins/replays/HARN-64.json b/test/fixtures/review-pins/replays/HARN-64.json new file mode 100644 index 000000000..7dc29e49e --- /dev/null +++ b/test/fixtures/review-pins/replays/HARN-64.json @@ -0,0 +1 @@ +{"replay":"HARN-64","justification":"HARN-64 no-loss replay (CREW rule 15): deterministic, no paid run. lib/review-risk.ts adds HASH_MANIFEST_LINE and hashManifest(): a file whose every changed line is a 32-128 hex digest, one or two spaces, an optional * and a path of [\\w./+@~-] (sha256sum output) skips the money, security, data and eval line rules; its path rules and the secret line rule still run, and one other line restores every rule. It can only drop line-rule hits on such files. Replay (GStack Minder drive handoffs/GSTA-757/harn64-replay.ts, rows harn64-replay.jsonl): on each commit's collectCommit input (scope {}, gate scan 0 on both sides), classifyDiff from main dd611038 and from this branch over 460 first-parent main commits (gstack 200 to dd611038, harness-evals 60 to f7dc2f9c, gstack-evals 200 to d8f8d1ba). 447 touch no manifest-shaped file, so both sides run the same code; the 13 that do (harness-evals 10, gstack-evals 3: pins.sha256, SHA256SUMS, MANIFEST.sha256, items.sha256, pack.sha256) give the same class and risk classes on all 13. 460 of 460 identical, none lowered. The one intended drop is harness-evals#538 (a PR, not on main): its pins.sha256 no longer reads as money (security, data and eval remain, full depth). Reviewer text is unchanged."} diff --git a/test/review-exclude-pin-manifest.test.ts b/test/review-exclude-pin-manifest.test.ts new file mode 100644 index 000000000..ea064997d --- /dev/null +++ b/test/review-exclude-pin-manifest.test.ts @@ -0,0 +1,79 @@ +/** + * review_exclude_paths on a results PR whose only reader of the data is a hash or pin manifest (HARN-64, harness-evals#538): + * the manifest named all 2,140 matched files by full path, so the exclusion's name scan kept every one as named-by-code + * (and git grep -o over 2,140 strings ran past its 120 s bound first), and the review refused a 13.3 MB diff. A manifest of + * digest-and-path lines names files without reading them; a real code file, or a manifest with any other line, still keeps + * what it names. The consumer-scan cap gets an override and a plan line naming both remedies. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { CONSUMER_SCAN_CAP, consumerScanCap } from '../lib/review-collect'; +import { REVIEW_EXCLUDE_KEY_VERSION } from '../lib/ship-policy'; +import { cleanup, commit, makeFixtureRepo, runBin, type FixtureRepo } from './helpers/pregate-fixture'; + +const repos: FixtureRepo[] = []; +afterEach(() => { while (repos.length) cleanup(repos.pop()!); }); + +const H = (n: number) => n.toString(16).padStart(2, '0').repeat(32); +const DATA = ['data/run/a.json', 'data/run/b.json']; +function repoWith(extra: Record) { + const repo = makeFixtureRepo({ prefix: 'gstack-xpin-', baseFiles: { '.gstack/ship-policy.json': JSON.stringify({ review_exclude_paths: ['data/**'], min_gstack_version: REVIEW_EXCLUDE_KEY_VERSION }) + '\n' } }); + repos.push(repo); + commit(repo, { 'data/run/a.json': '{"score": 1}\n', 'data/run/b.json': '{"score": 2}\n', ...extra }); + return repo; +} +const planned = (repo: FixtureRepo, env: Record = {}) => { + const r = runBin(repo, 'gstack-review-plan', ['--base', 'main', '--json'], env); + expect(r.status, r.err).toBe(0); + const x = JSON.parse(r.out).review_exclude; + return { excluded: x.excluded as number, kept: Object.fromEntries((x.kept_files as Array<{ path: string; reason: string }>).map(k => [k.path, k.reason])) }; +}; +const manifest = (lines: string[] = []) => [...DATA.map((p, i) => `${H(i)} ${p}`), ...lines].join('\n') + '\n'; + +describe('a hash or pin manifest does not keep the files it lists (HARN-64)', () => { + // Value: protects=a results PR whose pins.sha256 lists its matched data still gets review_exclude_paths; fails_when=the + // manifest counts as code naming every listed file (harness-evals#538 kept 2,140 files and refused 13.3 MB); why_new=HARN-64; + // seam=gstack-review-plan --json on a real repository; no_claim=the scan's speed on large trees (measured on #538 instead) + test('files a pins.sha256 lists are still excluded', () => { + expect(planned(repoWith({ 'docs/run/pins.sha256': manifest() }))).toEqual({ excluded: 2, kept: {} }); + }, 120_000); + + // Value: protects=a code file that names a data file still keeps it, beside a manifest (negative control); fails_when=the + // manifest rule widens to every consumer; seam=gstack-review-plan --json + test('a code file naming a listed file still keeps it in review', () => { + expect(planned(repoWith({ 'docs/run/pins.sha256': manifest(), 'lib/load.ts': "export const f = 'data/run/a.json';\n" }))).toEqual({ excluded: 1, kept: { 'data/run/a.json': 'named-by-code' } }); + }, 120_000); + + // Value: protects=a manifest-shaped file with any other line is read as a consumer (negative control); fails_when=a few digest + // lines exempt a file that also carries code or prose; seam=gstack-review-plan --json + // Value: protects=the scan still reads consumer names when git is set to color grep output; fails_when=git grep -l wraps names + // in ANSI escapes, every lookup misses and each file stays as consumer-scan-unavailable; why_new=the -l call lost --no-color; + // seam=gstack-review-plan --json with color.grep=always from GIT_CONFIG_*; no_claim=other color.* settings + test('files a pins.sha256 lists are still excluded when git colors grep output', () => { + expect(planned(repoWith({ 'docs/run/pins.sha256': manifest() }), { GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'color.grep', GIT_CONFIG_VALUE_0: 'always' })).toEqual({ excluded: 2, kept: {} }); + }, 120_000); + + test('a manifest with a code line keeps what it names', () => { + expect(planned(repoWith({ 'docs/run/pins.sha256': manifest(['run(process.argv[2])']) }))).toEqual({ excluded: 0, kept: { 'data/run/a.json': 'named-by-code', 'data/run/b.json': 'named-by-code' } }); + }, 120_000); +}); + +describe('the consumer-scan cap reads GSTACK_REVIEW_CONSUMER_SCAN_CAP and names both remedies (HARN-64)', () => { + // Value: protects=the cap keeps its default and bounds and the plan says what a tripped cap did and how to lift it; fails_when= + // an invalid value moves the cap, the override is ignored, or a tripped cap is silent; seam=consumerScanCap and the plan text + test('the override, its bounds and the plan line', () => { + const saved = process.env.GSTACK_REVIEW_CONSUMER_SCAN_CAP; + try { + const at = (v: string | undefined) => { if (v === undefined) delete process.env.GSTACK_REVIEW_CONSUMER_SCAN_CAP; else process.env.GSTACK_REVIEW_CONSUMER_SCAN_CAP = v; return consumerScanCap(); }; + expect(CONSUMER_SCAN_CAP).toBe(2000); + for (const v of [undefined, '', 'many', '0', '-3']) expect(at(v), String(v)).toBe(2000); + expect(at('5000')).toBe(5000); + expect(at('1.9')).toBe(1); + } finally { if (saved === undefined) delete process.env.GSTACK_REVIEW_CONSUMER_SCAN_CAP; else process.env.GSTACK_REVIEW_CONSUMER_SCAN_CAP = saved; } + const repo = repoWith({}); + const capped = runBin(repo, 'gstack-review-plan', ['--base', 'main'], { GSTACK_REVIEW_CONSUMER_SCAN_CAP: '1' }); + expect(capped.status, capped.err).toBe(0); + expect(capped.out).toContain('CONSUMER_SCAN: skipped: more than 1 data files changed'); + expect(capped.out).toContain('set GSTACK_REVIEW_CONSUMER_SCAN_CAP above that count, or move the data into its own PR'); + expect(runBin(repo, 'gstack-review-plan', ['--base', 'main']).out).not.toContain('CONSUMER_SCAN:'); + }, 120_000); +}); diff --git a/test/review-risk-hash-manifest.test.ts b/test/review-risk-hash-manifest.test.ts new file mode 100644 index 000000000..7be4a7c97 --- /dev/null +++ b/test/review-risk-hash-manifest.test.ts @@ -0,0 +1,34 @@ +/** + * A hash or pin manifest (each line a hex digest and a path, as sha256sum writes) names files; it does not spend, authenticate + * or hold secrets (HARN-64: a preregistration's pins.sha256 listed a path whose words read as money, and the plan printed the + * full five-reader panel). Its lines are skipped by the risk classes; a manifest with any other line is classified as before. + */ +import { describe, expect, test } from 'bun:test'; +import { matchRisk } from '../lib/review-risk'; + +const H = (n: number) => n.toString(16).padStart(2, '0').repeat(32); +const pins = ['docs/benchmarks/run/results/spend-ledger.json', 'docs/benchmarks/run/billing/charge-plan.yaml', 'docs/benchmarks/run/auth/session-keys.md']; +const classes = (p: string, lines: string[]) => [...matchRisk({ codePaths: [p], added: { [p]: lines }, scopeAuth: true }).keys()]; + +describe('hash and pin manifests carry no risk class by their lines (HARN-64)', () => { + // Value: protects=a pins.sha256 of digests and paths plans at its own depth, not the risk panel; fails_when=a money, auth or + // secret word inside a pinned path makes the manifest a risk file; seam=matchRisk; no_claim=the manifest's own path tokens + test('digest-and-path lines (sha256sum text and binary forms, md5 to sha512) name no risk', () => { + const lines = pins.map((p, i) => `${H(i)} ${p}`); + expect(classes('docs/benchmarks/run/pins.sha256', lines)).toEqual([]); + expect(classes('docs/benchmarks/run/pins.sha256', [`${H(1)} *${pins[0]}`, `${H(2).slice(0, 32)} ${pins[1]}`, `${H(3).repeat(2)} ${pins[2]}`])).toEqual([]); + }); + + // Value: protects=a manifest-shaped file that carries anything else is still read line by line (negative control); fails_when= + // one digest line exempts a file that also spends, or a code or prose line hides behind digests; seam=matchRisk + test('a manifest with a code or prose line is classified as before', () => { + const lines = pins.map((p, i) => `${H(i)} ${p}`); + expect(classes('docs/benchmarks/run/pins.sha256', [...lines, 'const spend_cap_usd = 5;'])).toEqual(['money']); + expect(classes('docs/benchmarks/run/pins.sha256', [...lines, '# the charge for each billing run is capped at $5'])).toContain('money'); + expect(classes('docs/benchmarks/run/pins.sha256', [`${H(1)} ${pins[0]} # spend_cap_usd = 5`])).not.toEqual([]); + expect(classes('src/pay.ts', ['const spend_cap_usd = 5;'])).toEqual(['money']); + expect(classes('docs/benchmarks/run/pins.sha256', [...lines, `${H(4)} run(process.argv[2]);`])).not.toEqual([]); + expect(classes('docs/benchmarks/run/pins.sha256', [...lines, `${H(5)} OPENAI_API_KEY=sk-proj-${'Ab3'.repeat(12)}`])).not.toEqual([]); + expect(classes('docs/benchmarks/run/pins.sha256', [...lines, `${H(6)} home/runner/.netrc`])).toContain('secret'); + }); +});