From 4f3c64b0d1460d64da5e3181d537f52005f682cb Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 10 Nov 2026 09:43:03 -0800 Subject: [PATCH] ci(images): resume optional container security scans through Charon Signed-off-by: Prekshi Vyas --- .../scripts/managed-image-scan-results.mts | 103 +++++++++ .github/scripts/scan-managed-image.sh | 80 +++++++ .github/workflows/base-image.yaml | 7 + .github/workflows/managed-images.yaml | 175 ++++++++++++++- ci/managed-image-security-scans.md | 55 +++++ ci/source-shape-test-budget.json | 10 + .../managed-image-security-scan.test.ts | 209 ++++++++++++++++++ test/helpers/vitest-watch-triggers.ts | 7 + ...managed-image-publication-workflow.test.ts | 6 +- test/repository/vitest-watch-triggers.test.ts | 2 + 10 files changed, 652 insertions(+), 2 deletions(-) create mode 100644 .github/scripts/managed-image-scan-results.mts create mode 100755 .github/scripts/scan-managed-image.sh create mode 100644 ci/managed-image-security-scans.md create mode 100644 test/e2e/support/managed-image-security-scan.test.ts diff --git a/.github/scripts/managed-image-scan-results.mts b/.github/scripts/managed-image-scan-results.mts new file mode 100644 index 00000000000..56520c007eb --- /dev/null +++ b/.github/scripts/managed-image-scan-results.mts @@ -0,0 +1,103 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +type RecordValue = Record; +function record(value: unknown): RecordValue { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error("Invalid scan evidence."); + } + return value as RecordValue; +} + +// Never include scanner-controlled text in an error or public summary. +export function scanPassed(kind: string, exitCode: number, source: string): boolean { + if (kind === "secrets") { + if (![0, 185, 189].includes(exitCode)) return false; + const results = source.split(/\r?\n/u).filter((line) => line.trim()); + const verified = results.map((line) => { + const result = record(JSON.parse(line)); + if (typeof result.Verified !== "boolean") throw new Error("Invalid scan evidence."); + return result.Verified; + }); + // 189 means all findings were allowlisted by the repository's reviewed allowlist. + return exitCode === 189 || !verified.some(Boolean); + } + if (exitCode !== 0) return false; + const report = record(JSON.parse(source)); + if (kind === "vulnerabilities") { + if (!Array.isArray(report.matches)) throw new Error("Invalid scan evidence."); + return report.matches.every((match) => { + const severity = record(record(match).vulnerability).severity; + if (typeof severity !== "string") throw new Error("Invalid scan evidence."); + return severity.toLowerCase() !== "critical"; + }); + } + if (kind === "malware") { + const data = record(report.data); + if (!Array.isArray(data.report)) throw new Error("Invalid scan evidence."); + return data.status === "CLEAN"; + } + throw new Error("Unknown scan category."); +} + +export function candidateReference(value: unknown, env: NodeJS.ProcessEnv): string { + const candidate = record(value); + const source = record(candidate.source); + const run = record(candidate.run); + const evidence = record(candidate.publicationEvidence); + const workload = record(evidence.workloadDescriptor); + const platform = record(workload.platform); + const digest = /^sha256:[0-9a-f]{64}$/u; + if ( + candidate.contractVersion !== 2 || + candidate.phase !== "candidate" || + candidate.agent !== env.AGENT || + candidate.platform !== env.PLATFORM || + candidate.image !== env.IMAGE || + typeof candidate.digest !== "string" || + !digest.test(candidate.digest) || + candidate.reference !== `${candidate.image}@${candidate.digest}` || + source.repository !== "NVIDIA/NemoClaw" || + source.repository !== env.GITHUB_REPOSITORY || + source.revision !== env.GITHUB_SHA || + source.ref !== "refs/heads/main" || + env.GITHUB_REF !== "refs/heads/main" || + env.GITHUB_EVENT_NAME !== "workflow_dispatch" || + run.id !== Number(env.GITHUB_RUN_ID) || + !Number.isSafeInteger(run.attempt) || + Number(run.attempt) < 1 || + Number(run.attempt) > Number(env.GITHUB_RUN_ATTEMPT) || + typeof workload.digest !== "string" || + !digest.test(workload.digest) || + workload.mediaType !== "application/vnd.oci.image.manifest.v1+json" || + `${platform.os}/${platform.architecture}` !== env.PLATFORM + ) { + throw new Error("Candidate does not belong to this publication."); + } + // Scan the platform workload, not the OCI index containing its attestations. + return `${candidate.image}@${workload.digest}`; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + try { + const [mode, ...args] = process.argv.slice(2); + if (mode === "candidate" && args.length === 1) { + process.stdout.write( + candidateReference(JSON.parse(readFileSync(args[0]!, "utf8")), process.env), + ); + } else if (mode === "result" && args.length === 3) { + const code = Number(args[1]); + if (!Number.isSafeInteger(code) || code < 0 || code > 255) + throw new Error("Invalid exit code."); + process.exitCode = scanPassed(args[0]!, code, readFileSync(args[2]!, "utf8")) ? 0 : 1; + } else { + throw new Error("Invalid arguments."); + } + } catch { + console.error("Scan evidence is missing, invalid, or blocking."); + process.exitCode = 1; + } +} diff --git a/.github/scripts/scan-managed-image.sh b/.github/scripts/scan-managed-image.sh new file mode 100755 index 00000000000..bbe34c9ee7f --- /dev/null +++ b/.github/scripts/scan-managed-image.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +set -euo pipefail +umask 077 + +scan_root="${SCAN_ROOT:?Missing SCAN_ROOT}" +helper="$GITHUB_WORKSPACE/.github/scripts/managed-image-scan-results.mts" +prefix="managed-scan-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-${AGENT}-${ARCH}" +failed=0 + +# Called by the EXIT trap, including scanner failures. +# shellcheck disable=SC2329 +cleanup() { + local cleanup_failed=0 name + for name in grype secrets malware; do + docker rm --force "$prefix-$name" >/dev/null 2>&1 || true + if ! remaining="$(docker ps -aq --filter "name=^/$prefix-$name$")" || [ -n "$remaining" ]; then + cleanup_failed=1 + fi + done + rm -rf "$scan_root" + if [ "$cleanup_failed" -ne 0 ]; then + echo "ERROR: Could not remove a scan container." >&2 + exit 1 + fi +} +trap cleanup EXIT + +# Pull by workload digest. No candidate image is executed or given credentials. +reference="$(node "$helper" candidate "$CONTRACT")" +docker pull --platform "$PLATFORM" "$reference" >"$scan_root/pull.log" 2>&1 +image_id="$(docker image inspect --format '{{.Id}}' "$reference")" +[[ "$image_id" =~ ^sha256:[0-9a-f]{64}$ ]] +docker save "$image_id" >"$scan_root/image.tar" + +record_result() { + local category="$1" code="$2" path="$3" result=FAIL + if node "$helper" result "$category" "$code" "$path" >/dev/null 2>&1; then + result=PASS + else + failed=1 + fi + # Only fixed category names and pass/fail reach the public job summary. + printf '| %s | %s |\n' "$category" "$result" >>"$GITHUB_STEP_SUMMARY" +} +printf '### Managed image security scans\n\n| Scan | Result |\n| --- | --- |\n' >>"$GITHUB_STEP_SUMMARY" + +code=0 +docker run --rm --name "$prefix-grype" --cap-drop=ALL --security-opt=no-new-privileges \ + --volume "$scan_root/image.tar:/scan/image.tar:ro" \ + "$GRYPE_IMAGE" docker-archive:/scan/image.tar --fail-on critical --output json \ + >"$scan_root/vulnerabilities.json" 2>"$scan_root/grype.log" || code=$? +record_result vulnerabilities "$code" "$scan_root/vulnerabilities.json" + +code=0 +docker run --rm --name "$prefix-secrets" --cap-drop=ALL --security-opt=no-new-privileges \ + --volume "$scan_root/image.tar:/scan/image.tar:ro" \ + --volume "$GITHUB_WORKSPACE/.nspect-allowlist.toml:/allowlist.toml:ro" \ + "$PULSE_SECRET_IMAGE" docker --image file:///scan/image.tar \ + --allowlist=/allowlist.toml --json --results=verified,unknown --fail --fail-on-scan-errors \ + >"$scan_root/secrets.jsonl" 2>"$scan_root/secrets.log" || code=$? +record_result secrets "$code" "$scan_root/secrets.jsonl" + +# The approved scanner alone receives short-lived OIDC request credentials. +# Charon authorizes image submission and report retrieval for this repository/ref. +code=0 +docker create --name "$prefix-malware" --network host \ + --cap-drop=ALL --security-opt=no-new-privileges --workdir /tmp \ + --env ACTIONS_ID_TOKEN_REQUEST_URL --env ACTIONS_ID_TOKEN_REQUEST_TOKEN \ + --env CI=true --env GITHUB_ACTIONS=true \ + "$PULSE_MALWARE_IMAGE" pulse-malware-scanner-cli \ + --nspect "$NSPECT_ID" --tenant github-first --base-url http://127.0.0.1:8888 \ + --output-dir=. --wait=true --wait-retries=50 --backoff-sec=2 --max-poll-wait-sec=60 \ + image-scan --image-ref "$reference" --platform "$PLATFORM" >/dev/null +docker start --attach "$prefix-malware" >"$scan_root/malware.log" 2>&1 || code=$? +docker cp "$prefix-malware:/tmp/malware_report_1.json" "$scan_root/malware.json" >/dev/null 2>&1 || code=1 +record_result malware "$code" "$scan_root/malware.json" +exit "$failed" diff --git a/.github/workflows/base-image.yaml b/.github/workflows/base-image.yaml index 710991bc285..4661fcf8794 100644 --- a/.github/workflows/base-image.yaml +++ b/.github/workflows/base-image.yaml @@ -108,6 +108,11 @@ on: - "scripts/lib/sandbox-rlimits.sh" workflow_dispatch: inputs: + run_security_scans: + description: "Scan managed images before promotion (requires Pulse onboarding)" + required: false + type: boolean + default: false openclaw_version: description: "OpenClaw version to install (leave blank to use the default in Dockerfile.base)" required: false @@ -448,8 +453,10 @@ jobs: permissions: contents: read packages: write + id-token: write uses: ./.github/workflows/managed-images.yaml with: + run_security_scans: ${{ inputs.run_security_scans || false }} dcode-base-contract-base64: ${{ needs.build-and-push-dcode.outputs.contract-base64 }} hermes-base-contract-base64: ${{ needs.build-and-push-hermes.outputs.contract-base64 }} openclaw-base-contract-base64: ${{ needs.build-and-push-openclaw.outputs.contract-base64 }} diff --git a/.github/workflows/managed-images.yaml b/.github/workflows/managed-images.yaml index 869a9c0d68b..a35f82401ee 100644 --- a/.github/workflows/managed-images.yaml +++ b/.github/workflows/managed-images.yaml @@ -20,6 +20,11 @@ name: Images / Build, Test, and Publish Managed Images on: workflow_call: inputs: + run_security_scans: + description: "Scan managed images before promotion on manual main runs" + required: false + type: boolean + default: false dcode-base-contract-base64: required: true type: string @@ -2218,7 +2223,7 @@ jobs: timeout-minutes: 120 strategy: fail-fast: false - matrix: + matrix: &managed_image_inventory include: - agent: openclaw arch: amd64 @@ -2997,11 +3002,179 @@ jobs: overwrite: true retention-days: 1 + # Reuse the publication inventory; Pi and llama.cpp have separate publishers. + security-scan-managed-images: + name: Security scan ${{ matrix.display_name }} (${{ matrix.arch }}) + if: >- + ${{ inputs.run_security_scans && github.repository == 'NVIDIA/NemoClaw' && + github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' }} + needs: build-and-validate + runs-on: linux-amd64-cpu4 + timeout-minutes: 120 + permissions: + contents: read + packages: read + id-token: write + strategy: + fail-fast: false + matrix: *managed_image_inventory + env: + # Pulse Malware 1.3.0, Pulse Secret 3.95.9-nvidia.1, and Grype 0.121.3. + PULSE_MALWARE_IMAGE: nvcr.io/0898940053369630/pulse/pulse-malware-scanner-cli@sha256:9d1f9c6868ae5c63322adb345e66f2d7d00f4027d3dbac47ba7861c3332be831 + PULSE_SECRET_IMAGE: nvcr.io/0898940053369630/pulse/pulse-secret-scanner@sha256:5ba66735e5a5408c89025eb43f9fe0242e071d494a826e415964399bc9a85fc1 + GRYPE_IMAGE: anchore/grype@sha256:13113eeceab017260370cf540e1d25442c59665fd07d1b09b66d63bb0c282887 + NSPECT_ID: ${{ vars.NSPECT_ID }} + steps: + - name: Check scanner configuration + env: + NV_VAULT_URL: ${{ vars.NV_VAULT_URL }} + NVCR_VAULT_ROLE: ${{ vars.NVCR_VAULT_ROLE }} + NVCR_VAULT_JWT_PATH: ${{ vars.NVCR_VAULT_JWT_PATH }} + NVCR_VAULT_NAMESPACE: ${{ vars.NVCR_VAULT_NAMESPACE }} + NVCR_VAULT_SECRET_PATH: ${{ vars.NVCR_VAULT_SECRET_PATH }} + run: | + set -euo pipefail + [[ "$NSPECT_ID" =~ ^NSPECT-[A-Z0-9]{4}-[A-Z0-9]{4}$ ]] + for name in NV_VAULT_URL NVCR_VAULT_ROLE NVCR_VAULT_JWT_PATH NVCR_VAULT_NAMESPACE NVCR_VAULT_SECRET_PATH; do + if [ -z "${!name}" ]; then + echo "::error::Missing platform variable: $name" + exit 1 + fi + done + root="$(mktemp -d "$RUNNER_TEMP/managed-scan.XXXXXX")" + mkdir -m 700 "$root/docker" "$root/scan" + printf 'SCAN_PRIVATE_ROOT=%s\nDOCKER_CONFIG=%s/docker\nSCAN_ROOT=%s/scan\n' "$root" "$root" "$root" >> "$GITHUB_ENV" + + - name: Checkout trusted publication + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24.22.1 + + - name: Restore managed image candidate + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: managed-image-candidate-${{ github.run_id }}-${{ matrix.agent }}-${{ matrix.artifact_platform }} + path: ${{ env.SCAN_PRIVATE_ROOT }}/candidate + digest-mismatch: error + + - name: Import scanner registry credentials + uses: hashicorp/vault-action@4c06c5ccf5c0761b6029f56cfb1dcf5565918a3b # v3.4.0 + with: + url: ${{ vars.NV_VAULT_URL }} + role: ${{ vars.NVCR_VAULT_ROLE }} + method: jwt + path: ${{ vars.NVCR_VAULT_JWT_PATH }} + jwtGithubAudience: https://token.actions.githubusercontent.com + namespace: ${{ vars.NVCR_VAULT_NAMESPACE }} + secrets: | + ${{ vars.NVCR_VAULT_SECRET_PATH }} username | NVCR_IO_USERNAME ; + ${{ vars.NVCR_VAULT_SECRET_PATH }} password | NVCR_IO_PASSWORD + + - name: Pull pinned scanners + run: | + set -euo pipefail + trap 'docker logout nvcr.io >/dev/null 2>&1 || true' EXIT + printf '%s' "$NVCR_IO_PASSWORD" | docker login nvcr.io -u "$NVCR_IO_USERNAME" --password-stdin >/dev/null + docker pull "$PULSE_MALWARE_IMAGE" >/dev/null + docker pull "$PULSE_SECRET_IMAGE" >/dev/null + docker pull "$GRYPE_IMAGE" >/dev/null + printf 'NVCR_IO_USERNAME=\nNVCR_IO_PASSWORD=\n' >> "$GITHUB_ENV" + + - name: Authenticate image pull + uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ github.token }} + logout: false + + - name: Install Charon tunnel client + uses: teleport-actions/setup@b638ff596557cc3959eb6b5287d5e58e0c8ac6a6 # v1 + with: + version: auto + proxy: ext-nv-prd-apps.teleport.sh:443 + + - name: Open authorized Pulse tunnel + run: | + set -euo pipefail + umask 077 + cat > "$SCAN_PRIVATE_ROOT/tbot.yaml" <<'EOF' + version: v2 + proxy_server: ext-nv-prd-apps.teleport.sh:443 + onboarding: + join_method: github + token: charon-gha-runners + storage: + type: memory + outputs: [] + services: + - type: application-tunnel + app_name: charon + listen: tcp://127.0.0.1:8888 + EOF + tbot start -c "$SCAN_PRIVATE_ROOT/tbot.yaml" > "$SCAN_PRIVATE_ROOT/tbot.log" 2>&1 & + pid=$! + printf 'SCAN_TBOT_PID=%s\n' "$pid" >> "$GITHUB_ENV" + for _ in {1..30}; do + kill -0 "$pid" 2>/dev/null || exit 1 + if curl --fail --silent http://127.0.0.1:8888/ready >/dev/null; then exit 0; fi + sleep 1 + done + echo "::error::Pulse tunnel is unavailable. Check repository/ref onboarding." + exit 1 + + - name: Scan the managed image workload + env: + AGENT: ${{ matrix.agent }} + ARCH: ${{ matrix.arch }} + PLATFORM: ${{ matrix.platform }} + IMAGE: ghcr.io/${{ matrix.image }} + CONTRACT: ${{ env.SCAN_PRIVATE_ROOT }}/candidate/contract.json + run: bash .github/scripts/scan-managed-image.sh + + - name: Remove private scanner state + if: always() + env: + AGENT: ${{ matrix.agent }} + ARCH: ${{ matrix.arch }} + run: | + set -euo pipefail + failed=0 + if [ -n "${SCAN_TBOT_PID:-}" ]; then + kill "$SCAN_TBOT_PID" 2>/dev/null || true + fi + prefix="managed-scan-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}-${AGENT}-${ARCH}" + for suffix in grype secrets malware; do + docker rm --force "$prefix-$suffix" >/dev/null 2>&1 || true + if ! remaining="$(docker ps -aq --filter "name=^/$prefix-$suffix$")" || [ -n "$remaining" ]; then failed=1; fi + done + if [ -n "${SCAN_PRIVATE_ROOT:-}" ]; then + case "$SCAN_PRIVATE_ROOT" in "$RUNNER_TEMP"/managed-scan.*) ;; *) exit 1 ;; esac + rm -rf "$SCAN_PRIVATE_ROOT" + fi + exit "$failed" + promote: name: Promote complete multi-platform managed image cohort + if: >- + ${{ + !cancelled() && + needs.publication-identity.result == 'success' && + needs.build-and-validate.result == 'success' && + ( + (inputs.run_security_scans && needs.security-scan-managed-images.result == 'success') || + (!inputs.run_security_scans && needs.security-scan-managed-images.result == 'skipped') + ) + }} needs: - publication-identity - build-and-validate + - security-scan-managed-images runs-on: ubuntu-24.04 timeout-minutes: 30 permissions: diff --git a/ci/managed-image-security-scans.md b/ci/managed-image-security-scans.md new file mode 100644 index 00000000000..d680bd85414 --- /dev/null +++ b/ci/managed-image-security-scans.md @@ -0,0 +1,55 @@ + + + +# Optional managed-image security scans + +The manual base-image publication workflow accepts `run_security_scans`, defaulting to false. +When selected on canonical `main`, all six OpenClaw, Hermes, and Deep Agents Code platform images +must pass scanning before cohort promotion. Tags and ordinary publication retain their existing behavior. +Pi and llama.cpp use separate publication paths and are outside this option. + +This continues the scope recorded in [PR #11876](https://github.com/NVIDIA/NemoClaw/pull/11876). +The checks cover the published workload digest and its base layers: + +- Grype blocks Critical vulnerabilities. Lower severities do not block. +- Pulse Secret Scanner blocks verified secrets and scan errors. Unverified findings remain advisory; + findings covered by the reviewed `.nspect-allowlist.toml` do not block. +- Pulse Malware Scanner submits the workload image and platform through Charon. Only a successful + process with a valid `CLEAN` report passes. Submission alone is insufficient. + +These are image scans. The source-code workflows in `NVIDIA/security-workflows` do not replace them. +Grype results are not Pulse container vulnerability records or nSpect inventory updates. + +## Platform prerequisites + +Before the first live run, the platform owner must provision: + +- Access to the NVIDIA `linux-amd64-cpu4` runner pool. +- The existing `NV_VAULT_URL` and `NVCR_VAULT_*` organization variables for the repository. +- A repository `NSPECT_ID` Actions variable identifying the intended NemoClaw program. +- A Charon tenant for `NVIDIA/NemoClaw`, allowing `refs/heads/main` and the malware CLI's + nSpect verification, image-digest lookup, image-scan submission, and report retrieval routes. +- Pulse permission to pull the published GHCR images and use the `github-first` tenant for image scans. + +The scan job retrieves the NVCR pull credential from Vault through GitHub OIDC. Its private Docker +configuration is deleted during cleanup. The pinned malware scanner receives only the short-lived +GitHub OIDC request environment; Charon supplies backend authorization. No static SSA secret is needed. +The candidate image is never executed. Grype and the secret scanner receive no OIDC or registry credentials. + +Raw reports and scanner logs remain in job-private temporary files and are deleted during cleanup. +Public summaries contain only scan categories and pass/fail. The workflow uploads no raw reports. +Use the authorized Pulse backend for detailed malware evidence and remediation. + +## Qualification before enabling production scans + +Local tests establish candidate binding, result handling, promotion decisions, and cleanup with +stubbed scanners. They do not establish live scanner access or detection. + +Before production use, retain restricted evidence of an actual image scan on both architectures. +Record the source commit, workload digest, scanner digest, backend scan record, and final verdict. +Use approved harmless fixtures to verify detection and the promotion block. Verify that missing access, +scanner failure, invalid reports, and timeout block promotion, and confirm temporary-state cleanup. +Keep detailed findings out of public logs and artifacts. + +NemoClaw's Charon tenant and image-scan permission were not confirmed when this change was prepared. +Do not interpret passing local tests or source-code scans in another repository as image-scan qualification. diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 3f5c9251acc..f31bf6243c5 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -520,6 +520,16 @@ "file": "test/automation/pull-requests/candidate-upgrade-admission-workflow.test.ts", "test": "refreshes admission through the configured %s review handoff after %s", "category": "security" + }, + { + "file": "test/e2e/support/managed-image-security-scan.test.ts", + "test": "evaluates promotion with scans selected %s and scan result %s", + "category": "security" + }, + { + "file": "test/e2e/support/managed-image-security-scan.test.ts", + "test": "keeps scans optional and reuses the complete publication inventory", + "category": "security" } ] } diff --git a/test/e2e/support/managed-image-security-scan.test.ts b/test/e2e/support/managed-image-security-scan.test.ts new file mode 100644 index 00000000000..c48e0935ae0 --- /dev/null +++ b/test/e2e/support/managed-image-security-scan.test.ts @@ -0,0 +1,209 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { spawnSync } from "node:child_process"; +import { describe, expect, it } from "vitest"; +import { parse } from "yaml"; +import { + candidateReference, + scanPassed, +} from "../../../.github/scripts/managed-image-scan-results.mts"; + +const root = resolve(import.meta.dirname, "../../.."); +const digest = `sha256:${"a".repeat(64)}`; +const workloadDigest = `sha256:${"b".repeat(64)}`; +const env = { + AGENT: "openclaw", + ARCH: "amd64", + PLATFORM: "linux/amd64", + IMAGE: "ghcr.io/nvidia/nemoclaw/openclaw-sandbox", + GITHUB_REPOSITORY: "NVIDIA/NemoClaw", + GITHUB_REF: "refs/heads/main", + GITHUB_EVENT_NAME: "workflow_dispatch", + GITHUB_SHA: "c".repeat(40), + GITHUB_RUN_ID: "42", + GITHUB_RUN_ATTEMPT: "2", +}; +function candidate() { + return { + contractVersion: 2, + phase: "candidate", + agent: env.AGENT, + platform: env.PLATFORM, + image: env.IMAGE, + digest, + reference: `${env.IMAGE}@${digest}`, + source: { repository: env.GITHUB_REPOSITORY, revision: env.GITHUB_SHA, ref: env.GITHUB_REF }, + run: { id: 42, attempt: 1 }, + publicationEvidence: { + workloadDescriptor: { + digest: workloadDigest, + mediaType: "application/vnd.oci.image.manifest.v1+json", + platform: { os: "linux", architecture: "amd64" }, + }, + }, + }; +} + +describe("Managed image scan evidence", () => { + it("scans the workload digest retained by a successful producer attempt", () => { + expect(candidateReference(candidate(), env)).toBe(`${env.IMAGE}@${workloadDigest}`); + }); + it.each([ + { GITHUB_RUN_ID: "43" }, + { GITHUB_RUN_ATTEMPT: "0" }, + { GITHUB_SHA: "d".repeat(40) }, + { GITHUB_REF: "refs/tags/v1" }, + { GITHUB_EVENT_NAME: "pull_request" }, + { GITHUB_REPOSITORY: "someone/NemoClaw" }, + { PLATFORM: "linux/arm64" }, + { IMAGE: "ghcr.io/other/image" }, + { AGENT: "hermes" }, + ])("rejects a candidate outside the publication identity: %j", (override) => { + expect(() => candidateReference(candidate(), { ...env, ...override })).toThrow(); + }); + it("rejects a mutable workload reference", () => { + const value = candidate(); + value.publicationEvidence.workloadDescriptor.digest = "latest"; + expect(() => candidateReference(value, env)).toThrow(); + }); + it.each(["SUSPICIOUS", "MALICIOUS", "FAILED", "PENDING", ""])( + "blocks malware status %s even with a zero exit code", + (status) => { + expect(scanPassed("malware", 0, JSON.stringify({ data: { status, report: [] } }))).toBe( + false, + ); + }, + ); + it("requires both a clean malware report and a successful scanner process", () => { + const clean = JSON.stringify({ data: { status: "CLEAN", report: [] } }); + expect(scanPassed("malware", 0, clean)).toBe(true); + expect(() => scanPassed("malware", 0, '{"data":{"status":"CLEAN"}}')).toThrow(); + }); + it.each([1, 2, 4, 5, 6, 137])("blocks malware process exit %s despite a clean report", (code) => { + expect( + scanPassed("malware", code, JSON.stringify({ data: { status: "CLEAN", report: [] } })), + ).toBe(false); + }); + it.each([1, 2, 183, 137])("blocks secret scanner process exit %s", (code) => { + expect(scanPassed("secrets", code, "")).toBe(false); + }); + it("blocks Critical vulnerabilities and malformed findings", () => { + const report = (severity: string) => + JSON.stringify({ matches: [{ vulnerability: { severity } }] }); + expect(scanPassed("vulnerabilities", 0, report("Critical"))).toBe(false); + expect(scanPassed("vulnerabilities", 0, report("High"))).toBe(true); + expect(scanPassed("vulnerabilities", 1, report("High"))).toBe(false); + expect(() => scanPassed("vulnerabilities", 0, "{}")).toThrow(); + }); + it("blocks verified secrets and scanner failures while preserving allowlisted results", () => { + const finding = JSON.stringify({ Verified: true, Raw: "must-not-be-published" }); + expect(scanPassed("secrets", 0, finding)).toBe(false); + expect(scanPassed("secrets", 185, finding)).toBe(false); + expect(scanPassed("secrets", 189, finding)).toBe(true); + expect(scanPassed("secrets", 185, '{"Verified":false}')).toBe(true); + expect(scanPassed("secrets", 0, "")).toBe(true); + expect(() => scanPassed("secrets", 0, "{bad-json-secret}")).toThrow(); + }); +}); + +describe("Managed image security gate", () => { + const workflow = parse(readFileSync(join(root, ".github/workflows/managed-images.yaml"), "utf8")); + const base = parse(readFileSync(join(root, ".github/workflows/base-image.yaml"), "utf8")); + // source-shape-contract: security -- The promotion expression must deny incomplete selected scans before any mutable alias can move. + it.each([ + [true, "success", true], + [true, "failure", false], + [true, "cancelled", false], + [true, "skipped", false], + [false, "success", false], + [false, "failure", false], + [false, "cancelled", false], + [false, "skipped", true], + ])( + "evaluates promotion with scans selected %s and scan result %s", + (requested, result, allowed) => { + const expression = workflow.jobs.promote.if + .replace(/\$\{\{|\}\}/gu, "") + .replace(/needs\.([a-z-]+)/gu, 'needs["$1"]'); + const needs = { + "publication-identity": { result: "success" }, + "build-and-validate": { result: "success" }, + "security-scan-managed-images": { result }, + }; + const gate = new Function("cancelled", "inputs", "needs", `return (${expression});`); + expect(gate(() => false, { run_security_scans: requested }, needs)).toBe(allowed); + expect(gate(() => true, { run_security_scans: requested }, needs)).toBe(false); + }, + ); + // source-shape-contract: security -- Every published agent and architecture must enter the optional scan gate through the same inventory. + it("keeps scans optional and reuses the complete publication inventory", () => { + expect(base.on.workflow_dispatch.inputs.run_security_scans.default).toBe(false); + expect(workflow.on.workflow_call.inputs.run_security_scans.default).toBe(false); + expect(workflow.jobs["security-scan-managed-images"].strategy.matrix).toEqual( + workflow.jobs["build-and-validate"].strategy.matrix, + ); + expect(workflow.jobs["security-scan-managed-images"].strategy.matrix.include).toHaveLength(6); + expect(workflow.jobs.promote.needs).toContain("security-scan-managed-images"); + }); + it.each([0, 5])( + "runs container scans and removes private reports (malware exit %s)", + (malwareExit) => { + const temporary = mkdtempSync(join(tmpdir(), "managed-scan-test-")); + try { + const bin = join(temporary, "bin"); + const scan = join(temporary, "scan"); + mkdirSync(bin); + mkdirSync(scan); + const contract = join(temporary, "contract.json"); + writeFileSync(contract, JSON.stringify(candidate())); + writeFileSync( + join(bin, "docker"), + `#!/bin/sh +case "$1" in + image) printf '%s' '${workloadDigest}' ;; + pull|save|rm|ps|create) exit 0 ;; + run) + case "$*" in + *grype-image*) printf '%s' '{"matches":[]}' ;; + *secret-image*) printf '%s' '{"Verified":false,"Raw":"private-marker"}' ;; + *) exit 99 ;; + esac ;; + start) printf '%s' 'private-marker'; exit ${malwareExit} ;; + cp) printf '%s' '{"data":{"status":"CLEAN","report":[]}}' > "$3" ;; + *) exit 99 ;; +esac +`, + { mode: 0o700 }, + ); + const summary = join(temporary, "summary.md"); + const result = spawnSync("bash", [join(root, ".github/scripts/scan-managed-image.sh")], { + encoding: "utf8", + env: { + ...env, + PATH: `${bin}:${process.env.PATH}`, + HOME: temporary, + GITHUB_WORKSPACE: root, + GITHUB_STEP_SUMMARY: summary, + SCAN_ROOT: scan, + CONTRACT: contract, + GRYPE_IMAGE: "grype-image", + PULSE_SECRET_IMAGE: "secret-image", + PULSE_MALWARE_IMAGE: "malware-image", + NSPECT_ID: "NSPECT-TEST-1234", + }, + }); + expect(result.status, result.stderr).toBe(malwareExit === 0 ? 0 : 1); + const report = readFileSync(summary, "utf8"); + expect(report).toContain(`| malware | ${malwareExit === 0 ? "PASS" : "FAIL"} |`); + expect(report + result.stdout + result.stderr).not.toContain("private-marker"); + expect(() => readFileSync(join(scan, "secrets.jsonl"))).toThrow(); + } finally { + rmSync(temporary, { recursive: true, force: true }); + } + }, + ); +}); diff --git a/test/helpers/vitest-watch-triggers.ts b/test/helpers/vitest-watch-triggers.ts index df90e21a5c2..c1544cbd645 100644 --- a/test/helpers/vitest-watch-triggers.ts +++ b/test/helpers/vitest-watch-triggers.ts @@ -325,12 +325,18 @@ export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ { pattern: /(?:^|\/)\.github\/workflows\/base-image\.yaml$/, testsToRun: runTests( + "test/e2e/support/managed-image-security-scan.test.ts", "test/inference/managed/managed-base-image-contract.test.ts", "test/inference/managed/managed-image-mcp-bridge-publication.test.ts", "test/inference/managed/managed-image-publication-workflow.test.ts", "test/agents/deepagents/dcode-base-image-workflow.test.ts", ), }, + { + pattern: + /(?:^|\/)\.github\/scripts\/(?:scan-managed-image\.sh|managed-image-scan-results\.mts)$/, + testsToRun: runTests("test/e2e/support/managed-image-security-scan.test.ts"), + }, { pattern: /(?:^|\/)scripts\/export-managed-base-image-contract\.sh$/, testsToRun: runTests( @@ -342,6 +348,7 @@ export const vitestWatchTriggerPatterns: VitestWatchTriggerPattern[] = [ { pattern: /(?:^|\/)\.github\/workflows\/managed-images\.yaml$/, testsToRun: runTests( + "test/e2e/support/managed-image-security-scan.test.ts", "test/inference/managed/managed-image-discord-workflow-boundary.test.ts", "test/e2e/support/managed-podman-docker-guard.test.ts", "test/inference/managed/managed-image-mcp-bridge-publication.test.ts", diff --git a/test/inference/managed/managed-image-publication-workflow.test.ts b/test/inference/managed/managed-image-publication-workflow.test.ts index 0a2ec946e3a..1b56142daa9 100644 --- a/test/inference/managed/managed-image-publication-workflow.test.ts +++ b/test/inference/managed/managed-image-publication-workflow.test.ts @@ -1218,7 +1218,11 @@ ${required(qualification.run, "missing qualification command")}`, expect(publisher.steps?.map((candidate) => candidate.name)).not.toContain( "Export validated managed image candidate output", ); - expect(promoter.needs).toEqual(["publication-identity", "build-and-validate"]); + expect(promoter.needs).toEqual([ + "publication-identity", + "build-and-validate", + "security-scan-managed-images", + ]); expect(restoreCandidates).toMatchObject({ uses: "actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c", with: { diff --git a/test/repository/vitest-watch-triggers.test.ts b/test/repository/vitest-watch-triggers.test.ts index cfd7caea271..145a4a86f58 100644 --- a/test/repository/vitest-watch-triggers.test.ts +++ b/test/repository/vitest-watch-triggers.test.ts @@ -292,12 +292,14 @@ describe("Vitest opaque-input watch triggers", () => { "test/e2e/support/jetson-dispatch-client.test.ts", ]); expect(triggeredBy(".github/workflows/base-image.yaml")).toEqual([ + "test/e2e/support/managed-image-security-scan.test.ts", "test/inference/managed/managed-base-image-contract.test.ts", "test/inference/managed/managed-image-mcp-bridge-publication.test.ts", "test/inference/managed/managed-image-publication-workflow.test.ts", "test/agents/deepagents/dcode-base-image-workflow.test.ts", ]); expect(triggeredBy(".github/workflows/managed-images.yaml")).toEqual([ + "test/e2e/support/managed-image-security-scan.test.ts", "test/inference/managed/managed-image-discord-workflow-boundary.test.ts", "test/e2e/support/managed-podman-docker-guard.test.ts", "test/inference/managed/managed-image-mcp-bridge-publication.test.ts",