From 284214fd896f493471b1bb5e98bcdc899a87bcdb Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Tue, 24 Nov 2026 11:33:34 -0800 Subject: [PATCH] Large added files pass the secrets check in overlapping parts instead of failing (GST-3665) (#4796) The secrets check now scans an added file over 16 MiB in line-aligned, overlapping parts and reports each finding at its line in the file, instead of failing the whole file as HIGH with nothing to read. Why: gstack-redact refuses any input over 16 MiB, so every pull request that adds a large data file (harness-evals#609, a 60.5 MB trials.jsonl) was blocked with no way through. Nothing to do. A line that cannot be scanned with enough of the text before it still fails, and so does any part the scanner does not report on. Replaces #4792. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- ...ads-large-added-files-in-parts-gst-3665.md | 6 + docs/pregate.md | 5 +- lib/pregate/checks/secrets.ts | 107 ++++++-- test/pregate-secrets-large-file.test.ts | 255 ++++++++++++++++++ 4 files changed, 351 insertions(+), 22 deletions(-) create mode 100644 changelog.d/secrets-check-reads-large-added-files-in-parts-gst-3665.md create mode 100644 test/pregate-secrets-large-file.test.ts diff --git a/changelog.d/secrets-check-reads-large-added-files-in-parts-gst-3665.md b/changelog.d/secrets-check-reads-large-added-files-in-parts-gst-3665.md new file mode 100644 index 000000000..a37d88326 --- /dev/null +++ b/changelog.d/secrets-check-reads-large-added-files-in-parts-gst-3665.md @@ -0,0 +1,6 @@ +--- +important: blocker +--- +### Fixed + +- **The pre-merge secrets check now scans an added file over 16 MiB instead of failing it unread.** gstack-redact refuses any input over 16 MiB, so a branch that added a large data file, such as a 60 MB `trials.jsonl` of eval results, failed the check as HIGH with nothing to fix. The check now scans such a file in parts cut at line ends, each repeating at least 64K characters of the text before it (more when a credential environment value is longer), and reports every finding at its line in the file. A single line too long to scan whole, or too long to share a part with that much context, still fails and names the line, and a scanner run that prints no report is an incomplete scan, never a pass. (#4796) diff --git a/docs/pregate.md b/docs/pregate.md index 1dd5cc8c5..52ca7fdfc 100644 --- a/docs/pregate.md +++ b/docs/pregate.md @@ -228,7 +228,10 @@ Two stages with separate clocks, both printed: under its YAML key) are caught in UTF-16 text as in plain text. Only credential findings count in such a file, so image bytes that look like a phone number are not reported. A file whose scanned text is over the - scanner's 16 MiB limit fails the check, and the pre-push hook blocks a push + scanner's 16 MiB limit is scanned in parts cut at line ends, each repeating + at least 64K characters of the text before it, with findings reported at + their line in the file; a single line too long to scan whole, or to share a + part with that context, fails the check and names the line. The pre-push hook blocks a push whose diff is over 64 MiB. The hook leaves deleted files out of that diff, so removing a large binary does not count toward the limit, but a replaced binary's old bytes still do. Keep large binaries in Git LFS, whose small diff --git a/lib/pregate/checks/secrets.ts b/lib/pregate/checks/secrets.ts index 75f417d84..11a7892d0 100644 --- a/lib/pregate/checks/secrets.ts +++ b/lib/pregate/checks/secrets.ts @@ -6,11 +6,14 @@ * never env.value); a scanner that does not finish or exits outside its * contract is PREGATE_ENVIRONMENT (kind tool), never a pass, and so is a * merge-base diff git did not finish. Files git calls binary are read too - * (scannableReadings). Runs regardless of lint tools. + * (scannableReadings). A reading over gstack-redact's 16 MiB limit is + * scanned in overlapping line-aligned parts (scanParts); a single line over + * it fails. Runs regardless of lint tools. */ import { spawnSync } from '../../spawn-sync'; import * as fs from 'node:fs'; import * as path from 'node:path'; +import { credentialEnvValues, normalizeWithMap } from '../../redact-engine'; import { runScriptSync } from '../../script-invocation'; import { allowlistDigest, applyAllowlist, describeAllowlisted, describeMissed, describeUntested, displayPath, type AllowlistFinding } from '../allowlist'; import { baseInputs, sha256 } from '../context'; @@ -203,9 +206,67 @@ export function addedLines(ctx: PregateContext): Array<{ file: string; texts: st .map(({ text, ...p }) => ({ ...p, texts: scannableReadings(text), ...(text.includes('\0') ? { binary: true } : {}) })) .filter(p => p.texts.some(text => text.trim())); } +/** gstack-redact refuses a file over 16 MiB, whatever --max-bytes says, and asks for the input in parts (bin/gstack-redact). */ +const SCAN_MAX_BYTES = 16 * 1024 * 1024; +/** Lines a part repeats from the end of the part before it, so a block of lines (a PEM key) that crosses a cut is read whole in one part. */ +const SCAN_OVERLAP_LINES = 256; +/** Characters, as the scanner reads them, a part always repeats from the text before it: well over the widest context a rule reads around a match (400, PARCEL_CONTEXT_CHARS), so a key and the word that marks it (`aws_secret_access_key` within 100) are never cut apart. The check raises it to the longest credential environment value, which env.value matches whole. */ +const SCAN_OVERLAP_CHARS = 64 * 1024; + +/** + * GST-3665: a reading over gstack-redact's limit is scanned in line-aligned + * parts of at most `maxBytes`. Each part after the first repeats the end of + * the part before it: whole lines holding at least `overlapChars` + * characters as the scanner reads them (normalizeWithMap drops zero-width + * characters, so raw length can overstate the context), then up to `overlapLines` lines while the repeat stays under a quarter of + * the limit, so every part reads new lines. `first` is the 0-based index of + * a part's first line in the reading. A line that cannot be scanned whole, or + * cannot share a part with that much of the text before it, comes back as + * `{ line, why }` (1-based) and the reading is never scanned as a pass. + */ +export function scanParts(text: string, maxBytes = SCAN_MAX_BYTES, overlapLines = SCAN_OVERLAP_LINES, overlapChars = SCAN_OVERLAP_CHARS): Array<{ first: number; text: string }> | { line: number; why: string } { + if (Buffer.byteLength(text) <= maxBytes) return [{ first: 0, text }]; + const lines = text.split('\n'); + const size = lines.map(line => Buffer.byteLength(line) + 1); + const long = size.findIndex(n => n - 1 > maxBytes); + if (long >= 0) return { line: long + 1, why: `${size[long]! - 1} bytes, over the limit` }; + const parts: Array<{ first: number; text: string }> = []; + for (let first = 0, next = 0, overlap = 0; next < lines.length; ) { + let bytes = overlap; + let end = next; + while (end < lines.length && bytes + size[end]! - 1 <= maxBytes) bytes += size[end++]!; + parts.push({ first, text: lines.slice(first, end).join('\n') }); + if (end === lines.length) break; + next = first = end; + overlap = 0; + let chars = 0; + while (first > 0 && overlap + size[first - 1]! + size[next]! - 1 <= maxBytes && (chars < overlapChars || (next - first < overlapLines && overlap + size[first - 1]! <= maxBytes / 4))) { + overlap += size[--first]!; + chars += normalizeWithMap(lines[first]!).normalized.length + 1; + } + if (first > 0 && chars < overlapChars) return { line: next + 1, why: `${size[next]! - 1} bytes, too long to share the limit with the ${overlapChars} characters before it that a secret's context can span` }; + } + return parts; +} + type Finding = { id?: string; description?: string; severity?: string; category?: string; line?: number; col?: number; file: string; fileLine?: boolean }; type Scanned = Finding & AllowlistFinding; +/** + * Readings of one binary file that keep a line unchanged, and the lines a part repeats from the part before it, report a token again: list each finding once. + * The key holds a small id for the line's text, never the text itself, so thousands of findings on one long line build short keys. + */ +export function uniqueFindings>(findings: T[], keys = new Set()): T[] { + const textIds = new Map(); + return findings.filter(f => { + if (!textIds.has(f.lineText)) textIds.set(f.lineText, textIds.size); + const key = JSON.stringify([f.file, f.id, f.line, f.col, textIds.get(f.lineText)]); + if (keys.has(key)) return false; + keys.add(key); + return true; + }); +} + function run(ctx: PregateContext): CheckResult { let parts: ReturnType; try { parts = addedLines(ctx); } catch (err) { @@ -222,28 +283,31 @@ function run(ctx: PregateContext): CheckResult { let high = false; let medium = false; let parsedAll = true; - for (const [i, part] of parts.entries()) for (const [j, text] of part.texts.entries()) for (const [k, name] of scratchNames(part).entries()) { - const file = path.join(tmp, `${i}.${j}.${k}`, name); - fs.mkdirSync(path.dirname(file), { mode: 0o700 }); - fs.writeFileSync(file, text, { mode: 0o600 }); - const r = runScriptSync(path.join(BIN_DIR, 'gstack-redact'), ['--from-file', file, '--json', '--max-bytes', String(64 * 1024 * 1024)], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: Math.min(ctx.timeoutMs, 300_000), maxBuffer: 64 * 1024 * 1024, env: ctx.env }); - if (r.error || r.status === null) return environmentResult(base, launchCause('tool', `gstack-redact did not finish on ${part.file ? displayPath(part.file) : 'added lines'} (${r.error?.message ?? 'killed'})`), `gstack-redact did not finish on ${part.file ? displayPath(part.file) : 'added lines'}; an incomplete scan never passes`); - if (r.status !== 0 && r.status !== 2 && r.status !== 3) return environmentResult(base, launchCause('tool', `gstack-redact exited ${r.status} on ${part.file ? displayPath(part.file) : 'added lines'}: ${(r.stderr ?? '').trim().split('\n').pop() ?? ''}`), `gstack-redact exited ${r.status}; an incomplete scan never passes`); - high ||= r.status === 3; - medium ||= r.status === 2; - const lines = text.split('\n'); - try { for (const f of (JSON.parse(r.stdout).findings ?? []).filter((f: Omit) => (!part.binary || f.category === 'secret') && (!part.keep || f.id?.startsWith('engine.') || (f.line !== undefined && part.keep.includes(f.line)))).map((f: Omit) => ({ ...f, id: f.id ?? 'finding', category: f.category ?? '?', severity: f.severity ?? '?', file: part.file, fileLine: !!part.keep, lineText: f.line ? lines[f.line - 1] : undefined }))) findings.push(f); } catch { parsedAll = false; } + const unsplit = new Set(); + const overlapChars = Math.max(SCAN_OVERLAP_CHARS, ...credentialEnvValues(ctx.env ?? process.env).map(({ value }) => normalizeWithMap(value).normalized.length)); + for (const [i, part] of parts.entries()) for (const [j, reading] of part.texts.entries()) { + const pieces = scanParts(reading, SCAN_MAX_BYTES, SCAN_OVERLAP_LINES, overlapChars); + if (!Array.isArray(pieces)) { unsplit.add(`${part.file ? `${displayPath(part.file)}, ` : ''}${part.keep ? 'line' : 'added line'} ${pieces.line} (${pieces.why})`); continue; } + for (const [k, name] of scratchNames(part).entries()) for (const [m, { first, text }] of pieces.entries()) { + const file = path.join(tmp, `${i}.${j}.${k}.${m}`, name); + fs.mkdirSync(path.dirname(file), { mode: 0o700 }); + fs.writeFileSync(file, text, { mode: 0o600 }); + const r = runScriptSync(path.join(BIN_DIR, 'gstack-redact'), ['--from-file', file, '--json', '--max-bytes', String(64 * 1024 * 1024)], { cwd: ctx.repoRoot, encoding: 'utf8', timeout: Math.min(ctx.timeoutMs, 300_000), maxBuffer: 64 * 1024 * 1024, env: ctx.env }); + if (r.error || r.status === null) return environmentResult(base, launchCause('tool', `gstack-redact did not finish on ${part.file ? displayPath(part.file) : 'added lines'} (${r.error?.message ?? 'killed'})`), `gstack-redact did not finish on ${part.file ? displayPath(part.file) : 'added lines'}; an incomplete scan never passes`); + if (r.status !== 0 && r.status !== 2 && r.status !== 3) return environmentResult(base, launchCause('tool', `gstack-redact exited ${r.status} on ${part.file ? displayPath(part.file) : 'added lines'}: ${(r.stderr ?? '').trim().split('\n').pop() ?? ''}`), `gstack-redact exited ${r.status}; an incomplete scan never passes`); + high ||= r.status === 3; + medium ||= r.status === 2; + const lines = text.split('\n'); + try { for (const f of (JSON.parse(r.stdout).findings ?? []).map((f: Omit) => ({ ...f, lineText: f.line ? lines[f.line - 1] : undefined, ...(f.line !== undefined ? { line: f.line + first } : {}) })).filter((f: Omit) => (!part.binary || f.category === 'secret') && (!part.keep || f.id?.startsWith('engine.') || (f.line !== undefined && part.keep.includes(f.line)))).map((f: Omit) => ({ ...f, id: f.id ?? 'finding', category: f.category ?? '?', severity: f.severity ?? '?', file: part.file, fileLine: !!part.keep }))) findings.push(f); } catch { + if (r.status !== 3) return environmentResult(base, launchCause('tool', `gstack-redact exited ${r.status} with no JSON report on ${part.file ? displayPath(part.file) : 'added lines'}`), `gstack-redact printed no JSON report; an incomplete scan never passes`); + parsedAll = false; + } + } } // The allowlist applies only to findings the scanner reported in full; an unparsed report keeps its exit-code verdict. - const applied = parsedAll && ctx.config.allowlist.length ? applyAllowlist(findings, ctx.config.allowlist) : { kept: findings, allowlisted: [], untested: [], missed: [] }; - // Readings of one binary file that keep a line unchanged report its token again: list each finding once. - const reported = new Set(); - const kept = applied.kept.filter(f => { - const key = JSON.stringify([f.file, f.id, f.line, f.col, f.lineText]); - if (reported.has(key)) return false; - reported.add(key); - return true; - }); + const unique = uniqueFindings(findings); + const applied = parsedAll && ctx.config.allowlist.length ? applyAllowlist(unique, ctx.config.allowlist) : { kept: unique, allowlisted: [], untested: [], missed: [] }; + const kept = applied.kept; if (parsedAll) { high = kept.some(f => f.severity === 'HIGH'); medium = kept.some(f => f.severity === 'MEDIUM'); } const render = (f: Scanned) => `${f.severity} ${f.id} [${f.category}]: ${f.description ?? ''}${f.line ? ` (${f.file ? `${displayPath(f.file)}, ` : ''}${f.fileLine ? 'line' : 'added line'} ${f.line})` : ''}`; const allowLines = [...applied.allowlisted.map(describeAllowlisted), ...applied.untested.map(describeUntested), ...applied.missed.map(describeMissed)]; @@ -257,6 +321,7 @@ function run(ctx: PregateContext): CheckResult { const scanned = `${parts.length} file${parts.length === 1 ? '' : 's'}${binary ? ` (${binary} binary)` : ''}`; const lineCount = parts.reduce((n, p) => n + (p.keep?.length ?? p.texts[0].split('\n').length), 0); const fail = (lines: string[], detail: string): CheckResult => ({ ...base, status: 'fail', cause: 'diff', lines: [...lines, ...allowLines], code: 'PREGATE_SECRETS', detail: `${detail}${allowNote}`, fix: 'rotate and remove the credential from the added lines (history included); secrets cannot be downgraded (a benign finding is allowlisted by id, path and pattern in the policy, never env.value)' }); + if (unsplit.size) return { ...base, status: 'fail', cause: 'diff', lines: [...[...unsplit].map(l => `line not scanned within 16 MiB: ${l}`), ...[...blocking, ...advisory].map(render), ...allowLines], code: 'PREGATE_SECRETS', detail: `${unsplit.size} added line(s) cannot be scanned within gstack-redact's 16 MiB limit; a line is never cut for scanning, so it never passes${allowNote}`, fix: 'break the long lines into shorter ones (one record per line) or keep the file out of the branch; the secrets scan reads each line whole, beside 64K characters of the text before it, in parts of at most 16 MiB' }; if (!high && !medium) return { ...base, status: 'pass', ...(allowLines.length ? { lines: allowLines } : {}), detail: `${lineCount} added lines clean in ${scanned}${kept.length ? ` (${kept.length} WARN)` : ''}${allowNote}` }; if (blocking.length) return fail([...blocking, ...advisory].map(render), `${blocking.length} credential finding(s) in added lines (${blocking.map(f => f.id).join(', ')})`); if (high) return fail(kept.map(render), 'HIGH finding(s) in added lines'); diff --git a/test/pregate-secrets-large-file.test.ts b/test/pregate-secrets-large-file.test.ts new file mode 100644 index 000000000..8c4ba02a2 --- /dev/null +++ b/test/pregate-secrets-large-file.test.ts @@ -0,0 +1,255 @@ +/** + * GST-3665: pregate `secrets` scans an added file over gstack-redact's 16 MiB + * limit in overlapping line-aligned parts instead of failing it unread, and + * still fails closed on a line it cannot split or a part it cannot read. + * Every large fixture is built in the test's temporary directory at run time. + */ +import { afterEach, describe, expect, test } from 'bun:test'; +import { spawnSync } from 'child_process'; +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { scanParts, uniqueFindings } from '../lib/pregate/checks/secrets'; +import { applyAllowlist } from '../lib/pregate/allowlist'; +import { scan } from '../lib/redact-engine'; +import { secretsCheck } from '../lib/pregate/checks/secrets'; +import type { PregateContext } from '../lib/pregate/types'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const PREGATE = path.join(ROOT, 'bin', 'gstack-pregate'); +const MIB = 1024 * 1024; +const AWS = 'AKIA' + 'ZQ3XN7P2LM4RT8WV'; +const PAT = ['ghp', 'Zq8Lm2Xv7Nc4Rt9Wy1Kp6Hd3Fs5Gb0Jx8Ue2'].join('_'); +/** An AWS secret key the scanner reports only with `aws_secret_access_key` within 100 characters, here the end of the line before it. */ +const AWS_SECRET = ['Zq8Lm2Xv7Nc4Rt9Wy1Kp6Hd3', 'Fs5Gb0Jx8Ue2Ab1C'].join(''); +const AWS_SECRET_NAME = 'aws_secret_access_key:'; +const PEM = ['-----BEGIN ' + 'RSA PRIVATE KEY-----', ...Array.from({ length: 29 }, (_, i) => 'MIIEowIBAAKCAQEA' + String(i).padStart(2, '0').repeat(24)), '-----END ' + 'RSA PRIVATE KEY-----']; +/** One 1,024-byte line with its newline, so 16,384 of them fill one 16 MiB part. */ +const row = (n: number, text = `{"trial":${n},"task":"repo-fix-${n % 97}","passed":${n % 3 > 0}}`) => text.padEnd(1023, ' '); +const roots: string[] = []; +afterEach(() => { for (const r of roots.splice(0)) fs.rmSync(r, { recursive: true, force: true }); }); + +/** A repository whose branch commits `files` on top of main, with pregate's secrets check as the user runs it. */ +function repo(files: Record) { + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'pregate-large-'))); + roots.push(root); + const dir = path.join(root, 'work'); + const env = { ...process.env, HOME: root, GIT_CONFIG_GLOBAL: '/dev/null', GIT_CONFIG_NOSYSTEM: '1' }; + const git = (...args: string[]) => { + const r = spawnSync('git', args, { cwd: dir, encoding: 'utf8', env, timeout: 120_000 }); + if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`); + return r.stdout.trim(); + }; + fs.mkdirSync(dir); + git('init', '-q', '-b', 'main'); + git('config', 'user.email', 'fixture@example.test'); + git('config', 'user.name', 'Fixture'); + fs.writeFileSync(path.join(dir, 'README'), 'base\n'); + git('add', '.'); + git('commit', '-qm', 'base'); + git('init', '-q', '--bare', path.join(root, 'remote.git')); + git('remote', 'add', 'origin', path.join(root, 'remote.git')); + git('push', '-q', 'origin', 'main'); + git('fetch', '-q', 'origin'); + git('checkout', '-qb', 'feat'); + for (const [rel, text] of Object.entries(files)) { fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true }); fs.writeFileSync(path.join(dir, rel), text); } + git('add', '.'); + git('commit', '-qm', 'feat'); + const secrets = (extraEnv: Record = {}) => { + const r = spawnSync(PREGATE, ['--base', 'main', '--only', 'secrets', '--json'], { cwd: dir, encoding: 'utf8', env: { ...env, ...extraEnv }, timeout: 300_000, maxBuffer: 64 * MIB }); + const check = JSON.parse(r.stdout).checks.find((c: { id: string }) => c.id === 'secrets'); + return { status: check.status as string, detail: check.detail as string, lines: (check.lines ?? []) as string[] }; + }; + return { root, dir, env, mergeBase: git('merge-base', 'origin/main', 'HEAD'), secrets }; +} + +/** `count` rows of 1,024 bytes, with `at` replacing the rows at those 1-based line numbers. */ +function rows(count: number, at: Record = {}): string { + return Array.from({ length: count }, (_, i) => row(i + 1, at[i + 1])).join('\n') + '\n'; +} + +/** The 1-based line numbers of the findings a fail lists, in order. */ +const findingLines = (lines: string[]) => lines.map(l => /added line (\d+)\)$/.exec(l)?.[1]).filter(Boolean).map(Number); + +describe('scanParts: line-aligned overlapping parts under the scanner limit (GST-3665)', () => { + test('text at or under the limit is one part, unchanged', () => { + expect(scanParts('a\nb', 3)).toEqual([{ first: 0, text: 'a\nb' }]); + }); + + test('parts repeat the last overlap lines of the part before and cover every line in order', () => { + const lines = Array.from({ length: 25 }, (_, i) => `line-${String(i).padStart(4, '0')}`); + const parts = scanParts(lines.join('\n'), 100, 2, 0); + expect(Array.isArray(parts) && parts.map(p => p.first)).toEqual([0, 8, 16]); + expect(Array.isArray(parts) && parts.map(p => p.text)).toEqual([lines.slice(0, 10).join('\n'), lines.slice(8, 18).join('\n'), lines.slice(16).join('\n')]); + }); + + // Value: protects=every part fits the scanner, starts and ends on a line, and no line is skipped; fails_when=a cut lands mid-line, a part passes the limit, a line falls between parts, or the overlap stops shrinking for a long line; why_new=GST-3665; seam=pure splitter; no_claim=the scanner's own verdict + test('random line lengths, multi-byte text included: each part fits, is line-aligned, and the parts leave no gap', () => { + let seed = 7; + const rand = (n: number) => { seed = (seed * 1103515245 + 12345) % 2 ** 31; return seed % n; }; + for (let trial = 0; trial < 200; trial++) { + const max = 40 + rand(200); + const lines = Array.from({ length: 1 + rand(80) }, () => rand(4) ? 'x'.repeat(rand(max + 1)) : 'é'.repeat(rand(Math.floor(max / 2) + 1))); + const chars = rand(3) ? 0 : rand(max); + const parts = scanParts(lines.join('\n'), max, 1 + rand(6), chars); + if (!Array.isArray(parts)) { expect(chars).toBeGreaterThan(0); continue; } + let covered = 0; + for (const { first, text } of parts) { + expect(Buffer.byteLength(text)).toBeLessThanOrEqual(max); + expect(first).toBeLessThanOrEqual(covered); + if (first > 0) expect(lines.slice(first, covered).join('\n').length + 1).toBeGreaterThanOrEqual(chars); + const count = text.split('\n').length; + expect(text).toBe(lines.slice(first, first + count).join('\n')); + expect(first + count).toBeGreaterThan(covered); + covered = first + count; + } + expect(covered).toBe(lines.length); + } + }); + + test('a line one byte over the limit cannot be split and is named; a line exactly at the limit is scanned alone', () => { + expect(scanParts(['ok', 'x'.repeat(101), 'ok'].join('\n'), 100)).toEqual({ line: 2, why: '101 bytes, over the limit' }); + expect(scanParts(['é'.repeat(50) + 'x', 'ok'].join('\n'), 100)).toEqual({ line: 1, why: '101 bytes, over the limit' }); + expect(scanParts(['ok', 'x'.repeat(100), 'ok'].join('\n'), 100, 256, 0)).toEqual([{ first: 0, text: 'ok' }, { first: 1, text: 'x'.repeat(100) }, { first: 2, text: 'ok' }]); + }); + + // Value: protects=a match and the context its rule reads (a key and the name beside it) always share a part; fails_when=the repeat drops a long line before a cut, or two lines too long to share a part with that context are scanned apart and pass; why_new=GST-3665 review (second-model reader); seam=pure splitter; no_claim=rules reading more than 64K characters around a match + test('the line before a cut is repeated whole however long it is, and lines that cannot share a part with that context fail', () => { + const lines = ['x'.repeat(20), 'y'.repeat(60), 'z'.repeat(30)]; + expect(scanParts(lines.join('\n'), 100, 1, 40)).toEqual([{ first: 0, text: lines.slice(0, 2).join('\n') }, { first: 1, text: lines.slice(1).join('\n') }]); + expect(scanParts(['a'.repeat(60), 'b'.repeat(60)].join('\n'), 100, 256, 30)).toEqual({ line: 2, why: '60 bytes, too long to share the limit with the 30 characters before it that a secret\'s context can span' }); + }); + + // Value: protects=the repeat is measured in characters the scanner keeps, so text it drops (zero-width characters) cannot stand in for context; fails_when=raw length counts toward the repeat; why_new=GST-3665 final review (second-model reader); seam=pure splitter; no_claim=normalization beyond what normalizeWithMap does + test('zero-width characters do not count toward the repeat, and a line that cannot share a part with enough kept text fails', () => { + const lines = ['a'.repeat(40), '\u200b'.repeat(60), 'b'.repeat(40)]; + expect(scanParts(lines.join('\n'), 230, 1, 30)).toEqual({ line: 3, why: '40 bytes, too long to share the limit with the 30 characters before it that a secret\'s context can span' }); + }); + + test('a 40 MiB reading of 1,024-byte lines splits into three 16 MiB parts that repeat 256 lines', () => { + const parts = scanParts(rows(40_960).slice(0, -1)); + expect(Array.isArray(parts) && parts.map(p => [p.first, p.text.split('\n').length, Buffer.byteLength(p.text) <= 16 * MIB])).toEqual([[0, 16_384, true], [16_128, 16_384, true], [32_256, 8_704, true]]); + }); +}); + +describe('pregate secrets on an added file over 16 MiB (GST-3665)', () => { + // Value: protects=a results PR adding a clean data file over 16 MiB passes the secrets check; fails_when=the check hands the whole file to gstack-redact, which refuses it with exit 3 and no report, read as HIGH; why_new=GST-3665 (harness-evals#609, 60.5 MB trials.jsonl); seam=gstack-pregate end to end; no_claim=scan speed on other content + test('a clean 20 MiB data file passes instead of failing as HIGH', () => { + const r = repo({ 'results/trials.jsonl': rows(20_480) }).secrets(); + expect({ status: r.status, detail: r.detail }).toEqual({ status: 'pass', detail: '20480 added lines clean in 1 file' }); + }, 300_000); + + // Value: protects=a real secret anywhere in a split file still fails at its own line; fails_when=a part is skipped, a part's findings are dropped, line numbers stay relative to the part, or a block crossing a cut is missed; why_new=GST-3665; seam=gstack-pregate end to end; no_claim=secrets the scanner itself does not recognise + test('secrets in the first, middle and last parts and a key block across a cut each fail at their own line', () => { + const pem = Object.fromEntries(PEM.map((line, i) => [16_370 + i, line])); + const at = { 100: `{"aws_access_key_id":"${AWS}"}`, ...pem, 24_000: `{"token":"${PAT}"}`, 40_000: `{"aws_access_key_id":"${AWS}"}` }; + const text = rows(40_960, at); + const parts = scanParts(text.slice(0, -1)); + expect(Array.isArray(parts) && parts.map(p => [p.first + 1, p.first + p.text.split('\n').length])).toEqual([[1, 16_384], [16_129, 32_512], [32_257, 40_960]]); + const r = repo({ 'results/trials.jsonl': text }).secrets(); + expect(r.status).toBe('fail'); + expect(r.detail).toContain('credential finding(s)'); + expect([...new Set(findingLines(r.lines))].sort((a, b) => a - b)).toEqual([100, 16_370, 24_000, 40_000]); + }, 300_000); + + // Value: protects=a secret whose rule needs the line before it is found when a 5 MiB line ends right at a cut; fails_when=the repeat skips long lines, so neither part holds the key and its name; why_new=GST-3665 review (second-model reader); seam=gstack-pregate end to end, with a scanner-level control; no_claim=none + test('an AWS secret key named at the end of a 5 MiB line before a cut fails at its own line', () => { + expect(scan(`"${AWS_SECRET}"`, {}).findings.map(f => f.id)).toEqual([]); + expect(scan(`${AWS_SECRET_NAME}\n"${AWS_SECRET}"`, {}).findings.map(f => f.id)).toEqual(['aws.secret_key']); + const named = AWS_SECRET_NAME.padStart(5 * MIB - 1, ' '); + const text = rows(11_264) + named + '\n' + rows(1_024, { 1: `"${AWS_SECRET}"` }); + const parts = scanParts(text.slice(0, -1)); + expect(Array.isArray(parts) && parts.map(p => p.first)).toEqual([0, 11_264]); + const r = repo({ 'results/trials.jsonl': text }).secrets(); + expect(r.status).toBe('fail'); + expect(r.lines.filter(l => l.includes('aws.secret_key')).map(l => findingLines([l])[0])).toEqual([11_266]); + }, 300_000); + + // Value: protects=a secret whose name sits behind a 4.5 MB line of zero-width characters ending at a cut still fails; fails_when=the repeat counts characters the scanner drops, so the name never reaches the secret's part; why_new=GST-3665 final review, reproduced as a clean pass at cb50e0e; seam=gstack-pregate end to end; no_claim=none + test('an AWS secret key whose name is cut off by a zero-width line before a cut fails at its own line', () => { + const lines = [...Array.from({ length: 11_989 }, (_, i) => row(i + 1)), AWS_SECRET_NAME, '\u200b'.repeat(1_500_000), row(11_992, `"${AWS_SECRET}"`), ...Array.from({ length: 4_000 }, (_, i) => row(11_993 + i))]; + const text = lines.join('\n') + '\n'; + const parts = scanParts(text.slice(0, -1)); + expect(Array.isArray(parts) && [parts[0]!.text.split('\n').length, parts[1]!.first <= 11_989]).toEqual([11_991, true]); + const r = repo({ 'results/trials.jsonl': text }).secrets(); + expect(r.status).toBe('fail'); + expect(r.lines.filter(l => l.includes('aws.secret_key')).map(l => findingLines([l])[0])).toEqual([11_992]); + }, 300_000); + + // Value: protects=a credential environment value longer than the 64K repeat is found when it crosses a cut; fails_when=the repeat stays at 64K, so no part holds the whole value env.value matches; why_new=GST-3665 final review (second-model reader); seam=gstack-pregate end to end with the value in the scanner's environment; no_claim=values too long to share a part with their own text (they fail closed) + test('a 100K-character credential environment value that crosses a cut fails at its first line', () => { + let seed = 11; + const ALNUM = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + const value = Array.from({ length: 1_000 }, () => Array.from({ length: 99 }, () => { seed = (seed * 1103515245 + 12345) % 2 ** 31; return ALNUM[seed % 62]; }).join('')).join('\n'); + const text = rows(16_300) + value + '\n' + rows(2_000); + const parts = scanParts(text.slice(0, -1)); + const cut = Array.isArray(parts) ? parts[0]!.text.split('\n').length : 0; + expect(cut > 16_300 && cut < 17_300).toBe(true); + const r = repo({ 'results/trials.jsonl': text }).secrets({ FIXTURE_LONG_TOKEN: value }); + expect(r.status).toBe('fail'); + expect(r.lines.filter(l => l.includes('env.value')).map(l => findingLines([l])[0])).toEqual([16_301]); + }, 300_000); + + // Value: protects=a finding in the lines two parts share is allowlisted and reported once; fails_when=duplicates from the repeat reach the allowlist, so its note counts one finding twice; why_new=GST-3665 review (testing specialist); seam=secretsCheck.run in process with a policy allowlist; no_claim=allowlist matching itself (pregate-allowlist.test.ts) + test('an allowlisted finding in the lines two parts share is counted once', async () => { + const key = ['sk', 'trial', '1f2e3d4c-5b6a-7f8e-9d0c-1b2a3f4e5d6c'].join('-'); + const f = repo({ 'evals/trials.jsonl': rows(20_480, { 16_300: ` "key": "${key}",` }) }); + const scratch = path.join(f.root, 'scratch'); + fs.mkdirSync(scratch); + const allowlist = [{ finding: 'env.kv', paths: ['evals/**'], pattern: 'sk-trial-[0-9a-f-]+', reason: 'dummy per-trial meter ids' }]; + const check = await secretsCheck.run({ repoRoot: f.dir, mergeBase: f.mergeBase, wtree: 'w', head: 'h', baseRef: 'origin/main', baseSha: f.mergeBase, touched: [], config: { allowlist }, scratch, timeoutMs: 120_000, env: f.env } as unknown as PregateContext); + expect({ status: check.status, detail: check.detail }).toEqual({ status: 'pass', detail: '20480 added lines clean in 1 file; 1 allowlisted (env.kv)' }); + }, 300_000); + + // Value: protects=listing findings once stays small on a long line with many allowlisted matches, and still keeps findings whose line text differs apart; fails_when=the line's text is copied into every finding's key, so a 1 MiB line with thousands of matches builds gigabytes of keys; why_new=GST-3665 review (second-model review); seam=uniqueFindings then applyAllowlist, as secretsCheck.run calls them; no_claim=gstack-redact's matching + test('listing findings once builds short keys for many allowlisted matches on one long line', () => { + const key = ['sk', 'trial', '1f2e3d4c-5b6a-7f8e-9d0c-1b2a3f4e5d6c'].join('-'); + const cell = `"key": "${key}", `; + const line = cell.repeat(Math.ceil(MIB / cell.length)); + const at = (n: number, lineText = line) => ({ id: 'env.kv', category: 'secret', severity: 'HIGH', file: 'evals/trials.jsonl', line: 7, col: n * cell.length + 9, lineText }); + const findings = Array.from({ length: 4_000 }, (_, n) => at(n)); + const keys = new Set(); + const unique = uniqueFindings([...findings, ...findings, at(0, 'x'.repeat(8) + key)], keys); + expect(unique.length).toBe(4_001); + expect([...keys].reduce((n, k) => n + k.length, 0)).toBeLessThan(4_001 * 100); + const allowlist = [{ finding: 'env.kv', paths: ['evals/**'], pattern: 'sk-trial-[0-9a-f-]+', reason: 'dummy per-trial meter ids' }]; + const applied = applyAllowlist(unique, allowlist as never); + expect({ kept: applied.kept.length, allowlisted: applied.allowlisted.length }).toEqual({ kept: 0, allowlisted: 4_001 }); + }); + + // Value: protects=a line too long to split keeps failing closed and says why; fails_when=the over-limit line is skipped, cut mid-line or scanned as a pass; why_new=GST-3665; seam=gstack-pregate end to end; no_claim=none + test('a single line over 16 MiB fails closed and names the line', () => { + const r = repo({ 'results/blob.json': `{"a":1}\n"${'x'.repeat(16 * MIB)}"\n{"b":2}\n` }).secrets(); + expect(r.status).toBe('fail'); + expect(r.detail).toBe("1 added line(s) cannot be scanned within gstack-redact's 16 MiB limit; a line is never cut for scanning, so it never passes"); + expect(r.lines).toContain(`line not scanned within 16 MiB: results/blob.json, added line 2 (${16 * MIB + 2} bytes, over the limit)`); + }, 300_000); + + // Value: protects=a part the scanner does not report on never passes; fails_when=a later part's exit 0 or 2 with no JSON reads as clean or a warning; why_new=GST-3665 (each part is its own scanner run); seam=runScriptSync replaced in a child process; no_claim=gstack-redact's own output + test('a part that prints no JSON or exits outside the contract fails closed', () => { + const f = repo({ 'results/trials.jsonl': rows(20_480) }); + const worker = path.join(f.root, 'worker.ts'); + const invocation = path.join(ROOT, 'lib', 'script-invocation.ts'); + fs.writeFileSync(worker, ` +import { mock } from 'bun:test'; +const real = await import(${JSON.stringify(invocation)}); +const [status, stdout] = JSON.parse(process.argv[2]); +let calls = 0; +mock.module(${JSON.stringify(invocation)}, () => ({ ...real, runScriptSync: () => ++calls === 1 ? { status: 0, stdout: '{"findings":[]}', stderr: '' } : { status, stdout, stderr: 'stub' } })); +const { secretsCheck } = await import(${JSON.stringify(path.join(ROOT, 'lib', 'pregate', 'checks', 'secrets.ts'))}); +const scratch = ${JSON.stringify(path.join(f.root, 'scratch'))}; +require('node:fs').mkdirSync(scratch, { recursive: true }); +const check = await secretsCheck.run({ repoRoot: ${JSON.stringify(f.dir)}, mergeBase: ${JSON.stringify(f.mergeBase)}, wtree: 'w', head: 'h', baseRef: 'origin/main', baseSha: ${JSON.stringify(f.mergeBase)}, touched: [], config: { allowlist: [] }, scratch, timeoutMs: 60_000, env: process.env }); +console.log(JSON.stringify({ calls, status: check.status, code: check.code, detail: check.detail })); +`); + const run = (status: number, stdout: string) => { + const r = spawnSync(process.execPath, [worker, JSON.stringify([status, stdout])], { cwd: f.dir, encoding: 'utf8', env: f.env, timeout: 120_000 }); + if (r.status !== 0) throw new Error(`worker exited ${r.status}: ${r.stderr}`); + return JSON.parse(r.stdout.trim().split('\n').pop() || 'null'); + }; + expect(run(0, '')).toMatchObject({ calls: 2, status: 'incomplete', code: 'PREGATE_ENVIRONMENT', detail: 'gstack-redact printed no JSON report; an incomplete scan never passes' }); + expect(run(2, 'not json')).toMatchObject({ calls: 2, status: 'incomplete', code: 'PREGATE_ENVIRONMENT' }); + expect(run(1, '')).toMatchObject({ calls: 2, status: 'incomplete', code: 'PREGATE_ENVIRONMENT', detail: 'gstack-redact exited 1; an incomplete scan never passes' }); + expect(run(3, '')).toMatchObject({ calls: 2, status: 'fail', code: 'PREGATE_SECRETS' }); + }, 300_000); +});