Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions .github/security-drafts/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
17 changes: 16 additions & 1 deletion .github/security-drafts/code-safety.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion .github/workflows/code-safety.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
99 changes: 78 additions & 21 deletions scripts/security/code-safety.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -22,42 +22,90 @@ 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;
let manifest;
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;
Expand All @@ -67,25 +115,25 @@ 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 };
}

// 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) {
Expand All @@ -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;
}
}

Expand Down
Loading
Loading