diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3002f49..ae8541c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -120,6 +120,8 @@ jobs: image: localhost:5000/e2e/vulnerable context: test/fixtures/vulnerable push: "true" + # keep the check strict when this CI job itself is re-run + bypass-on-rerun: "false" - name: Verify vulnerable image was blocked env: @@ -200,6 +202,26 @@ jobs: echo "$tags" | grep -q '"latest"' if grep -v 'task.setsecret' "$RUNNER_TEMP/azure-vars.log" | grep -q s3cret; then echo "::error::password leaked to the log"; exit 1; fi + - name: Re-run of a failed job accepts vulnerabilities + env: + INPUT_IMAGE: localhost:5001/e2e/rerun + INPUT_CONTEXT: test/fixtures/vulnerable + INPUT_SBOM: "false" + CONTAINER_REGISTRY: localhost:5001 + CONTAINER_REGISTRY_USERNAME: tester + SECRET_CONTAINER_REGISTRY_PASSWORD: s3cret + SYSTEM_JOBATTEMPT: "2" + BUILD_SOURCEVERSION: ${{ github.sha }} + BUILD_SOURCEBRANCH: refs/heads/main + BUILD_REASON: IndividualCI + BUILD_SOURCESDIRECTORY: ${{ github.workspace }} + AGENT_TEMPDIRECTORY: ${{ runner.temp }} + run: | + set -euo pipefail + node azure/tasks/ContainerBuild/index.js | tee "$RUNNER_TEMP/azure-rerun.log" + grep -q 'accepted because this is a re-run' "$RUNNER_TEMP/azure-rerun.log" + curl -sf -u tester:s3cret localhost:5001/v2/e2e/rerun/tags/list | grep -q latest + e2e-reusable-workflow: needs: check permissions: diff --git a/README.md b/README.md index 3b2e9e4..17d4d0e 100644 --- a/README.md +++ b/README.md @@ -264,10 +264,25 @@ GitHub uses `kebab-case` names, Azure DevOps uses `camelCase` names. | `severity` | `severity` | `CRITICAL,HIGH` | Severities to report. | | `fail-on-vulnerabilities` | `failOnVulnerabilities` | `true` | Fail and skip the push when vulnerabilities are found. | | `ignore-unfixed` | `ignoreUnfixed` | `true` | Ignore vulnerabilities without an available fix. | +| `bypass-on-rerun` | `bypassOnRerun` | `true` | On a re-run of a failed job, accept vulnerabilities and too-new packages (never malware). See [Re-running a failed build](#re-running-a-failed-build). | | `trivy-version` | `trivyVersion` | pinned | Trivy version, or a full scanner image reference (e.g. an internal mirror). | To accept specific vulnerabilities, list their IDs in a `.trivyignore` file in the build context or repository root. +## Re-running a failed build + +When a vulnerability or safe-chain's minimum package age (a package version younger than 48 hours) fails a build, +people normally have a good reason to re-run it, for example because a fix isn't released yet or a just-published patch +is needed. So when a failed job is re-run (*Re-run failed jobs* on GitHub, *Rerun failed jobs* on Azure DevOps, +detected from `GITHUB_RUN_ATTEMPT` / `System.JobAttempt`): + +- vulnerabilities found by the scan are reported as warnings and the image is pushed +- package installs in the Dockerfile run with `--safe-chain-skip-minimum-package-age` +- **known malware is still blocked**, because a second click must not let a compromised package through +- the job log and summary state that the checks were relaxed for this attempt + +Set `bypass-on-rerun: false` (`bypassOnRerun: false` on Azure DevOps) to enforce the checks on every attempt. + ## Outputs | GitHub | Azure DevOps | Description | diff --git a/action.yml b/action.yml index a07699d..19bdfba 100644 --- a/action.yml +++ b/action.yml @@ -76,6 +76,10 @@ inputs: description: "Ignore vulnerabilities that have no fix available." required: false default: "true" + bypass-on-rerun: + description: "When a failed job is re-run, report vulnerabilities and safe-chain's minimum package age as warnings instead of failing. Malware is always blocked." + required: false + default: "true" trivy-version: description: "Trivy version (or full scanner image reference)." required: false diff --git a/azure/overview.md b/azure/overview.md index de5fd37..f9687e7 100644 --- a/azure/overview.md +++ b/azure/overview.md @@ -38,4 +38,8 @@ The task: A summary of the scan is attached to the build results page. +When you **re-run a failed job**, vulnerabilities and safe-chain's minimum package age are reported as warnings +instead of failing, because there is usually a good reason for the re-run. Known malware is always blocked. Set +`bypassOnRerun: false` to enforce the checks on every attempt. + See the [documentation](https://github.com/onek8s/container-build-extension#readme) for all options. diff --git a/azure/tasks/ContainerBuild/task.json b/azure/tasks/ContainerBuild/task.json index 64dfa28..175f3a1 100644 --- a/azure/tasks/ContainerBuild/task.json +++ b/azure/tasks/ContainerBuild/task.json @@ -177,6 +177,15 @@ "groupName": "scan", "visibleRule": "scan = true" }, + { + "name": "bypassOnRerun", + "type": "boolean", + "label": "Accept findings when a failed job is re-run", + "defaultValue": "true", + "required": false, + "groupName": "scan", + "helpMarkDown": "When a failed job is re-run (\"Rerun failed jobs\"), vulnerabilities and safe-chain's minimum package age are reported as warnings instead of failing the build. Malware is always blocked." + }, { "name": "trivyVersion", "type": "string", diff --git a/dist/index.js b/dist/index.js index 046847a..930430e 100644 --- a/dist/index.js +++ b/dist/index.js @@ -431,6 +431,7 @@ function readInputs(platform2, machine) { sbom: parseBool(platform2.getInput("sbom"), true, "sbom"), sbomFormat, safeChain: parseBool(platform2.getInput("safeChain"), true, "safeChain"), + rerunBypass: parseBool(platform2.getInput("bypassOnRerun"), true, "bypassOnRerun") && (ctx.attempt ?? 1) > 1, trivyImage: trivyVersion.includes("/") ? trivyVersion : `ghcr.io/aquasecurity/trivy:${trivyVersion.replace(/^v/, "")}` }; } @@ -446,14 +447,16 @@ var SHA256 = { }; var SAFE_CHAIN_CONTEXT = "container-build-safe-chain"; var MOUNT_DIR = "/tmp/.container-build-safe-chain"; -var MOUNTS = [ +var SKIP_AGE_SHIMS = "shims-skip-minimum-age"; +var mounts = (shims) => [ // writable, not part of the image: safe-chain keeps its malware lists and certificates here `--mount=type=cache,id=${SAFE_CHAIN_CONTEXT},target=${MOUNT_DIR},mode=0777`, `--mount=type=bind,from=${SAFE_CHAIN_CONTEXT},source=bin,target=${MOUNT_DIR}/bin`, - `--mount=type=bind,from=${SAFE_CHAIN_CONTEXT},source=shims,target=${MOUNT_DIR}/shims` + `--mount=type=bind,from=${SAFE_CHAIN_CONTEXT},source=${shims},target=${MOUNT_DIR}/shims` ].join(" "); var PREFIX = `export PATH="${MOUNT_DIR}/shims:${MOUNT_DIR}/bin:$PATH";`; -function instrumentDockerfile(content) { +function instrumentDockerfile(content, opts = {}) { + const MOUNTS = mounts(opts.skipMinimumPackageAge ? SKIP_AGE_SHIMS : "shims"); const lines = content.split("\n"); for (const line of lines) { const m = line.match(/^#\s*([a-z]+)\s*=\s*(.*)$/i); @@ -516,9 +519,24 @@ async function prepareSafeChain(exec2, cacheDir, arch = process.arch, expected = for (const k of ["GITHUB_PATH", "BASH_ENV", "TF_BUILD"]) delete env[k]; await exec2(bin, ["setup-ci"], { silent: true, env }); } + const relaxed = path3.join(dir, SKIP_AGE_SHIMS); + if (!fs3.existsSync(path3.join(relaxed, "npm"))) createSkipAgeShims(path3.join(dir, "shims"), relaxed); fs3.rmSync(path3.join(dir, "certs"), { recursive: true, force: true }); return dir; } +function createSkipAgeShims(from, to) { + const tmp = `${to}.tmp`; + fs3.rmSync(tmp, { recursive: true, force: true }); + fs3.mkdirSync(tmp, { recursive: true }); + for (const name of fs3.readdirSync(from)) { + const src = fs3.readFileSync(path3.join(from, name), "utf8"); + const out = src.replace(/exec safe-chain (\S+) "\$@"/g, 'exec safe-chain $1 --safe-chain-skip-minimum-package-age "$@"'); + if (out === src) throw new Error(`Unexpected safe-chain shim format: ${name}`); + fs3.writeFileSync(path3.join(tmp, name), out, { mode: 493 }); + } + fs3.rmSync(to, { recursive: true, force: true }); + fs3.renameSync(tmp, to); +} // src/core/scan.ts var fs4 = __toESM(require("node:fs")); @@ -697,7 +715,9 @@ async function prepareBuild(platform2, exec2, inputs) { platform2.warning(`safe-chain is only supported on Linux x64/arm64 agents; building without it.`); return { ...plain, safeChain: "unsupported agent" }; } - const result = instrumentDockerfile(fs5.readFileSync(inputs.dockerfile, "utf8")); + const result = instrumentDockerfile(fs5.readFileSync(inputs.dockerfile, "utf8"), { + skipMinimumPackageAge: inputs.rerunBypass + }); if (result.wrapped === 0) { platform2.info(`safe-chain: no RUN instructions to protect${result.reason ? ` (${result.reason})` : ""}.`); return { ...plain, safeChain: "nothing to protect" }; @@ -735,6 +755,11 @@ async function run(platform2, exec2 = exec) { if (ctx.sha) labels["org.opencontainers.image.revision"] = ctx.sha; const result = { imageRefs, pushed: false }; const summary = [`### Container build: \`${inputs.repository}\``, "", `Tags: ${tags.map((t) => `\`${t}\``).join(", ")}`, ""]; + if (inputs.rerunBypass) { + const msg = `Re-run (attempt ${ctx.attempt}): vulnerabilities found by the scan and safe-chain's minimum package age do not fail this build. Malware is still blocked.`; + platform2.warning(msg); + summary.push(`\u26A0\uFE0F ${msg}`, ""); + } const build = await prepareBuild(platform2, exec2, inputs); await group( platform2, @@ -781,11 +806,11 @@ async function run(platform2, exec2 = exec) { summary.push("#### Security scan", "", summaryMarkdown(scan, inputs.severity), ""); if (scan.vulnerabilities.length > 0) { const msg = `Found ${scan.vulnerabilities.length} vulnerabilities with severity ${inputs.severity}`; - if (inputs.failOnVulnerabilities) { + if (inputs.failOnVulnerabilities && !inputs.rerunBypass) { platform2.addSummary(summary.join("\n")); throw new Error(`${msg}. Image was not pushed. Fix them, add them to .trivyignore, or set failOnVulnerabilities to false.`); } - platform2.warning(msg); + platform2.warning(inputs.rerunBypass ? `${msg}; accepted because this is a re-run` : msg); } else { platform2.info("No vulnerabilities found."); } @@ -848,6 +873,7 @@ var GitHubPlatform = class { this.context = { project: owner || void 0, repository: repo || void 0, + attempt: Number(env.GITHUB_RUN_ATTEMPT) || void 0, sha: env.GITHUB_SHA, ref: env.GITHUB_REF, isPullRequest: ["pull_request", "pull_request_target"].includes(env.GITHUB_EVENT_NAME ?? ""), diff --git a/src/azure/platform.ts b/src/azure/platform.ts index 6e9e817..78a35ad 100644 --- a/src/azure/platform.ts +++ b/src/azure/platform.ts @@ -43,6 +43,7 @@ export class AzurePlatform implements Platform { this.context = { project: env.SYSTEM_TEAMPROJECT || undefined, repository: repo || undefined, + attempt: Number(env.SYSTEM_JOBATTEMPT) || undefined, sha: env.BUILD_SOURCEVERSION, ref: env.BUILD_SOURCEBRANCH, isPullRequest: env.BUILD_REASON === 'PullRequest', diff --git a/src/core/inputs.ts b/src/core/inputs.ts index 51de257..46e0848 100644 --- a/src/core/inputs.ts +++ b/src/core/inputs.ts @@ -24,6 +24,8 @@ export interface Inputs { sbom: boolean; sbomFormat: SbomFormat; safeChain: boolean; + /** Re-run of a failed job: vulnerabilities and too-new packages do not fail the build. */ + rerunBypass: boolean; } export const DEFAULT_TRIVY_VERSION = '0.76.2'; @@ -122,6 +124,7 @@ export function readInputs(platform: Platform, machine?: MachineSettings): Input sbom: parseBool(platform.getInput('sbom'), true, 'sbom'), sbomFormat, safeChain: parseBool(platform.getInput('safeChain'), true, 'safeChain'), + rerunBypass: parseBool(platform.getInput('bypassOnRerun'), true, 'bypassOnRerun') && (ctx.attempt ?? 1) > 1, trivyImage: trivyVersion.includes('/') ? trivyVersion : `ghcr.io/aquasecurity/trivy:${trivyVersion.replace(/^v/, '')}`, }; } diff --git a/src/core/platform.ts b/src/core/platform.ts index 4df4d90..5159e82 100644 --- a/src/core/platform.ts +++ b/src/core/platform.ts @@ -17,6 +17,8 @@ export interface BuildContext { sha?: string; /** Git ref, e.g. refs/heads/main, refs/tags/v1.0.0, refs/pull/1/merge. */ ref?: string; + /** Attempt number of the job: greater than 1 when the user re-runs it ("Re-run failed jobs"). */ + attempt?: number; /** True when running for a pull request. */ isPullRequest: boolean; /** Directory used for temporary files. */ diff --git a/src/core/run.ts b/src/core/run.ts index 3d8d231..f97de5a 100644 --- a/src/core/run.ts +++ b/src/core/run.ts @@ -43,7 +43,9 @@ async function prepareBuild( return { ...plain, safeChain: 'unsupported agent' }; } - const result = instrumentDockerfile(fs.readFileSync(inputs.dockerfile, 'utf8')); + const result = instrumentDockerfile(fs.readFileSync(inputs.dockerfile, 'utf8'), { + skipMinimumPackageAge: inputs.rerunBypass, + }); if (result.wrapped === 0) { platform.info(`safe-chain: no RUN instructions to protect${result.reason ? ` (${result.reason})` : ''}.`); return { ...plain, safeChain: 'nothing to protect' }; @@ -90,6 +92,13 @@ export async function run(platform: Platform, exec: Exec = defaultExec): Promise const result: RunResult = { imageRefs, pushed: false }; const summary: string[] = [`### Container build: \`${inputs.repository}\``, '', `Tags: ${tags.map((t) => `\`${t}\``).join(', ')}`, '']; + if (inputs.rerunBypass) { + const msg = + `Re-run (attempt ${ctx.attempt}): vulnerabilities found by the scan and safe-chain's minimum package age ` + + 'do not fail this build. Malware is still blocked.'; + platform.warning(msg); + summary.push(`⚠️ ${msg}`, ''); + } const build = await prepareBuild(platform, exec, inputs); await group(platform, 'Build image', () => @@ -136,11 +145,11 @@ export async function run(platform: Platform, exec: Exec = defaultExec): Promise if (scan.vulnerabilities.length > 0) { const msg = `Found ${scan.vulnerabilities.length} vulnerabilities with severity ${inputs.severity}`; - if (inputs.failOnVulnerabilities) { + if (inputs.failOnVulnerabilities && !inputs.rerunBypass) { platform.addSummary(summary.join('\n')); throw new Error(`${msg}. Image was not pushed. Fix them, add them to .trivyignore, or set failOnVulnerabilities to false.`); } - platform.warning(msg); + platform.warning(inputs.rerunBypass ? `${msg}; accepted because this is a re-run` : msg); } else { platform.info('No vulnerabilities found.'); } diff --git a/src/core/safechain.ts b/src/core/safechain.ts index c340436..5f8c05d 100644 --- a/src/core/safechain.ts +++ b/src/core/safechain.ts @@ -20,12 +20,16 @@ const SHA256: Record = { export const SAFE_CHAIN_CONTEXT = 'container-build-safe-chain'; const MOUNT_DIR = '/tmp/.container-build-safe-chain'; -const MOUNTS = [ - // writable, not part of the image: safe-chain keeps its malware lists and certificates here - `--mount=type=cache,id=${SAFE_CHAIN_CONTEXT},target=${MOUNT_DIR},mode=0777`, - `--mount=type=bind,from=${SAFE_CHAIN_CONTEXT},source=bin,target=${MOUNT_DIR}/bin`, - `--mount=type=bind,from=${SAFE_CHAIN_CONTEXT},source=shims,target=${MOUNT_DIR}/shims`, -].join(' '); +/** Shims that pass --safe-chain-skip-minimum-package-age; malware is still blocked. */ +const SKIP_AGE_SHIMS = 'shims-skip-minimum-age'; + +const mounts = (shims: string) => + [ + // writable, not part of the image: safe-chain keeps its malware lists and certificates here + `--mount=type=cache,id=${SAFE_CHAIN_CONTEXT},target=${MOUNT_DIR},mode=0777`, + `--mount=type=bind,from=${SAFE_CHAIN_CONTEXT},source=bin,target=${MOUNT_DIR}/bin`, + `--mount=type=bind,from=${SAFE_CHAIN_CONTEXT},source=${shims},target=${MOUNT_DIR}/shims`, + ].join(' '); const PREFIX = `export PATH="${MOUNT_DIR}/shims:${MOUNT_DIR}/bin:$PATH";`; export interface InstrumentResult { @@ -40,7 +44,8 @@ export interface InstrumentResult { * RUN npm ci -> RUN --mount=... export PATH=":$PATH"; npm ci * Exec-form RUN, heredocs and stages using a custom SHELL are left untouched. */ -export function instrumentDockerfile(content: string): InstrumentResult { +export function instrumentDockerfile(content: string, opts: { skipMinimumPackageAge?: boolean } = {}): InstrumentResult { + const MOUNTS = mounts(opts.skipMinimumPackageAge ? SKIP_AGE_SHIMS : 'shims'); const lines = content.split('\n'); // parser directives (only at the very top) for (const line of lines) { @@ -122,7 +127,24 @@ export async function prepareSafeChain( for (const k of ['GITHUB_PATH', 'BASH_ENV', 'TF_BUILD']) delete env[k]; await exec(bin, ['setup-ci'], { silent: true, env }); } + const relaxed = path.join(dir, SKIP_AGE_SHIMS); + if (!fs.existsSync(path.join(relaxed, 'npm'))) createSkipAgeShims(path.join(dir, 'shims'), relaxed); // do not ship the host CA key into the build; safe-chain creates its own inside the build fs.rmSync(path.join(dir, 'certs'), { recursive: true, force: true }); return dir; } + +/** Copies the shims, adding --safe-chain-skip-minimum-package-age to every package manager call. */ +export function createSkipAgeShims(from: string, to: string): void { + const tmp = `${to}.tmp`; + fs.rmSync(tmp, { recursive: true, force: true }); + fs.mkdirSync(tmp, { recursive: true }); + for (const name of fs.readdirSync(from)) { + const src = fs.readFileSync(path.join(from, name), 'utf8'); + const out = src.replace(/exec safe-chain (\S+) "\$@"/g, 'exec safe-chain $1 --safe-chain-skip-minimum-package-age "$@"'); + if (out === src) throw new Error(`Unexpected safe-chain shim format: ${name}`); + fs.writeFileSync(path.join(tmp, name), out, { mode: 0o755 }); + } + fs.rmSync(to, { recursive: true, force: true }); + fs.renameSync(tmp, to); +} diff --git a/src/github/platform.ts b/src/github/platform.ts index de4fee6..3987c36 100644 --- a/src/github/platform.ts +++ b/src/github/platform.ts @@ -24,6 +24,7 @@ export class GitHubPlatform implements Platform { this.context = { project: owner || undefined, repository: repo || undefined, + attempt: Number(env.GITHUB_RUN_ATTEMPT) || undefined, sha: env.GITHUB_SHA, ref: env.GITHUB_REF, isPullRequest: ['pull_request', 'pull_request_target'].includes(env.GITHUB_EVENT_NAME ?? ''), diff --git a/test/platforms.test.ts b/test/platforms.test.ts index 94af3f4..d4013ff 100644 --- a/test/platforms.test.ts +++ b/test/platforms.test.ts @@ -16,10 +16,11 @@ describe('GitHubPlatform', () => { GITHUB_SHA: 'abc', GITHUB_REF: 'refs/pull/1/merge', GITHUB_EVENT_NAME: 'pull_request', + GITHUB_RUN_ATTEMPT: '2', }); expect(p.getInput('buildArgs')).toBe('A=1'); expect(p.getInput('failOnVulnerabilities')).toBeUndefined(); - expect(p.context).toMatchObject({ sha: 'abc', ref: 'refs/pull/1/merge', isPullRequest: true }); + expect(p.context).toMatchObject({ sha: 'abc', ref: 'refs/pull/1/merge', isPullRequest: true, attempt: 2 }); }); it('uses github token for ghcr.io only', () => { @@ -177,8 +178,13 @@ describe('AzurePlatform', () => { }); it('maps context and escapes logging commands', () => { - const p = new AzurePlatform({ BUILD_SOURCEBRANCH: 'refs/heads/main', BUILD_SOURCEVERSION: 'abc', BUILD_REASON: 'PullRequest' }); - expect(p.context).toMatchObject({ ref: 'refs/heads/main', sha: 'abc', isPullRequest: true }); + const p = new AzurePlatform({ + BUILD_SOURCEBRANCH: 'refs/heads/main', + BUILD_SOURCEVERSION: 'abc', + BUILD_REASON: 'PullRequest', + SYSTEM_JOBATTEMPT: '3', + }); + expect(p.context).toMatchObject({ ref: 'refs/heads/main', sha: 'abc', isPullRequest: true, attempt: 3 }); const write = vi.spyOn(process.stdout, 'write').mockImplementation(() => true); p.setOutput('digest', 'a;b]\nc'); expect(write).toHaveBeenCalledWith('##vso[task.setvariable variable=digest;isOutput=true]a;b]%0Ac' + os.EOL); diff --git a/test/run-safechain.test.ts b/test/run-safechain.test.ts index 5f8fb22..12b3151 100644 --- a/test/run-safechain.test.ts +++ b/test/run-safechain.test.ts @@ -38,6 +38,21 @@ describe.runIf(supported)('run with safe-chain', () => { expect(p.summary).toContain('Safe Chain'); }); + it('skips the minimum package age (not malware) on a re-run', async () => { + const { run } = await import('../src/core/run'); + const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'ws-')); + fs.writeFileSync(path.join(workspace, 'Dockerfile'), 'FROM node\nRUN npm ci\n'); + const builds: string[][] = []; + const exec: Exec = async (_c, args) => { + if (args[0] === 'build') builds.push(args); + return { exitCode: 0, stdout: '', stderr: '' }; + }; + const ctx = { isPullRequest: false, tempDir: workspace, workspace, attempt: 2 }; + await run(new FakePlatform({ image: 'reg.io/app', scan: 'false', sbom: 'false', push: 'false' }, ctx), exec); + const dockerfile = builds[0][builds[0].indexOf('--file') + 1]; + expect(fs.readFileSync(dockerfile, 'utf8')).toContain('source=shims-skip-minimum-age,'); + }); + it('uses the original Dockerfile when there is nothing to protect', async () => { const { run } = await import('../src/core/run'); const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'ws-')); diff --git a/test/run.test.ts b/test/run.test.ts index 7e48945..251f6b9 100644 --- a/test/run.test.ts +++ b/test/run.test.ts @@ -64,6 +64,22 @@ describe('run', () => { expect(p.summary).toContain('CVE-1'); }); + it('accepts vulnerabilities on a re-run and pushes', async () => { + const { calls, exec, ctx } = setup([vuln]); + const p = new FakePlatform({ image: 'reg.io/app', safeChain: 'false' }, { ...ctx, attempt: 2 }); + const r = await run(p, exec); + expect(r.pushed).toBe(true); + expect(calls.some((c) => c.args[0] === 'push')).toBe(true); + expect(p.logs.some((l) => l.startsWith('WARN Re-run (attempt 2)'))).toBe(true); + expect(p.summary).toContain('Re-run (attempt 2)'); + }); + + it('still fails on a re-run when bypassOnRerun is false', async () => { + const { exec, ctx } = setup([vuln]); + const p = new FakePlatform({ image: 'reg.io/app', safeChain: 'false', bypassOnRerun: 'false' }, { ...ctx, attempt: 3 }); + await expect(run(p, exec)).rejects.toThrow(/vulnerabilities/); + }); + it('only warns when failOnVulnerabilities is false', async () => { const { calls, exec, ctx } = setup([vuln]); const p = new FakePlatform({ image: 'reg.io/app', failOnVulnerabilities: 'false', safeChain: 'false' }, ctx); diff --git a/test/safechain.test.ts b/test/safechain.test.ts index 923853a..7b51855 100644 --- a/test/safechain.test.ts +++ b/test/safechain.test.ts @@ -4,7 +4,7 @@ import * as path from 'node:path'; import { createHash } from 'node:crypto'; import { describe, expect, it } from 'vitest'; import type { Exec } from '../src/core/exec'; -import { instrumentDockerfile, prepareSafeChain, SAFE_CHAIN_CONTEXT, SAFE_CHAIN_VERSION } from '../src/core/safechain'; +import { createSkipAgeShims, instrumentDockerfile, prepareSafeChain, SAFE_CHAIN_CONTEXT, SAFE_CHAIN_VERSION } from '../src/core/safechain'; const MOUNT = `--mount=type=cache,id=${SAFE_CHAIN_CONTEXT}`; @@ -58,12 +58,29 @@ describe('instrumentDockerfile', () => { expect(r.content.split('\n')[2]).toBe(' RUN=2'); }); + it('mounts the shims that skip the minimum package age on request', () => { + expect(instrumentDockerfile('FROM a\nRUN npm ci').content).toContain('source=shims,'); + expect(instrumentDockerfile('FROM a\nRUN npm ci', { skipMinimumPackageAge: true }).content).toContain( + 'source=shims-skip-minimum-age,', + ); + }); + it('skips Windows Dockerfiles', () => { const r = instrumentDockerfile('# escape=`\nFROM mcr.microsoft.com/windows\nRUN echo hi'); expect(r).toMatchObject({ wrapped: 0, reason: expect.stringContaining('escape') }); }); }); +describe('createSkipAgeShims', () => { + it('rejects shims in an unknown format', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'shims-')); + fs.mkdirSync(path.join(dir, 'shims')); + fs.writeFileSync(path.join(dir, 'shims', 'npm'), '#!/bin/sh\nexec something-else'); + expect(() => createSkipAgeShims(path.join(dir, 'shims'), path.join(dir, 'out'))).toThrow(/Unexpected/); + expect(fs.existsSync(path.join(dir, 'out'))).toBe(false); + }); +}); + describe('prepareSafeChain', () => { const content = 'fake-binary'; const sha = createHash('sha256').update(content).digest('hex'); @@ -77,7 +94,7 @@ describe('prepareSafeChain', () => { expect(opts?.env?.GITHUB_PATH).toBeUndefined(); const dir = path.dirname(path.dirname(cmd)); fs.mkdirSync(path.join(dir, 'shims'), { recursive: true }); - fs.writeFileSync(path.join(dir, 'shims', 'npm'), '#!/bin/sh'); + fs.writeFileSync(path.join(dir, 'shims', 'npm'), '#!/bin/sh\n PATH=$(x) exec safe-chain npm "$@"\n'); fs.mkdirSync(path.join(dir, 'certs'), { recursive: true }); } return { exitCode: 0, stdout: '', stderr: '' }; @@ -95,6 +112,9 @@ describe('prepareSafeChain', () => { expect(calls[0]).toEqual(expect.arrayContaining(['curl', expect.stringContaining(`/${SAFE_CHAIN_VERSION}/safe-chain-linuxstatic-x64`)])); expect(fs.existsSync(path.join(dir, 'shims', 'npm'))).toBe(true); expect(fs.existsSync(path.join(dir, 'certs'))).toBe(false); + expect(fs.readFileSync(path.join(dir, 'shims-skip-minimum-age', 'npm'), 'utf8')).toContain( + 'exec safe-chain npm --safe-chain-skip-minimum-package-age "$@"', + ); const second = fakeExec(); await prepareSafeChain(second.exec, cache, 'x64', sha);