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 1/3] 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) => { From e488cc968d819204881f009beb4c88d806951e68 Mon Sep 17 00:00:00 2001 From: jose luis <2064537+sosan@users.noreply.github.com> Date: Tue, 24 Nov 2026 12:20:01 +0100 Subject: [PATCH 2/3] fix(security): formatea code-safety y atribuye el fallo de cleanup al scanner El runner no estaba formateado con Biome, asi que el paso "Biome lint and format" fallaba y los tests de Linux y Windows ni siquiera se ejecutaban: - Se formatean code-safety.mjs, code-safety.test.mjs y run-semgrep.test.mjs con el formateador del repositorio (lineWidth 160, comillas simples). - Se elimina el binding `error` sin usar del catch de runProvision. Ademas, un fallo de cleanup en el workflow de zizmor se reportaba como "semgrep-run-failed:cleanup" sin scanner, de modo que code-safety.mjs lo atribuia a semgrep: justamente la mezcla que este PR elimina. El fallo de cleanup pasa ahora por el mismo bloque de atribucion que el resto y arrastra scanner y durationMs. Se cubre con un test para ambos scanners. --- scripts/security/code-safety.mjs | 48 ++++++++++------ scripts/security/code-safety.test.mjs | 80 +++++++++++++++------------ scripts/security/run-semgrep.mjs | 9 ++- scripts/security/run-semgrep.test.mjs | 64 ++++++++++++++------- 4 files changed, 129 insertions(+), 72 deletions(-) diff --git a/scripts/security/code-safety.mjs b/scripts/security/code-safety.mjs index 8b77805..76aa8fe 100644 --- a/scripts/security/code-safety.mjs +++ b/scripts/security/code-safety.mjs @@ -23,13 +23,26 @@ const UNSAFE = /[\p{Cc}\p{Cf}]/u; const MAX_REPORT_BYTES = 16 * 1024 * 1024; 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', + '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]); @@ -66,14 +79,15 @@ function runnerError(error, fallbackScanner) { }); } -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, -}); +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('input'); @@ -94,7 +108,7 @@ async function runProvision(argv, deps) { let result; try { result = await provisionTools({ manifest, destination }); - } catch (error) { + } catch { throw new CodeSafetyError({ className: 'infrastructure', scanner: null, stage: 'provision', durationMs: 0 }); } if (result === null || typeof result !== 'object') fail('provision-result'); @@ -155,9 +169,7 @@ export async function cli(argv, deps = {}, output = {}) { stdout(serialize(await main(argv, deps))); return 0; } catch (error) { - const failure = error instanceof CodeSafetyError - ? error - : new CodeSafetyError({ className: 'contract', stage: 'unknown' }); + 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)); } diff --git a/scripts/security/code-safety.test.mjs b/scripts/security/code-safety.test.mjs index 716b913..276e7f8 100644 --- a/scripts/security/code-safety.test.mjs +++ b/scripts/security/code-safety.test.mjs @@ -152,14 +152,17 @@ test('CLI reports a closed contract diagnostic without leaking invalid input', ( 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.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)); } @@ -233,8 +236,12 @@ test('CLI emits closed diagnostics and distinct exit codes for contract and infr }, }; const exit = await cli(['scan', '/repo', COMMIT, '/wheels', '/parent'], deps, { - stdout: (text) => { stdout += text; }, - stderr: (text) => { stderr += text; }, + stdout: (text) => { + stdout += text; + }, + stderr: (text) => { + stderr += text; + }, }); assert.equal(exit, expectedExit); assert.equal(stdout, ''); @@ -243,14 +250,17 @@ test('CLI emits closed diagnostics and distinct exit codes for contract and infr 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.deepEqual( + { ...parsed, durationMs: 27 }, + { + label: FAIL, + scanner, + stage, + class: expectedClass, + exit: internalExit, + durationMs: 27, + }, + ); assert.ok(Number.isInteger(parsed.durationMs) && parsed.durationMs >= 0); } }); @@ -259,34 +269,36 @@ 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 }); }, + 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, + (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' }); }, + runSemgrep: () => { + throw err('semgrep-run-failed:trusted-lock', { scanner: 'semgrep' }); + }, runZizmor: () => ({ findings: [] }), }), - (error) => error.message === FAIL - && error.className === 'contract' - && error.stage === 'trusted-lock', + (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 }); }, + 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', + (error) => error.message === FAIL && error.className === 'infrastructure' && error.stage === 'scanner' && error.scanner === 'zizmor', ); }); diff --git a/scripts/security/run-semgrep.mjs b/scripts/security/run-semgrep.mjs index 6be3ccd..6b1f327 100644 --- a/scripts/security/run-semgrep.mjs +++ b/scripts/security/run-semgrep.mjs @@ -266,7 +266,14 @@ function runScanner(input, deps = {}, workflow = false) { if (control && !removeDir(control)) cleanupFailed = true; if (inventory && inventory.root && !removeDir(inventory.root)) cleanupFailed = true; } - if (cleanupFailed) fail('cleanup'); + // A cleanup failure outranks a scanner failure, but it must still be attributed to + // the scanner that actually ran. Routing it through the shared block below keeps a + // zizmor cleanup failure from surfacing as "semgrep-run-failed" and carries the + // scanner/duration metadata every other failure already gets. + if (cleanupFailed) { + failure = new Error('semgrep-run-failed:cleanup'); + failure.internalExit = null; + } if (failure) { if (failure.message.startsWith('semgrep-run-failed:')) { const stage = failure.message.slice('semgrep-run-failed:'.length); diff --git a/scripts/security/run-semgrep.test.mjs b/scripts/security/run-semgrep.test.mjs index cb61069..54d4f86 100644 --- a/scripts/security/run-semgrep.test.mjs +++ b/scripts/security/run-semgrep.test.mjs @@ -35,6 +35,29 @@ function fixture(t) { return { base, root, source, wheelhouse, parent, inventory }; } +// zizmor scans workflows, so its inventory exposes mounted `NNNNNN.yml` files that map +// back to `.github/workflows/.yml` originals instead of js/ts sources. +function zizmorFixture(t) { + const base = mkdtempSync(join(tmpdir(), 'run-zizmor-')); + t.after(() => rmSync(base, { recursive: true, force: true })); + const root = join(base, 'snapshot'); + mkdirSync(root); + const source = join(root, '000000.yml'); + writeFileSync(source, 'on: push'); + const wheelhouse = join(base, 'wheels'); + mkdirSync(wheelhouse); + const parent = join(base, 'out'); + mkdirSync(parent); + const inventory = { + commit: COMMIT, + root, + targets: [{ path: source, originalPath: '.github/workflows/ci.yml', sha256: sha('on: push') }], + excluded: [], + }; + return { base, root, source, wheelhouse, parent, inventory }; +} +const zizmorReport = () => ({ version: '1.30.1', reports: [{ path: '/inputs/000000.yml', findings: [] }] }); + const input = (f) => ({ repo: '/repo', commit: COMMIT, wheelhouse: f.wheelhouse, parent: f.parent }); const deps = (f, execute, extra = {}) => ({ platform: 'linux', uid: 1000, gid: 1000, exportSnapshot: () => f.inventory, execute, ...extra }); @@ -189,17 +212,11 @@ test('unparseable and incomplete reports fail at distinct report stages', (t) => 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: '' }, - ); + 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), + (error) => + error.message === 'zizmor-run-failed:docker-create' && error.scanner === 'zizmor' && error.internalExit === 17 && Number.isInteger(error.durationMs), ); }); @@ -239,16 +256,25 @@ test('uncertain create still attempts named cleanup and never returns success', assert.ok(!existsSync(f.root)); }); -test('cleanup failure is operational, never green', (t) => { - const f = fixture(t); - const { execute } = capture((args) => - args[0] === 'create' - ? { status: 0, stdout: '', stderr: '' } - : args[0] === 'start' - ? { status: 0, stdout: JSON.stringify(report()), stderr: '' } - : { status: 1, stdout: '', stderr: 'permission denied' }, - ); - assert.throws(() => runSemgrep(input(f), deps(f, execute)), /semgrep-run-failed:cleanup/); +test('cleanup failure is operational, never green, and names the scanner that ran', (t) => { + for (const [run, scanner, fixtureFor, stdout] of [ + [runSemgrep, 'semgrep', fixture, JSON.stringify(report())], + [runZizmor, 'zizmor', zizmorFixture, JSON.stringify(zizmorReport())], + ]) { + const f = fixtureFor(t); + const { execute } = capture((args) => + args[0] === 'create' + ? { status: 0, stdout: '', stderr: '' } + : args[0] === 'start' + ? { status: 0, stdout, stderr: '' } + : { status: 1, stdout: '', stderr: 'permission denied' }, + ); + assert.throws( + () => run(input(f), deps(f, execute)), + (error) => error.message === `${scanner}-run-failed:cleanup` && error.scanner === scanner && Number.isInteger(error.durationMs), + scanner, + ); + } }); test('never echoes raw scanner output or secrets in errors', (t) => { From 2ab5d4099e679fbdcf69af1d78ce5a4d8d9d2781 Mon Sep 17 00:00:00 2001 From: jose luis <2064537+sosan@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:34:25 +0100 Subject: [PATCH 3/3] fix(security): un fallo de limpieza no tapa el fallo de integridad (#276) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Si el scanner detectaba un `tamper` y además fallaba la eliminación del contenedor, `cleanup` sustituía al error de integridad: el diagnóstico salía como exit 3 / `infrastructure` (reintentable) en vez del exit 2 / `contract` que exige `tamper`. Ahora la limpieza solo se reporta cuando no hay otro fallo. La clase del fallo principal es la que decide si relanzar puede servir, así que degradarla daba la respuesta equivocada. - Regresión en el runner: tamper + cleanup fallido → `semgrep-run-failed:tamper`. - Regresión end-to-end por `cli()` con el runner real y transporte simulado → exit 2, stage `tamper`, class `contract`. - README documenta la precedencia. --- .github/security-drafts/README.md | 6 ++ scripts/security/code-safety.test.mjs | 82 ++++++++++++++++++++++++++- scripts/security/run-semgrep.mjs | 11 ++-- scripts/security/run-semgrep.test.mjs | 23 ++++++++ 4 files changed, 116 insertions(+), 6 deletions(-) diff --git a/.github/security-drafts/README.md b/.github/security-drafts/README.md index 1a30cdc..b35d74b 100644 --- a/.github/security-drafts/README.md +++ b/.github/security-drafts/README.md @@ -58,6 +58,12 @@ consumidor tenga política de reintentos. `report-parse` se distingue de `report porque la salida truncada del scanner es infraestructura, mientras que normalizar un JSON válido es contrato. +Un fallo de limpieza (`cleanup`) no sustituye al fallo principal: si el scanner ya había +fallado, se reporta ese, porque su clase es la que decide si relanzar puede servir. Así un +`tamper` sigue siendo exit 2 aunque además el contenedor se quede sin eliminar, y no baja a +infraestructura reintentable. `cleanup` solo se reporta cuando no hay otro fallo, y entonces +el run tampoco sale con `0`. + 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 diff --git a/scripts/security/code-safety.test.mjs b/scripts/security/code-safety.test.mjs index 276e7f8..e094f78 100644 --- a/scripts/security/code-safety.test.mjs +++ b/scripts/security/code-safety.test.mjs @@ -5,13 +5,19 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; -import { readFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; import { main, cli } from './code-safety.mjs'; +import { runSemgrep } from './run-semgrep.mjs'; const MODULE = fileURLToPath(new URL('./code-safety.mjs', import.meta.url)); const FAIL = 'code-safety-failed'; const COMMIT = 'a'.repeat(40); +const sha256 = (bytes) => createHash('sha256').update(bytes).digest('hex'); +const report = () => ({ version: '1.180.0', errors: [], skipped_rules: [], paths: { scanned: ['/inputs/000000.ts'] }, results: [] }); const reject = (promise) => assert.rejects(promise, { message: FAIL }); const bump = () => { throw new Error('dependency must not run'); @@ -194,6 +200,16 @@ test('CLI emits closed diagnostics and distinct exit codes for contract and infr scanner: 'semgrep', internalExit: null, }, + { + // La integridad nunca es reintentable: `tamper` es exit 2 aunque la + // limpieza también falle. + runner: 'runSemgrep', + stage: 'tamper', + expectedExit: 2, + expectedClass: 'contract', + scanner: 'semgrep', + internalExit: null, + }, { runner: 'runSemgrep', stage: 'docker-create', @@ -326,3 +342,67 @@ test('importing the module performs no work and no CLI call', () => { assert.equal(result.stdout, ''); assert.equal(result.stderr, ''); }); + +test('a cleanup failure does not downgrade an integrity failure to infrastructure', async () => { + // La combinación que faltaba: el scanner detecta una modificación del snapshot + // (integridad) y además la limpieza del contenedor falla. El diagnóstico tiene + // que seguir siendo `tamper` —contrato, exit 2, nunca reintentable— y no + // `cleanup` —infraestructura, exit 3—. Se recorre el runner real con un + // transporte simulado, como en la reproducción. + const base = mkdtempSync(join(tmpdir(), 'code-safety-')); + try { + const root = join(base, 'snapshot'); + mkdirSync(root); + const source = join(root, '000000.ts'); + writeFileSync(source, 'void 0;'); + const wheelhouse = join(base, 'wheels'); + mkdirSync(wheelhouse); + const parent = join(base, 'out'); + mkdirSync(parent); + const inventory = { + commit: COMMIT, + root, + targets: [{ path: source, originalPath: 'src/a.ts', sha256: sha256('void 0;') }], + excluded: [], + }; + const execute = (_command, daemonArgs) => { + const args = daemonArgs[0] === '--host' ? daemonArgs.slice(2) : daemonArgs; + if (args[0] === 'create') return { status: 0, stdout: '', stderr: '' }; + if (args[0] === 'start') { + // El snapshot cambia mientras el scanner corre: es un fallo de integridad. + chmodSync(source, 0o600); + writeFileSync(source, 'tampered'); + return { status: 0, stdout: JSON.stringify(report()), stderr: '' }; + } + // La limpieza falla: el contenedor se queda. + return { status: 1, stdout: '', stderr: 'permission denied' }; + }; + let stdout = ''; + let stderr = ''; + const exit = await cli( + ['scan', '/repo', COMMIT, wheelhouse, parent], + { + runSemgrep: (input) => runSemgrep(input, { uid: 1000, gid: 1000, exportSnapshot: () => inventory, execute }), + runZizmor: bump, + }, + { + stdout: (text) => { + stdout += text; + }, + stderr: (text) => { + stderr += text; + }, + }, + ); + assert.equal(exit, 2); + assert.equal(stdout, ''); + const separator = stderr.indexOf(' '); + assert.equal(stderr.slice(0, separator), FAIL); + const parsed = JSON.parse(stderr.slice(separator + 1)); + assert.equal(parsed.stage, 'tamper'); + assert.equal(parsed.class, 'contract'); + assert.equal(parsed.scanner, 'semgrep'); + } finally { + rmSync(base, { recursive: true, force: true }); + } +}); diff --git a/scripts/security/run-semgrep.mjs b/scripts/security/run-semgrep.mjs index 6b1f327..4f6f9ad 100644 --- a/scripts/security/run-semgrep.mjs +++ b/scripts/security/run-semgrep.mjs @@ -266,11 +266,12 @@ function runScanner(input, deps = {}, workflow = false) { if (control && !removeDir(control)) cleanupFailed = true; if (inventory && inventory.root && !removeDir(inventory.root)) cleanupFailed = true; } - // A cleanup failure outranks a scanner failure, but it must still be attributed to - // the scanner that actually ran. Routing it through the shared block below keeps a - // zizmor cleanup failure from surfacing as "semgrep-run-failed" and carries the - // scanner/duration metadata every other failure already gets. - if (cleanupFailed) { + // A cleanup failure never replaces an earlier failure: when the scanner already + // failed, that is the reason worth reporting. It also decides whether retrying + // can help, so downgrading the primary cause would give the wrong answer — + // `tamper` (integrity, exit 2, never retried) must not become `cleanup` + // (infrastructure, exit 3, retryable). Cleanup alone still fails the run. + if (!failure && cleanupFailed) { failure = new Error('semgrep-run-failed:cleanup'); failure.internalExit = null; } diff --git a/scripts/security/run-semgrep.test.mjs b/scripts/security/run-semgrep.test.mjs index 54d4f86..f9362c8 100644 --- a/scripts/security/run-semgrep.test.mjs +++ b/scripts/security/run-semgrep.test.mjs @@ -319,3 +319,26 @@ test('detects snapshot and control mutation around the scanner', (t) => { assert.throws(() => runSemgrep(input(f), deps(f, execute)), /semgrep-run-failed:tamper/, which); } }); + +test('a cleanup failure does not mask the integrity failure', (t) => { + // El snapshot se modifica (integridad) y además el contenedor no se puede + // eliminar (limpieza). Lo que hay que reportar es `tamper`: si la limpieza + // lo tapara, el fallo de integridad passaría a ser infraestructura + // reintentable, que es justo lo que no debe pasar. + const f = fixture(t); + const { execute } = capture((args) => { + if (args[0] === 'create') return { status: 0, stdout: '', stderr: '' }; + if (args[0] === 'start') { + chmodSync(f.source, 0o600); + writeFileSync(f.source, 'tampered'); + return { status: 0, stdout: JSON.stringify(report()), stderr: '' }; + } + // La limpieza falla: el contenedor se queda. + return { status: 1, stdout: '', stderr: 'permission denied' }; + }); + assert.throws( + () => runSemgrep(input(f), deps(f, execute)), + (error) => error.message === 'semgrep-run-failed:tamper' && error.scanner === 'semgrep', + 'la limpieza no debe sustituir al fallo de integridad', + ); +});