From 2f57b07495f04e53ab146747d48dd9aed2aded29 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Thu, 19 Nov 2026 02:40:12 +0800 Subject: [PATCH] gstack's script runner and merge-queue checks now refuse cut-off command output (GST-3104) (#4502) The helper that runs gstack's own scripts and `bash -c` commands, and the merge queue's branch-ownership, stacked-test, release-version and merge-group record checks, now fail with `SPAWN_OUTPUT_INCOMPLETE` when Bun cuts a command's output off, instead of treating part of it as the whole answer. Why: #4492 added this for the scanners and gates but left these on Node's `spawnSync`, and its release note claimed wider coverage than it shipped. Nothing to do: a new test stops any new gstack command from calling Node's `spawnSync` directly. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- ...r-and-merge-queue-refuse-cut-off-output.md | 1 + crew/lib/lane-ownership.ts | 2 +- crew/lib/ship-queue-gate.ts | 2 +- crew/lib/ship-queue-stack-tests.ts | 2 +- crew/lib/ship-queue-train-record.ts | 2 +- crew/lib/version-gate-train.ts | 2 +- lib/script-invocation.ts | 3 +- test/fixtures/spawn-sync-raw-importers.json | 73 ++++++++++ test/helpers/doctor-fixture.ts | 2 +- test/helpers/free-fixtures-data.ts | 1 + test/plan-tune-cathedral.test.ts | 2 +- test/script-invocation.test.ts | 28 ++++ test/spawn-sync.test.ts | 127 +++++++++++++++++- test/timeline-stop-hook-slug.test.ts | 1 + 14 files changed, 237 insertions(+), 11 deletions(-) create mode 100644 changelog.d/script-runner-and-merge-queue-refuse-cut-off-output.md create mode 100644 test/fixtures/spawn-sync-raw-importers.json diff --git a/changelog.d/script-runner-and-merge-queue-refuse-cut-off-output.md b/changelog.d/script-runner-and-merge-queue-refuse-cut-off-output.md new file mode 100644 index 000000000..4a13297b9 --- /dev/null +++ b/changelog.d/script-runner-and-merge-queue-refuse-cut-off-output.md @@ -0,0 +1 @@ +- **gstack's script runner and merge-queue checks now also refuse cut-off output.** The helper that runs gstack's own scripts and `bash -c` commands, and the merge queue's branch-ownership, stacked-test, release-version and merge-group record checks, now fail with `SPAWN_OUTPUT_INCOMPLETE` when Bun cuts a command's output off at its read limit, as the pre-push hook and the pre-merge scans already do. The earlier entry about cut-off output said every other gstack command that reads large git or gh output was covered; it was not, because these went straight to Node's `spawnSync`. A new test now stops any gstack command from calling Node's `spawnSync` directly. The 68 files that still do so mostly run short commands or already check for this error. The rest (the co-author trailer helper's commit-log read, the CI health report and the release-stamp precondition) never decide a security check, a ship record or a merge check. The test lists them, and the list can only shrink. The browser's process-list read is still not covered. diff --git a/crew/lib/lane-ownership.ts b/crew/lib/lane-ownership.ts index e58b09b85..82a8adb8a 100644 --- a/crew/lib/lane-ownership.ts +++ b/crew/lib/lane-ownership.ts @@ -8,7 +8,7 @@ * resolved is reported (`LANE_REF_UNAVAILABLE`), never assumed clear. Planned * paths may be globs (`lib/**`); `*` and `**` are the only wildcards. */ -import { spawnSync } from 'node:child_process'; +import { spawnSync } from '../../lib/spawn-sync'; import { globToRegExp } from '../../lib/ship-policy'; export interface LaneRef { branch: string; pr: number | null; ref: string } diff --git a/crew/lib/ship-queue-gate.ts b/crew/lib/ship-queue-gate.ts index 313760eb4..586963710 100644 --- a/crew/lib/ship-queue-gate.ts +++ b/crew/lib/ship-queue-gate.ts @@ -17,7 +17,7 @@ * to leave the lane's machine. */ import { createHash, randomBytes } from 'node:crypto'; -import { spawnSync } from 'node:child_process'; +import { spawnSync } from '../../lib/spawn-sync'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { mergeChangelogs } from '../../lib/changelog-check'; diff --git a/crew/lib/ship-queue-stack-tests.ts b/crew/lib/ship-queue-stack-tests.ts index 87e9d8e0f..949dad4b6 100644 --- a/crew/lib/ship-queue-stack-tests.ts +++ b/crew/lib/ship-queue-stack-tests.ts @@ -14,7 +14,7 @@ import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; +import { spawnSync } from '../../lib/spawn-sync'; import { bunIsolationArgs } from '../../lib/bun-isolation'; import { git } from './ship-queue-gate'; import type { TrainPrefix, TrainSlot } from './ship-queue-train-record'; diff --git a/crew/lib/ship-queue-train-record.ts b/crew/lib/ship-queue-train-record.ts index c147d9d00..25cb6db23 100644 --- a/crew/lib/ship-queue-train-record.ts +++ b/crew/lib/ship-queue-train-record.ts @@ -8,7 +8,7 @@ * record is written locally before its note, and the note before any remote * effect that depends on it. */ -import { spawnSync } from 'node:child_process'; +import { spawnSync } from '../../lib/spawn-sync'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { redactFindingSpans } from '../../lib/redact-engine'; diff --git a/crew/lib/version-gate-train.ts b/crew/lib/version-gate-train.ts index 9aaad48e9..779ca53b3 100644 --- a/crew/lib/version-gate-train.ts +++ b/crew/lib/version-gate-train.ts @@ -7,7 +7,7 @@ * scripts/compare-pr-version.ts can accept an unstamped head and hold a * stamped one to the version the restamp allocates (base + the policy bump). */ -import { spawnSync } from 'node:child_process'; +import { spawnSync } from '../../lib/spawn-sync'; import * as fs from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; diff --git a/lib/script-invocation.ts b/lib/script-invocation.ts index 7ce46cc4d..df5d19b3c 100644 --- a/lib/script-invocation.ts +++ b/lib/script-invocation.ts @@ -28,12 +28,13 @@ * Paths are forward-slashed: Bun's spawnSync on Windows returns ENOENT for a * backslash exe path containing spaces, and bash reads backslashes as escapes. */ -import { spawnSync, type SpawnSyncOptions, type SpawnSyncOptionsWithStringEncoding, type SpawnSyncReturns } from 'node:child_process'; +import type { SpawnSyncOptions, SpawnSyncOptionsWithStringEncoding, SpawnSyncReturns } from 'node:child_process'; import * as fs from 'node:fs'; import * as path from 'node:path'; import { fileURLToPath } from 'node:url'; import { bunIsolationArgs } from './bun-isolation'; import { resultLine } from './result-codes'; +import { spawnSync } from './spawn-sync'; export const BIN_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin'); diff --git a/test/fixtures/spawn-sync-raw-importers.json b/test/fixtures/spawn-sync-raw-importers.json new file mode 100644 index 000000000..c1b61303b --- /dev/null +++ b/test/fixtures/spawn-sync-raw-importers.json @@ -0,0 +1,73 @@ +{ + "about": "Product files that still import spawnSync from node:child_process (GST-3104). This list may only shrink: a new product file imports spawnSync from lib/spawn-sync.ts, and a file that stops importing it raw leaves this list. Each one was checked as not reading unbounded security, receipt or gate output, or as already checking the result's error.", + "files": [ + "bin/gstack-approval-classes", + "bin/gstack-approvals", + "bin/gstack-brain-cache", + "bin/gstack-brain-context-load.ts", + "bin/gstack-checks", + "bin/gstack-contributor-mode", + "bin/gstack-decision-log", + "bin/gstack-eval-plan", + "bin/gstack-factory-scorecard", + "bin/gstack-gbrain-sync.ts", + "bin/gstack-global-discover.ts", + "bin/gstack-inventory", + "bin/gstack-lane-check", + "bin/gstack-next-version", + "bin/gstack-plain-title", + "bin/gstack-pr-shots", + "bin/gstack-redact", + "bin/gstack-regen", + "bin/gstack-release-stamp", + "bin/gstack-ship-policy", + "bin/gstack-ship-queue", + "bin/gstack-tree-receipt", + "browse/src/browse-client.ts", + "browse/src/browser-skills.ts", + "browse/src/bun-polyfill.cjs", + "browse/src/cli.ts", + "browse/src/domain-skill-commands.ts", + "browse/src/session-name.ts", + "browse/src/terminal-agent-control.ts", + "browser-skills/hackernews-frontpage/_lib/browse-client.ts", + "crew/bin/gstack-coauthor-trailers", + "crew/lib/restamp-release.ts", + "ios-qa/daemon/src/devicectl.ts", + "ios-qa/daemon/src/tunnel-bootstrap.ts", + "lib/aside-render.ts", + "lib/autoplan-admission.ts", + "lib/autoplan-gate-items.ts", + "lib/autoplan-prompts.ts", + "lib/bin-context.ts", + "lib/claude-code-migration.ts", + "lib/code-intelligence/gbrain-adapter.ts", + "lib/code-intelligence/graphify-adapter.ts", + "lib/cso/preparation-container.ts", + "lib/cso/windows-docker.ts", + "lib/gbrain-guards.ts", + "lib/gbrain-sources.ts", + "lib/harness-register.ts", + "lib/install-verdict.ts", + "lib/land-docs-only.ts", + "lib/pregate/checks/lanes.ts", + "lib/pregate/runtime.ts", + "lib/pregate/supervise.ts", + "lib/qa-deadline.ts", + "lib/qa-evidence.ts", + "lib/repo-state-clean.ts", + "lib/review-selection.ts", + "lib/review-sweep.ts", + "lib/ruled-notes.ts", + "lib/ship-clock.ts", + "lib/stamp-only.ts", + "make-pdf/src/pdftotext.ts", + "scripts/bump-harness-version.ts", + "scripts/ci-tree-reuse.ts", + "scripts/exercised-map.ts", + "scripts/gen-ship-goldens.ts", + "scripts/lib/free-ci-health.ts", + "scripts/size-ledger.ts", + "scripts/test-free-shards.ts" + ] +} diff --git a/test/helpers/doctor-fixture.ts b/test/helpers/doctor-fixture.ts index f8f49c1a2..373c8b938 100644 --- a/test/helpers/doctor-fixture.ts +++ b/test/helpers/doctor-fixture.ts @@ -23,7 +23,7 @@ const COPIED = [ 'autoplan/SKILL.md', // its frontmatter registers the autoplan hook the hooks-row test breaks 'bin/gstack-launch-probe.sh', 'bin/gstack-doctor-check.sh', 'bin/gstack-doctor-components.sh', 'bin/gstack-runtime-pins.ts', 'lib/runtime-pins.ts', - 'bin/gstack-windows-bash.ts', 'lib/script-invocation.ts', 'lib/bun-isolation.ts', 'lib/result-codes.ts', 'lib/result-codes-release.ts', 'lib/result-codes-capy.ts', 'lib/result-codes-budget.ts', 'lib/result-codes-eval.ts', 'lib/result-codes-plan.ts', 'lib/result-codes-autoplan.ts', 'lib/result-codes-browse.ts', 'lib/result-codes-clean.ts', 'lib/result-codes-plain.ts', // the windows bash row + 'bin/gstack-windows-bash.ts', 'lib/script-invocation.ts', 'lib/spawn-sync.ts', 'lib/bun-isolation.ts', 'lib/result-codes.ts', 'lib/result-codes-release.ts', 'lib/result-codes-capy.ts', 'lib/result-codes-budget.ts', 'lib/result-codes-eval.ts', 'lib/result-codes-plan.ts', 'lib/result-codes-autoplan.ts', 'lib/result-codes-browse.ts', 'lib/result-codes-clean.ts', 'lib/result-codes-plain.ts', // the windows bash row ]; const bases: string[] = []; /** Registers the per-test fixture cleanup; each test file calls it at top level (a hook in this module would bind to the first importing file only). */ diff --git a/test/helpers/free-fixtures-data.ts b/test/helpers/free-fixtures-data.ts index f0ba12010..56dec2674 100644 --- a/test/helpers/free-fixtures-data.ts +++ b/test/helpers/free-fixtures-data.ts @@ -252,6 +252,7 @@ export const FREE_FIXTURES: Readonly> = { 'test/fixtures/skill-contract/**': ['test/skill-contract-stop-hook.test.ts', 'test/skill-contract.test.ts'], 'test/fixtures/skill-evals/**': ['test/skill-eval-checks.test.ts', 'test/skill-eval-tasks.test.ts'], 'test/fixtures/skill-md-size-allowlist.json': ['test/skill-md-size-guard.test.ts'], + 'test/fixtures/spawn-sync-raw-importers.json': ['test/spawn-sync.test.ts'], 'test/fixtures/state-matrix-6792/**': ['test/state-matrix.test.ts'], 'test/fixtures/pregate-timing/**': ['test/pregate-timing.test.ts'], 'test/fixtures/skillify-narration/**': ['test/skill-fixture.test.ts'], diff --git a/test/plan-tune-cathedral.test.ts b/test/plan-tune-cathedral.test.ts index cbe751a23..af98307ed 100644 --- a/test/plan-tune-cathedral.test.ts +++ b/test/plan-tune-cathedral.test.ts @@ -71,7 +71,7 @@ function scaffoldFixture(workDir: string): { workDir: string; stateRoot: string; // These imports are resolved relative to the copied install, not the source checkout. const libDir = path.join(workDir, 'lib'); fs.mkdirSync(libDir, { recursive: true }); - for (const file of ['jsonl-store.ts', 'is-conductor.ts', 'state-root.ts', 'bin-context.ts', 'remote-identity.ts', 'script-invocation.ts', 'bun-isolation.ts', 'result-codes.ts', 'result-codes-release.ts', 'result-codes-capy.ts', 'result-codes-budget.ts', 'result-codes-eval.ts', 'result-codes-plan.ts', 'result-codes-autoplan.ts', 'result-codes-browse.ts', 'result-codes-clean.ts', 'result-codes-plain.ts']) { + for (const file of ['jsonl-store.ts', 'is-conductor.ts', 'state-root.ts', 'bin-context.ts', 'remote-identity.ts', 'script-invocation.ts', 'spawn-sync.ts', 'bun-isolation.ts', 'result-codes.ts', 'result-codes-release.ts', 'result-codes-capy.ts', 'result-codes-budget.ts', 'result-codes-eval.ts', 'result-codes-plan.ts', 'result-codes-autoplan.ts', 'result-codes-browse.ts', 'result-codes-clean.ts', 'result-codes-plain.ts']) { fs.copyFileSync(path.join(ROOT, 'lib', file), path.join(libDir, file)); } diff --git a/test/script-invocation.test.ts b/test/script-invocation.test.ts index 2959f648d..516b291d2 100644 --- a/test/script-invocation.test.ts +++ b/test/script-invocation.test.ts @@ -226,3 +226,31 @@ describe('wtreeFingerprint', () => { } finally { fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(shim, { recursive: true, force: true }); } }); }); + +describe('runScriptSync and runBashSync with output past maxBuffer (GST-3104)', () => { + // A child that ignores SIGTERM outlives Bun's overflow kill and exits 0, so raw spawnSync would + // report status 0 with ENOBUFS and cut-off stdout (GST-3086); these runners must report status null. + const OVERFLOW = "process.on('SIGTERM', () => {}); process.stdout.write('x'.repeat(200000)); setTimeout(() => {}, 300);"; + const expectIncomplete = (r: { status: number | null; error?: Error; stderr: string }) => { + expect(r.status).toBeNull(); + expect((r.error as NodeJS.ErrnoException | undefined)?.code).toBe('ENOBUFS'); + expect(r.stderr.trimEnd().split('\n').pop() ?? '').toEndWith('(SPAWN_OUTPUT_INCOMPLETE)'); + }; + + test('a bun-shebang script that overflows and exits 0 is not a finished read', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'script-invocation-overflow-')); + try { + const script = path.join(dir, 'gstack-overflow'); + fs.writeFileSync(script, `#!/usr/bin/env bun\n${OVERFLOW}\n`, { mode: 0o755 }); + expectIncomplete(runScriptSync(script, [], { encoding: 'utf8', maxBuffer: 1024, timeout: 20_000 })); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + // POSIX only: the command needs a POSIX bash with trap and /dev/zero. + test.skipIf(process.platform === 'win32')('a bash -c string that overflows and exits 0 is not a finished read', () => { + expectIncomplete(runBashSync("trap '' TERM; head -c 200000 /dev/zero | tr '\\0' x; sleep 0.3; exit 0", { encoding: 'utf8', maxBuffer: 1024, timeout: 20_000 })); + }); +}); + diff --git a/test/spawn-sync.test.ts b/test/spawn-sync.test.ts index 2df711430..f655158ce 100644 --- a/test/spawn-sync.test.ts +++ b/test/spawn-sync.test.ts @@ -12,8 +12,20 @@ import * as os from 'node:os'; import * as path from 'node:path'; import { RESULT_CODES } from '../lib/result-codes'; import { spawnSync } from '../lib/spawn-sync'; +import { listRepoFiles } from '../lib/pregate/import-graph'; import { gitEnv } from './helpers/git-env'; +/** + * The git binary itself, from `git --exec-path`, so a stub named git cannot be reached again through + * a PATH-resolving git wrapper (Bun.which('git') can return the wrapper). Falls back to Bun.which. + */ +function realGit(env: NodeJS.ProcessEnv = process.env): string { + const r = rawSpawnSync('git', ['--exec-path'], { encoding: 'utf8', timeout: 10_000, env }); + const bin = path.join((r.stdout ?? '').trim(), process.platform === 'win32' ? 'git.exe' : 'git'); + if (r.status === 0 && fs.existsSync(bin)) return bin; + return Bun.which('git', { PATH: env.PATH }) || '/usr/bin/git'; +} + const OVERFLOW = "process.on('SIGTERM', () => {}); process.stdout.write('x'.repeat(200000)); setTimeout(() => {}, 300);"; const overflowArgs = ['-e', OVERFLOW]; @@ -82,17 +94,17 @@ describe('the pre-push credential scan with a cut-off diff', () => { const head = git(['rev-parse', 'HEAD']); // The diff call prints about 90 MB of context lines first, so the real diff (and its key) lands past the // hook's 64 MiB maxBuffer; it ignores SIGTERM and exits 0, which is what Bun then reports as the status. - const realGit = Bun.which('git') || '/usr/bin/git'; + const gitBin = realGit(); const stub = [ '#!/bin/sh', 'if [ "$1" = "diff" ]; then', " trap '' TERM", " printf 'diff --git a/pad.txt b/pad.txt\\n--- a/pad.txt\\n+++ b/pad.txt\\n@@ -1,2000000 +1,2000000 @@\\n'", " yes ' padding line that only fills the read buffer of the scanner' | head -n 2000000", - ` "${realGit}" "$@"`, + ` "${gitBin}" "$@"`, ' exit 0', 'fi', - `exec "${realGit}" "$@"`, + `exec "${gitBin}" "$@"`, '', ].join('\n'); fs.writeFileSync(path.join(stubDir, 'git'), stub, { mode: 0o755 }); @@ -112,3 +124,112 @@ describe('the pre-push credential scan with a cut-off diff', () => { } }, 90_000); }); + +describe('the stub git finds the real git binary', () => { + // POSIX only: the wrapper is a #!/bin/sh file named git. + test.skipIf(process.platform === 'win32')('a PATH-resolving git wrapper first on PATH does not become the stub\'s real git', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spawn-sync-wrapper-')); + try { + fs.writeFileSync(path.join(dir, 'git'), `#!/bin/sh\nPATH=${process.env.PATH}\nexec git "$@"\n`, { mode: 0o755 }); + const PATH = `${dir}${path.delimiter}${process.env.PATH ?? ''}`; + expect(Bun.which('git', { PATH })).toBe(path.join(dir, 'git')); + const git = realGit({ ...process.env, PATH }); + expect(path.dirname(git)).not.toBe(dir); + expect(fs.readFileSync(git).subarray(0, 2).toString()).not.toBe('#!'); + expect(rawSpawnSync(git, ['--version'], { encoding: 'utf8', timeout: 10_000 }).stdout).toStartWith('git version'); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +}); + +describe('listRepoFiles (lib/pregate/import-graph.ts) refuses an unfinished git ls-files', () => { + test('a git that cannot start throws instead of returning no files', () => { + expect(() => listRepoFiles(path.join(os.tmpdir(), 'spawn-sync-no-such-repo', String(process.pid)))).toThrow('git ls-files did not finish'); + }); + + // POSIX only: the stub is a #!/bin/sh file named git, which Windows does not run. + test.skipIf(process.platform === 'win32')('a file list cut off past 64 MiB that exits 0 throws SPAWN_OUTPUT_INCOMPLETE', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'spawn-sync-ls-files-')); + const pathKey = Object.keys(process.env).find(k => k.toLowerCase() === 'path') || 'PATH'; + const saved = process.env[pathKey]; + try { + fs.writeFileSync(path.join(dir, 'git'), "#!/bin/sh\ntrap '' TERM\nyes 'lib/a-file-name-that-fills-the-list.ts' | head -n 2000000\nexit 0\n", { mode: 0o755 }); + process.env[pathKey] = `${dir}${path.delimiter}${saved ?? ''}`; + expect(() => listRepoFiles(dir)).toThrow('SPAWN_OUTPUT_INCOMPLETE'); + } finally { + process.env[pathKey] = saved; + fs.rmSync(dir, { recursive: true, force: true }); + } + }, 60_000); +}); + +/** + * GST-3104: product code takes spawnSync from lib/spawn-sync.ts. The files that still import it from + * node:child_process are listed in test/fixtures/spawn-sync-raw-importers.json, and that list may only + * shrink. Only code files and bin/ scripts are listed and read. + */ +const ROOT = path.resolve(import.meta.dir, '..'); +const BASELINE_PATH = 'test/fixtures/spawn-sync-raw-importers.json'; +const OWNER = 'lib/spawn-sync.ts'; + +const CODE = /\.(?:[cm]?[jt]s|tsx)$/; +const BIN = /(?:^|\/)bin\/[^/.]+$/; +const CODE_PATHSPECS = ['*.ts', '*.tsx', '*.mts', '*.cts', '*.js', '*.mjs', '*.cjs', 'bin/*', '*/bin/*']; +const isTest = (f: string) => /(^|\/)(test|tests|__tests__|fixtures)\//.test(f) || /\.test\.[cm]?[jt]sx?$/.test(f) || f === 'test-setup.ts'; +const CHILD_PROCESS = String.raw`['"](?:node:)?child_process['"]`; + +/** Whether this source takes spawnSync from node:child_process (named, aliased, namespace, default or require). */ +export function importsRawSpawnSync(text: string): boolean { + for (const m of text.matchAll(new RegExp(String.raw`import\s*\{([^}]*)\}\s*from\s*${CHILD_PROCESS}`, 'g'))) { + if (/(?:^|[,{\s])spawnSync\b/.test(m[1].replace(/\btype\s+spawnSync\b/g, ''))) return true; + } + for (const m of text.matchAll(new RegExp(String.raw`import\s+(?:\*\s+as\s+)?(\w+)\s+from\s*${CHILD_PROCESS}`, 'g'))) { + if (new RegExp(String.raw`\b${m[1]}\.spawnSync\b`).test(text)) return true; + } + return new RegExp(String.raw`require\(\s*${CHILD_PROCESS}\s*\)`).test(text) && /\bspawnSync\b/.test(text); +} + +function productSources(): Map { + const r = rawSpawnSync('git', ['ls-files', '-z', '--', ...CODE_PATHSPECS], { cwd: ROOT, encoding: 'utf8', timeout: 60_000, maxBuffer: 256 * 1024 * 1024 }); + if (r.status !== 0 || r.error) throw new Error(`git ls-files failed: ${r.error?.message ?? r.stderr}`); + const out = new Map(); + for (const f of r.stdout.split('\0').filter(Boolean)) { + if (isTest(f) || f === OWNER) continue; + const bin = BIN.test(f); + if (!CODE.test(f) && !bin) continue; + let text: string; + try { text = fs.readFileSync(path.join(ROOT, f), 'utf8'); } catch { continue; } + if (bin && !/^#!.*\b(?:bun|node|tsx)\b/.test(text)) continue; + out.set(f, text); + } + return out; +} + +describe('raw spawnSync import ratchet', () => { + const baseline = (JSON.parse(fs.readFileSync(path.join(ROOT, BASELINE_PATH), 'utf8')) as { files: string[] }).files; + const raw = [...productSources()].filter(([, text]) => importsRawSpawnSync(text)).map(([f]) => f).sort(); + + test('no product file outside the baseline imports spawnSync from node:child_process', () => { + const added = raw.filter(f => !baseline.includes(f)); + expect(added, `import spawnSync from ${OWNER} instead (it fails closed on cut-off output, GST-3086)`).toEqual([]); + }); + + test('the baseline only shrinks: a file that no longer imports it raw leaves the list', () => { + const stale = baseline.filter(f => !raw.includes(f)); + expect(stale, `remove these from ${BASELINE_PATH}`).toEqual([]); + expect([...baseline].sort(), `keep ${BASELINE_PATH} sorted`).toEqual(baseline); + }); + + test('the scanner sees every import form and ignores type-only and other imports', () => { + expect(importsRawSpawnSync("import { spawnSync } from 'node:child_process';")).toBe(true); + expect(importsRawSpawnSync('import { execSync, spawnSync as run } from "child_process";')).toBe(true); + expect(importsRawSpawnSync("import {\n spawn,\n spawnSync,\n} from 'node:child_process';")).toBe(true); + expect(importsRawSpawnSync("import * as cp from 'node:child_process';\ncp.spawnSync('git', [], { timeout: 1000 });")).toBe(true); + expect(importsRawSpawnSync("const { spawnSync } = require('child_process');")).toBe(true); + expect(importsRawSpawnSync("import type { SpawnSyncReturns } from 'node:child_process';")).toBe(false); + expect(importsRawSpawnSync("import { spawn, type spawnSync } from 'node:child_process';")).toBe(false); + expect(importsRawSpawnSync("import * as cp from 'node:child_process';\ncp.spawn('git', []);")).toBe(false); + expect(importsRawSpawnSync("import { spawnSync } from './spawn-sync';")).toBe(false); + }); +}); diff --git a/test/timeline-stop-hook-slug.test.ts b/test/timeline-stop-hook-slug.test.ts index f29681471..1b2e8eafa 100644 --- a/test/timeline-stop-hook-slug.test.ts +++ b/test/timeline-stop-hook-slug.test.ts @@ -28,6 +28,7 @@ const HOOK_FILES = [ 'lib/bin-context.ts', 'lib/remote-identity.ts', 'lib/script-invocation.ts', + 'lib/spawn-sync.ts', 'lib/bun-isolation.ts', 'lib/result-codes.ts', 'lib/result-codes-release.ts',