Skip to content
Merged
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
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
4 changes: 4 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions azure/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
9 changes: 9 additions & 0 deletions azure/tasks/ContainerBuild/task.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
38 changes: 32 additions & 6 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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/, "")}`
};
}
Expand All @@ -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);
Expand Down Expand Up @@ -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"));
Expand Down Expand Up @@ -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" };
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.");
}
Expand Down Expand Up @@ -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 ?? ""),
Expand Down
1 change: 1 addition & 0 deletions src/azure/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
3 changes: 3 additions & 0 deletions src/core/inputs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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/, '')}`,
};
}
2 changes: 2 additions & 0 deletions src/core/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down
15 changes: 12 additions & 3 deletions src/core/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' };
Expand Down Expand Up @@ -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', () =>
Expand Down Expand Up @@ -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.');
}
Expand Down
36 changes: 29 additions & 7 deletions src/core/safechain.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ const SHA256: Record<string, string> = {
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 {
Expand All @@ -40,7 +44,8 @@ export interface InstrumentResult {
* RUN npm ci -> RUN --mount=... export PATH="<safe-chain shims>:$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) {
Expand Down Expand Up @@ -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);
}
1 change: 1 addition & 0 deletions src/github/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?? ''),
Expand Down
12 changes: 9 additions & 3 deletions test/platforms.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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);
Expand Down
15 changes: 15 additions & 0 deletions test/run-safechain.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-'));
Expand Down
Loading
Loading