diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c6ae3e5..0d8fa5c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -112,3 +112,34 @@ 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 + install-only: true + - name: Build archives and SBOMs without publishing or signing + 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 \ + --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..d7149b5 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] @@ -35,10 +57,15 @@ dockers_v2: tags: - "{{ .Version }}" - "{{ .Tag }}" - - latest + - "{{ if not .Prerelease }}latest{{ end }}" 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,25 @@ 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. + prerelease: auto + # 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/AGENTS.md b/AGENTS.md index 13e1a0b..db5f685 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -80,6 +80,11 @@ make stand-down - English only. Conventional Commits. Do not hand-edit `CHANGELOG.md`. - Do not invent agent-local ADR numbers that shadow main-repo ADRs; link them. - Git flow: branch `feature/*` from `develop`, open PRs into `develop`. + Promote to `main` **only** via `release/` or `hotfix/` — + never a direct feature/fix/chore PR into `main`. Agents may merge into + `develop` after Checks green; **never** merge anything whose base is `main` + (release PR, release-please, back-merge — maintainer only). «Делай» does not + override this. - After opening or pushing a PR, babysit checks (`gh pr checks`, Codecov) until green; fix failures yourself. Report only when review-ready or blocked on a secret/decision. @@ -88,3 +93,4 @@ make stand-down See [CONTRIBUTING.md](CONTRIBUTING.md) § Releasing. Do not invent tags outside release-please. Do not push or merge to `main` unless the maintainer asks. +Path: `develop` → `release/` → `main` (merge commit) → release-please tag. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2dc2a82..60ff5cb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,10 +10,10 @@ engineering and release discipline as files, aggregates them, encodes **pprof**, and pushes to Pyroscope. The PHP library and `tracewick-drain` remain the spool writers / reference drain. -> **Beta (`0.2.x`).** Capacity evidence (agent as reader) lives in +> **Release candidate (`1.0.0-rc.1`).** 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 included; 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,16 +110,50 @@ 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 -`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. +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). Do not invent tags outside that flow. + +### Release candidates + +The 1.0 series uses `versioning: prerelease`, `prerelease-type: rc` and +`prerelease: true` in `release-please-config.json`. A parseable Conventional +Commit in the preparation branch selects the first candidate: + +```text +chore: prepare 1.0.0-rc.1 + +Release-As: 1.0.0-rc.1 +``` + +The maintainer merges that branch with a merge commit, then reviews and merges +the generated `chore: release 1.0.0-rc.1` PR. The bot creates `v1.0.0-rc.1`; +do not edit the manifest/changelog or create tags manually. GitHub's default +`Merge pull request #N` subject does not parse a Release-As footer. + +GoReleaser uses `prerelease: auto` to preserve the GitHub prerelease status. +Prerelease images publish only their versioned tags; `latest` remains stable. +Keep prerelease mode for subsequent candidates and update the documented version. +To select a version explicitly, add a new Release-As footer. For final 1.0.0, +switch `versioning` to `default`, set `prerelease: false`, remove `prerelease-type` +and use `Release-As: 1.0.0` on a Conventional Commit. Review the generated version +and prerelease status before merging. + +The E2E `make php-drain` fixture pins the published core `1.0.0-rc.1`, including +when refreshing an existing local cache. It does not change the wire contract. ## License diff --git a/Makefile b/Makefile index 73100db..e4db6bb 100644 --- a/Makefile +++ b/Makefile @@ -69,14 +69,12 @@ goreleaser-check: ## Validate .goreleaser.yaml (does not publish) @command -v goreleaser >/dev/null || $(GO) install github.com/goreleaser/goreleaser/v2@latest goreleaser check -php-drain: ## Install Packagist tracewick/tracewick for Go+PHP-drain e2e +php-drain: ## Install Packagist core 1.0.0-rc.1 for Go+PHP-drain e2e @command -v composer >/dev/null || (echo 'composer required for make php-drain' && exit 1) @command -v php >/dev/null || (echo 'php required for make php-drain' && exit 1) mkdir -p $(PHP_DRAIN_DIR) - @if [ ! -f $(PHP_DRAIN_DIR)/composer.json ]; then \ - printf '%s\n' '{"name":"tracewick/agent-e2e-drain","require":{"tracewick/tracewick":"^0.1"},"config":{"sort-packages":true}}' \ - > $(PHP_DRAIN_DIR)/composer.json; \ - fi + @printf '%s\n' '{"name":"tracewick/agent-e2e-drain","require":{"tracewick/tracewick":"1.0.0-rc.1"},"config":{"sort-packages":true}}' \ + > $(PHP_DRAIN_DIR)/composer.json cd $(PHP_DRAIN_DIR) && composer update --no-interaction --no-progress --prefer-dist --no-dev @test -x $(PHP_DRAIN_BIN) || test -f $(PHP_DRAIN_BIN) diff --git a/README.md b/README.md index 24160f4..0985171 100644 --- a/README.md +++ b/README.md @@ -14,26 +14,29 @@ PHP applications write **spool v2** files; this agent claims them, aggregates, encodes **pprof**, and pushes via the Pyroscope Push API. > [!WARNING] -> **Beta (`0.2.x`).** Capacity evidence for the default spool path (with this -> agent as reader) is published in -> [`tracewick/benchmarks`](https://github.com/tracewick/benchmarks). Flags, -> defaults, and ops behaviour are not frozen until 1.0.0 — pin a release and -> read the changelog before upgrading. Not a production / highload readiness -> claim. +> **Release candidate (`1.0.0-rc.1`).** Pin the candidate explicitly and read the +> changelog before upgrading from 0.2. Flags, defaults and operational behaviour +> may still need compatibility fixes during RC validation; the stable contract +> starts with final 1.0.0. Capacity evidence lives in +> [`tracewick/benchmarks`](https://github.com/tracewick/benchmarks) and describes +> its recorded versions and workloads. ## Status -| In beta | Later (RC / 1.0+) | +| In this candidate | Later | | --- | --- | -| 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 (new since 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 @@ -70,6 +73,10 @@ Canonical cloud goldens use depth-48 stacks on an 8 vCPU Timeweb VPS with Full tables and pins: +- [72-hour RoadRunner + agent soak](https://github.com/tracewick/benchmarks/blob/main/reports/2026-11-22-soak-rr-agent-72h.md) + records agent `a15f0d3`; the [current-development campaign](https://github.com/tracewick/benchmarks/pull/11) + covers this candidate's runtime source `d464fac`, including recovery and real Symfony delivery. + The latter is a separate campaign, not another 72-hour run. - [soak FPM](https://github.com/tracewick/benchmarks/blob/main/reports/2026-11-07-soak-fpm-agent-depth48-cloud.md) · [Swoole](https://github.com/tracewick/benchmarks/blob/main/reports/2026-11-07-soak-swoole-agent-depth48-cloud.md) · [RoadRunner](https://github.com/tracewick/benchmarks/blob/main/reports/2026-11-08-soak-rr-agent-depth48-cloud.md) @@ -112,22 +119,28 @@ 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). +For this candidate, first [verify the signed checksums and matching archive/SBOM](deploy/verify-release.md). +The commands below become usable after the candidate's release workflow publishes its assets. ### Binary (linux amd64 / arm64) Archives ship the binary as `tracewick-agent`: ```bash -VER=0.2.0 +VER=1.0.0-rc.1 ARCH=amd64 # or arm64 -curl -fsSL -o agent.tgz \ - "https://github.com/tracewick/agent/releases/download/v${VER}/tracewick-agent_${VER}_linux_${ARCH}.tar.gz" +ARCHIVE="tracewick-agent_${VER}_linux_${ARCH}.tar.gz" +curl -fsSL -o "$ARCHIVE" \ + "https://github.com/tracewick/agent/releases/download/v${VER}/${ARCHIVE}" || exit 1 curl -fsSL -o checksums.txt \ - "https://github.com/tracewick/agent/releases/download/v${VER}/checksums.txt" -sha256sum -c --ignore-missing checksums.txt -tar -xzf agent.tgz tracewick-agent + "https://github.com/tracewick/agent/releases/download/v${VER}/checksums.txt" || exit 1 +# Authenticate checksums.txt with Cosign as linked above before continuing. +awk -v name="$ARCHIVE" '$2 == name {print; count++} END {if (count != 1) exit 1}' \ + checksums.txt > selected-checksum.txt || exit 1 +sha256sum --check selected-checksum.txt || exit 1 +tar -xzf "$ARCHIVE" tracewick-agent sudo install -m 0755 tracewick-agent /usr/local/bin/tracewick-agent tracewick-agent version ``` @@ -135,12 +148,13 @@ tracewick-agent version ### Container (GHCR) ```bash -docker pull ghcr.io/tracewick/agent:0.2.0 +docker pull ghcr.io/tracewick/agent:1.0.0-rc.1 # pin by digest in production when possible: # docker pull ghcr.io/tracewick/agent@sha256:… ``` Compose / Kubernetes examples (UID-compatible): [`deploy/`](deploy/). +RC images have versioned tags (`1.0.0-rc.1` and `v1.0.0-rc.1`); they do not update `latest`. ## Configure and run @@ -156,11 +170,33 @@ and a Pyroscope base URL. | Tenant (`X-Scope-OrgID`) | `--pyroscope-tenant` | `TRACEWICK_PYROSCOPE_TENANT` | | Prometheus `/metrics` | `--metrics-listen` | `TRACEWICK_METRICS_LISTEN` | | Extra TLS CA PEM | `--tls-ca` | `TRACEWICK_TLS_CA` | - -CLI flags override env when both are set. Password must never appear on argv or -in `--pyroscope-url` userinfo. Other knobs (`--reader-id`, `--aggregation-window`, -`--sleep`, decode/memory caps, `--once`, …) are flags today — see -`tracewick-agent run --help`. +| Reader identity | `--reader-id` | `TRACEWICK_READER_ID` | +| Merge window (integer seconds, 10–15) | `--aggregation-window` | `TRACEWICK_AGGREGATION_WINDOW` | +| Idle delay (duration, e.g. `250ms`, `5s`) | `--sleep` | `TRACEWICK_SLEEP` | +| Shutdown grace (duration, e.g. `30s`) | `--shutdown-grace` | `TRACEWICK_SHUTDOWN_GRACE` | +| Rejected-file retention (count) | `--max-rejected-files` | `TRACEWICK_MAX_REJECTED_FILES` | +| Stack cap (count) | `--max-stacks` | `TRACEWICK_MAX_STACKS` | +| Frame cap (count) | `--max-frames` | `TRACEWICK_MAX_FRAMES` | +| String cap (count) | `--max-strings` | `TRACEWICK_MAX_STRINGS` | +| Held decoded budget (decimal bytes) | `--max-held-decoded-bytes` | `TRACEWICK_MAX_HELD_DECODED_BYTES` | +| In-flight budget (decimal bytes) | `--max-in-flight-bytes` | `TRACEWICK_MAX_IN_FLIGHT_BYTES` | + +An explicitly supplied CLI option wins over env **including an empty value**. Empty optional +strings clear the setting (for example `--metrics-listen=` disables metrics); `--reader-id=` +resets the automatic host/pid identifier. Empty required strings or numeric/duration options +fail validation, without falling back to env. A valid CLI override ignores an invalid env value. +Empty environment variables mean unset and use defaults. `--once` and `--help` remain CLI-only. + +Formats and bounds match CLI. Zero sleep/grace and rejected retention are valid; zero decode/memory +caps keep existing defaults. Byte budgets use decimal byte counts, not `64M` suffixes. PHP drain +uses integer seconds in `TRACEWICK_SLEEP_SECONDS`; this agent uses duration strings in +`TRACEWICK_SLEEP`. Defaults are unchanged (see `tracewick-agent run --help`). + +The agent reads the process environment (`os.Getenv`); it does not load `.env` files. Docker +Compose's `.env` is an interpolation source: pass values through `environment` or `env_file` +to put them in the container environment. systemd can supply them with `EnvironmentFile`. +Password remains environment-only and must not appear on argv or in URL userinfo; clearing an +auth user while a password is present is an error. ### Long-running sidecar (recommended) @@ -221,7 +257,7 @@ docker run --rm --user "$(id -u):$(id -g)" \ -e TRACEWICK_SPOOL_DIR=/var/spool/tracewick \ -e TRACEWICK_PYROSCOPE_URL=https://pyroscope.example \ -e TRACEWICK_PYROSCOPE_PASSWORD \ - ghcr.io/tracewick/agent:0.2.0 run --reader-id=sidecar-1 + ghcr.io/tracewick/agent:1.0.0-rc.1 run --reader-id=sidecar-1 ``` For a one-shot pass, append `--once`. Compose and Kubernetes manifests: diff --git a/deploy/.env.example b/deploy/.env.example index b4dfea9..8094033 100644 --- a/deploy/.env.example +++ b/deploy/.env.example @@ -7,3 +7,16 @@ TRACEWICK_PYROSCOPE_URL=http://host.docker.internal:4040 # TRACEWICK_PYROSCOPE_PASSWORD= # TRACEWICK_PYROSCOPE_TENANT= # TRACEWICK_METRICS_LISTEN=0.0.0.0:9090 + +# Compose forwards these into the agent process; the binary does not read this file. +# TRACEWICK_TLS_CA=/etc/ssl/extra-ca.pem +# TRACEWICK_READER_ID=compose-agent +# TRACEWICK_AGGREGATION_WINDOW=15 +# TRACEWICK_SLEEP=5s +# TRACEWICK_SHUTDOWN_GRACE=30s +# TRACEWICK_MAX_REJECTED_FILES=100 +# TRACEWICK_MAX_STACKS=4096 +# TRACEWICK_MAX_FRAMES=16384 +# TRACEWICK_MAX_STRINGS=32768 +# TRACEWICK_MAX_HELD_DECODED_BYTES=67108864 +# TRACEWICK_MAX_IN_FLIGHT_BYTES=67108864 diff --git a/deploy/README.md b/deploy/README.md index 2f2d2f1..74447b7 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -35,7 +35,10 @@ writes `/var/spool/tracewick`. | Source | Image | | --- | --- | | Local | `make docker-build` → `tracewick-agent:local` | -| Release | `ghcr.io/tracewick/agent:` (multi-arch amd64/arm64; e.g. `0.2.0`) | +| Release | `ghcr.io/tracewick/agent:` (multi-arch amd64/arm64; candidate `1.0.0-rc.1`) | + +Candidate images become available after publication. Prereleases do not move the +stable `latest` tag; pin the candidate version or its verified image digest. ```bash make docker-build @@ -46,4 +49,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/docker-compose.yml b/deploy/docker-compose.yml index 422bbdf..47ae96c 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -56,12 +56,20 @@ services: TRACEWICK_PYROSCOPE_PASSWORD: ${TRACEWICK_PYROSCOPE_PASSWORD:-} TRACEWICK_PYROSCOPE_TENANT: ${TRACEWICK_PYROSCOPE_TENANT:-} TRACEWICK_METRICS_LISTEN: ${TRACEWICK_METRICS_LISTEN:-} + TRACEWICK_TLS_CA: ${TRACEWICK_TLS_CA:-} + TRACEWICK_READER_ID: ${TRACEWICK_READER_ID:-compose-agent} + TRACEWICK_AGGREGATION_WINDOW: ${TRACEWICK_AGGREGATION_WINDOW:-} + TRACEWICK_SLEEP: ${TRACEWICK_SLEEP:-} + TRACEWICK_SHUTDOWN_GRACE: ${TRACEWICK_SHUTDOWN_GRACE:-} + TRACEWICK_MAX_REJECTED_FILES: ${TRACEWICK_MAX_REJECTED_FILES:-} + TRACEWICK_MAX_STACKS: ${TRACEWICK_MAX_STACKS:-} + TRACEWICK_MAX_FRAMES: ${TRACEWICK_MAX_FRAMES:-} + TRACEWICK_MAX_STRINGS: ${TRACEWICK_MAX_STRINGS:-} + TRACEWICK_MAX_HELD_DECODED_BYTES: ${TRACEWICK_MAX_HELD_DECODED_BYTES:-} + TRACEWICK_MAX_IN_FLIGHT_BYTES: ${TRACEWICK_MAX_IN_FLIGHT_BYTES:-} volumes: - spool:/var/spool/tracewick - command: - - run - - --reader-id=compose-agent - - --sleep=5s + command: [run] restart: unless-stopped volumes: 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/internal/config/config.go b/internal/config/config.go index 5b19dd5..b8f07e9 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -84,6 +84,8 @@ func Load(args []string, getenv func(string) string) (Config, error) { MaxCardinality: defaultMaxCardinality, } + args = withEnvironmentOptions(args, getenv) + for i := 0; i < len(args); i++ { arg := args[i] switch { @@ -341,6 +343,44 @@ func Load(args []string, getenv func(string) string) (Config, error) { return cfg, nil } +// withEnvironmentOptions supplies only options absent from argv. Appending them +// keeps --help independent of malformed environment values and reuses CLI parsing +// and validation without changing the caller's argument slice. +func withEnvironmentOptions(args []string, getenv func(string) string) []string { + supplied := make(map[string]bool) + for i := 0; i < len(args); i++ { + arg := args[i] + if arg == "--once" || arg == "--help" || arg == "-h" { + continue + } + name, _, inline := strings.Cut(arg, "=") + supplied[name] = true + if !inline { + i++ // The existing parser consumes the next token as this option's value. + } + } + resolved := append([]string(nil), args...) + for _, option := range []struct{ flag, env string }{ + {"--reader-id", "TRACEWICK_READER_ID"}, + {"--aggregation-window", "TRACEWICK_AGGREGATION_WINDOW"}, + {"--sleep", "TRACEWICK_SLEEP"}, + {"--shutdown-grace", "TRACEWICK_SHUTDOWN_GRACE"}, + {"--max-rejected-files", "TRACEWICK_MAX_REJECTED_FILES"}, + {"--max-stacks", "TRACEWICK_MAX_STACKS"}, + {"--max-frames", "TRACEWICK_MAX_FRAMES"}, + {"--max-strings", "TRACEWICK_MAX_STRINGS"}, + {"--max-held-decoded-bytes", "TRACEWICK_MAX_HELD_DECODED_BYTES"}, + {"--max-in-flight-bytes", "TRACEWICK_MAX_IN_FLIGHT_BYTES"}, + } { + if !supplied[option.flag] { + if value := getenv(option.env); value != "" { + resolved = append(resolved, option.flag+"="+value) + } + } + } + return resolved +} + // DeliveryLimits returns DefaultLimits with positive Config overrides applied. func (c *Config) DeliveryLimits() delivery.Limits { l := delivery.DefaultLimits() @@ -375,21 +415,25 @@ Options: --pyroscope-url=URL Pyroscope base URL (env TRACEWICK_PYROSCOPE_URL) --pyroscope-user=USER basic auth user (env TRACEWICK_PYROSCOPE_USER) --pyroscope-tenant=ID X-Scope-OrgID (env TRACEWICK_PYROSCOPE_TENANT) - --reader-id=ID claim reader id (default: host-pid) - --aggregation-window=S merge window 10–15 seconds (default: 15) - --sleep=DURATION idle poll delay (default: 5s) - --shutdown-grace=DURATION after SIGTERM stop new claims immediately; finish in-flight for DURATION (0=stop now; default: 30s) - --max-rejected-files=N keep up to N files under rejected/ (default: 100; 0 deletes) - --max-stacks=N decode/merge stack cap (default: 4096; raise with PHP builder) - --max-frames=N decode/merge frame cap (default: 16384) - --max-strings=N decode/merge string cap (default: 32768) - --max-held-decoded-bytes=N sum of estimated decoded profile bytes per pass (default: 64MiB) - --max-in-flight-bytes=N sum of claimed spool bytes per pass / encoded push cap (default: 64MiB) + --reader-id=ID claim reader id (default: host-pid) (env TRACEWICK_READER_ID) + --aggregation-window=S merge window 10–15 seconds (default: 15) (env TRACEWICK_AGGREGATION_WINDOW) + --sleep=DURATION idle poll delay (default: 5s) (env TRACEWICK_SLEEP) + --shutdown-grace=DURATION after SIGTERM stop new claims immediately; finish in-flight for DURATION (0=stop now; default: 30s) (env TRACEWICK_SHUTDOWN_GRACE) + --max-rejected-files=N keep up to N files under rejected/ (default: 100; 0 deletes) (env TRACEWICK_MAX_REJECTED_FILES) + --max-stacks=N decode/merge stack cap (default: 4096; raise with PHP builder) (env TRACEWICK_MAX_STACKS) + --max-frames=N decode/merge frame cap (default: 16384) (env TRACEWICK_MAX_FRAMES) + --max-strings=N decode/merge string cap (default: 32768) (env TRACEWICK_MAX_STRINGS) + --max-held-decoded-bytes=N sum of estimated decoded profile bytes per pass (default: 64MiB) (env TRACEWICK_MAX_HELD_DECODED_BYTES) + --max-in-flight-bytes=N sum of claimed spool bytes per pass / encoded push cap (default: 64MiB) (env TRACEWICK_MAX_IN_FLIGHT_BYTES) --metrics-listen=ADDR Prometheus /metrics bind (env TRACEWICK_METRICS_LISTEN; empty disables) --tls-ca=PATH extra PEM CA roots for HTTPS (env TRACEWICK_TLS_CA) --once deliver one pass and exit --help show this help +Explicit CLI options override env, including empty values. Empty optional strings +clear settings; empty required/numeric values are errors. Empty env uses defaults. +No .env file is loaded. --once and --help are CLI-only. + Password: set TRACEWICK_PYROSCOPE_PASSWORD in the environment (never argv). Do not put credentials in --pyroscope-url; use TRACEWICK_PYROSCOPE_USER / TRACEWICK_PYROSCOPE_PASSWORD. `) + "\n" diff --git a/internal/config/environment_test.go b/internal/config/environment_test.go new file mode 100644 index 0000000..594b1ce --- /dev/null +++ b/internal/config/environment_test.go @@ -0,0 +1,122 @@ +package config_test + +import ( + "strings" + "testing" + "time" + + "github.com/tracewick/agent/internal/config" +) + +func TestOperationalEnvironment(t *testing.T) { + t.Parallel() + cfg, err := config.Load(nil, envMap{ + "TRACEWICK_SPOOL_DIR": "/spool", "TRACEWICK_PYROSCOPE_URL": "http://localhost:4040", + "TRACEWICK_READER_ID": "env-reader", "TRACEWICK_AGGREGATION_WINDOW": "10", + "TRACEWICK_SLEEP": "250ms", "TRACEWICK_SHUTDOWN_GRACE": "0s", "TRACEWICK_MAX_REJECTED_FILES": "0", + "TRACEWICK_MAX_STACKS": "8", "TRACEWICK_MAX_FRAMES": "16", "TRACEWICK_MAX_STRINGS": "32", + "TRACEWICK_MAX_HELD_DECODED_BYTES": "65536", "TRACEWICK_MAX_IN_FLIGHT_BYTES": "131072", + }.get) + if err != nil { + t.Fatal(err) + } + if cfg.ReaderID != "env-reader" || cfg.AggregationWindowSec != 10 || cfg.Sleep != 250*time.Millisecond || cfg.ShutdownGrace != 0 || cfg.MaxRejectedFiles != 0 { + t.Fatalf("unexpected operational settings: %#v", cfg) + } + limits := cfg.DeliveryLimits() + if limits.MaxStacks != 8 || limits.MaxFrames != 16 || limits.MaxStrings != 32 || limits.MaxHeldDecodedBytes != 65536 || limits.MaxInFlightBytes != 131072 { + t.Fatalf("limits: %#v", limits) + } +} + +func TestOperationalEnvironmentPrecedenceAndValidation(t *testing.T) { + t.Parallel() + for _, tc := range []struct{ flag, variable, valid, invalid string }{ + {"reader-id", "TRACEWICK_READER_ID", "reader", "a/b"}, + {"aggregation-window", "TRACEWICK_AGGREGATION_WINDOW", "10", "9"}, + {"sleep", "TRACEWICK_SLEEP", "250ms", "bad"}, + {"shutdown-grace", "TRACEWICK_SHUTDOWN_GRACE", "0s", "-1s"}, + {"max-rejected-files", "TRACEWICK_MAX_REJECTED_FILES", "0", "100001"}, + {"max-stacks", "TRACEWICK_MAX_STACKS", "10", "-1"}, + {"max-frames", "TRACEWICK_MAX_FRAMES", "20", "-1"}, + {"max-strings", "TRACEWICK_MAX_STRINGS", "30", "-1"}, + {"max-held-decoded-bytes", "TRACEWICK_MAX_HELD_DECODED_BYTES", "65536", "9223372036854775808"}, + {"max-in-flight-bytes", "TRACEWICK_MAX_IN_FLIGHT_BYTES", "131072", "-1"}, + } { + t.Run(tc.flag, func(t *testing.T) { + required := []string{"--spool-dir=/spool", "--pyroscope-url=http://localhost:4040"} + baseline, err := config.Load(append(required, "--"+tc.flag+"="+tc.valid), envMap{}.get) + if err != nil { + t.Fatal(err) + } + fromEnv, err := config.Load(required, envMap{tc.variable: tc.valid}.get) + if err != nil || fromEnv != baseline { + t.Fatalf("env mismatch: %v %#v", err, fromEnv) + } + for _, args := range [][]string{ + append(required, "--"+tc.flag+"="+tc.valid), + append(required, "--"+tc.flag, tc.valid), + } { + actual, loadErr := config.Load(args, envMap{tc.variable: tc.invalid}.get) + if loadErr != nil || actual != baseline { + t.Fatalf("CLI override: %v %#v", loadErr, actual) + } + } + if _, loadErr := config.Load(required, envMap{tc.variable: tc.invalid}.get); loadErr == nil { + t.Fatal("invalid env accepted") + } + empty, err := config.Load(required, envMap{tc.variable: ""}.get) + defaults, defaultErr := config.Load(required, envMap{}.get) + if err != nil || defaultErr != nil || empty != defaults { + t.Fatalf("empty env: %v %v", err, defaultErr) + } + explicit, err := config.Load(append(required, "--"+tc.flag+"="), envMap{tc.variable: tc.valid}.get) + if tc.flag == "reader-id" { + if err != nil || explicit.ReaderID == tc.valid || explicit.ReaderID == "" { + t.Fatalf("reader reset: %v", err) + } + } else if err == nil { + t.Fatal("empty numeric/duration CLI accepted") + } + if _, err := config.Load([]string{"--help"}, envMap{tc.variable: tc.invalid}.get); !config.IsHelp(err) { + t.Fatalf("help blocked: %v", err) + } + }) + } +} + +func TestExplicitEmptyStringsOverrideEnvironment(t *testing.T) { + t.Parallel() + cfg, err := config.Load([]string{"--spool-dir=/spool", "--pyroscope-url=http://localhost:4040", "--pyroscope-tenant=", "--metrics-listen=", "--tls-ca=", "--pyroscope-user="}, envMap{ + "TRACEWICK_PYROSCOPE_TENANT": "tenant", "TRACEWICK_METRICS_LISTEN": ":9090", "TRACEWICK_TLS_CA": "/ca.pem", "TRACEWICK_PYROSCOPE_USER": "user", + }.get) + if err != nil || cfg.PyroscopeTenant != "" || cfg.MetricsListen != "" || cfg.TLSCAFile != "" || cfg.PyroscopeUser != "" { + t.Fatalf("clear settings: %v %#v", err, cfg) + } + _, err = config.Load([]string{"--spool-dir=/spool", "--pyroscope-url=http://localhost:4040", "--pyroscope-user="}, envMap{"TRACEWICK_PYROSCOPE_USER": "u", "TRACEWICK_PYROSCOPE_PASSWORD": "secret"}.get) + if err == nil || !strings.Contains(err.Error(), "authentication") { + t.Fatalf("cleared auth user: %v", err) + } + for _, flag := range []string{"--spool-dir=", "--pyroscope-url="} { + _, err = config.Load([]string{flag}, envMap{"TRACEWICK_SPOOL_DIR": "/spool", "TRACEWICK_PYROSCOPE_URL": "http://localhost:4040"}.get) + if err == nil { + t.Fatalf("empty required value accepted: %s", flag) + } + } +} + +func TestZeroEnvironmentBudgetsKeepDeliveryDefaults(t *testing.T) { + t.Parallel() + args := []string{"--spool-dir=/spool", "--pyroscope-url=http://localhost:4040"} + baseline, err := config.Load(args, envMap{}.get) + if err != nil { + t.Fatal(err) + } + cfg, err := config.Load(args, envMap{ + "TRACEWICK_MAX_STACKS": "0", "TRACEWICK_MAX_FRAMES": "0", "TRACEWICK_MAX_STRINGS": "0", + "TRACEWICK_MAX_HELD_DECODED_BYTES": "0", "TRACEWICK_MAX_IN_FLIGHT_BYTES": "0", "TRACEWICK_SLEEP": "0s", + }.get) + if err != nil || cfg.DeliveryLimits() != baseline.DeliveryLimits() || cfg.Sleep != 0 { + t.Fatalf("zero overrides: %v %#v", err, cfg) + } +} diff --git a/release-please-config.json b/release-please-config.json index c2b7971..b2cb018 100644 --- a/release-please-config.json +++ b/release-please-config.json @@ -1,6 +1,9 @@ { "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json", "release-type": "simple", + "versioning": "prerelease", + "prerelease-type": "rc", + "prerelease": true, "bump-minor-pre-major": true, "include-component-in-tag": false, "include-v-in-tag": true, 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() diff --git a/test/e2e/README.md b/test/e2e/README.md index 8f6817b..f92a907 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -18,10 +18,12 @@ still runs (httptest). CI `e2e.yml` starts the stand and exports the env. ## Release posture -README marks **beta (`0.2.x`)**, not production readiness. Keep release cuts +README marks **release candidate (`1.0.0-rc.1`)**, not production readiness. Keep release cuts (GoReleaser), honest unsigned notes until cosign, and soak via [`tracewick/benchmarks`](https://github.com/tracewick/benchmarks). E2E here covers stand, Toxiproxy chaos, Querier live, and Go + PHP-drain coexistence. +`make php-drain` installs the published core `1.0.0-rc.1` for this candidate's +coexistence check; version numbers do not replace the spool v2 contract. ## Canon (parity with `tracewick/tracewick`) @@ -46,7 +48,8 @@ covers stand, Toxiproxy chaos, Querier live, and Go + PHP-drain coexistence. `make e2e` uses `-v` so lines prefixed `e2e:` show progress in CI. - Done: UID-mismatch (Docker volume, wrong UID vs matching `33`) — `TestUIDMismatchCannotClaimMatchingCan` (skips without docker). -- Next: benchmarks soak. Mutation MSI gate is `make mutation` (Checks step, not +- Load/soak evidence lives in benchmarks with its own source pins; it is not + produced by this E2E suite. Mutation MSI gate is `make mutation` (Checks step, not e2e). FakeHttp-class faults live under `internal/testhttp` + `internal/pyroscope` (unit). diff --git a/test/e2e/environment_test.go b/test/e2e/environment_test.go new file mode 100644 index 0000000..e46c8c7 --- /dev/null +++ b/test/e2e/environment_test.go @@ -0,0 +1,54 @@ +//go:build e2e + +package e2e_test + +import ( + "context" + "os" + "os/exec" + "strings" + "testing" + "time" +) + +func TestExecutableEnvironmentConfiguration(t *testing.T) { + bin := agentBinary(t) + env := []string{} + for _, entry := range os.Environ() { + if !strings.HasPrefix(entry, "TRACEWICK_") { + env = append(env, entry) + } + } + env = append(env, + "TRACEWICK_SPOOL_DIR="+t.TempDir(), "TRACEWICK_PYROSCOPE_URL=http://127.0.0.1:1", + "TRACEWICK_READER_ID=env-process", "TRACEWICK_SLEEP=bad", "TRACEWICK_AGGREGATION_WINDOW=10", + "TRACEWICK_MAX_STACKS=4096", "TRACEWICK_MAX_FRAMES=16384", "TRACEWICK_MAX_STRINGS=32768", + "TRACEWICK_MAX_HELD_DECODED_BYTES=67108864", "TRACEWICK_MAX_IN_FLIGHT_BYTES=67108864", + "TRACEWICK_SHUTDOWN_GRACE=0s", "TRACEWICK_MAX_REJECTED_FILES=0", + ) + for _, tc := range []struct { + name string + args []string + wantError bool + message string + }{ + {"invalid env", []string{"run", "--once"}, true, "--sleep"}, + {"CLI overrides invalid env", []string{"run", "--once", "--sleep=0s"}, false, ""}, + {"explicit empty required", []string{"run", "--once", "--sleep=0s", "--spool-dir="}, true, "spool-dir"}, + {"help ignores invalid env", []string{"run", "--help"}, false, "TRACEWICK_SLEEP"}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, bin, tc.args...) + cmd.Env = env + output, err := cmd.CombinedOutput() + if (err != nil) != tc.wantError || ctx.Err() != nil { + t.Fatalf("exit: %v timeout: %v output: %s", err, ctx.Err(), output) + } + if !strings.Contains(string(output), tc.message) { + t.Fatalf("expected %q: %s", tc.message, output) + } + }) + } +}