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>
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-24 19:33:34 +00:00
1 parent 3b9d9757fd
commit 284214fd89
4 files changed
+351 -22

No files matched your search

+86 -21
View File
@@ -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<T extends Pick<Scanned, 'file' | 'id' | 'line' | 'col' | 'lineText'>>(findings: T[], keys = new Set<string>()): T[] {
const textIds = new Map<string | undefined, number>();
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<typeof addedLines>;
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<Finding, 'file'>) => (!part.binary || f.category === 'secret') && (!part.keep || f.id?.startsWith('engine.') || (f.line !== undefined && part.keep.includes(f.line)))).map((f: Omit<Finding, 'file'>) => ({ ...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<string>();
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<Finding, 'file'>) => ({ ...f, lineText: f.line ? lines[f.line - 1] : undefined, ...(f.line !== undefined ? { line: f.line + first } : {}) })).filter((f: Omit<Finding, 'file'>) => (!part.binary || f.category === 'secret') && (!part.keep || f.id?.startsWith('engine.') || (f.line !== undefined && part.keep.includes(f.line)))).map((f: Omit<Finding, 'file'>) => ({ ...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<string>();
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');