* test(#3055): add the process seam and route runGsdTools through it Adds tests/helpers/process-seam.cjs — runNode/runGit/runHook over spawnSync, each returning a typed discriminated union { outcome, exitCode, stdout, stderr, timedOut, signal, killed, code }. Every call is timeout-bounded; there is no unbounded path. runGsdTools becomes an adapter over the seam. Its legacy { success, output, error, exitCode } shape and retry-once-on-kill behaviour are preserved byte-identically, so none of its 136 caller files change. Outcome discrimination was corrected against probed runtime behaviour rather than assumption: a timeout and a maxBuffer overflow are identical on both status (null) and signal (SIGTERM), and differ only by code (ETIMEDOUT vs ENOBUFS). Overflow is therefore classified before timeout. This fixes a live defect — the previous isKilled() treated an overflow as a kill, retried it for a second full 60s run, and then reported "host OOM or scheduler contention" for a child that had merely printed too much. Also widens the ESLint tests glob from tests/**/*.test.cjs to tests/**/*.cjs, which brought 31 previously unlinted shared helpers under the same rules their sibling test files already obey, and fixes the 5 violations that surfaced — including a bare npm invocation without shell:true in tests/helpers/emitted-runtime.cjs (DEFECT.WINDOWS-TEST-PORTABILITY), now routed through the existing portable runNpm helper. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(#3055): migrate every local spawn wrapper onto the process seam Replaces the spawn body of all 25 local runHook/runGuard/runGate definitions with a call to tests/helpers/process-seam.cjs. Each wrapper keeps its name, parameter list, return shape and post-processing (JSON parse, ANSI strip, env sanitising, field extraction) — only the spawn mechanism changes, so no test assertion moves. The 4 bash-driven wrappers use the seam's explicit `interpreter` option rather than a fourth primitive; it is explicit rather than inferred from the file extension, because guessing an interpreter from a path fails silently when a script's name does not match its shebang. Seven wrappers were previously unbounded and now carry an explicit timeout sized to what each actually runs, not the seam default. Two of those seven (gsd-write-guard, lint-docs-command-form) were absent from the issue's inventory entirely and were found by scanning after the migration. Adds the CONTEXT.md `### Process seam` glossary entry and a CONTRIBUTING.md reference section covering the three primitives, the discriminated union, and the two rules the seam enforces. Scope disclosure recorded in the phase design notes: the issue scoped three identifier names. A scan for local helpers that spawn AND return the spawn result finds 113 across 82 names, 71 of them unbounded, plus 122 unbounded direct git call sites. This change bounds 25 of those. The remaining surface is the same defect class and is NOT closed by this PR. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3055): classify an externally-killed child as KILLED, not EXITED Blocker found in this branch's own diff, independently confirmed by an isolated reviewer. A child killed by an external signal — a genuine bench OOM kill — makes spawnSync return { status: null, signal: 'SIGKILL' } with NO .error field. The seam's "no error implies EXITED" rule therefore classified it as a clean exit, and runGsdTools returned { success: false, exitCode: 1 } without retrying. That silently defeated the #969 kill-discrimination for precisely the case it was built for: the old isKilled() fired on `signal != null`, retried once, then threw a labelled resource-starvation error. A real OOM would have been reported as an ordinary assertion failure. Adds a fifth outcome, KILLED, for "no error but a signal is set", and makes the adapter retry on TIMED_OUT or KILLED — reproducing the old `killed || signal != null || code === 'ETIMEDOUT'` condition exactly. SPAWN_FAILED still does not retry (matching the old behaviour, where signal was null). BUFFER_OVERFLOW still does not retry, which remains a deliberate divergence: the old code retried it because signal was SIGTERM, burning a second 60s run on a child that had merely printed too much. All five outcomes verified against the live runtime rather than assumed: SIGKILL -> killed, exit 0/7 -> exited, timeout -> timed_out (ETIMEDOUT), >1MB stdout -> buffer_overflow (ENOBUFS). Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3055): address standards-review findings on this branch Three findings from the standards axis of the review, all in this branch's own diff. The CONTEXT.md glossary entry this branch introduced was already stale on the branch's own last commit: it enumerated a 4-member OUTCOME while the code had 5, because the KILLED fix did not update it. That is precisely the drift the "module changes update Domain-terms" gate exists to catch, so the entry now lists all five and explains KILLED. api-coverage-gate-e2e compared an outcome against the raw string 'exited' rather than OUTCOME.EXITED, the only such outlier; the enum is now imported and used. A sweep for the other four outcome literals found no further comparison sites. Three call sites hand the literal bash flag '-c' to the seam's first parameter, which the JSDoc described as an absolute script path. Rather than add a fourth primitive, the contract is corrected to match reality: the parameter is renamed `target` and documented as the first argv element handed to the interpreter — normally a script path, but for an interpreter invoked with an inline program it may be that interpreter's own flag. No behaviour change. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * test(#3055): assert the cross-platform timeout contract, not the macOS one The remote runner failed on both Linux lanes (node 22 and node 24, identical) while the same tests passed locally on macOS. Two assertions encoded a platform-specific behaviour as a cross-platform guarantee. When spawnSync times out, macOS preserves the child's partial stdout/stderr; Linux discards it and returns empty strings. Verified on node v26.5.1 both ways. The seam passes through whatever spawnSync hands it and cannot manufacture output that was discarded, so the production code was correct — the tests were wrong. Both tests now assert the guarantee the seam actually makes on every platform: outcome TIMED_OUT, timedOut true, and stdout/stderr always being strings rather than undefined or a Buffer. The partial-content assertions are retained behind an explicit process.platform === 'darwin' guard so the macOS coverage is not lost, and the first test is renamed to say what it now guarantees. This is the failure mode the remote matrix exists to catch: local macOS verification would have shipped it. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(#3055): classify a failed spawn as SPAWN_FAILED, not a timeout Windows CI caught two defects the Linux matrix could not. tests/context-predicates-query.test.cjs passes a 32K-char argv value. On Windows that exceeds the argv limit and spawnSync fails with code ENAMETOOLONG, signal null, status null. The seam's fallback rule — "otherwise, status === null implies TIMED_OUT" — swallowed it, so the adapter retried a spawn that can never succeed and then threw the resource-starvation error. The old isKilled() returned false for that shape and returned an ordinary failure result. TIMED_OUT is now identified positively: code === 'ETIMEDOUT' OR signal is set. Anything else carrying an error is SPAWN_FAILED, which covers ENAMETOOLONG, E2BIG, EACCES and ENOENT alike. The signal clause is what keeps a platform whose timeout errno differs classified correctly, so the greedy catch-all is no longer needed. The second defect is a contract regression I introduced and had claimed otherwise. That same test asserts `typeof r.exitCode === 'number'`, and toLegacyShape was returning null for BUFFER_OVERFLOW and SPAWN_FAILED, so the assertion failed on type. The old code returned `err.status ?? 1` on every non-retried failure path. The adapter now returns 1 again for both, and the comment claiming "never coerced to exitCode:1, unlike the pre-seam helper" is retracted: the seam keeps the richer truth (exitCode null plus a distinct outcome), the legacy adapter keeps the old numeric contract its callers actually depend on. Verified on this host: a 4MB argv yields E2BIG -> SPAWN_FAILED; ENOENT -> SPAWN_FAILED; timeout -> TIMED_OUT; >1MB stdout -> BUFFER_OVERFLOW; SIGKILL -> KILLED; clean exit -> EXITED. Refs #3051 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: sim <sim@local> Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
287 lines
12 KiB
JavaScript
287 lines
12 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Regression test for #114 — npm dependency integrity gate.
|
|
*
|
|
* Verifies that scripts/check-npm-integrity.cjs correctly detects:
|
|
* 1. Clean install — exits 0, no stderr findings
|
|
* 2. Version drift — exits 1, stderr names the offending package + both versions
|
|
* (reproduces the ws 8.20.1 declared vs 8.20.0 installed incident)
|
|
* 3. Extraneous — exits 1 without --ignore-extraneous; exits 0 with it
|
|
* 4. Missing — exits 1 regardless of flags
|
|
*
|
|
* Each fixture lives under tests/fixtures/npm-integrity/<name>/.
|
|
* The test spawns the script as a subprocess — no require/import of internals.
|
|
*
|
|
* Sources:
|
|
* - npm CLI docs: https://docs.npmjs.com/cli/v10/commands/npm-ls
|
|
* - NIST SSDF PW.4.1: https://csrc.nist.gov/publications/detail/sp/800-218/final
|
|
*/
|
|
|
|
const { describe, test } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const { spawnSync } = require('node:child_process');
|
|
const path = require('node:path');
|
|
const { runNode } = require('./helpers/process-seam.cjs');
|
|
|
|
const ROOT = path.resolve(__dirname, '..');
|
|
const SCRIPT = path.join(ROOT, 'scripts', 'check-npm-integrity.cjs');
|
|
const FIXTURES = path.join(__dirname, 'fixtures', 'npm-integrity');
|
|
|
|
/**
|
|
* Run the integrity gate script against a fixture directory.
|
|
*
|
|
* @param {string} fixtureName - subdirectory under tests/fixtures/npm-integrity/
|
|
* @param {string[]} [extraArgs] - additional CLI args passed to the script
|
|
* @returns {{ status: number, stdout: string, stderr: string }}
|
|
*/
|
|
function runGate(fixtureName, extraArgs = []) {
|
|
const fixtureDir = path.join(FIXTURES, fixtureName);
|
|
const r = runNode([SCRIPT, ...extraArgs], { cwd: fixtureDir, timeoutMs: 30_000 });
|
|
return {
|
|
status: r.exitCode ?? 1,
|
|
stdout: r.stdout,
|
|
stderr: r.stderr,
|
|
};
|
|
}
|
|
|
|
// ─── Scenario 1: Clean ───────────────────────────────────────────────────────
|
|
|
|
describe('#114: npm integrity gate — clean fixture', () => {
|
|
test('exits 0 when install matches lockfile', () => {
|
|
const { status } = runGate('clean');
|
|
assert.strictEqual(status, 0, 'expected exit 0 for clean install');
|
|
});
|
|
|
|
test('emits no integrity findings to stderr on clean install', () => {
|
|
const { stderr } = runGate('clean');
|
|
// No "FAIL:" lines expected
|
|
assert.ok(
|
|
!stderr.includes('FAIL:'),
|
|
`expected no FAIL: lines in stderr; got:\n${stderr}`
|
|
);
|
|
});
|
|
});
|
|
|
|
// ─── Scenario 2: Drift (declared vs installed mismatch) ─────────────────────
|
|
// Reproduces: ws 8.20.1 declared in lockfile, 8.20.0 installed in node_modules
|
|
// Fixture uses: stable-dep@8.20.1 (declared) vs stable-dep@8.20.0 (installed)
|
|
|
|
describe('#114: npm integrity gate — drift fixture (declared vs installed mismatch)', () => {
|
|
test('exits 1 on version drift', () => {
|
|
const { status } = runGate('drift');
|
|
assert.strictEqual(status, 1, 'expected exit 1 for version drift');
|
|
});
|
|
|
|
test('stderr names the offending package', () => {
|
|
const { stderr } = runGate('drift');
|
|
assert.ok(
|
|
stderr.includes('stable-dep'),
|
|
`expected stderr to name "stable-dep"; got:\n${stderr}`
|
|
);
|
|
});
|
|
|
|
test('stderr includes both the declared and installed versions', () => {
|
|
const { stderr } = runGate('drift');
|
|
assert.ok(
|
|
stderr.includes('8.20.0'),
|
|
`expected stderr to include installed version "8.20.0"; got:\n${stderr}`
|
|
);
|
|
assert.ok(
|
|
stderr.includes('8.20.1'),
|
|
`expected stderr to include declared version "8.20.1"; got:\n${stderr}`
|
|
);
|
|
});
|
|
});
|
|
|
|
// ─── Scenario 3: Extraneous ──────────────────────────────────────────────────
|
|
|
|
describe('#114: npm integrity gate — extraneous fixture', () => {
|
|
test('exits 1 when extraneous package present (default behavior)', () => {
|
|
const { status } = runGate('extraneous');
|
|
assert.strictEqual(status, 1, 'expected exit 1 for extraneous package without --ignore-extraneous');
|
|
});
|
|
|
|
test('stderr names the extraneous package', () => {
|
|
const { stderr } = runGate('extraneous');
|
|
assert.ok(
|
|
stderr.includes('ghost-pkg'),
|
|
`expected stderr to name "ghost-pkg"; got:\n${stderr}`
|
|
);
|
|
});
|
|
|
|
test('exits 0 with --ignore-extraneous flag', () => {
|
|
const { status } = runGate('extraneous', ['--ignore-extraneous']);
|
|
assert.strictEqual(status, 0, 'expected exit 0 for extraneous package with --ignore-extraneous');
|
|
});
|
|
});
|
|
|
|
// ─── Scenario 4: Missing ─────────────────────────────────────────────────────
|
|
|
|
describe('#114: npm integrity gate — missing fixture', () => {
|
|
test('exits 1 when required package is missing from node_modules', () => {
|
|
const { status } = runGate('missing');
|
|
assert.strictEqual(status, 1, 'expected exit 1 for missing package');
|
|
});
|
|
|
|
test('stderr names the missing package', () => {
|
|
const { stderr } = runGate('missing');
|
|
assert.ok(
|
|
stderr.includes('absent-dep'),
|
|
`expected stderr to name "absent-dep"; got:\n${stderr}`
|
|
);
|
|
});
|
|
|
|
test('exits 1 even with --ignore-extraneous (missing is not extraneous)', () => {
|
|
const { status } = runGate('missing', ['--ignore-extraneous']);
|
|
assert.strictEqual(status, 1, 'expected exit 1 for missing package even with --ignore-extraneous');
|
|
});
|
|
});
|
|
|
|
// ─── Smoke test: --help ───────────────────────────────────────────────────────
|
|
|
|
describe('#114: npm integrity gate — --help output', () => {
|
|
test('exits 0 with --help flag', () => {
|
|
const result = spawnSync(process.execPath, [SCRIPT, '--help'], {
|
|
cwd: ROOT,
|
|
encoding: 'utf-8',
|
|
timeout: 10_000,
|
|
});
|
|
assert.strictEqual(result.status, 0, '--help should exit 0');
|
|
});
|
|
|
|
test('--help output mentions --ignore-extraneous', () => {
|
|
const result = spawnSync(process.execPath, [SCRIPT, '--help'], {
|
|
cwd: ROOT,
|
|
encoding: 'utf-8',
|
|
timeout: 10_000,
|
|
});
|
|
// The .cjs script writes --help to stdout.
|
|
const helpText = (result.stdout ?? '') + (result.stderr ?? '');
|
|
assert.ok(
|
|
helpText.includes('--ignore-extraneous'),
|
|
`expected --help output to document --ignore-extraneous; got:\n${helpText}`
|
|
);
|
|
});
|
|
});
|
|
|
|
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
// Folded from tests/bug-3588-npm-audit-clean.test.cjs — consolidation epic #1969 (B6 #1975)
|
|
// ────────────────────────────────────────────────────────────────────────
|
|
{
|
|
const { describe: __foldDescribe } = require('node:test');
|
|
__foldDescribe("folded:bug-3588-npm-audit-clean (consolidation epic #1969 B6 #1975)", () => {
|
|
'use strict';
|
|
|
|
/**
|
|
* Regression test for #3588 — production dependency tree must not carry
|
|
* high or moderate npm-audit advisories.
|
|
*
|
|
* Strategy: run `npm audit --omit=dev --json` against both the root
|
|
* workspace and the embedded SDK package and assert that the metadata
|
|
* vulnerability counts are zero across info/low/moderate/high/critical.
|
|
*
|
|
* The test is intentionally strict — any advisory of any severity (other
|
|
* than 'low' if the maintainer accepts it; that branch is left explicit
|
|
* here) blocks CI. If a future advisory lands without an upstream patch,
|
|
* either bump the patched transitive (preferred), or annotate the
|
|
* acceptance below with a justification AND a link to the upstream tracker.
|
|
*
|
|
* Skips automatically when `node_modules/` is absent (a fresh checkout
|
|
* before `npm install`) so the test does not falsely report on developer
|
|
* machines mid-setup.
|
|
*/
|
|
|
|
const { test, describe } = require('node:test');
|
|
const assert = require('node:assert/strict');
|
|
const path = require('node:path');
|
|
const fs = require('node:fs');
|
|
const { execFileSync } = require('node:child_process');
|
|
|
|
const ROOT = path.resolve(__dirname, '..');
|
|
const SDK = path.join(ROOT, 'sdk');
|
|
const AUDIT_TIMEOUT_MS = 180_000;
|
|
const TEST_TIMEOUT_MS = AUDIT_TIMEOUT_MS + 30_000;
|
|
|
|
function auditProductionVulns(cwd) {
|
|
if (!fs.existsSync(path.join(cwd, 'package.json'))) {
|
|
return null; // signal "skip" to caller
|
|
}
|
|
if (!fs.existsSync(path.join(cwd, 'node_modules'))) {
|
|
return null; // signal "skip" to caller
|
|
}
|
|
const isWindows = process.platform === 'win32';
|
|
const npmCandidates = isWindows ? ['npm.cmd', 'npm'] : ['npm'];
|
|
const args = ['audit', '--omit=dev', '--json'];
|
|
let out;
|
|
let lastErr = null;
|
|
for (const npmCmd of npmCandidates) {
|
|
try {
|
|
out = execFileSync(
|
|
npmCmd,
|
|
args,
|
|
{
|
|
cwd,
|
|
encoding: 'utf-8',
|
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
timeout: AUDIT_TIMEOUT_MS,
|
|
shell: isWindows,
|
|
}
|
|
);
|
|
lastErr = null;
|
|
break;
|
|
} catch (e) {
|
|
// `npm audit` exits non-zero when advisories are present; the JSON is
|
|
// still on stdout in that case. Recover and let the assertion classify.
|
|
if (e && typeof e.stdout !== 'undefined' && e.stdout !== undefined && e.stdout !== null) {
|
|
out = Buffer.isBuffer(e.stdout) ? e.stdout.toString('utf-8') : String(e.stdout);
|
|
lastErr = null;
|
|
break;
|
|
}
|
|
lastErr = e;
|
|
}
|
|
}
|
|
if (lastErr) throw lastErr;
|
|
const parsed = JSON.parse(out);
|
|
// `null` is reserved for the "node_modules missing → skip" signal above.
|
|
// Any other unexpected JSON shape is a real failure of the audit harness
|
|
// (npm changed its output format, audit aborted before metadata, etc.) —
|
|
// throw so the test fails loudly instead of skipping silently.
|
|
if (parsed && parsed.metadata && parsed.metadata.vulnerabilities) {
|
|
return parsed.metadata.vulnerabilities;
|
|
}
|
|
throw new Error(`Unexpected npm audit JSON shape in ${cwd}: missing metadata.vulnerabilities`);
|
|
}
|
|
|
|
describe('#3588: npm audit --omit=dev reports zero advisories', () => {
|
|
test('root workspace production tree has no advisories', { timeout: TEST_TIMEOUT_MS }, (t) => {
|
|
const vulns = auditProductionVulns(ROOT);
|
|
if (vulns === null) {
|
|
t.skip('auditable npm package not present or node_modules/ missing');
|
|
return;
|
|
}
|
|
assert.strictEqual(vulns.critical, 0, `expected 0 critical; got ${vulns.critical}`);
|
|
assert.strictEqual(vulns.high, 0, `expected 0 high; got ${vulns.high}`);
|
|
assert.strictEqual(vulns.moderate, 0, `expected 0 moderate; got ${vulns.moderate}`);
|
|
// Low advisories are not explicitly forbidden by the #3588 acceptance
|
|
// criterion but the issue listed only high/moderate as actual findings —
|
|
// tighten if any future low advisory is introduced.
|
|
assert.strictEqual(vulns.low, 0, `expected 0 low; got ${vulns.low}`);
|
|
});
|
|
|
|
test('sdk/ production tree has no advisories', { timeout: TEST_TIMEOUT_MS }, (t) => {
|
|
const vulns = auditProductionVulns(SDK);
|
|
if (vulns === null) {
|
|
t.skip('sdk/ is not an auditable npm package or sdk/node_modules/ is missing');
|
|
return;
|
|
}
|
|
assert.strictEqual(vulns.critical, 0, `expected 0 critical; got ${vulns.critical}`);
|
|
assert.strictEqual(vulns.high, 0, `expected 0 high; got ${vulns.high}`);
|
|
assert.strictEqual(vulns.moderate, 0, `expected 0 moderate; got ${vulns.moderate}`);
|
|
assert.strictEqual(vulns.low, 0, `expected 0 low; got ${vulns.low}`);
|
|
});
|
|
});
|
|
});
|
|
}
|