mirror of
https://github.com/garrytan/gstack.git
synced 2026-12-02 04:43:59 +01:00
/cso searches the whole repository in one call with a hard time limit (GST-3588) (#4742)
/cso can now search every file in a repository with one helper call, which stops at a hard time limit, and a daily report.md lists its low-confidence hypotheses. Why: audits that started never reached the vulnerable file because each file took its own helper call inside a 10-minute budget (gstack-evals#443). Nothing to do: the next `/cso` run uses it. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
1 parent
45b48f17d9
commit
a3ecfd530d
9 files changed
+254
-18
No files matched your search
+120
@@ -183,6 +183,7 @@ Usage:
|
||||
gstack-cso inspect RUN
|
||||
gstack-cso read RUN PATH_OR_HANDLE
|
||||
gstack-cso history RUN [PATH_OR_HANDLE]
|
||||
gstack-cso search RUN REGEX [--seconds N]
|
||||
gstack-cso submit RUN SUBMISSION.json
|
||||
gstack-cso scan RUN gitleaks|osv|semgrep|zizmor|trivy|schemathesis [REQUEST.json]
|
||||
gstack-cso scanner-outcome RUN ARTIFACT_ID
|
||||
@@ -1659,6 +1660,122 @@ async function read(args: string[]) {
|
||||
data = readBoundedStable(full, 1024 * 1024, 'Snapshot path');
|
||||
emit(data.toString('utf8'));
|
||||
}
|
||||
const SEARCH_PATTERN_LIMIT = 512,
|
||||
SEARCH_OUTPUT_BUDGET = 96 * 1024,
|
||||
SEARCH_LISTED = 50,
|
||||
SEARCH_SECONDS = 60;
|
||||
const listed = (paths: string[]) =>
|
||||
paths.slice(0, SEARCH_LISTED).join(', ') +
|
||||
(paths.length > SEARCH_LISTED ? `, and ${paths.length - SEARCH_LISTED} more` : '');
|
||||
/** One regex over every readable snapshot file in a worker the helper stops at a hard time limit; paths it could not search are listed as a coverage gap. */
|
||||
async function search(args: string[]) {
|
||||
const { dir } = run(args);
|
||||
let seconds = SEARCH_SECONDS;
|
||||
if (args.length === 3 && args[1] === '--seconds') {
|
||||
seconds = Number(args[2]);
|
||||
if (!Number.isInteger(seconds) || seconds < 1 || seconds > SEARCH_SECONDS)
|
||||
throw new CsoError('INVALID_ARGUMENT', `--seconds must be a whole number from 1 to ${SEARCH_SECONDS}`);
|
||||
args.splice(1, 2);
|
||||
}
|
||||
if (args.length !== 1) throw new CsoError('INVALID_ARGUMENT', 'search requires one regular expression');
|
||||
if (!args[0] || args[0].length > SEARCH_PATTERN_LIMIT)
|
||||
throw new CsoError('INVALID_ARGUMENT', `Search pattern must be 1 to ${SEARCH_PATTERN_LIMIT} characters`);
|
||||
try {
|
||||
new RegExp(args[0]);
|
||||
} catch {
|
||||
throw new CsoError('INVALID_ARGUMENT', 'Search pattern is not a valid regular expression');
|
||||
}
|
||||
const stopAt = Date.now() + seconds * 1000,
|
||||
manifest = readSnapshotManifest(dir);
|
||||
assertSnapshot(dir, manifest);
|
||||
const readable = join(dir, 'readable'),
|
||||
files: Array<{ path: string; shown: string }> = [],
|
||||
unsearched: string[] = [],
|
||||
windowed: string[] = [],
|
||||
out: string[] = [];
|
||||
let noCopy = 0,
|
||||
bytes = 0,
|
||||
hidden = 0,
|
||||
failed = false,
|
||||
current = '',
|
||||
settle: ((done: boolean) => void) | undefined,
|
||||
unfinished: string[] = [];
|
||||
for (const entry of manifest.entries) {
|
||||
const transformation = entry.transformation ?? '';
|
||||
if (transformation === OUTSIDE_AUDIT_PATHS) continue;
|
||||
if (
|
||||
/^(withheld|excluded):/.test(transformation) &&
|
||||
transformation !== 'withheld: exceeds the 1 MiB redacting-reader limit' &&
|
||||
!fs.existsSync(containedFile(readable, entry.path))
|
||||
) {
|
||||
noCopy++;
|
||||
continue;
|
||||
}
|
||||
files.push({ path: entry.path, shown: publicSnapshotPath(manifest, entry.path, entry.pathId).path });
|
||||
}
|
||||
const worker = new Worker(new URL('./search-worker.ts', import.meta.url).href),
|
||||
step = (message: object) =>
|
||||
new Promise<boolean>((resolve) => {
|
||||
const timer = setTimeout(() => resolve(false), Math.max(0, stopAt - Date.now()));
|
||||
settle = (done) => (clearTimeout(timer), resolve(done));
|
||||
worker.postMessage(message);
|
||||
});
|
||||
worker.onmessage = (event) => {
|
||||
const reply = event.data as { hit?: { line: number; text: string }; done?: boolean; windowed?: boolean };
|
||||
if (reply.hit) {
|
||||
const line = `${current}:${reply.hit.line}:${reply.hit.text}`;
|
||||
if (bytes + Buffer.byteLength(line) > SEARCH_OUTPUT_BUDGET) hidden++;
|
||||
else (out.push(line), (bytes += Buffer.byteLength(line) + 1));
|
||||
}
|
||||
if (reply.windowed) windowed.push(current);
|
||||
if (reply.done) settle?.(true);
|
||||
};
|
||||
worker.onerror = () => ((failed = true), settle?.(true));
|
||||
try {
|
||||
if (!(await step({ pattern: args[0] }))) unfinished = files.map((file) => file.shown);
|
||||
for (let index = 0; !failed && !unfinished.length && index < files.length; index++) {
|
||||
current = files[index].shown;
|
||||
let text: string;
|
||||
try {
|
||||
text = readBoundedStable(
|
||||
containedFile(readable, files[index].path),
|
||||
1024 * 1024,
|
||||
'Snapshot path',
|
||||
).toString('utf8');
|
||||
} catch (error) {
|
||||
if (!(error instanceof CsoError) || error.code !== 'MISSING_INPUT') throw error;
|
||||
unsearched.push(current);
|
||||
continue;
|
||||
}
|
||||
if (Date.now() >= stopAt || !(await step({ text })))
|
||||
unfinished = files.slice(index).map((file) => file.shown);
|
||||
}
|
||||
} finally {
|
||||
worker.terminate();
|
||||
}
|
||||
if (failed) throw new CsoError('INVALID_SCHEMA', 'Search worker failed');
|
||||
if (!out.length && !hidden) out.push('[gstack-cso search: no matches]');
|
||||
if (hidden) out.push(`[gstack-cso search: ${hidden} more matching lines not shown; narrow the pattern]`);
|
||||
if (unfinished.length)
|
||||
out.push(
|
||||
`[gstack-cso search: stopped at the ${seconds}-second limit; ${unfinished.length} paths not searched, a coverage gap: ${listed(unfinished)}]`,
|
||||
);
|
||||
if (unsearched.length)
|
||||
out.push(
|
||||
`[gstack-cso search: ${unsearched.length} unsearched paths (unreadable or over 1 MiB), a coverage gap: ${listed(unsearched)}]`,
|
||||
);
|
||||
if (windowed.length)
|
||||
out.push(
|
||||
`[gstack-cso search: ${windowed.length} paths have lines over 4096 characters, matched in overlapping 4 KiB windows where ^, $, lookbehind and matches over 256 characters are approximate: ${listed(windowed)}]`,
|
||||
);
|
||||
if (noCopy)
|
||||
out.push(
|
||||
`[gstack-cso search: ${noCopy} paths the snapshot excluded or withheld have no readable copy; inspect and report.md list them]`,
|
||||
);
|
||||
emit(out.join('\n'));
|
||||
if (unfinished.length)
|
||||
(await new Promise<void>((resolve) => process.stdout.write('', () => resolve())), process.exit(0));
|
||||
}
|
||||
async function history(args: string[]) {
|
||||
const { dir } = run(args),
|
||||
manifest = readSnapshotManifest(dir);
|
||||
@@ -2886,6 +3003,9 @@ export async function dispatchCsoCommand(
|
||||
case 'history':
|
||||
await history(args);
|
||||
return;
|
||||
case 'search':
|
||||
await search(args);
|
||||
return;
|
||||
case 'submit':
|
||||
result = submit(args);
|
||||
break;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
const WINDOW = 4096,
|
||||
OVERLAP = 256,
|
||||
EXCERPT = 300,
|
||||
LEAD = 100;
|
||||
let pattern: RegExp | undefined;
|
||||
|
||||
/** Matches one file's lines in bounded windows and posts each hit as it is found, so a search stopped mid-file keeps the hits before the stop. */
|
||||
self.onmessage = (event: MessageEvent) => {
|
||||
const message = event.data as { pattern?: string; text?: string };
|
||||
if (typeof message.pattern === 'string') {
|
||||
pattern = new RegExp(message.pattern);
|
||||
postMessage({ done: true });
|
||||
return;
|
||||
}
|
||||
let windowed = false;
|
||||
(message.text ?? '').split('\n').forEach((line, index) => {
|
||||
if (line.length > WINDOW) windowed = true;
|
||||
for (let start = 0; ; start += WINDOW - OVERLAP) {
|
||||
const found = pattern!.exec(line.slice(start, start + WINDOW));
|
||||
if (found) {
|
||||
const from = Math.max(0, start + found.index - LEAD);
|
||||
postMessage({ hit: { line: index + 1, text: line.slice(from, from + EXCERPT) } });
|
||||
return;
|
||||
}
|
||||
if (start + WINDOW >= line.length) return;
|
||||
}
|
||||
});
|
||||
postMessage({ done: true, windowed });
|
||||
};
|
||||
+19
-1
@@ -930,11 +930,29 @@ export function saveReport(dir: string, report: RunReportV3): void {
|
||||
);
|
||||
}
|
||||
try {
|
||||
atomicWriteSync(join(dir, 'report.md'), renderReport(safe), { mode: 0o600 });
|
||||
atomicWriteSync(join(dir, 'report.md'), readableReport(safe), { mode: 0o600 });
|
||||
} catch {
|
||||
throw new CsoError('PERSISTENCE_FAILED', 'JSON was saved but the readable report could not be written');
|
||||
}
|
||||
}
|
||||
/** A daily report.md also lists saved hypotheses, in the section the shared renderer writes for comprehensive runs. */
|
||||
function readableReport(report: RunReportV3): string {
|
||||
const text = renderReport(report),
|
||||
next = '\nSnapshot transformations:\n';
|
||||
const at = text.indexOf(next);
|
||||
if (
|
||||
at < 0 ||
|
||||
report.policy.mode === 'comprehensive' ||
|
||||
!report.findings.some((f) => f.evidence === 'hypothesis')
|
||||
)
|
||||
return text;
|
||||
const full = renderReport({ ...report, policy: { ...report.policy, mode: 'comprehensive' } });
|
||||
return (
|
||||
text.slice(0, at) +
|
||||
full.slice(full.indexOf('\nHypotheses (unconfirmed):\n'), full.indexOf(next)) +
|
||||
text.slice(at)
|
||||
);
|
||||
}
|
||||
export function loadReport(dir: string): RunReportV3 {
|
||||
const v = readJson(join(dir, 'report.json'));
|
||||
if (v.schemaVersion !== 3 || !Array.isArray(v.coverage) || !Array.isArray(v.findings))
|
||||
|
||||
Reference in new issue
Block a user