diff --git a/.github/workflows/release-image.yml b/.github/workflows/release-image.yml index 8f6d17c..b372e74 100644 --- a/.github/workflows/release-image.yml +++ b/.github/workflows/release-image.yml @@ -8,8 +8,17 @@ # (released images are never overwritten) # build one native build per platform (no QEMU), pushed by digest, with # BuildKit SBOM + SLSA provenance attestations attached -# publish one multi-arch index tagged and `latest`; SBOM artifact, -# digest in the job summary +# publish one multi-arch index tagged and `latest`; the SLSA +# provenance of every platform checked against this run and commit, +# signed with the provenance key (Cloud KMS) and attached to the +# index; SBOM artifact, digest in the job summary +# +# The provenance is signed in `publish`, the one job that runs no code of the +# repository being released: no build, no checkout of it. Its signing account +# is a separate identity that the workload identity provider grants only to +# this workflow at a harness tag on a main or version-tag push, so neither a +# Dockerfile step nor a job of the caller can sign. No step of a build job +# holds a credentials file: the build context never contains one. # # The git tag is set afterwards by release-tag.yml (a job of its own in the # caller, `needs` this one), so this workflow never needs write access to the @@ -112,6 +121,20 @@ on: description: Publisher service account (email). type: string required: true + provenance-key: + description: >- + Cloud KMS key version that signs the SLSA provenance of a released + image, as cosign names it + (gcpkms://projects//locations//keyRings//cryptoKeys//versions/). + A release fails without it; a dry run does not need it. + type: string + default: ${{ vars.IMAGE_PROVENANCE_KEY }} + provenance-service-account: + description: >- + Service account (email) allowed to sign with the provenance key; + only this workflow's publish job uses it. + type: string + default: ${{ vars.IMAGE_PROVENANCE_SERVICE_ACCOUNT }} outputs: digest: description: Digest of the published multi-arch index (empty in a dry run). @@ -204,6 +227,22 @@ jobs: exit 1 fi echo "$SHA is part of $BRANCH" + # Checked before anything is built: a release without signed provenance + # never starts. + - name: the provenance key is configured + if: steps.version.outputs.push == 'true' + env: + KEY: ${{ inputs.provenance-key }} + SIGNER: ${{ inputs.provenance-service-account }} + run: | + if [ -z "$KEY" ] || [ -z "$SIGNER" ]; then + echo "::error::no provenance key: set the organization variables IMAGE_PROVENANCE_KEY and IMAGE_PROVENANCE_SERVICE_ACCOUNT, or the inputs provenance-key and provenance-service-account" + exit 1 + fi + case "$KEY" in + gcpkms://*/versions/[0-9]*) ;; + *) echo "::error::provenance-key '$KEY' is not a Cloud KMS key version (gcpkms://projects/.../cryptoKeys//versions/)"; exit 1 ;; + esac - id: auth if: steps.version.outputs.push == 'true' uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3 @@ -212,6 +251,9 @@ jobs: service_account: ${{ inputs.service-account }} token_format: access_token access_token_lifetime: 300s + # Only the access token is used. The default credentials file would + # land in the workspace and hold the run's token-request bearer. + create_credentials_file: false - name: the image tag id: image env: @@ -280,6 +322,10 @@ jobs: service_account: ${{ inputs.service-account }} token_format: access_token access_token_lifetime: 3600s + # The build context is the workspace: a credentials file there would + # be readable by every Dockerfile step after `COPY . .`, and the + # image would carry it. + create_credentials_file: false - name: build ${{ matrix.platform }}${{ needs.verify.outputs.push == 'true' && ' and push by digest' || ' (dry run)' }} id: build env: @@ -295,7 +341,15 @@ jobs: REVISION: ${{ github.sha }} VERSION: ${{ needs.verify.outputs.image-tag }} ARTIFACT_PREFIX: ${{ inputs.artifact-prefix }} + # The provenance's builder id: this run (publish checks it before signing). + BUILDER_ID: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }} run: | + # The context stays inside the checkout: one around it (the runner's + # home) would hand the registry login to the Dockerfile's steps. + case "$(realpath -- "$CONTEXT")/" in + "$(realpath -- "$GITHUB_WORKSPACE")"/*) ;; + *) echo "::error::context '$CONTEXT' is outside the checkout"; exit 1 ;; + esac args=(--platform "$PLATFORM" -f "$DOCKERFILE" --label "org.opencontainers.image.source=$SOURCE_URL" --label "org.opencontainers.image.revision=$REVISION" @@ -311,7 +365,7 @@ jobs: fi if [ "$PUSH" = true ]; then echo "$TOKEN" | docker login -u oauth2accesstoken --password-stdin "https://$REGISTRY" - args+=(--sbom=true --provenance=mode=max + args+=(--sbom=true --provenance="mode=max,version=v1,builder-id=$BUILDER_ID" --output "type=image,name=$IMAGE,push-by-digest=true,name-canonical=true,push=true") else args+=(--output type=cacheonly) @@ -335,7 +389,12 @@ jobs: publish: needs: [verify, build] - if: needs.verify.outputs.push == 'true' && needs.verify.outputs.build == 'true' + # Also after a skipped build: a re-run of a release whose image this + # commit already published (verify said build=false) still signs the + # provenance if an earlier attempt failed before that. + if: >- + !cancelled() && needs.verify.result == 'success' && needs.verify.outputs.push == 'true' + && (needs.build.result == 'success' || (needs.build.result == 'skipped' && needs.verify.outputs.build == 'false')) runs-on: ubuntu-24.04 timeout-minutes: 15 permissions: @@ -345,10 +404,48 @@ jobs: digest: ${{ steps.index.outputs.digest }} steps: - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + if: needs.build.result == 'success' with: pattern: ${{ inputs.artifact-prefix }}digest-* path: ${{ runner.temp }}/digests merge-multiple: true + # The scripts that sign come from the commit this workflow file runs + # from (the job_workflow_sha claim of the job's OIDC token), not from the + # caller's harness-ref input: the signing identity is granted to this + # workflow at a harness tag, so the code that signs must be that code. + - name: the harness commit of this workflow + id: harness + run: | + token=$(curl -fsS -H "Authorization: Bearer $ACTIONS_ID_TOKEN_REQUEST_TOKEN" \ + "$ACTIONS_ID_TOKEN_REQUEST_URL&audience=ironflock-harness-commit" | jq -r .value) + echo "::add-mask::$token" + payload=$(cut -d. -f2 <<<"$token" | tr '_-' '/+') + while [ $((${#payload} % 4)) != 0 ]; do payload+="="; done + claims=$(base64 -d <<<"$payload") + ref=$(jq -r '.job_workflow_ref // empty' <<<"$claims") + sha=$(jq -r '.job_workflow_sha // empty' <<<"$claims") + case "$ref" in + IronFlock/workflows/.github/workflows/release-image.yml@*) ;; + *) echo "::error::this job runs from '$ref', not from IronFlock/workflows release-image.yml"; exit 1 ;; + esac + [[ "$sha" =~ ^[0-9a-f]{40}$ ]] || { echo "::error::the job's OIDC token names no workflow commit"; exit 1; } + echo "harness: $ref at $sha" + echo "sha=$sha" >> "$GITHUB_OUTPUT" + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: IronFlock/workflows + ref: ${{ steps.harness.outputs.sha }} + path: .harness + persist-credentials: false + sparse-checkout: | + scripts + tools.lock + sparse-checkout-cone-mode: false + - name: move harness out of the workspace, install cosign + run: | + mv .harness "$RUNNER_TEMP/harness" + echo "HARNESS=$RUNNER_TEMP/harness" >> "$GITHUB_ENV" + "$RUNNER_TEMP/harness/scripts/install-tool.sh" cosign - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - id: auth uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3 @@ -356,7 +453,8 @@ jobs: workload_identity_provider: ${{ inputs.workload-identity-provider }} service_account: ${{ inputs.service-account }} token_format: access_token - access_token_lifetime: 600s + access_token_lifetime: 900s + create_credentials_file: false - name: multi-arch index ${{ needs.verify.outputs.image-tag }} id: index env: @@ -366,15 +464,20 @@ jobs: TAG: ${{ needs.verify.outputs.image-tag }} LATEST: ${{ inputs.latest }} PLATFORMS: ${{ inputs.platforms }} + BUILT: ${{ needs.build.result == 'success' }} run: | echo "$TOKEN" | docker login -u oauth2accesstoken --password-stdin "https://$REGISTRY" - refs=() - for f in "$RUNNER_TEMP"/digests/*; do refs+=("$IMAGE@sha256:$(basename "$f")"); done - want=$(jq length <<<"$PLATFORMS") - [ "${#refs[@]}" -eq "$want" ] || { echo "::error::expected $want platform digests, got ${#refs[@]}"; exit 1; } - tags=(-t "$IMAGE:$TAG") - if [ "$LATEST" = true ]; then tags+=(-t "$IMAGE:latest"); fi - docker buildx imagetools create "${tags[@]}" "${refs[@]}" + if [ "$BUILT" = true ]; then + refs=() + for f in "$RUNNER_TEMP"/digests/*; do refs+=("$IMAGE@sha256:$(basename "$f")"); done + want=$(jq length <<<"$PLATFORMS") + [ "${#refs[@]}" -eq "$want" ] || { echo "::error::expected $want platform digests, got ${#refs[@]}"; exit 1; } + tags=(-t "$IMAGE:$TAG") + if [ "$LATEST" = true ]; then tags+=(-t "$IMAGE:latest"); fi + docker buildx imagetools create "${tags[@]}" "${refs[@]}" + else + echo "::notice::$IMAGE:$TAG was already published from this commit (verify): only its provenance is signed, if not yet" + fi digest=$(docker buildx imagetools inspect "$IMAGE:$TAG" --format '{{json .Manifest}}' | jq -r .digest) echo "digest=$digest" >> "$GITHUB_OUTPUT" mkdir -p "$RUNNER_TEMP/sbom" @@ -388,8 +491,30 @@ jobs: echo "|---|---|" echo "| index digest | \`$digest\` |" echo "| platforms | $(jq -r 'map(.platform) | join(", ")' <<<"$PLATFORMS") |" - echo "| attestations | SBOM (SPDX) + SLSA provenance attached to the image |" + echo "| attestations | SBOM (SPDX) per platform image; SLSA v1 provenance per platform, signed, on the index |" } >> "$GITHUB_STEP_SUMMARY" + # The signing identity, separate from the publisher. cosign reaches Cloud + # KMS through Application Default Credentials, i.e. this credentials + # file: nothing in this job builds or runs code of the repository. + - id: signer + uses: google-github-actions/auth@7c6bc770dae815cd3e89ee6cdf493a5fab2cc093 # v3 + with: + workload_identity_provider: ${{ inputs.workload-identity-provider }} + service_account: ${{ inputs.provenance-service-account }} + - name: sign the provenance + env: + TOKEN: ${{ steps.auth.outputs.access_token }} + REGISTRY: ${{ needs.verify.outputs.registry }} + IMAGE: ${{ inputs.image }} + DIGEST: ${{ steps.index.outputs.digest }} + COSIGN_KEY: ${{ inputs.provenance-key }} + EXPECT_SOURCE: ${{ github.server_url }}/${{ github.repository }} + EXPECT_REVISION: ${{ github.sha }} + EXPECT_RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + echo "$TOKEN" | docker login -u oauth2accesstoken --password-stdin "https://$REGISTRY" + "$HARNESS/scripts/sign-provenance.sh" sign "$IMAGE@$DIGEST" + docker logout "https://$REGISTRY" - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: ${{ inputs.artifact-prefix }}release-sbom diff --git a/.github/workflows/selftest.yml b/.github/workflows/selftest.yml index 6828c9a..1570b9e 100644 --- a/.github/workflows/selftest.yml +++ b/.github/workflows/selftest.yml @@ -76,6 +76,8 @@ jobs: run: bash scripts/test_pr.sh - name: publish.sh unit tests run: bash scripts/test_publish.sh + - name: sign-provenance.sh check unit tests + run: bash scripts/test_sign_provenance.sh - name: tools.lock has every tool for x86_64 and arm64 run: bash scripts/test_tools_lock.sh # Public repository: no internal document names or plan IDs. @@ -131,6 +133,7 @@ jobs: bun --version uv --version uvx --version + cosign version TOOLS exit "$fail" @@ -544,6 +547,31 @@ jobs: artifact-prefix: build-context- harness-ref: ${{ github.sha }} + # The publish job's provenance signing (sign-provenance.sh sign) end to end: + # a two-platform index with BuildKit provenance in a throwaway registry, + # signed with throwaway cosign key files in place of the KMS key; refusal, + # re-run and another key's attestation included. + provenance-sign: + runs-on: ubuntu-24.04 + timeout-minutes: 15 + services: + registry: + image: registry:3@sha256:d4032d4cc323c1731c707931ecada07a53076eac38e3b61ae57533f170f2c6c3 + ports: + - 5000:5000 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - run: scripts/install-tool.sh cosign + - uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + with: + # The builder reaches the registry service on localhost. + driver-opts: network=host + - name: sign, verify, re-run, refuse + run: bash scripts/test_sign_provenance_registry.sh localhost:5000 + assert-planted: needs: [security-planted, security-helm, lint-planted] # Also when a scanner job broke: the counts then show what is missing. @@ -579,7 +607,7 @@ jobs: # above succeeded (skipped or cancelled counts as failed). selftest-ok: if: ${{ always() }} - needs: [lint-self, lint-templates, lint-planted, scripts, gate-pass, gate-fail, node-gate-npm, node-gate-npm-tools, node-gate-bun, node-gate-fail, python-gate-pass, python-gate-fail, shell-gate-pass, shell-gate-artifact, shell-gate-fail, shell-gate-arm64, tools-arm64, security-clean, security-clean-node, security-planted, config-scan-skipped-chart, security-helm, release-dry-run, release-dry-run-package-json, build-context-artifact, release-dry-run-build-context, release-dry-run-image-tag, assert-image-tag, assert-planted] + needs: [lint-self, lint-templates, lint-planted, scripts, gate-pass, gate-fail, node-gate-npm, node-gate-npm-tools, node-gate-bun, node-gate-fail, python-gate-pass, python-gate-fail, shell-gate-pass, shell-gate-artifact, shell-gate-fail, shell-gate-arm64, tools-arm64, security-clean, security-clean-node, security-planted, config-scan-skipped-chart, security-helm, release-dry-run, release-dry-run-package-json, build-context-artifact, release-dry-run-build-context, release-dry-run-image-tag, assert-image-tag, provenance-sign, assert-planted] runs-on: ubuntu-latest timeout-minutes: 5 steps: diff --git a/README.md b/README.md index 1e6e74a..4d59d05 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ The inputs of each workflow are documented in its `on.workflow_call` block. | [security.yml](.github/workflows/security.yml) | `gitleaks`, `deps`, `semgrep`, `sbom`, `config`, `licenses`, `image`, `report` | security screening; `report` applies `fail-on` | | [workflows-lint.yml](.github/workflows/workflows-lint.yml) | `lint` | actionlint, zizmor, pinact on the caller's workflows; always blocking | | [release-intent.yml](.github/workflows/release-intent.yml) | `intent` | the version file decides: a rise makes a release PR (title `release ` required), an unchanged version a no-release PR; output `kind` gates the release dry run; listed in the `needs` of `ci-ok` | -| [release-image.yml](.github/workflows/release-image.yml) | `verify`, `build`, `publish` | release of a container image on the merge of a release PR into the protected `main`; native multi-arch build, SBOM + provenance attached, keyless push; on a release PR a dry run (every platform build, no push); re-runs are safe; read rights only; `build-contexts-artifact` hands data an earlier job prepared (with secrets the build must not see) to the build as named contexts | +| [release-image.yml](.github/workflows/release-image.yml) | `verify`, `build`, `publish` | release of a container image on the merge of a release PR into the protected `main`; native multi-arch build, SBOM attached, SLSA provenance signed with a Cloud KMS key and attached (see [Signed image provenance](#signed-image-provenance)), keyless push; on a release PR a dry run (every platform build, no push); re-runs are safe; read rights only; `build-contexts-artifact` hands data an earlier job prepared (with secrets the build must not see) to the build as named contexts | | [release-tag.yml](.github/workflows/release-tag.yml) | `tag` | the annotated git tag of a release, after every image job of the caller; a tag always means "in the registry"; written with a token of the release GitHub App from the caller's `release` environment | | [selftest.yml](.github/workflows/selftest.yml) | — | proves the harness against [tests/fixtures](tests/fixtures) | @@ -136,6 +136,48 @@ form for a script to embed, `fingerprint` the fingerprint the operator docs publish, `keygen` a development key for tests. The commands are documented at the top of [main.go](tools/sign-openpgp/main.go). +## Signed image provenance + +Every image `release-image.yml` releases carries, on its multi-arch index, one +signed in-toto attestation per platform: the SLSA v1 provenance BuildKit +recorded for that platform's build (source repository, commit, Dockerfile, +build arguments, base images; the platform in +`buildDefinition.internalParameters.targetPlatform`). The `publish` job signs +it with [scripts/sign-provenance.sh](scripts/sign-provenance.sh) and cosign, +after checking that it names this run as builder and the released commit of +the calling repository as a clean source. The key is a Cloud KMS key version; +the attestation is kept in the registry next to the image (an OCI referrer of +the index) and goes to no transparency log, so no image name or digest of a +private repository becomes public. + +The signing account is not the publisher: the workload identity provider maps +an attribute that only this workflow, called at a harness tag (`@v1`) on a +push to `main` or of a version tag, receives, and only that attribute may act +as the signing account, which holds `roles/cloudkms.signerVerifier` on the key +and nothing else. A caller's own jobs and the Dockerfile's steps, which run in +the build job, cannot obtain it; no build job holds a credentials file. The +`publish` job takes its scripts and cosign from the commit of +`release-image.yml` it runs from (the `job_workflow_sha` claim of its OIDC +token), never from the caller's `harness-ref`. + +Configuration: the organization variables `IMAGE_PROVENANCE_KEY` (cosign's +form, `gcpkms://projects//locations//keyRings//cryptoKeys//versions/`) +and `IMAGE_PROVENANCE_SERVICE_ACCOUNT`, or the inputs `provenance-key` and +`provenance-service-account`. A release without them fails in `verify`, +before anything is built; dry runs need neither. A re-run signs only what is +missing. + +Verify a released image with the public key +(`cosign public-key --key ` prints it): + +```sh +cosign verify-attestation --key provenance.pub --type slsaprovenance1 \ + --insecure-ignore-tlog @ +``` + +`--insecure-ignore-tlog` only tells cosign that no transparency log entry is +expected; the signature is checked against the key. + ## Protected main branch Each repository protects `main` with a ruleset: changes only through pull diff --git a/scripts/sign-provenance.sh b/scripts/sign-provenance.sh new file mode 100644 index 0000000..c1184d4 --- /dev/null +++ b/scripts/sign-provenance.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +# Signed SLSA provenance of a released image, run by release-image.yml's +# publish job: the only job of a release that runs no code of the repository +# being released. +# +# sign-provenance.sh sign @ +# For every platform image of the multi-arch index: take the SLSA v1 +# provenance BuildKit attached at build time, `check` that it describes +# this run's build of this commit, and attach it to the index as an +# in-toto attestation signed with COSIGN_KEY (cosign, without +# transparency log or timestamp service: nothing about the image leaves +# the registry). A platform whose signed provenance is already attached +# is skipped, so a re-run never signs twice. Afterwards the signed +# provenance of every platform must verify with the same key. +# Env: COSIGN_KEY (a KMS URI such as gcpkms://..., or a key file for +# tests), EXPECT_SOURCE, EXPECT_REVISION, EXPECT_RUN (see check). +# Optional: COSIGN_PUBLIC_KEY (what verifies: default COSIGN_KEY, as a +# KMS URI does both; a test's key file needs its .pub), COSIGN (the +# binary, default cosign), COSIGN_ALLOW_HTTP=1 (a plain-HTTP test +# registry). Registry credentials: docker login. +# +# sign-provenance.sh check +# the predicate is BuildKit's SLSA v1 provenance of , built by +# run EXPECT_RUN (its URL; builder id /attempts/, any +# attempt) from the clean checkout of EXPECT_REVISION of repository +# EXPECT_SOURCE (a trailing .git aside). +# +# Each attestation names its platform (predicate.buildDefinition +# .internalParameters.targetPlatform). Verify a released image with the +# public key (`cosign public-key --key ` prints it): +# cosign verify-attestation --key provenance.pub --type slsaprovenance1 \ +# --insecure-ignore-tlog @ +set -euo pipefail + +BUILDKIT_SLSA_V1=https://github.com/moby/buildkit/blob/master/docs/attestations/slsa-definitions.md + +check() { + local file=$1 platform=$2 btype target builder revision source attempt + : "${EXPECT_SOURCE:?}" "${EXPECT_REVISION:?}" "${EXPECT_RUN:?}" + IFS=$'\t' read -r btype target builder revision source < <(jq -r '[ + .buildDefinition.buildType, + .buildDefinition.internalParameters.targetPlatform, + .runDetails.builder.id, + .runDetails.metadata.buildkit_metadata.vcs.revision, + .runDetails.metadata.buildkit_metadata.vcs.source + ] | map(if . == null or . == "" then "-" else . end) | @tsv' "$file") + if [ "$btype" != "$BUILDKIT_SLSA_V1" ]; then + echo "::error::the provenance of $platform is not BuildKit's SLSA v1 provenance (buildType $btype)" + return 1 + fi + if [ "$target" != "$platform" ]; then + echo "::error::the provenance attached for $platform describes a build for $target" + return 1 + fi + attempt=${builder#"$EXPECT_RUN/attempts/"} + if [ "$attempt" = "$builder" ] || ! [[ "$attempt" =~ ^[0-9]+$ ]]; then + echo "::error::the provenance of $platform was built by $builder, not by this run ($EXPECT_RUN)" + return 1 + fi + if [ "$revision" != "$EXPECT_REVISION" ]; then + echo "::error::the provenance of $platform names revision $revision, not $EXPECT_REVISION (a -dirty revision: the build context had uncommitted changes)" + return 1 + fi + if [ "${source%.git}" != "${EXPECT_SOURCE%.git}" ]; then + echo "::error::the provenance of $platform names source $source, not $EXPECT_SOURCE" + return 1 + fi +} + +# signed : the platforms whose signed provenance on +# (for subject ) verifies with the public key, one per line; cosign's +# messages go to (none attached yet is an error to cosign, too) +signed() { + local ref=$1 digest=$2 log=$3 + { "$COSIGN" verify-attestation "${registry_flags[@]}" --key "${COSIGN_PUBLIC_KEY:-$COSIGN_KEY}" \ + --type slsaprovenance1 --insecure-ignore-tlog "$ref" 2>"$log" || true; } | + jq -r --arg d "${digest#sha256:}" '.payload | @base64d | fromjson + | select(any(.subject[]?; .digest.sha256 == $d)) + | .predicate.buildDefinition.internalParameters.targetPlatform // empty' | + sort -u +} + +sign() { + local ref=$1 image digest work platforms provenance platform have missing=0 + : "${COSIGN_KEY:?}" + image=${ref%@*} + digest=${ref##*@} + [[ "$digest" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "::error::sign-provenance: want @sha256:, got $ref" >&2; return 2; } + work=$(mktemp -d) + trap 'rm -rf "$work"' RETURN + + platforms=$(docker buildx imagetools inspect "$ref" --raw | jq -r '.manifests[] + | select(.annotations["vnd.docker.reference.type"] != "attestation-manifest") + | .platform | "\(.os)/\(.architecture)\(if .variant then "/" + .variant else "" end)"') + [ -n "$platforms" ] || { echo "::error::$ref is not a multi-arch index with platform images"; return 1; } + provenance=$(docker buildx imagetools inspect "$ref" --format '{{json .Provenance}}') + have=$(signed "$ref" "$digest" "$work/verify.log") + + # No transparency log, no timestamp service: an empty signing config. + "$COSIGN" signing-config create --out "$work/no-services.json" >/dev/null + + while read -r platform; do + if grep -qxF -- "$platform" <<<"$have"; then + echo "$platform: signed provenance already attached" + continue + fi + jq --arg p "$platform" --argjson n "$(wc -l <<<"$platforms")" \ + 'if has("SLSA") and $n == 1 then .SLSA else .[$p].SLSA end // empty' <<<"$provenance" >"$work/predicate.json" + if [ ! -s "$work/predicate.json" ]; then + echo "::error::$image has no BuildKit provenance for $platform (built without --provenance?)" + return 1 + fi + check "$work/predicate.json" "$platform" + "$COSIGN" attest --yes "${registry_flags[@]}" --key "$COSIGN_KEY" \ + --signing-config "$work/no-services.json" \ + --type slsaprovenance1 --predicate "$work/predicate.json" "$ref" >/dev/null + echo "$platform: provenance signed and attached" + done <<<"$platforms" + + have=$(signed "$ref" "$digest" "$work/verify.log") + while read -r platform; do + grep -qxF -- "$platform" <<<"$have" || { echo "::error::no signed provenance of $platform verifies on $ref"; missing=1; } + done <<<"$platforms" + if [ "$missing" != 0 ]; then + echo "cosign verify-attestation said:" + sed 's/^/ /' "$work/verify.log" + fi + return "$missing" +} + +COSIGN=${COSIGN:-cosign} +registry_flags=() +if [ "${COSIGN_ALLOW_HTTP:-}" = 1 ]; then registry_flags=(--allow-http-registry); fi + +case "${1:-}" in + check) check "$2" "$3" ;; + sign) sign "$2" ;; + *) echo "usage: sign-provenance.sh sign @ | check " >&2; exit 2 ;; +esac diff --git a/scripts/test_sign_provenance.sh b/scripts/test_sign_provenance.sh new file mode 100644 index 0000000..a64e4dd --- /dev/null +++ b/scripts/test_sign_provenance.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Tests of sign-provenance.sh check against a BuildKit SLSA v1 predicate: +# bash scripts/test_sign_provenance.sh +# Signing itself (cosign, a registry) is exercised by selftest.yml's +# provenance-sign job. +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +script="$here/sign-provenance.sh" +fixture="$here/../tests/fixtures/provenance/predicate.json" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +failures=0 + +export EXPECT_SOURCE=https://github.com/IronFlock/example +export EXPECT_REVISION=0123456789abcdef0123456789abcdef01234567 +export EXPECT_RUN=https://github.com/IronFlock/example/actions/runs/123 + +check() { # check [] + local name=$1 want=$2 edit=$3 platform=${4:-linux/amd64} got=0 + jq "$edit" "$fixture" >"$work/predicate.json" + bash "$script" check "$work/predicate.json" "$platform" >"$work/log" 2>&1 || got=$? + if { [ "$want" = 0 ] && [ "$got" = 0 ]; } || { [ "$want" = 1 ] && [ "$got" != 0 ]; }; then + echo "ok $name" + else + echo "FAIL $name (exit $got, wanted $want)" + sed 's/^/ /' "$work/log" + failures=$((failures + 1)) + fi +} + +check "this run's build of this commit" 0 . +check "a re-run attempt of this run" 0 '.runDetails.builder.id = "https://github.com/IronFlock/example/actions/runs/123/attempts/2"' +check "source without .git" 0 '.runDetails.metadata.buildkit_metadata.vcs.source = "https://github.com/IronFlock/example"' +check "a variant platform" 0 '.buildDefinition.internalParameters.targetPlatform = "linux/arm/v7"' linux/arm/v7 + +check "another platform's provenance" 1 . linux/arm64 +check "another run" 1 '.runDetails.builder.id = "https://github.com/IronFlock/example/actions/runs/1234/attempts/1"' +check "another repository's run" 1 '.runDetails.builder.id = "https://github.com/IronFlock/other/actions/runs/123/attempts/1"' +check "a builder id with more after the attempt" 1 '.runDetails.builder.id = "https://github.com/IronFlock/example/actions/runs/123/attempts/1/x"' +check "no builder id" 1 '.runDetails.builder.id = ""' +check "uncommitted changes in the build context" 1 '.runDetails.metadata.buildkit_metadata.vcs.revision += "-dirty"' +check "another commit" 1 '.runDetails.metadata.buildkit_metadata.vcs.revision = "fedcba9876543210fedcba9876543210fedcba98"' +check "no vcs information" 1 'del(.runDetails.metadata.buildkit_metadata.vcs)' +check "another repository" 1 '.runDetails.metadata.buildkit_metadata.vcs.source = "https://github.com/IronFlock/example-fork.git"' +check "SLSA v0.2 provenance" 1 '{buildType: "https://mobyproject.org/buildkit@v1", builder: {id: .runDetails.builder.id}}' +check "not JSON" 1 '"not a predicate"' + +if [ "$failures" -gt 0 ]; then + echo "$failures failed" + exit 1 +fi +echo "all passed" diff --git a/scripts/test_sign_provenance_registry.sh b/scripts/test_sign_provenance_registry.sh new file mode 100644 index 0000000..8db23df --- /dev/null +++ b/scripts/test_sign_provenance_registry.sh @@ -0,0 +1,93 @@ +#!/usr/bin/env bash +# End-to-end test of sign-provenance.sh sign against a plain-HTTP registry, +# with throwaway cosign key files instead of the KMS key: +# bash scripts/test_sign_provenance_registry.sh +# Needs docker buildx (a builder that reaches the registry: BUILDX_BUILDER), +# emulation for the second platform, cosign on PATH (or COSIGN) and jq. +# selftest.yml's provenance-sign job runs it against a registry service. +set -euo pipefail + +registry=${1:?usage: test_sign_provenance_registry.sh } +here=$(cd "$(dirname "$0")" && pwd) +script="$here/sign-provenance.sh" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +failures=0 +export COSIGN=${COSIGN:-cosign} COSIGN_ALLOW_HTTP=1 COSIGN_PASSWORD=selftest + +expect() { # expect + local name=$1 want=$2 got=0 + shift 2 + "$@" >"$work/log" 2>&1 || got=$? + if { [ "$want" = 0 ] && [ "$got" = 0 ]; } || { [ "$want" = 1 ] && [ "$got" != 0 ]; }; then + echo "ok $name" + else + echo "FAIL $name (exit $got, wanted $want)" + sed 's/^/ /' "$work/log" + failures=$((failures + 1)) + fi +} + +# attestations : how many signed provenance attestations +# on verify with the key +attestations() { + { "$COSIGN" verify-attestation --allow-http-registry --key "$2" --type slsaprovenance1 \ + --insecure-ignore-tlog "$1" 2>/dev/null || true; } | grep -c . || true +} + +# The build context: a clean git repository, so the provenance names a known +# source and revision. +src="$work/src" +mkdir -p "$src" +cp "$here/../tests/fixtures/release/Dockerfile" "$src/" +git -C "$src" init -q -b main +git -C "$src" config user.email t@example.invalid +git -C "$src" config user.name test +git -C "$src" add Dockerfile +git -C "$src" commit -qm fixture +git -C "$src" remote add origin https://github.com/IronFlock/selftest-provenance.git +run=https://github.com/IronFlock/selftest-provenance/actions/runs/1 +image="$registry/selftest/provenance" + +# build : push it by digest the way release-image.yml does; prints the digest +build() { + docker buildx build --platform "$1" -f "$src/Dockerfile" --build-arg VERSION=v0.0.1 \ + --provenance="mode=max,version=v1,builder-id=$run/attempts/1" \ + --metadata-file "$work/metadata.json" \ + --output "type=image,name=$image,push-by-digest=true,name-canonical=true,push=true" \ + "$src" >"$work/build.log" 2>&1 || { cat "$work/build.log"; return 1; } + jq -r '."containerimage.digest"' "$work/metadata.json" +} +amd64=$(build linux/amd64) +arm64=$(build linux/arm64) +docker buildx imagetools create -t "$image:v0.0.1" "$image@$amd64" "$image@$arm64" >/dev/null 2>&1 +docker buildx imagetools create -t "$image:single" "$image@$amd64" >/dev/null 2>&1 +index=$image@$(docker buildx imagetools inspect "$image:v0.0.1" --format '{{json .Manifest}}' | jq -r .digest) +single=$image@$(docker buildx imagetools inspect "$image:single" --format '{{json .Manifest}}' | jq -r .digest) + +(cd "$work" && "$COSIGN" generate-key-pair --output-key-prefix release >/dev/null 2>&1) +(cd "$work" && "$COSIGN" generate-key-pair --output-key-prefix other >/dev/null 2>&1) +export COSIGN_KEY="$work/release.key" COSIGN_PUBLIC_KEY="$work/release.pub" +export EXPECT_SOURCE=https://github.com/IronFlock/selftest-provenance +export EXPECT_REVISION +EXPECT_REVISION=$(git -C "$src" rev-parse HEAD) +export EXPECT_RUN=$run + +expect "another commit expected: refused" 1 env EXPECT_REVISION=fedcba9876543210fedcba9876543210fedcba98 bash "$script" sign "$index" +expect " and nothing attached" 0 test "$(attestations "$index" "$work/release.pub")" = 0 +expect "both platforms signed" 0 bash "$script" sign "$index" +expect " two attestations verify" 0 test "$(attestations "$index" "$work/release.pub")" = 2 +expect " they name both platforms" 0 bash -c "\"$COSIGN\" verify-attestation --allow-http-registry --key '$work/release.pub' --type slsaprovenance1 --insecure-ignore-tlog '$index' 2>/dev/null | jq -r '.payload | @base64d | fromjson | .predicate.buildDefinition.internalParameters.targetPlatform' | sort | paste -sd, - | grep -qx linux/amd64,linux/arm64" +expect " another key verifies none" 0 test "$(attestations "$index" "$work/other.pub")" = 0 +expect "re-run signs nothing twice" 0 bash "$script" sign "$index" +expect " still two attestations" 0 test "$(attestations "$index" "$work/release.pub")" = 2 +expect "a single-platform index" 0 env COSIGN_KEY="$work/other.key" COSIGN_PUBLIC_KEY="$work/other.pub" bash "$script" sign "$single" +expect " an attestation by another key does not count" 0 bash "$script" sign "$single" +expect " one attestation verifies with each key" 0 test "$(attestations "$single" "$work/release.pub")$(attestations "$single" "$work/other.pub")" = 11 +expect "not a digest reference" 1 bash "$script" sign "$image:v0.0.1" + +if [ "$failures" -gt 0 ]; then + echo "$failures failed" + exit 1 +fi +echo "all passed" diff --git a/tests/fixtures/provenance/predicate.json b/tests/fixtures/provenance/predicate.json new file mode 100644 index 0000000..066abd0 --- /dev/null +++ b/tests/fixtures/provenance/predicate.json @@ -0,0 +1,59 @@ +{ + "buildDefinition": { + "buildType": "https://github.com/moby/buildkit/blob/master/docs/attestations/slsa-definitions.md", + "externalParameters": { + "configSource": { + "path": "Dockerfile" + }, + "request": { + "args": { + "build-arg:VERSION": "v0.0.1" + }, + "compatibilityVersion": 30, + "frontend": "dockerfile.v0", + "locals": [ + { + "name": "context" + }, + { + "name": "dockerfile" + } + ] + } + }, + "internalParameters": { + "builderPlatform": "linux/amd64", + "targetPlatform": "linux/amd64" + }, + "resolvedDependencies": [ + { + "digest": { + "sha256": "be2656061b536c1883c4034790e21d0a09c5aaaf51968b89368a3c0371ea2c9a" + }, + "uri": "pkg:docker/alpine@3.24?platform=linux%2Famd64" + } + ] + }, + "runDetails": { + "builder": { + "id": "https://github.com/IronFlock/example/actions/runs/123/attempts/1" + }, + "metadata": { + "buildkit_completeness": { + "request": true, + "resolvedDependencies": false + }, + "buildkit_metadata": { + "vcs": { + "source": "https://github.com/IronFlock/example.git", + "revision": "0123456789abcdef0123456789abcdef01234567", + "localdir:context": ".", + "localdir:dockerfile": "." + } + }, + "finishedOn": "2026-11-05T08:00:10Z", + "invocationId": "example", + "startedOn": "2026-11-05T08:00:00Z" + } + } +} diff --git a/tools.lock b/tools.lock index 380ee57..c8fc8d2 100644 --- a/tools.lock +++ b/tools.lock @@ -38,3 +38,5 @@ uv 0.13.0 1468ebd5a5541121837c5a2817b9972ba6090fa6caa3d142620850a47fb7 uv/arm64 0.13.0 3ccfb6af6e242433eb552f7d9676abd5412c6595c497e990d9c8cb7b5bd4d2c3 https://github.com/astral-sh/uv/releases/download/0.13.0/uv-aarch64-unknown-linux-gnu.tar.gz uv-aarch64-unknown-linux-gnu/uv uvx 0.13.0 1468ebd5a5541121837c5a2817b9972ba6090fa6caa3d142620850a47fb75154 https://github.com/astral-sh/uv/releases/download/0.13.0/uv-x86_64-unknown-linux-gnu.tar.gz uv-x86_64-unknown-linux-gnu/uvx uvx/arm64 0.13.0 3ccfb6af6e242433eb552f7d9676abd5412c6595c497e990d9c8cb7b5bd4d2c3 https://github.com/astral-sh/uv/releases/download/0.13.0/uv-aarch64-unknown-linux-gnu.tar.gz uv-aarch64-unknown-linux-gnu/uvx +cosign 3.1.4 424e2c97d0b45fd7a6b608a87f090f35633f4c23ece5f092d48bba11aaf4bbfa https://github.com/sigstore/cosign/releases/download/v3.1.4/cosign-linux-amd64 - +cosign/arm64 3.1.4 ade83b7aac62e131cacfe96d958948b2150cc9efec46a570a2649b8e27dedad2 https://github.com/sigstore/cosign/releases/download/v3.1.4/cosign-linux-arm64 -