From 96338fbf0e5204fdad4dd530599d095d9c8cefd6 Mon Sep 17 00:00:00 2001 From: jose luis <2064537+sosan@users.noreply.github.com> Date: Mon, 23 Nov 2026 02:18:31 +0100 Subject: [PATCH] fix(security): diagnostic cerrado en code-safety con exit 2/3 y etapa del fallo (#276) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La causa de la intermitencia quedaba oculta: el CLI colapsaba todo error a code-safety-failed con exit 2, descartando la etapa que run-semgrep ya distinguía. Esta instrumentación conserva solo identificadores cerrados: - Exit 0: run resuelto (los findings siguen siendo advisory). - Exit 2: error de contrato determinista (argv, bad-command, input, platform, uid, trusted-files, trusted-lock, snapshot, mount-path, wheelhouse, control, control-hash, snapshot-hash, trusted-manifest, provision-result, report-normalize, tamper, unknown). - Exit 3: error de infraestructura donde relanzar puede servir (docker-create, scanner, report-parse, cleanup, provision). report se separa en report-parse (salida del scanner truncada, infra) y report-normalize (JSON válido, contrato), como pidió la revisión. El diagnóstico se emite en una única línea de stderr y en GITHUB_STEP_SUMMARY con solo campos cerrados (label, scanner, stage, class, exit, durationMs); runZizmor ahora se identifica como zizmor, no semgrep. No se propaga salida del scanner, rutas, commits, dependencias ni snippets, y no se suben artefactos. README documenta la migración para consumidores con baseline fijada; tamper queda marcado como fallo de integridad no reintentable. --- .github/security-drafts/README.md | 34 ++++++ .github/security-drafts/code-safety.yml | 17 ++- .github/workflows/code-safety.yml | 17 ++- scripts/security/code-safety.mjs | 99 +++++++++++---- scripts/security/code-safety.test.mjs | 156 +++++++++++++++++++++++- scripts/security/run-semgrep.mjs | 26 ++-- scripts/security/run-semgrep.test.mjs | 36 ++++-- 7 files changed, 341 insertions(+), 44 deletions(-) diff --git a/.github/security-drafts/README.md b/.github/security-drafts/README.md index ac68bb5..1a30cdc 100644 --- a/.github/security-drafts/README.md +++ b/.github/security-drafts/README.md @@ -43,6 +43,27 @@ capabilities eliminadas, no-new-privileges, límites de CPU/memoria/procesos y t El runner elimina sus temporales y contenedores; el operador elimina el wheelhouse cuando termine. Una creación Docker que termine tarde tras un timeout no tiene garantía absoluta de ausencia de residuos. +## Códigos de salida y diagnóstico (criterios de #276) + +`code-safety.mjs scan` sale con `0` solo cuando el análisis se resuelve, tenga o no findings +(los hallazgos son advisory y nunca cambian el exit). Ante un fallo: + +| Exit | Clase | Etapas | +| --- | --- | --- | +| `2` | Contrato (determinista; relanzar no sirve) | `argv`, `bad-command`, `input`, `platform`, `uid`, `trusted-files`, `trusted-lock`, `snapshot`, `mount-path`, `wheelhouse`, `control`, `control-hash`, `snapshot-hash`, `trusted-manifest`, `provision-result`, `report-normalize`, `tamper`, `unknown` | +| `3` | Infraestructura (relanzar puede servir) | `docker-create`, `scanner`, `report-parse`, `cleanup`, `provision` | + +`tamper` es un fallo de integridad: nunca debe relanzarse automáticamente, aunque un +consumidor tenga política de reintentos. `report-parse` se distingue de `report-normalize` +porque la salida truncada del scanner es infraestructura, mientras que normalizar un JSON +válido es contrato. + +El diagnóstico se imprime en stderr y en `$GITHUB_STEP_SUMMARY` (workflow) como una única +línea JSON con solo campos cerrados: `label`, `scanner` (`semgrep`/`zizmor`/`null`), +`stage` (tabla anterior), `class` (`contract`/`infrastructure`), `exit` (código de la +herramienta interna, `null` si no aplica) y `durationMs`. No se propaga stdout/stderr del +scanner, rutas, commits, dependencias ni snippets, y no se suben artefactos. + ## Cobertura e integridad - Inventario independiente desde Git: rutas originales, bytes, SHA-256 y exclusiones explícitas. @@ -102,3 +123,16 @@ RED→GREEN observado. No se recortan pruebas para reducir el tamaño de revisi `bootstrap.json` únicamente declara la copia futura con `ensure`; no ejecutarlo con apply ahora. Los pins de checkout/setup-node son los previamente revisados. El runner hospedado y el major Node son plataforma administrada, no pins herméticos. Rollback futuro: retirar solo esta capa mediante cambio revisado. + +## Migración para consumidores (baseline fijada) + +Quienes consuman `code-safety.mjs` desde un `TRUSTED_BASELINE` (p. ej. cadencia) deben +actualizar esa baseline a un commit que incluya este cambio. Al hacerlo: + +- `0` continúa significando run resuelto (con o sin findings); no se añade un exit de hallazgo. +- `2` pasa a significar error de contrato determinista: relanzar no ayudará. +- El nuevo `3` indica infraestructura: relanzar puede servir, si la política del consumidor + lo permite. `tamper` (exit 2) no debe reintentarse jamás. +- El workflow de ejemplo ahora escribe el diagnóstico de campos cerrados en + `$GITHUB_STEP_SUMMARY` además de stderr. Los consumidores que subían artefactos con el + detalle deben retirarlos: el contrato no incluye texto libre ni salidas del scanner. diff --git a/.github/security-drafts/code-safety.yml b/.github/security-drafts/code-safety.yml index fe2f8fa..e2c1817 100644 --- a/.github/security-drafts/code-safety.yml +++ b/.github/security-drafts/code-safety.yml @@ -67,9 +67,24 @@ jobs: - name: Analyze inert Git blobs offline shell: bash run: | + diagnostic_file="$RUNNER_TEMP/quorb-code-safety/diagnostic.txt" + set +e node trusted/scripts/security/code-safety.mjs scan \ "$GITHUB_WORKSPACE/target" "$TARGET_COMMIT" \ - "$RUNNER_TEMP/quorb-code-safety/wheels" "$RUNNER_TEMP/quorb-code-safety" + "$RUNNER_TEMP/quorb-code-safety/wheels" "$RUNNER_TEMP/quorb-code-safety" 2>"$diagnostic_file" + code=$? + set -e + if [[ "$code" -ne 0 ]]; then + diagnostic="$(cat "$diagnostic_file")" + printf '%s\n' "$diagnostic" >&2 + { + echo '## Code safety diagnostic' + echo + printf '%s\n' "$diagnostic" + } >> "$GITHUB_STEP_SUMMARY" + fi + rm -f -- "$diagnostic_file" + exit "$code" - name: Remove temporary downloaded tools if: always() shell: bash diff --git a/.github/workflows/code-safety.yml b/.github/workflows/code-safety.yml index fe2f8fa..e2c1817 100644 --- a/.github/workflows/code-safety.yml +++ b/.github/workflows/code-safety.yml @@ -67,9 +67,24 @@ jobs: - name: Analyze inert Git blobs offline shell: bash run: | + diagnostic_file="$RUNNER_TEMP/quorb-code-safety/diagnostic.txt" + set +e node trusted/scripts/security/code-safety.mjs scan \ "$GITHUB_WORKSPACE/target" "$TARGET_COMMIT" \ - "$RUNNER_TEMP/quorb-code-safety/wheels" "$RUNNER_TEMP/quorb-code-safety" + "$RUNNER_TEMP/quorb-code-safety/wheels" "$RUNNER_TEMP/quorb-code-safety" 2>"$diagnostic_file" + code=$? + set -e + if [[ "$code" -ne 0 ]]; then + diagnostic="$(cat "$diagnostic_file")" + printf '%s\n' "$diagnostic" >&2 + { + echo '## Code safety diagnostic' + echo + printf '%s\n' "$diagnostic" + } >> "$GITHUB_STEP_SUMMARY" + fi + rm -f -- "$diagnostic_file" + exit "$code" - name: Remove temporary downloaded tools if: always() shell: bash diff --git a/scripts/security/code-safety.mjs b/scripts/security/code-safety.mjs index 051654f..8b77805 100644 --- a/scripts/security/code-safety.mjs +++ b/scripts/security/code-safety.mjs @@ -22,18 +22,66 @@ const COMMIT_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/; const UNSAFE = /[\p{Cc}\p{Cf}]/u; const MAX_REPORT_BYTES = 16 * 1024 * 1024; -const fail = () => { - throw new Error(FAIL); +const CONTRACT_STAGES = new Set([ + 'argv', 'bad-command', 'input', 'platform', 'uid', 'trusted-files', 'trusted-lock', + 'snapshot', 'mount-path', 'wheelhouse', 'control', 'control-hash', 'snapshot-hash', + 'trusted-manifest', 'report-normalize', 'provision-result', 'tamper', 'unknown', +]); +const INFRASTRUCTURE_STAGES = new Set([ + 'docker-create', 'scanner', 'report-parse', 'cleanup', 'provision', +]); +const SCANNERS = new Set(['semgrep', 'zizmor']); +const ALL_STAGES = new Set([...CONTRACT_STAGES, ...INFRASTRUCTURE_STAGES]); + +class CodeSafetyError extends Error { + constructor({ className, scanner = null, stage = 'unknown', exit = null, durationMs = 0 }) { + super(FAIL); + this.name = 'CodeSafetyError'; + this.className = className === 'infrastructure' ? 'infrastructure' : 'contract'; + this.scanner = SCANNERS.has(scanner) ? scanner : null; + this.stage = ALL_STAGES.has(stage) ? stage : 'unknown'; + this.exit = Number.isInteger(exit) ? exit : null; + this.durationMs = Number.isFinite(durationMs) ? Math.max(0, Math.round(durationMs)) : 0; + } +} + +const fail = (stage = 'unknown') => { + const safeStage = ALL_STAGES.has(stage) ? stage : 'unknown'; + const className = INFRASTRUCTURE_STAGES.has(safeStage) ? 'infrastructure' : 'contract'; + throw new CodeSafetyError({ className, stage: safeStage }); }; const defaultReadManifest = () => JSON.parse(readFileSync(MANIFEST_PATH, 'utf8')); +function runnerError(error, fallbackScanner) { + const match = /^(semgrep|zizmor)-run-failed:([a-z0-9-]+)$/.exec(error?.message ?? ''); + const scanner = SCANNERS.has(error?.scanner) ? error.scanner : (match?.[1] ?? fallbackScanner); + const stage = ALL_STAGES.has(match?.[2]) ? match[2] : 'unknown'; + const className = INFRASTRUCTURE_STAGES.has(stage) ? 'infrastructure' : 'contract'; + return new CodeSafetyError({ + className, + scanner, + stage, + exit: error?.internalExit, + durationMs: error?.durationMs, + }); +} + +const diagnosis = (error) => JSON.stringify({ + label: FAIL, + scanner: SCANNERS.has(error?.scanner) ? error.scanner : null, + stage: ALL_STAGES.has(error?.stage) ? error.stage : 'unknown', + class: error?.className === 'infrastructure' ? 'infrastructure' : 'contract', + exit: Number.isInteger(error?.exit) ? error.exit : null, + durationMs: Number.isFinite(error?.durationMs) ? Math.max(0, Math.round(error.durationMs)) : 0, +}); + function safePath(value) { - if (typeof value !== 'string' || !isAbsolute(value) || UNSAFE.test(value)) fail(); + if (typeof value !== 'string' || !isAbsolute(value) || UNSAFE.test(value)) fail('input'); return value; } async function runProvision(argv, deps) { - if (argv.length !== 2) fail(); + if (argv.length !== 2) fail('argv'); const destination = safePath(argv[1]); const provisionTools = deps.provisionTools ?? defaultProvisionTools; const readManifest = deps.readManifest ?? defaultReadManifest; @@ -41,23 +89,23 @@ async function runProvision(argv, deps) { try { manifest = await readManifest(); } catch { - return fail(); + return fail('trusted-manifest'); } let result; try { result = await provisionTools({ manifest, destination }); - } catch { - return fail(); + } catch (error) { + throw new CodeSafetyError({ className: 'infrastructure', scanner: null, stage: 'provision', durationMs: 0 }); } - if (result === null || typeof result !== 'object') fail(); + if (result === null || typeof result !== 'object') fail('provision-result'); return { directory: result.directory, artifacts: result.artifacts }; } async function runScan(argv, deps) { - if (argv.length !== 5) fail(); + if (argv.length !== 5) fail('argv'); const repo = safePath(argv[1]); const commit = argv[2]; - if (typeof commit !== 'string' || !COMMIT_SHA.test(commit)) fail(); + if (typeof commit !== 'string' || !COMMIT_SHA.test(commit)) fail('input'); const wheelhouse = safePath(argv[3]); const parent = safePath(argv[4]); const runSemgrep = deps.runSemgrep ?? defaultRunSemgrep; @@ -67,14 +115,14 @@ async function runScan(argv, deps) { let semgrep; try { semgrep = await runSemgrep(input); - } catch { - return fail(); + } catch (error) { + throw runnerError(error, 'semgrep'); } let zizmor; try { zizmor = await runZizmor(input); - } catch { - return fail(); + } catch (error) { + throw runnerError(error, 'zizmor'); } return { semgrep, zizmor }; } @@ -82,10 +130,10 @@ async function runScan(argv, deps) { // Returns the report object so tests can assert on it; the CLI wrapper below owns // stdout. Strict argv length and shape are validated per command. export async function main(argv, deps = {}) { - if (!Array.isArray(argv) || argv.length === 0) fail(); + if (!Array.isArray(argv) || argv.length === 0) fail('argv'); if (argv[0] === 'provision') return runProvision(argv, deps); if (argv[0] === 'scan') return runScan(argv, deps); - fail(); + fail('bad-command'); } function serialize(report) { @@ -99,13 +147,22 @@ function serialize(report) { return `${json}\n`; } -async function cli(argv) { +export async function cli(argv, deps = {}, output = {}) { + const stdout = output.stdout ?? ((text) => process.stdout.write(text)); + const stderr = output.stderr ?? ((text) => process.stderr.write(text)); + const startedAt = performance.now(); try { - process.stdout.write(serialize(await main(argv))); + stdout(serialize(await main(argv, deps))); return 0; - } catch { - process.stderr.write(`${FAIL}\n`); - return 2; + } catch (error) { + const failure = error instanceof CodeSafetyError + ? error + : new CodeSafetyError({ className: 'contract', stage: 'unknown' }); + if (failure.durationMs === 0) { + failure.durationMs = Math.max(0, Math.round(performance.now() - startedAt)); + } + stderr(`${FAIL} ${diagnosis(failure)}\n`); + return failure.className === 'infrastructure' ? 3 : 2; } } diff --git a/scripts/security/code-safety.test.mjs b/scripts/security/code-safety.test.mjs index 4ceda79..716b913 100644 --- a/scripts/security/code-safety.test.mjs +++ b/scripts/security/code-safety.test.mjs @@ -7,7 +7,7 @@ import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { readFileSync } from 'node:fs'; import { fileURLToPath, pathToFileURL } from 'node:url'; -import { main } from './code-safety.mjs'; +import { main, cli } from './code-safety.mjs'; const MODULE = fileURLToPath(new URL('./code-safety.mjs', import.meta.url)); const FAIL = 'code-safety-failed'; @@ -135,18 +135,161 @@ test('provision loads the module-relative trusted manifest and forwards it verba ); }); -test('CLI child fails closed with a generic label, exit 2, empty stdout and no leaked input', () => { +test('CLI reports a closed contract diagnostic without leaking invalid input', () => { const secret = 'LEAK-ME-1234'; - const runs = [['bogus'], ['provision', `relative/${secret}`], ['scan', '/repo', 'not-a-hash', '/wheels', '/parent'], ['scan', '/repo', COMMIT]]; - for (const argv of runs) { + const runs = [ + { argv: ['bogus'], stage: 'bad-command' }, + { argv: ['provision', `relative/${secret}`], stage: 'input' }, + { argv: ['scan', '/repo', 'not-a-hash', '/wheels', '/parent'], stage: 'input' }, + { argv: ['scan', '/repo', COMMIT], stage: 'argv' }, + ]; + for (const { argv, stage } of runs) { const result = spawnSync(process.execPath, [MODULE, ...argv], { encoding: 'utf8' }); assert.equal(result.status, 2, argv.join(' ')); assert.equal(result.stdout, ''); - assert.equal(result.stderr, `${FAIL}\n`); + const [prefix, ...extra] = result.stderr.trimEnd().split('\n'); + assert.deepEqual(extra, []); + const separator = prefix.indexOf(' '); + assert.equal(prefix.slice(0, separator), FAIL); + const diagnostic = JSON.parse(prefix.slice(separator + 1)); + assert.deepEqual({ ...diagnostic, durationMs: 0 }, { + label: FAIL, + scanner: null, + stage, + class: 'contract', + exit: null, + durationMs: 0, + }); + assert.ok(Number.isInteger(diagnostic.durationMs) && diagnostic.durationMs >= 0); assert.ok(!result.stderr.includes(secret)); } }); +test('CLI emits closed diagnostics and distinct exit codes for contract and infrastructure', async () => { + for (const { runner, stage, expectedExit, expectedClass, scanner, internalExit } of [ + { + runner: 'runSemgrep', + stage: 'report-normalize', + expectedExit: 2, + expectedClass: 'contract', + scanner: 'semgrep', + internalExit: null, + }, + { + runner: 'runSemgrep', + stage: 'report-parse', + expectedExit: 3, + expectedClass: 'infrastructure', + scanner: 'semgrep', + internalExit: null, + }, + { + runner: 'runSemgrep', + stage: 'trusted-lock', + expectedExit: 2, + expectedClass: 'contract', + scanner: 'semgrep', + internalExit: null, + }, + { + runner: 'runSemgrep', + stage: 'docker-create', + expectedExit: 3, + expectedClass: 'infrastructure', + scanner: 'semgrep', + internalExit: 125, + }, + { + runner: 'runZizmor', + stage: 'scanner', + expectedExit: 3, + expectedClass: 'infrastructure', + scanner: 'zizmor', + internalExit: 2, + }, + ]) { + let stdout = ''; + let stderr = ''; + const deps = { + runSemgrep: async () => { + if (runner === 'runSemgrep') { + throw Object.assign(new Error(`${scanner}-run-failed:${stage}`), { + scanner, + internalExit, + durationMs: 27, + }); + } + return { findings: [] }; + }, + runZizmor: async () => { + if (runner === 'runZizmor') { + throw Object.assign(new Error(`${scanner}-run-failed:${stage}`), { + scanner, + internalExit, + durationMs: 27, + }); + } + return { findings: [] }; + }, + }; + const exit = await cli(['scan', '/repo', COMMIT, '/wheels', '/parent'], deps, { + stdout: (text) => { stdout += text; }, + stderr: (text) => { stderr += text; }, + }); + assert.equal(exit, expectedExit); + assert.equal(stdout, ''); + const [line, ...extra] = stderr.trimEnd().split('\n'); + assert.deepEqual(extra, []); + const separator = line.indexOf(' '); + assert.equal(line.slice(0, separator), FAIL); + const parsed = JSON.parse(line.slice(separator + 1)); + assert.deepEqual({ ...parsed, durationMs: 27 }, { + label: FAIL, + scanner, + stage, + class: expectedClass, + exit: internalExit, + durationMs: 27, + }); + assert.ok(Number.isInteger(parsed.durationMs) && parsed.durationMs >= 0); + } +}); + +test('classifies contract and infrastructure runner failures by stage', async () => { + const err = (message, meta) => Object.assign(new Error(message), meta); + await assert.rejects( + main(['scan', '/repo', COMMIT, '/wheels', '/parent'], { + runSemgrep: () => { throw err('semgrep-run-failed:docker-create', { scanner: 'semgrep', internalExit: 125, durationMs: 12 }); }, + runZizmor: () => ({ findings: [] }), + }), + (error) => error.message === FAIL + && error.className === 'infrastructure' + && error.stage === 'docker-create' + && error.scanner === 'semgrep' + && error.exit === 125 + && error.durationMs === 12, + ); + await assert.rejects( + main(['scan', '/repo', COMMIT, '/wheels', '/parent'], { + runSemgrep: () => { throw err('semgrep-run-failed:trusted-lock', { scanner: 'semgrep' }); }, + runZizmor: () => ({ findings: [] }), + }), + (error) => error.message === FAIL + && error.className === 'contract' + && error.stage === 'trusted-lock', + ); + await assert.rejects( + main(['scan', '/repo', COMMIT, '/wheels', '/parent'], { + runSemgrep: () => ({ findings: [] }), + runZizmor: () => { throw err('zizmor-run-failed:scanner', { scanner: 'zizmor', internalExit: 2, durationMs: 7 }); }, + }), + (error) => error.message === FAIL + && error.className === 'infrastructure' + && error.stage === 'scanner' + && error.scanner === 'zizmor', + ); +}); + test('workflow adoption pins the reviewed integrated baseline and keeps target execution separate', () => { const source = readFileSync(new URL('../../.github/security-drafts/code-safety.yml', import.meta.url), 'utf8'); const active = readFileSync(new URL('../../.github/workflows/code-safety.yml', import.meta.url), 'utf8'); @@ -157,8 +300,9 @@ test('workflow adoption pins the reviewed integrated baseline and keeps target e assert.match(workflow, /ref: \$\{\{ env\.TRUSTED_BASELINE \}\}/); assert.match(workflow, /ref: \$\{\{ env\.TARGET_COMMIT \}\}/); assert.match(workflow, /node trusted\/scripts\/security\/code-safety\.mjs scan/); + assert.match(workflow, /\$GITHUB_STEP_SUMMARY/); assert.match(workflow, /permissions:\r?\n contents: read/); - assert.doesNotMatch(workflow, /pull_request_target|secrets\.|contents: write/); + assert.doesNotMatch(workflow, /pull_request_target|secrets\.|contents: write|actions\/upload-artifact/); } }); diff --git a/scripts/security/run-semgrep.mjs b/scripts/security/run-semgrep.mjs index 4a8b192..6be3ccd 100644 --- a/scripts/security/run-semgrep.mjs +++ b/scripts/security/run-semgrep.mjs @@ -39,8 +39,10 @@ const MAX_REPORT_BYTES = 8 * 1024 * 1024; const MOUNT_BREAK = /[,\r\n]/; const COMMIT_SHA = /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/; -const fail = (stage) => { - throw new Error(`semgrep-run-failed:${stage}`); +const fail = (stage, internalExit = null) => { + const error = new Error(`semgrep-run-failed:${stage}`); + error.internalExit = Number.isInteger(internalExit) ? internalExit : null; + throw error; }; const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex'); @@ -174,6 +176,8 @@ export const runSemgrep = (input, deps) => runScanner(input, deps, false); export const runZizmor = (input, deps) => runScanner(input, deps, true); function runScanner(input, deps = {}, workflow = false) { + const scanner = workflow ? 'zizmor' : 'semgrep'; + const startedAt = performance.now(); const exportSnapshot = deps.exportSnapshot ?? defaultExportSnapshot; const execute = deps.execute ?? spawnSync; const rulesPath = deps.rulesPath ?? TRUSTED.rules; @@ -236,21 +240,21 @@ function runScanner(input, deps = {}, workflow = false) { name = `quorb-semgrep-${randomUUID()}`; const create = call(execute, createArgs({ name, wheelhouse, snapshot: inventory.root, control, uid, gid }), CREATE_TIMEOUT_MS, 1024 * 1024); - if (!succeeded(create)) fail('docker-create'); + if (!succeeded(create)) fail('docker-create', create.status); const start = call(execute, ['start', '--attach', name], SCAN_TIMEOUT_MS, MAX_REPORT_BYTES); - if (!succeeded(start) || typeof start.stdout !== 'string') fail('scanner'); + if (!succeeded(start) || typeof start.stdout !== 'string') fail('scanner', start.status); if (controlFingerprint() !== beforeControl || snapshotFingerprint(inventory, false) !== beforeSnapshot) fail('tamper'); let parsed; try { parsed = JSON.parse(start.stdout); } catch { - fail('report'); + fail('report-parse'); } try { report = workflow ? normalizeZizmor(parsed, inventory) : normalizeSnapshotReport(parsed, inventory); } catch { - fail('report'); + fail('report-normalize'); } } catch (error) { failure = error; @@ -263,6 +267,14 @@ function runScanner(input, deps = {}, workflow = false) { if (inventory && inventory.root && !removeDir(inventory.root)) cleanupFailed = true; } if (cleanupFailed) fail('cleanup'); - if (failure) throw failure; + if (failure) { + if (failure.message.startsWith('semgrep-run-failed:')) { + const stage = failure.message.slice('semgrep-run-failed:'.length); + failure.message = `${scanner}-run-failed:${stage}`; + } + failure.scanner = scanner; + failure.durationMs = Math.max(0, Math.round(performance.now() - startedAt)); + throw failure; + } return report; } diff --git a/scripts/security/run-semgrep.test.mjs b/scripts/security/run-semgrep.test.mjs index 56381e3..cb61069 100644 --- a/scripts/security/run-semgrep.test.mjs +++ b/scripts/security/run-semgrep.test.mjs @@ -8,7 +8,7 @@ import { createHash } from 'node:crypto'; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { runSemgrep } from './run-semgrep.mjs'; +import { runSemgrep, runZizmor } from './run-semgrep.mjs'; const IMAGE = 'docker.io/library/python@sha256:2ed6491b93cd49272ee6de2b5a38440c3448360322c089fc23e370722d74179d'; const COMMIT = 'a'.repeat(40); @@ -174,13 +174,33 @@ test('docker create and scanner failures are operational with host cleanup', (t) assert.throws(() => runSemgrep(input(f2), deps(f2, scanFail)), /semgrep-run-failed:scanner/); }); -test('unparseable or incomplete reports are operational', (t) => { - for (const stdout of ['not json', JSON.stringify(report(['/inputs/other.ts']))]) { - const f = fixture(t); - const { execute } = startedReport(stdout); - assert.throws(() => runSemgrep(input(f), deps(f, execute)), /semgrep-run-failed:report/); - assert.deepEqual(readdirSync(f.parent), []); - } +test('unparseable and incomplete reports fail at distinct report stages', (t) => { + const parseFixture = fixture(t); + const { execute: parseExecute } = startedReport('not json'); + assert.throws(() => runSemgrep(input(parseFixture), deps(parseFixture, parseExecute)), /semgrep-run-failed:report-parse/); + + const normalizeFixture = fixture(t); + const { execute: normalizeExecute } = startedReport(JSON.stringify(report(['/inputs/other.ts']))); + assert.throws(() => runSemgrep(input(normalizeFixture), deps(normalizeFixture, normalizeExecute)), /semgrep-run-failed:report-normalize/); + + assert.deepEqual(readdirSync(parseFixture.parent), []); + assert.deepEqual(readdirSync(normalizeFixture.parent), []); +}); + +test('zizmor failures identify the zizmor scanner and retain internal exit/duration', (t) => { + const f = fixture(t); + const { execute } = capture((args) => + args[0] === 'create' + ? { status: 17, stdout: '', stderr: '' } + : { status: 0, stdout: '', stderr: '' }, + ); + assert.throws( + () => runZizmor(input(f), deps(f, execute)), + (error) => error.message === 'zizmor-run-failed:docker-create' + && error.scanner === 'zizmor' + && error.internalExit === 17 + && Number.isInteger(error.durationMs), + ); }); test('removes container and host temp dirs on success and on start timeout', (t) => {