From 2efe8abbfb0c3b20881d4b2c934028dd40b70bdc Mon Sep 17 00:00:00 2001 From: Alexandr Date: Wed, 18 Nov 2026 21:08:14 +0300 Subject: [PATCH 1/2] ci: generate SBOMs and sign release artifacts --- .github/workflows/ci.yml | 29 +++++++ .github/workflows/release.yml | 58 ++++++++++++- .gitignore | 1 + .goreleaser.yaml | 46 +++++++++- CONTRIBUTING.md | 18 ++-- README.md | 13 +-- deploy/README.md | 4 +- deploy/verify-release.md | 132 +++++++++++++++++++++++++++++ scripts/check-release-artifacts.py | 78 +++++++++++++++++ scripts/test_release_artifacts.py | 104 +++++++++++++++++++++++ 10 files changed, 465 insertions(+), 18 deletions(-) create mode 100644 deploy/verify-release.md create mode 100644 scripts/check-release-artifacts.py create mode 100644 scripts/test_release_artifacts.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c6ae3e5..6b72cda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -112,3 +112,32 @@ jobs: - name: Tests run: go test -race ./... + + release-check: + name: Release packaging (unsigned) + runs-on: ubuntu-latest + timeout-minutes: 15 + # No OIDC or publishing permissions: PRs build and inspect snapshots only. + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 0 + - uses: actions/setup-go@v7 + with: + go-version: ${{ env.GO_VERSION }} + cache: true + - uses: anchore/sbom-action/download-syft@fffec3d851af758d56fee099cf3fbf8aa8779843 # v0.24.3 + with: + syft-version: v1.57.2 + - uses: goreleaser/goreleaser-action@v7 + with: + distribution: goreleaser + version: v2.20.2 + args: check + - name: Build archives and SBOMs without publishing or signing + run: goreleaser release --snapshot --clean --skip=publish,sign,docker + - name: Validate snapshot and reject damaged evidence + run: | + python3 scripts/check-release-artifacts.py dist --unsigned \ + --version "$(jq -r .version dist/metadata.json)" + python3 -m unittest discover -s scripts -p 'test_*.py' -v diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7ac5331..a422c51 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -63,17 +63,32 @@ jobs: name: GoReleaser needs: [release-please] # always(): still run on workflow_dispatch when release-please is skipped. - if: ${{ always() && !cancelled() && (needs.release-please.outputs.release_created == 'true' || (github.event_name == 'workflow_dispatch' && inputs.publish_tag != '')) }} + if: ${{ always() && !cancelled() && github.repository == 'tracewick/agent' && github.ref == 'refs/heads/main' && (needs.release-please.outputs.release_created == 'true' || (github.event_name == 'workflow_dispatch' && inputs.publish_tag != '')) }} runs-on: ubuntu-latest timeout-minutes: 45 permissions: contents: write packages: write + id-token: write + env: + RELEASE_TAG: ${{ needs.release-please.outputs.tag_name || inputs.publish_tag }} steps: + - name: Validate the release tag input + shell: bash + run: | + [[ "$RELEASE_TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]] || exit 1 + - uses: actions/checkout@v7 with: fetch-depth: 0 - ref: ${{ inputs.publish_tag || github.sha }} + ref: ${{ env.RELEASE_TAG }} + + - name: Require a tag from main with signed-release support + shell: bash + run: | + test "$(git rev-parse HEAD)" = "$(git rev-parse "refs/tags/$RELEASE_TAG^{commit}")" + git merge-base --is-ancestor HEAD origin/main + test -f scripts/check-release-artifacts.py - uses: actions/setup-go@v7 with: @@ -93,6 +108,14 @@ jobs: - uses: docker/setup-qemu-action@v4 - uses: docker/setup-buildx-action@v4 + - uses: sigstore/cosign-installer@756fe2d284c7292c4e9b62c8a28f1e5629c59532 # v4.1.3 + with: + cosign-release: v3.1.4 + + - uses: anchore/sbom-action/download-syft@fffec3d851af758d56fee099cf3fbf8aa8779843 # v0.24.3 + with: + syft-version: v1.57.2 + - name: Login to GHCR uses: docker/login-action@v4 with: @@ -103,12 +126,41 @@ jobs: - uses: goreleaser/goreleaser-action@v7 with: distribution: goreleaser - version: "~> v2" + version: v2.20.2 args: release --clean env: # App token uploads assets to the App-created release; GHCR uses docker login above. GITHUB_TOKEN: ${{ steps.app-token.outputs.token || secrets.GITHUB_TOKEN }} + - name: Verify published release artifacts + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \ + --dir "$RUNNER_TEMP/release-verification" + python3 scripts/check-release-artifacts.py "$RUNNER_TEMP/release-verification" \ + --version "${RELEASE_TAG#v}" + + - name: Verify published image signature, revision and SBOMs + shell: bash + run: | + IMAGE=ghcr.io/tracewick/agent + DIGEST=$(docker buildx imagetools inspect "$IMAGE:${RELEASE_TAG#v}" --format '{{.Manifest.Digest}}') + [[ "$DIGEST" =~ ^sha256:[a-f0-9]{64}$ ]] || exit 1 + cosign verify \ + --certificate-identity 'https://github.com/tracewick/agent/.github/workflows/release.yml@refs/heads/main' \ + --certificate-oidc-issuer 'https://token.actions.githubusercontent.com' "$IMAGE@$DIGEST" + docker buildx imagetools inspect "$IMAGE@$DIGEST" --raw | \ + jq -e --arg ver "${RELEASE_TAG#v}" --arg rev "$(git rev-parse HEAD)" \ + '.annotations["org.opencontainers.image.version"] == $ver and + .annotations["org.opencontainers.image.revision"] == $rev' + docker buildx imagetools inspect "$IMAGE@$DIGEST" --format '{{json .SBOM}}' > "$RUNNER_TEMP/image-sboms.json" + jq -e '. as $sboms | ["linux/amd64", "linux/arm64"] | all(.[]; + $sboms[.].SPDX | (.spdxVersion | startswith("SPDX-")) and + ([.packages[].name] | index("base-files") != null and + index("stdlib") != null and index("github.com/tracewick/agent") != null))' \ + "$RUNNER_TEMP/image-sboms.json" + back-merge: name: Merge main back into develop needs: release-please diff --git a/.gitignore b/.gitignore index 57e9755..e4f25cc 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ /build/ .golangci.cache/ .cache/ +__pycache__/ # IDE / OS .idea/ diff --git a/.goreleaser.yaml b/.goreleaser.yaml index 015a1b4..ea5054f 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -1,5 +1,4 @@ -# Multi-arch binaries + GHCR images. Cosign / SBOM intentionally deferred; -# release footer states unsigned until they land. +# Multi-arch binaries and GHCR images, with SBOMs and keyless signatures. version: 2 project_name: tracewick-agent @@ -26,6 +25,29 @@ checksum: name_template: checksums.txt algorithm: sha256 +# These SBOMs describe the actual archives, not the source checkout. +sboms: + - artifacts: archive + documents: + - "{{ .ArtifactName }}.sbom.json" + args: + - "$artifact" + - "--output" + - "cyclonedx-json=$document" + - "--source-name={{ .ProjectName }}" + - "--source-version={{ .Version }}" + +# The checksum manifest covers both archives and their SBOMs. +signs: + - cmd: cosign + artifacts: checksum + signature: "${artifact}.sigstore.json" + args: + - sign-blob + - "--bundle=${signature}" + - "${artifact}" + - "--yes" + dockers_v2: - id: tracewick-agent ids: [tracewick-agent] @@ -39,6 +61,11 @@ dockers_v2: platforms: - linux/amd64 - linux/arm64 + # BuildKit attaches per-platform SPDX SBOMs to the OCI index. + sbom: true + annotations: + "index:org.opencontainers.image.version": "{{ .Version }}" + "index:org.opencontainers.image.revision": "{{ .FullCommit }}" labels: "org.opencontainers.image.title": "tracewick-agent" "org.opencontainers.image.description": "Tracewick spool sidecar for Pyroscope" @@ -47,13 +74,24 @@ dockers_v2: "org.opencontainers.image.version": "{{ .Version }}" "org.opencontainers.image.revision": "{{ .FullCommit }}" +# Sign the index by digest, binding its platform manifests and SBOM attestations. +docker_signs: + - artifacts: "" + args: + - sign + - "${artifact}@${digest}" + - "--yes" + changelog: disable: true release: draft: false - # release-please already wrote the changelog body; append the unsigned note. + # release-please already wrote the changelog body. mode: append footer: | --- - **Unsigned release:** no cosign signatures or SBOM yet. Prefer `checksums.txt` (SHA-256) and pinned image digests from `ghcr.io/tracewick/agent`. Cosign/SBOM land later. + Archive SBOMs and a Sigstore bundle for `checksums.txt` accompany this release. + GHCR image indexes are signed by digest and include per-platform SPDX SBOMs. + Verify the release workflow completed successfully and follow the + [verification instructions](https://github.com/tracewick/agent/blob/main/deploy/verify-release.md). diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2dc2a82..6422578 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,8 +12,8 @@ library and `tracewick-drain` remain the spool writers / reference drain. > **Beta (`0.2.x`).** Capacity evidence (agent as reader) lives in > [`tracewick/benchmarks`](https://github.com/tracewick/benchmarks). Do not claim -> production / highload readiness. Cosign/SBOM, broader env parity, and socket -> hand-off remain RC / later. +> production / highload readiness. Operational env parity is in develop; socket +> hand-off remains v1.1+. Signed-release configuration is described below. ## Path to release @@ -23,7 +23,7 @@ Alpha cut is done (`v0.1.0`). Keep the floor green while advancing RC work: | --- | --- | | Delivery proof | Stand + Toxiproxy chaos + Querier live + Go ↔ PHP-drain (see `test/e2e/`) | | Test proof | Coverage gates **and** fuzz / `go tool pprof` / mutation (Gremlins) on core | -| Release machine | release-please + GoReleaser: binaries + `ghcr.io/tracewick/agent`; unsigned until cosign | +| Release machine | release-please + GoReleaser: binaries, archive SBOMs, signed checksums and SBOM-bearing signed GHCR indexes | | Load truth | Soak/load via [`tracewick/benchmarks`](https://github.com/tracewick/benchmarks), not a weak mini-soak here | httptest is fine for unit and claim-smoke only — not a substitute for Toxiproxy chaos. @@ -110,14 +110,22 @@ Releases follow git flow and are automated with request into `main`. 3. Merging it tags `v` and runs GoReleaser: linux amd64/arm64 `tar.gz` + `checksums.txt`, multi-arch `ghcr.io/tracewick/agent`, and an - **unsigned** footer on the GitHub Release body (no cosign/SBOM yet). + footer linking [SBOM/signature verification](deploy/verify-release.md). + Archive SBOMs are generated with Syft, checksums are signed with keyless + Cosign, and BuildKit SBOM-bearing image indexes are signed by digest. 4. The workflow opens a pull request merging `main` back into `develop`. Tags `v*` are protected by a ruleset. The workflow uses a dedicated GitHub App (`RELEASE_APP_ID` / `RELEASE_APP_PRIVATE_KEY`, on the tag ruleset bypass list — same pattern as `tracewick/tracewick`). Do not force-push tags by hand. -Releases stay **unsigned** until cosign/SBOM land. Pin the next tag with +Existing 0.2.x releases remain **unsigned**. The first signed release must pass +the publishing job and verification steps; a local snapshot is not an OIDC test. +The Release workflow must run from main, including manual recovery, so its exact +certificate identity ends in `release.yml@refs/heads/main`. Only the publishing +job has OIDC permission; no persistent signing key is required. Tool versions are +pinned in the release and unsigned-packaging CI jobs; update them together. +See [verification and recovery](deploy/verify-release.md). Pin the next tag with `release-as` in `release-please-config.json` when forcing a version (then remove it after the release PR merges). Do not invent tags outside that flow. diff --git a/README.md b/README.md index 557079b..c8036ce 100644 --- a/README.md +++ b/README.md @@ -25,15 +25,18 @@ encodes **pprof**, and pushes via the Pyroscope Push API. | In beta | Later (RC / 1.0+) | | --- | --- | -| Spool claim → aggregate → pprof → Push → ack (`run` / `--once`) | Signed releases (cosign) / SBOM | +| Spool claim → aggregate → pprof → Push → ack (`run` / `--once`) | | | Same claim protocol as PHP `tracewick-drain` (at-least-once) | Unix socket hand-off (v1.1+) | -| Stand + Toxiproxy + live Querier + Go↔PHP-drain E2E | Broader CLI/env parity with drain | +| Stand + Toxiproxy + live Querier + Go↔PHP-drain E2E | | +| Operational CLI/env settings (develop; not in published 0.2.1) | | | linux amd64/arm64 binaries + `ghcr.io/tracewick/agent` | | | Codecov / mutation / fuzz / `go tool pprof` CI gates | | | Soak / RPS / chaos / spool-pressure goldens (agent reader) | | -GitHub Releases are **unsigned** until cosign is wired. Prefer `checksums.txt` -(SHA-256) and pinned GHCR digests. +The release workflow generates archive SBOMs, signs their checksum manifest with +keyless Cosign, and signs SBOM-bearing GHCR image indexes. Existing 0.2.x releases +remain **unsigned**; the first signed publication still needs a successful release +run. See [verification and recovery](deploy/verify-release.md). ### Ops assumptions @@ -112,7 +115,7 @@ Wire format and delivery decisions live in ## Install Pin a release tag (see [Releases](https://github.com/tracewick/agent/releases)). -Artifacts are **unsigned** — verify `checksums.txt` (and prefer an image digest +Existing 0.2.x artifacts are **unsigned** — verify `checksums.txt` (and prefer an image digest for containers). ### Binary (linux amd64 / arm64) diff --git a/deploy/README.md b/deploy/README.md index 2f2d2f1..e12d3d2 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -46,4 +46,6 @@ docker run --rm --user "$(id -u):$(id -g)" \ tracewick-agent:local run --once ``` -Published tags are **unsigned** until cosign lands; pin by digest when possible. +Existing 0.2.x releases are **unsigned**. For releases made by the signed-release +workflow, verify the checksum bundle or GHCR index signature before use, then pin +the image digest. See [SBOM/signature verification](verify-release.md). diff --git a/deploy/verify-release.md b/deploy/verify-release.md new file mode 100644 index 0000000..288599c --- /dev/null +++ b/deploy/verify-release.md @@ -0,0 +1,132 @@ +# Release SBOMs and signatures + +Releases made with the signed-release workflow provide: + +- Two Linux archives (amd64/arm64), each accompanied by `.sbom.json` in + CycloneDX JSON format. Syft scans the built archive, including the Go module, + Go standard library version and binary hashes; it does not inventory the source tree. +- `checksums.txt`, covering the archives and their SBOMs, and its keyless Cosign + bundle `checksums.txt.sigstore.json`. Authenticating this manifest and checking + its hashes authenticates both kinds of files. +- A signed multi-platform GHCR image index. BuildKit's per-platform SPDX SBOM + attestations are referenced by this index and include the base-image inventory. + They are registry artifacts, separate from the archive SBOMs in GitHub Releases. + +Existing 0.2.x releases remain unsigned. These instructions apply only after a +successful release using this workflow; changing the configuration does not sign +old downloads retroactively. An SBOM is an inventory, not a vulnerability verdict. +Scanners such as Trivy/Grype can consume it; the agent does not need it at runtime. + +## Trust identity + +Install Cosign 3 (the workflow uses 3.1.4). Require this exact certificate identity +and issuer, rather than accepting any valid Sigstore signature: + +```bash +IDENTITY='https://github.com/tracewick/agent/.github/workflows/release.yml@refs/heads/main' +ISSUER='https://token.actions.githubusercontent.com' +``` + +The workflow runs on `main`, including manual recovery. Checking out a release tag +does **not** change its OIDC workflow identity to `refs/tags/...`. Fulcio issues a +short-lived certificate from GitHub's OIDC identity; no persistent signing key or +new signing secret is stored. Cosign records signatures in the transparency log. +The existing release App and GHCR credentials still serve their existing purposes. + +## Verify an archive and its SBOM + +Choose an actual signed release in GitHub Releases; replace the example version. +Use a new directory and download the four matching assets: + +```bash +VER=1.0.0-rc.1 # example only; this does not imply that this release exists +ARCH=amd64 # or arm64 +ARCHIVE="tracewick-agent_${VER}_linux_${ARCH}.tar.gz" +gh release download "v${VER}" --repo tracewick/agent \ + --pattern "$ARCHIVE" --pattern "$ARCHIVE.sbom.json" \ + --pattern checksums.txt --pattern checksums.txt.sigstore.json || exit 1 + +cosign verify-blob --certificate-identity "$IDENTITY" \ + --certificate-oidc-issuer "$ISSUER" \ + --bundle checksums.txt.sigstore.json checksums.txt || exit 1 + +# Run only after signature verification succeeds. Check each requested file, +# and fail if the signed manifest does not contain exactly one matching entry. +for FILE in "$ARCHIVE" "$ARCHIVE.sbom.json"; do + awk -v name="$FILE" '$2 == name {print; count++} END {if (count != 1) exit 1}' \ + checksums.txt > selected-checksum.txt || exit 1 + sha256sum --check selected-checksum.txt || exit 1 +done +``` + +Stop on any error, before extracting or executing the binary. A bare SHA-256 +manifest provides integrity only; first authenticate it with Cosign. Each signed +manifest identifies its versioned archive filenames. Do not substitute the files +or manifest from another release. On macOS use `shasum -a 256 --check`. + +## Verify a container and retrieve its SBOM + +Resolve the selected version to its index digest, then verify and use that exact +digest throughout. Requires Docker Buildx for the inspection commands: + +```bash +IMAGE=ghcr.io/tracewick/agent +DIGEST=$(docker buildx imagetools inspect "$IMAGE:$VER" --format '{{.Manifest.Digest}}') || exit 1 +cosign verify --certificate-identity "$IDENTITY" \ + --certificate-oidc-issuer "$ISSUER" "$IMAGE@$DIGEST" || exit 1 + +# After successful verification, inspect/export the signed index's SBOMs. +docker buildx imagetools inspect "$IMAGE@$DIGEST" \ + --format '{{json .SBOM}}' > image-sboms.json +jq '.["linux/amd64"].SPDX' image-sboms.json > image-linux-amd64.spdx.json +docker pull "$IMAGE@$DIGEST" +``` + +The signature covers the **index digest**, which binds the platform manifests +and BuildKit attestations it references. It is not a separate Cosign SBOM +attestation; `cosign verify-attestation --type cyclonedx` is not its retrieval API. +An extracted SPDX JSON alone is not proof: keep its association with the verified +index. Pin the digest in deployment after verification; a tag may move. + +## Maintainer workflow and recovery + +release-please still creates the version/changelog/tag through the existing Git +flow. GoReleaser builds archives, Syft creates their SBOMs, Cosign signs the +checksum manifest, and Buildx publishes SBOM-bearing images which Cosign signs by +index digest. Only the publishing job receives `id-token: write`; PR checks do +not receive OIDC or publication permissions. + +The release job checks out the actual tag and requires its commit to belong to +`main`. After publication it downloads the release assets and verifies the +manifest's keyless signature, hashes, both ELF architectures, release identity +and SBOM-to-binary binding. It also verifies the image index's signature, +version/revision and both platform SBOMs. +Any signing or verification failure fails the job; it does +not fall back to an unsigned release. GitHub Release or image publication may +already be partial when a later step fails. Treat only a completed workflow as a +completed release; do not announce a failed/partial publication as verified. + +Manual recovery uses the existing `Release` workflow on **main** with +`publish_tag` set to the existing tag. The tagged source must contain this signed +release configuration and artifact verifier. Do not use it to retrofit old +unsigned tags. Rerunning rebuilds artifacts; it is not a promise of byte-identical +reproduction. Verify the successful rerun before using its resulting digests. + +For local/PR validation (GoReleaser 2.20.2 and Syft 1.57.2): + +```bash +goreleaser check +goreleaser release --snapshot --clean --skip=publish,sign,docker +python3 scripts/check-release-artifacts.py dist --unsigned \ + --version "$(jq -r .version dist/metadata.json)" +python3 -m unittest discover -s scripts -p 'test_*.py' -v +``` + +This checks real archive/SBOM output and negative controls without signing, +publishing or claiming an OIDC test. The first normal signed release must also +confirm GHCR signature/SBOM retrieval and asset verification with the production +identity. Snapshot success is not evidence that those remote steps have run. + +References: [GoReleaser signing](https://goreleaser.com/customization/sign/sign/), +[archive SBOMs](https://goreleaser.com/customization/sbom/), +[Docker v2](https://goreleaser.com/customization/package/dockers_v2/). diff --git a/scripts/check-release-artifacts.py b/scripts/check-release-artifacts.py new file mode 100644 index 0000000..bfb0a25 --- /dev/null +++ b/scripts/check-release-artifacts.py @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +"""Verify downloaded release assets, or explicitly unsigned local snapshots.""" + +import argparse +import hashlib +import json +from pathlib import Path +import re +import subprocess +import tarfile + +IDENTITY = "https://github.com/tracewick/agent/.github/workflows/release.yml@refs/heads/main" +ISSUER = "https://token.actions.githubusercontent.com" + + +def check(directory, version, unsigned=False): + manifest = directory / "checksums.txt" + if not unsigned: + subprocess.run([ + "cosign", "verify-blob", "--certificate-identity", IDENTITY, + "--certificate-oidc-issuer", ISSUER, + "--bundle", str(directory / "checksums.txt.sigstore.json"), str(manifest), + ], check=True) + + entries = {} + for line in manifest.read_text().splitlines(): + match = re.fullmatch(r"([a-f0-9]{64}) ([A-Za-z0-9_.+-]+)", line) + if not match or match[2] in entries or match[2] in (".", ".."): + raise ValueError("Malformed or duplicate checksum entry") + entries[match[2]] = match[1] + if not entries: + raise ValueError("Empty checksum manifest") + for name, digest in entries.items(): + path = directory / name + if path.is_symlink() or hashlib.sha256(path.read_bytes()).hexdigest() != digest: + raise ValueError(f"Checksum mismatch: {name}") + + for arch, machine in (("amd64", 62), ("arm64", 183)): + archive = f"tracewick-agent_{version}_linux_{arch}.tar.gz" + sbom_name = archive + ".sbom.json" + if archive not in entries or sbom_name not in entries: + raise ValueError(f"Archive or SBOM missing from checksums: {arch}") + with tarfile.open(directory / archive, "r:gz") as stream: + member = stream.getmember("tracewick-agent") + if not member.isfile(): + raise ValueError("Archive binary is not a regular file") + binary = stream.extractfile(member).read() + if binary[:6] != b"\x7fELF\x02\x01" or int.from_bytes(binary[18:20], "little") != machine: + raise ValueError(f"Wrong ELF architecture: {arch}") + + sbom = json.loads((directory / sbom_name).read_text()) + component = sbom.get("metadata", {}).get("component", {}) + if (sbom.get("bomFormat") != "CycloneDX" or component.get("name") != "tracewick-agent" + or component.get("version") != version): + raise ValueError(f"Wrong SBOM format or release identity: {arch}") + components = sbom.get("components", []) + if not any(c.get("name") == "stdlib" and c.get("version") for c in components): + raise ValueError(f"SBOM lacks the Go standard library: {arch}") + if not any(c.get("name") == "github.com/tracewick/agent" and any( + p.get("name") == "syft:metadata:architecture" and p.get("value") == arch + for p in c.get("properties", [])) for c in components): + raise ValueError(f"SBOM lacks the matching Go module architecture: {arch}") + binary_hash = hashlib.sha256(binary).hexdigest() + if not any(c.get("type") == "file" and c.get("name") == "/tracewick-agent" and any( + h.get("alg") == "SHA-256" and h.get("content") == binary_hash + for h in c.get("hashes", [])) for c in components): + raise ValueError(f"SBOM does not describe this archive's binary: {arch}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("directory", type=Path) + parser.add_argument("--version", required=True, help="Version without the v prefix") + parser.add_argument("--unsigned", action="store_true", help="Local/PR snapshots only; no identity claim") + args = parser.parse_args() + check(args.directory, args.version, args.unsigned) + print("Verified archive hashes, architectures and SBOM contents" + + (" (UNSIGNED snapshot)" if args.unsigned else " and release signature")) diff --git a/scripts/test_release_artifacts.py b/scripts/test_release_artifacts.py new file mode 100644 index 0000000..1eb00e6 --- /dev/null +++ b/scripts/test_release_artifacts.py @@ -0,0 +1,104 @@ +"""Negative controls against real GoReleaser/Syft snapshot output.""" + +import hashlib +import importlib.util +import json +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +ROOT = Path(__file__).resolve().parents[1] +SPEC = importlib.util.spec_from_file_location("release_check", ROOT / "scripts/check-release-artifacts.py") +CHECK = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(CHECK) + + +class ReleaseArtifactsTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.directory = Path(self.temp.name) + self.version = json.loads((ROOT / "dist/metadata.json").read_text())["version"] + for pattern in ("*.tar.gz", "*.sbom.json", "checksums.txt"): + for path in (ROOT / "dist").glob(pattern): + shutil.copyfile(path, self.directory / path.name) + self.sbom = next(self.directory.glob("*amd64*.sbom.json")) + + def rehash(self): + paths = sorted(self.directory.glob("*.tar.gz")) + sorted(self.directory.glob("*.sbom.json")) + (self.directory / "checksums.txt").write_text("".join( + f"{hashlib.sha256(p.read_bytes()).hexdigest()} {p.name}\n" for p in paths)) + + def edit_sbom(self, edit): + document = json.loads(self.sbom.read_text()) + edit(document) + self.sbom.write_text(json.dumps(document)) + self.rehash() + + def check(self): + CHECK.check(self.directory, self.version, unsigned=True) + + def test_complete_snapshot_passes(self): + self.check() + + def test_changed_archive_fails(self): + with next(self.directory.glob("*.tar.gz")).open("ab") as stream: + stream.write(b"tampered") + with self.assertRaisesRegex(ValueError, "Checksum mismatch"): + self.check() + + def test_swapped_platform_sboms_fail_even_with_updated_checksums(self): + other = next(self.directory.glob("*arm64*.sbom.json")) + first, second = self.sbom.read_bytes(), other.read_bytes() + self.sbom.write_bytes(second) + other.write_bytes(first) + self.rehash() + with self.assertRaisesRegex(ValueError, "architecture"): + self.check() + + def test_wrong_binary_hash_fails_even_with_updated_checksums(self): + def edit(document): + for component in document["components"]: + for digest in component.get("hashes", []): + digest["content"] = "0" * 64 + self.edit_sbom(edit) + with self.assertRaisesRegex(ValueError, "does not describe"): + self.check() + + def test_wrong_release_identity_fails(self): + self.edit_sbom(lambda d: d["metadata"]["component"].update(version="unrelated-release")) + with self.assertRaisesRegex(ValueError, "release identity"): + self.check() + + def test_missing_standard_library_fails(self): + self.edit_sbom(lambda d: d.update(components=[c for c in d["components"] if c["name"] != "stdlib"])) + with self.assertRaisesRegex(ValueError, "standard library"): + self.check() + + def test_missing_sbom_fails(self): + self.sbom.unlink() + self.rehash() + with self.assertRaisesRegex(ValueError, "missing from checksums"): + self.check() + + def test_path_traversal_and_duplicate_entries_fail(self): + manifest = self.directory / "checksums.txt" + original = manifest.read_text() + for extra in ("0" * 64 + " ../outside\n", original.splitlines()[0] + "\n"): + with self.subTest(extra=extra): + manifest.write_text(original + extra) + with self.assertRaisesRegex(ValueError, "Malformed or duplicate"): + self.check() + + def test_signature_failure_is_fatal_in_default_mode(self): + error = subprocess.CalledProcessError(1, "cosign verify-blob") + with patch.object(CHECK.subprocess, "run", side_effect=error): + with self.assertRaises(subprocess.CalledProcessError): + CHECK.check(self.directory, self.version) + + +if __name__ == "__main__": + unittest.main() From d94b8b1e6fd8b39d42ddacf382d5b79354a854a4 Mon Sep 17 00:00:00 2001 From: Alexandr Date: Wed, 18 Nov 2026 21:10:42 +0300 Subject: [PATCH 2/2] fix(ci): expose GoReleaser to packaging checks --- .github/workflows/ci.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6b72cda..0d8fa5c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -133,9 +133,11 @@ jobs: with: distribution: goreleaser version: v2.20.2 - args: check + install-only: true - name: Build archives and SBOMs without publishing or signing - run: goreleaser release --snapshot --clean --skip=publish,sign,docker + run: | + goreleaser check + goreleaser release --snapshot --clean --skip=publish,sign,docker - name: Validate snapshot and reject damaged evidence run: | python3 scripts/check-release-artifacts.py dist --unsigned \