From 3e78a4535021442c8b44973b9c490d00c65976c3 Mon Sep 17 00:00:00 2001 From: Jon Langevin Date: Wed, 25 Nov 2026 18:33:00 -0500 Subject: [PATCH 1/8] Pin and verify the Compute plugin release engine --- .github/workflows/archive-qualification.yml | 40 +++++++++++++++------ .github/workflows/release.yml | 32 +++++++++++++++-- scripts/check-release-archives_test.go | 40 +++++++++++++++++++-- 3 files changed, 96 insertions(+), 16 deletions(-) diff --git a/.github/workflows/archive-qualification.yml b/.github/workflows/archive-qualification.yml index 5a8208e..077c6ef 100644 --- a/.github/workflows/archive-qualification.yml +++ b/.github/workflows/archive-qualification.yml @@ -26,7 +26,7 @@ jobs: - uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7 with: distribution: goreleaser - version: v2.16.0 + version: v2.20.3 install-only: true - name: Bind source and immutable inputs before credentials id: scratch @@ -50,12 +50,20 @@ jobs: de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum fdce18cb82d409b7b3f70a0ed8fb8e28124fb3ee17f5783321249d6fbbad5609 scripts/check-release-archives.go - f964d19512034d68ec83a3b5d84209525511948cc6888cce20448ed827178ce6 scripts/check-release-archives_test.go + f725dfd8abea97fd54d066eb4dcccd9a0c635bcc0e6285e28aab5f463872f33f scripts/check-release-archives_test.go INPUTS test "$(go version)" = 'go version go1.27.4 linux/amd64' - goreleaser --version | tee "$RUNNER_TEMP/archive-goreleaser-version.txt" - grep -Eq '(^|[[:space:]])v?2[.]16[.]0([[:space:]]|$)' "$RUNNER_TEMP/archive-goreleaser-version.txt" - sha256sum "$(command -v go)" "$(command -v goreleaser)" + ENGINE_BIN="$(command -v goreleaser)" + verify_engine() { + case "$ENGINE_BIN" in /*) ;; *) return 1 ;; esac + test -f "$ENGINE_BIN" && test ! -L "$ENGINE_BIN" || return 1 + printf '%s %s\n' 'd124b61b79baf6d7e2727bb018e7115c045c076df82c13795bb19f9ace4b612d' "$ENGINE_BIN" | shasum -a 256 --check --strict + } + verify_engine + "$ENGINE_BIN" --version | tee "$RUNNER_TEMP/archive-goreleaser-version.txt" + grep -Eq '(^|[[:space:]])v?2[.]20[.]3([[:space:]]|$)' "$RUNNER_TEMP/archive-goreleaser-version.txt" + sha256sum "$(command -v go)" "$ENGINE_BIN" + printf 'engine_bin=%s\n' "$ENGINE_BIN" >> "$GITHUB_OUTPUT" printf 'merge=%s head=%s base=%s tree=%s\n' "$EXPECTED_SHA" "$PR_HEAD" "$PR_BASE" "$(git rev-parse 'HEAD^{tree}')" root="$(mktemp -d "$RUNNER_TEMP/archive-qualification.XXXXXXXX")" mkdir "$root/module-cache" "$root/build-cache" "$root/gopath" "$root/acquire-tmp" @@ -101,6 +109,7 @@ jobs: env: OWNED_ROOT: ${{ steps.scratch.outputs.root }} EXPECTED_SHA: ${{ github.sha }} + ENGINE_BIN: ${{ steps.scratch.outputs.engine_bin }} shell: bash --noprofile --norc -euo pipefail {0} run: | # Actual archives remain on the disposable runner. No upload step. @@ -110,11 +119,11 @@ jobs: de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum fdce18cb82d409b7b3f70a0ed8fb8e28124fb3ee17f5783321249d6fbbad5609 scripts/check-release-archives.go - f964d19512034d68ec83a3b5d84209525511948cc6888cce20448ed827178ce6 scripts/check-release-archives_test.go + f725dfd8abea97fd54d066eb4dcccd9a0c635bcc0e6285e28aab5f463872f33f scripts/check-release-archives_test.go INPUTS home="$(mktemp -d "$OWNED_ROOT/package-home.XXXXXXXX")" tmp="$(mktemp -d "$OWNED_ROOT/package-tmp.XXXXXXXX")" - tool_path="$(dirname "$(command -v go)"):$(dirname "$(command -v goreleaser)"):/usr/bin:/bin" + tool_path="$(dirname "$(command -v go)"):$(dirname "$ENGINE_BIN"):/usr/bin:/bin" clean() { env -i PATH="$tool_path" HOME="$home" TMPDIR="$tmp" \ GOTOOLCHAIN=local GOENV=off GOWORK=off GOAUTH=off GOTELEMETRY=off \ @@ -123,16 +132,25 @@ jobs: GOFLAGS='-p=1' GOMAXPROCS=2 GOMEMLIMIT=768MiB \ GOPATH="$OWNED_ROOT/gopath" GOMODCACHE="$OWNED_ROOT/module-cache" GOCACHE="$OWNED_ROOT/build-cache" "$@" } + verify_engine() { + case "$ENGINE_BIN" in /*) ;; *) return 1 ;; esac + test -f "$ENGINE_BIN" && test ! -L "$ENGINE_BIN" || return 1 + printf '%s %s\n' 'd124b61b79baf6d7e2727bb018e7115c045c076df82c13795bb19f9ace4b612d' "$ENGINE_BIN" | shasum -a 256 --check --strict + } + checked_engine() { + verify_engine || return "$?" + clean "$ENGINE_BIN" "$@" + } clean go run ./scripts/check-build-toolchain.go (cd scripts && clean go test -count=1 -timeout=45s check-release-archives.go check-release-archives_test.go) clean go run ./scripts/check-release-archives.go capture "$EXPECTED_SHA" "$OWNED_ROOT/before.json" - clean goreleaser check --config=.goreleaser.yaml - clean goreleaser release --config=.goreleaser.yaml --snapshot --clean --skip=publish,sign,notarize,sbom,docker,ko --parallelism=1 --timeout=10m + checked_engine check --config=.goreleaser.yaml + checked_engine release --config=.goreleaser.yaml --snapshot --clean --skip=publish,sign,notarize,sbom,docker,ko --parallelism=1 --timeout=10m clean go run ./scripts/check-release-archives.go verify "$EXPECTED_SHA" "$OWNED_ROOT/before.json" "$OWNED_ROOT/extracted" clean go run ./scripts/check-build-toolchain.go "$OWNED_ROOT/extracted/linux-amd64/workflow-plugin-compute" clean go run ./scripts/check-build-toolchain.go "$OWNED_ROOT/extracted/darwin-arm64/workflow-plugin-compute" owned_kib="$(du -sk "$OWNED_ROOT" | cut -f1)" dist_kib="$(du -sk dist | cut -f1)" test "$((owned_kib + dist_kib))" -lt 4194304 - # This is snapshot/compiler/archive evidence only. An upcoming gate is - # reconciling Release's floating '~> v2' engine before official release. + # This is snapshot/compiler/archive evidence only. Official release + # still requires authenticated engine bytes and tag-mode qualification. diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6295236..b8a2b09 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -35,13 +35,39 @@ jobs: chmod +x "${RUNNER_TEMP}/wfctl-bin/wfctl" - name: Validate plugin contract for publish (pre-build) run: "${{ runner.temp }}/wfctl-bin/wfctl plugin validate-contract --for-publish --tag ${{ github.ref_name }} ." - - uses: goreleaser/goreleaser-action@v7 + - uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7 with: distribution: goreleaser - version: '~> v2' - args: release --clean + version: v2.20.3 + install-only: true + - name: Publish with verified GoReleaser + shell: bash --noprofile --norc -euo pipefail {0} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + ENGINE_BIN="$(command -v goreleaser)" + verify_engine() { + case "$ENGINE_BIN" in /*) ;; *) return 1 ;; esac + test -f "$ENGINE_BIN" && test ! -L "$ENGINE_BIN" || return 1 + printf '%s %s\n' 'd124b61b79baf6d7e2727bb018e7115c045c076df82c13795bb19f9ace4b612d' "$ENGINE_BIN" | shasum -a 256 --check --strict + } + verify_engine + "$ENGINE_BIN" release --clean + # Preserve successful artifact/metadata log groups. Previous unnamed + # action outputs had no consumers. + for kind in artifacts metadata; do + metadata="dist/$kind.json" + if [ -s "$metadata" ]; then + content="$(cat "$metadata")" + if [ "$content" != null ]; then + label='Metadata output' + if [ "$kind" = artifacts ]; then label='Artifacts output'; fi + printf '::group::%s\n' "$label" + printf '%s\n' "$content" + echo '::endgroup::' + fi + fi + done # workflow#765: runtime truth-check via plugin verify-capabilities. - name: Verify capabilities (runtime truth-check) if: >- diff --git a/scripts/check-release-archives_test.go b/scripts/check-release-archives_test.go index a0d84f5..fe9a81f 100644 --- a/scripts/check-release-archives_test.go +++ b/scripts/check-release-archives_test.go @@ -30,13 +30,14 @@ func workflowContract(b string) bool { "actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803", "actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16", "goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de", - "version: v2.16.0", "install-only: true", "GOTOOLCHAIN: local", + "version: v2.20.3", "install-only: true", "GOTOOLCHAIN: local", + "v?2[.]20[.]3", "check --config=.goreleaser.yaml", "release --config=.goreleaser.yaml --snapshot --clean", "--skip=publish,sign,notarize,sbom,docker,ko --parallelism=1 --timeout=10m", "GOPROXY=off", "GOVCS='*:off'", "GOSUMDB=off", "env -i", "check-release-archives.go capture", "check-release-archives.go verify", "extracted/linux-amd64/workflow-plugin-compute", "extracted/darwin-arm64/workflow-plugin-compute", - "upcoming gate", "floating", "~> v2", + "authenticated engine bytes", "tag-mode qualification", } { if !strings.Contains(b, required) { return false @@ -74,6 +75,39 @@ func TestArchiveWorkflow(t *testing.T) { } } +func TestArchiveReleaseEngineParity(t *testing.T) { + for _, name := range []string{"archive-qualification.yml", "release.yml"} { + b, err := os.ReadFile("../.github/workflows/" + name) + if err != nil { + t.Fatal(err) + } + for _, required := range []string{ + "goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de", + "version: v2.20.3", + "d124b61b79baf6d7e2727bb018e7115c045c076df82c13795bb19f9ace4b612d", + "shasum -a 256 --check --strict", + "test -f \"$ENGINE_BIN\" && test ! -L \"$ENGINE_BIN\"", + } { + count := 1 + if name == "archive-qualification.yml" && (strings.HasPrefix(required, "d124") || strings.Contains(required, "shasum") || strings.HasPrefix(required, "test -f")) { + count = 2 // pre-credential binding and pre-execution recheck + } + if strings.Count(string(b), required) != count { + t.Errorf("%s must pin the shared engine contract: %s", name, required) + } + } + if name == "archive-qualification.yml" { + for _, required := range []string{"verify_engine\n \"$ENGINE_BIN\" --version", "clean \"$ENGINE_BIN\" \"$@\"", "checked_engine check --config", "checked_engine release --config", "ENGINE_BIN: ${{ steps.scratch.outputs.engine_bin }}"} { + if !strings.Contains(string(b), required) { + t.Errorf("archive engine binding missing: %s", required) + } + } + } else if strings.Contains(string(b), "args: release --clean") || !strings.Contains(string(b), "verify_engine\n \"$ENGINE_BIN\" release --clean") || !strings.Contains(string(b), "install-only: true") { + t.Error("release must install without execution, then verify and use the same absolute engine") + } + } +} + func TestArchiveWorkflowRefusals(t *testing.T) { b, err := os.ReadFile("../.github/workflows/archive-qualification.yml") if err != nil { @@ -84,6 +118,8 @@ func TestArchiveWorkflowRefusals(t *testing.T) { {"implicit-config", "check --config=.goreleaser.yaml", "check"}, {"publish", "--skip=publish,sign", "--skip=sign"}, {"old-compiler", "go-version: '1.27.4'", "go-version: '1.26.11'"}, + {"old-engine", "version: v2.20.3", "version: v2.16.0"}, + {"old-engine-guard", "v?2[.]20[.]3", "v?2[.]16[.]0"}, {"mutable-action", "actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16", "actions/setup-go@v6"}, {"code-during-acquisition", "mod tidy -diff", "run ./script.go"}, {"unrestricted-vcs", "GOVCS='*:off'", "GOVCS='*:all'"}, From 37bc1cd744ea1192676a64f202fa53fcd6d165cb Mon Sep 17 00:00:00 2001 From: Jon Langevin Date: Wed, 25 Nov 2026 18:58:01 -0500 Subject: [PATCH 2/8] Validate GoReleaser v2.20.3 metadata wire type --- .github/workflows/archive-qualification.yml | 8 +-- scripts/check-release-archives.go | 7 +-- scripts/check-release-archives_test.go | 55 ++++++++++++++++++++- 3 files changed, 62 insertions(+), 8 deletions(-) diff --git a/.github/workflows/archive-qualification.yml b/.github/workflows/archive-qualification.yml index 077c6ef..3ed9880 100644 --- a/.github/workflows/archive-qualification.yml +++ b/.github/workflows/archive-qualification.yml @@ -49,8 +49,8 @@ jobs: 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum - fdce18cb82d409b7b3f70a0ed8fb8e28124fb3ee17f5783321249d6fbbad5609 scripts/check-release-archives.go - f725dfd8abea97fd54d066eb4dcccd9a0c635bcc0e6285e28aab5f463872f33f scripts/check-release-archives_test.go + c33b50d1a150abdae97a710ec8d4607528e00e87a164214945b16af29afab00a scripts/check-release-archives.go + 3aedb5a4b7a0723210a8dd33c4cead8fe6d0215c520aa215033df1d5b5b3149e scripts/check-release-archives_test.go INPUTS test "$(go version)" = 'go version go1.27.4 linux/amd64' ENGINE_BIN="$(command -v goreleaser)" @@ -118,8 +118,8 @@ jobs: 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum - fdce18cb82d409b7b3f70a0ed8fb8e28124fb3ee17f5783321249d6fbbad5609 scripts/check-release-archives.go - f725dfd8abea97fd54d066eb4dcccd9a0c635bcc0e6285e28aab5f463872f33f scripts/check-release-archives_test.go + c33b50d1a150abdae97a710ec8d4607528e00e87a164214945b16af29afab00a scripts/check-release-archives.go + 3aedb5a4b7a0723210a8dd33c4cead8fe6d0215c520aa215033df1d5b5b3149e scripts/check-release-archives_test.go INPUTS home="$(mktemp -d "$OWNED_ROOT/package-home.XXXXXXXX")" tmp="$(mktemp -d "$OWNED_ROOT/package-tmp.XXXXXXXX")" diff --git a/scripts/check-release-archives.go b/scripts/check-release-archives.go index 346f677..2dfb123 100644 --- a/scripts/check-release-archives.go +++ b/scripts/check-release-archives.go @@ -781,9 +781,10 @@ func verifySnapshot(root, sha string, before *sourceState, extract string) (*arc seen := map[string]bool{} metadataCount, checksumCount := 0, 0 for _, a := range artifacts { - // v2.16.0 emits both the enum and its human-readable type. They must - // describe the same record, not provide two competing classifications. - kind := map[string]int{"Binary": 4, "Archive": 1, "Checksum": 12, "Metadata": 35}[a.Type] + // The pinned v2.20.3 engine emits both the enum and its human-readable + // type. Metadata is 36 after WingetLocale was added; do not accept the + // old v2.16.0 value or conflicting classifications. + kind := map[string]int{"Binary": 4, "Archive": 1, "Checksum": 12, "Metadata": 36}[a.Type] if kind == 0 || a.Internal != kind { return nil, fmt.Errorf("artifact wire type mismatch") } diff --git a/scripts/check-release-archives_test.go b/scripts/check-release-archives_test.go index fe9a81f..5d664fc 100644 --- a/scripts/check-release-archives_test.go +++ b/scripts/check-release-archives_test.go @@ -804,7 +804,15 @@ func TestRealArchiveProvenance(t *testing.T) { effective := []byte("# Synthetic metadata fixture; no GoReleaser execution.\nversion: 2\nproject_name: workflow-plugin-compute\n") writeFixture(t, filepath.Join(root, "dist/config.yaml"), effective) writeFixture(t, filepath.Join(root, "dist/checksums.txt"), []byte(checksums)) - artifacts = append(artifacts, releaseArtifact{Name: "checksums.txt", Path: "dist/checksums.txt", Type: "Checksum", Internal: 12}, releaseArtifact{Name: "metadata.json", Path: "dist/metadata.json", Type: "Metadata", Internal: 35}) + // Official v2.20.3 artifact enum/String/JSON tags (artifact.go blob + // 2cd550fa9ad2fcce89822b2b4ea367af617f849b): WingetLocale shifts + // Metadata to 36. This literal also comes from the isolated exact-source + // serializer probe; it is not evidence of GoReleaser archive execution. + var metadataArtifact releaseArtifact + if e = decodeExact([]byte(`{"name":"metadata.json","path":"dist/metadata.json","internal_type":36,"type":"Metadata"}`), &metadataArtifact); e != nil { + t.Fatal(e) + } + artifacts = append(artifacts, releaseArtifact{Name: "checksums.txt", Path: "dist/checksums.txt", Type: "Checksum", Internal: 12}, metadataArtifact) index, e := json.Marshal(artifacts) if e != nil { t.Fatal(e) @@ -824,6 +832,51 @@ func TestRealArchiveProvenance(t *testing.T) { if e = decodeExact(output, &report); e != nil || len(report.Archives) != 2 || report.Commit != sha { t.Fatalf("actual CLI refused synthetic producer bytes: %v", e) } + for _, tc := range []struct { + name, diagnostic string + mutate func(map[string]any) + }{ + {"metadata-v2.16.0-code", "artifact wire type mismatch", func(m map[string]any) { m["internal_type"] = 35 }}, + {"metadata-other-enum", "artifact wire type mismatch", func(m map[string]any) { m["internal_type"] = 37 }}, + {"metadata-missing-code", "artifact wire type mismatch", func(m map[string]any) { delete(m, "internal_type") }}, + {"metadata-zero-code", "artifact wire type mismatch", func(m map[string]any) { m["internal_type"] = 0 }}, + {"metadata-conflicting-label", "artifact wire type mismatch", func(m map[string]any) { m["type"] = "Binary" }}, + {"metadata-conflicting-code", "artifact wire type mismatch", func(m map[string]any) { m["internal_type"] = 4 }}, + {"metadata-string-code", "cannot unmarshal string", func(m map[string]any) { m["internal_type"] = "36" }}, + {"metadata-unknown-field", "unknown field", func(m map[string]any) { m["unrecognized_wire_field"] = true }}, + } { + t.Run(tc.name, func(t *testing.T) { + var bad []map[string]any + if e := json.Unmarshal(index, &bad); e != nil { + t.Fatal(e) + } + m := bad[len(bad)-1] + if m["name"] != "metadata.json" || m["internal_type"] != float64(36) || m["type"] != "Metadata" { + t.Fatal("official metadata mutation input changed") + } + tc.mutate(m) + b, e := json.Marshal(bad) + if e != nil { + t.Fatal(e) + } + writeFixture(t, filepath.Join(root, "dist/artifacts.json"), b) + defer writeFixture(t, filepath.Join(root, "dist/artifacts.json"), index) + extract := filepath.Join(owned, "refusal-"+tc.name) + cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin", "go"), "run", script, "verify", sha, stateFile, extract) + cmd.Dir = root + cmd.Env = append(os.Environ(), "GO111MODULE=off", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOPROXY=off", "GOSUMDB=off", "GOVCS=*:off", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null") + var stdout, stderr boundedOutput + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + exit, ok := err.(*exec.ExitError) + if !ok || exit.ExitCode() != 1 || stdout.b.Len() != 0 || stdout.overflow || stderr.overflow || !strings.Contains(stderr.b.String(), tc.diagnostic) { + t.Fatalf("actual CLI did not enforce wire refusal %s: %v", tc.name, err) + } + if _, e := os.Lstat(extract); !os.IsNotExist(e) { + t.Fatal("wire refusal created extraction output") + } + }) + } t.Run("original-manifest-raw-byte-binding", func(t *testing.T) { if !bytes.Equal(report.Source.Manifest, originalManifest) || report.Source.Files["plugin.json"].SHA256 != checksumBytes(originalManifest) { t.Fatal("actual capture/verify receipt did not preserve original manifest bytes") From a1f13070fce271f17c2865f3d48e63c94e9fd718 Mon Sep 17 00:00:00 2001 From: Jon Langevin Date: Wed, 25 Nov 2026 19:21:11 -0500 Subject: [PATCH 3/8] Validate the native plugin binary before release upload --- .github/workflows/archive-qualification.yml | 15 +- .github/workflows/release.yml | 31 +- .goreleaser.yaml | 2 + scripts/check-native-release.go | 177 ++++++++++++ scripts/check-native-release_test.go | 301 ++++++++++++++++++++ scripts/check-release-archives_test.go | 42 ++- 6 files changed, 542 insertions(+), 26 deletions(-) create mode 100644 scripts/check-native-release.go create mode 100644 scripts/check-native-release_test.go diff --git a/.github/workflows/archive-qualification.yml b/.github/workflows/archive-qualification.yml index 3ed9880..b8de1ff 100644 --- a/.github/workflows/archive-qualification.yml +++ b/.github/workflows/archive-qualification.yml @@ -40,17 +40,19 @@ jobs: [[ "$PR_HEAD" =~ ^[0-9a-f]{40}$ && "$PR_BASE" =~ ^[0-9a-f]{40}$ ]] test "$(git rev-parse HEAD)" = "$EXPECTED_SHA" test -z "$(git status --porcelain=v1 --untracked-files=all --ignored)" - for file in .goreleaser.yaml scripts/check-build-toolchain.go go.mod go.sum scripts/check-release-archives.go scripts/check-release-archives_test.go; do + for file in .goreleaser.yaml scripts/check-build-toolchain.go go.mod go.sum scripts/check-release-archives.go scripts/check-release-archives_test.go scripts/check-native-release.go scripts/check-native-release_test.go; do test -f "$file" && test ! -L "$file" done # Update these anchors together only after reviewing the affected bytes. sha256sum --check --strict <<'INPUTS' - ca7391c22eba7e030ad815c194da6c2ab40869a1936c8b2a2790895de3dd9baa .goreleaser.yaml + 8255a10418c3bcf015986e46a0bcf167fedbd80a66b81923d7095fd430653eff .goreleaser.yaml 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum c33b50d1a150abdae97a710ec8d4607528e00e87a164214945b16af29afab00a scripts/check-release-archives.go - 3aedb5a4b7a0723210a8dd33c4cead8fe6d0215c520aa215033df1d5b5b3149e scripts/check-release-archives_test.go + c87a9f0af027d073abc719b93ca6b2f1ec51c759891e3c8583dc126faf593855 scripts/check-release-archives_test.go + 254ac8d98a27300226ad38c9a849a084dd252438eb1f1a9f7e97d44c8f02e2a4 scripts/check-native-release.go + ad5b7c651d394e79028a03f387afbca8ecbaedff6811f93e52ed7b00019a880e scripts/check-native-release_test.go INPUTS test "$(go version)" = 'go version go1.27.4 linux/amd64' ENGINE_BIN="$(command -v goreleaser)" @@ -114,12 +116,14 @@ jobs: run: | # Actual archives remain on the disposable runner. No upload step. sha256sum --check --strict <<'INPUTS' - ca7391c22eba7e030ad815c194da6c2ab40869a1936c8b2a2790895de3dd9baa .goreleaser.yaml + 8255a10418c3bcf015986e46a0bcf167fedbd80a66b81923d7095fd430653eff .goreleaser.yaml 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum c33b50d1a150abdae97a710ec8d4607528e00e87a164214945b16af29afab00a scripts/check-release-archives.go - 3aedb5a4b7a0723210a8dd33c4cead8fe6d0215c520aa215033df1d5b5b3149e scripts/check-release-archives_test.go + c87a9f0af027d073abc719b93ca6b2f1ec51c759891e3c8583dc126faf593855 scripts/check-release-archives_test.go + 254ac8d98a27300226ad38c9a849a084dd252438eb1f1a9f7e97d44c8f02e2a4 scripts/check-native-release.go + ad5b7c651d394e79028a03f387afbca8ecbaedff6811f93e52ed7b00019a880e scripts/check-native-release_test.go INPUTS home="$(mktemp -d "$OWNED_ROOT/package-home.XXXXXXXX")" tmp="$(mktemp -d "$OWNED_ROOT/package-tmp.XXXXXXXX")" @@ -143,6 +147,7 @@ jobs: } clean go run ./scripts/check-build-toolchain.go (cd scripts && clean go test -count=1 -timeout=45s check-release-archives.go check-release-archives_test.go) + (cd scripts && clean go test -count=1 -timeout=45s check-native-release.go check-native-release_test.go) clean go run ./scripts/check-release-archives.go capture "$EXPECTED_SHA" "$OWNED_ROOT/before.json" checked_engine check --config=.goreleaser.yaml checked_engine release --config=.goreleaser.yaml --snapshot --clean --skip=publish,sign,notarize,sbom,docker,ko --parallelism=1 --timeout=10m diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b8a2b09..f3b2413 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -26,13 +26,17 @@ jobs: run: | git config --global url."https://x-access-token:${RELEASES_TOKEN}@github.com/GoCodeAlone/".insteadOf "https://github.com/GoCodeAlone/" go env -w GOPRIVATE=github.com/GoCodeAlone/* - - name: Install wfctl v0.78.2 + - name: Install authenticated wfctl v0.78.2 + shell: bash --noprofile --norc -euo pipefail {0} run: | - mkdir -p "${RUNNER_TEMP}/wfctl-bin" + umask 077 + mkdir "${RUNNER_TEMP}/wfctl-bin" curl -sSfL -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \ -o "${RUNNER_TEMP}/wfctl-bin/wfctl" \ "https://github.com/GoCodeAlone/workflow/releases/download/v0.78.2/wfctl-linux-amd64" - chmod +x "${RUNNER_TEMP}/wfctl-bin/wfctl" + test -f "${RUNNER_TEMP}/wfctl-bin/wfctl" && test ! -L "${RUNNER_TEMP}/wfctl-bin/wfctl" + printf '%s %s\n' '0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8' "${RUNNER_TEMP}/wfctl-bin/wfctl" | shasum -a 256 --check --strict + chmod 500 "${RUNNER_TEMP}/wfctl-bin/wfctl" - name: Validate plugin contract for publish (pre-build) run: "${{ runner.temp }}/wfctl-bin/wfctl plugin validate-contract --for-publish --tag ${{ github.ref_name }} ." - uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7 @@ -44,6 +48,7 @@ jobs: shell: bash --noprofile --norc -euo pipefail {0} env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + WFCTL_BIN: ${{ runner.temp }}/wfctl-bin/wfctl run: | ENGINE_BIN="$(command -v goreleaser)" verify_engine() { @@ -68,23 +73,9 @@ jobs: fi fi done - # workflow#765: runtime truth-check via plugin verify-capabilities. - - name: Verify capabilities (runtime truth-check) - if: >- - !github.event.deleted - && !contains(github.ref_name, '-') - && github.repository == 'GoCodeAlone/workflow-plugin-compute' - run: | - RUNNER_ARCH=$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/') - BIN=$(jq -r --arg arch "$RUNNER_ARCH" \ - '[.[] | select(.type=="Binary" and .goos=="linux" and .goarch==$arch and (.name|startswith("workflow-plugin-compute")))] | .[0].path // ""' \ - dist/artifacts.json) - if [ -z "$BIN" ] || [ "$BIN" = "null" ]; then - echo "::warning::No matching linux/$RUNNER_ARCH binary in dist/artifacts.json; skipping verify-capabilities" - jq '.[] | {name, type, goos, goarch, path}' dist/artifacts.json - exit 0 - fi - "${{ runner.temp }}/wfctl-bin/wfctl" plugin verify-capabilities --binary "$BIN" . + # Runtime identity/version and declared-IaC validation now runs as the + # native build post-hook before archives/publishing. Full capability-list + # parity and cross-platform runtime acceptance are not asserted. notify-workflow-registry: name: Notify workflow-registry diff --git a/.goreleaser.yaml b/.goreleaser.yaml index ad80d5e..f9793d9 100644 --- a/.goreleaser.yaml +++ b/.goreleaser.yaml @@ -20,6 +20,8 @@ builds: post: - cmd: 'env GOOS= GOARCH= go run ./scripts/check-build-toolchain.go "{{ .Path }}"' output: true + - cmd: 'env GOOS= GOARCH= go run ./scripts/check-native-release.go "{{ .Os }}" "{{ .Arch }}" "{{ .Path }}" "{{ .IsSnapshot }}"' + output: true env: - CGO_ENABLED=0 - GOPRIVATE=github.com/GoCodeAlone/* diff --git a/scripts/check-native-release.go b/scripts/check-native-release.go new file mode 100644 index 0000000..d89e87d --- /dev/null +++ b/scripts/check-native-release.go @@ -0,0 +1,177 @@ +//go:build ignore + +// Native release post-hook. wfctl v0.78.2 checks identity/version and declared +// IaC services, not complete capability-list parity. Snapshot and cross-target +// builds retain compiler/archive checks without claiming runtime acceptance. +package main + +import ( + "crypto/sha256" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" +) + +// Immutable official Workflow release v0.78.2, asset 442231027. This binds the +// downloaded bytes to its reviewed GitHub digest; no independent signature is +// claimed. Neither an environment variable nor a CLI flag can change the pin. +const nativeWfctlSHA = "0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8" + +// Dependencies are explicit for inert unit controls; main supplies fixed host, +// digest and real command/cleanup operations, without a runtime override. +type nativeCheckOptions struct { + host, tool, digest string + run func(*exec.Cmd) error + cleanup func(string) error +} + +func nativeDigest(path string, limit int64, executable bool) (string, error) { + st, err := os.Lstat(path) + if err != nil || !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() > limit || (executable && st.Mode().Perm()&0111 == 0) { + return "", errors.New("expected a bounded regular non-symlink file with required mode") + } + f, err := os.Open(path) + if err != nil { + return "", errors.New("cannot read validation input") + } + defer f.Close() + h := sha256.New() + n, err := io.Copy(h, io.LimitReader(f, limit+1)) + if err != nil || n != st.Size() || n > limit { + return "", errors.New("validation input read/size mismatch") + } + return fmt.Sprintf("%x", h.Sum(nil)), nil +} + +func nativeArtifactPath(root, rel string) (string, error) { + if filepath.Clean(rel) != rel || strings.ContainsAny(rel, "\\\x00\r\n") { + return "", errors.New("unexpected source/artifact path") + } + // v2.20.3 base.OptionsForTarget supplies an absolute .Path. Convert only + // canonical paths inside this source root; never admit outside artifacts. + if filepath.IsAbs(rel) { + var err error + rel, err = filepath.Rel(root, rel) + if err != nil { + return "", errors.New("unexpected source/artifact path") + } + } + if !strings.HasPrefix(rel, "dist/") { + return "", errors.New("unexpected source/artifact path") + } + p := root + for _, part := range strings.Split(rel, "/") { + if part == ".." || part == "." || part == "" { + return "", errors.New("noncanonical source/artifact path") + } + p = filepath.Join(p, part) + st, err := os.Lstat(p) + if err != nil || st.Mode()&os.ModeSymlink != 0 { + return "", errors.New("source/artifact path missing or redirected") + } + } + return p, nil +} + +func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (result string, err error) { + if len(args) != 4 || (args[3] != "true" && args[3] != "false") { + return "", errors.New("expected OS ARCH ARTIFACT SNAPSHOT_BOOL") + } + target := args[0] + "/" + args[1] + if target != "linux/amd64" && target != "darwin/arm64" { + return "", errors.New("unsupported release target") + } + if args[3] == "true" { + return "snapshot: native runtime check not performed; compiler/archive gates remain", nil + } + if target == "darwin/arm64" { + return "cross target: native runtime check not performed; compiler/archive gates remain", nil + } + if opt.host != "linux/amd64" { + return "", errors.New("native release verification requires a linux/amd64 host") + } + root, err = filepath.Abs(root) + if err != nil { + return "", errors.New("cannot resolve project root") + } + root, err = filepath.EvalSymlinks(root) + if err != nil { + return "", errors.New("cannot resolve project root") + } + artifact, err := nativeArtifactPath(root, args[2]) + if err != nil { + return "", err + } + manifest := filepath.Join(root, "plugin.json") + if !filepath.IsAbs(opt.tool) || filepath.Clean(opt.tool) != opt.tool { + return "", errors.New("WFCTL_BIN must be an absolute verifier path") + } + toolSHA, err := nativeDigest(opt.tool, 160<<20, true) + if err != nil || toolSHA != opt.digest { + return "", errors.New("wfctl authentication failed") + } + artifactSHA, err := nativeDigest(artifact, 128<<20, true) + if err != nil { + return "", fmt.Errorf("artifact validation failed: %w", err) + } + manifestSHA, err := nativeDigest(manifest, 64<<10, false) + if err != nil { + return "", fmt.Errorf("manifest validation failed: %w", err) + } + owned, err := os.MkdirTemp("", "compute-native-check-") + if err != nil { + return "", errors.New("cannot create owned verifier directory") + } + defer func() { + if e := opt.cleanup(owned); e != nil { + err = errors.Join(err, fmt.Errorf("owned verifier cleanup failed: %w", e)) + result = "" + } + }() + home, tmp := filepath.Join(owned, "home"), filepath.Join(owned, "tmp") + if os.Mkdir(home, 0700) != nil || os.Mkdir(tmp, 0700) != nil { + return "", errors.New("cannot prepare owned verifier environment") + } + cmd := exec.Command(opt.tool, "plugin", "verify-capabilities", "--binary", artifact, root) + cmd.Dir = root + cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=" + home, "TMPDIR=" + tmp, "LANG=C", "LC_ALL=C", "WFCTL_DIFFCACHE=:memory:", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_TERMINAL_PROMPT=0"} + // No raw plugin output or inherited stdin: only fixed gate diagnostics. + cmd.Stdout, cmd.Stderr = io.Discard, io.Discard + if e := opt.run(cmd); e != nil { + return "", fmt.Errorf("runtime identity/version/declared-IaC verifier failed: %w", e) + } + for _, input := range []struct { + path, before string + limit int64 + executable bool + }{{opt.tool, toolSHA, 160 << 20, true}, {artifact, artifactSHA, 128 << 20, true}, {manifest, manifestSHA, 64 << 10, false}} { + after, e := nativeDigest(input.path, input.limit, input.executable) + if e != nil || after != input.before { + return "", errors.New("verifier, artifact or manifest changed during validation") + } + } + return "native runtime identity/version and declared IaC verified; full capability parity not asserted", nil +} + +func main() { + root, err := os.Getwd() + if err == nil { + var result string + result, err = checkNativeRelease(root, os.Args[1:], nativeCheckOptions{ + host: runtime.GOOS + "/" + runtime.GOARCH, tool: os.Getenv("WFCTL_BIN"), digest: nativeWfctlSHA, + run: (*exec.Cmd).Run, cleanup: os.RemoveAll, + }) + if err == nil { + fmt.Println(result) + } + } + if err != nil { + fmt.Fprintln(os.Stderr, "native release check:", err) + os.Exit(1) + } +} diff --git a/scripts/check-native-release_test.go b/scripts/check-native-release_test.go new file mode 100644 index 0000000..374b2cc --- /dev/null +++ b/scripts/check-native-release_test.go @@ -0,0 +1,301 @@ +//go:build ignore + +// Named-file, stdlib-only controls. Digest/host seams are unit-only; main has +// fixed production policy. No test launches wfctl or an actual plugin binary. +package main + +import ( + "bytes" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" +) + +func nativeFixture(t *testing.T) (string, []string, nativeCheckOptions) { + t.Helper() + root, e := filepath.EvalSymlinks(t.TempDir()) + if e != nil { + t.Fatal(e) + } + if e = os.Mkdir(filepath.Join(root, "dist"), 0700); e != nil { + t.Fatal(e) + } + for name, body := range map[string]string{"plugin.json": `{"name":"inert-fixture","version":"1.2.3"}`, "dist/plugin": "inert artifact bytes, never executed", "verifier": "inert verifier bytes, not an executable program"} { + if e = os.WriteFile(filepath.Join(root, name), []byte(body), 0700); e != nil { + t.Fatal(e) + } + } + tool := filepath.Join(root, "verifier") + digest, e := nativeDigest(tool, 160<<20, true) + if e != nil { + t.Fatal(e) + } + opt := nativeCheckOptions{host: "linux/amd64", tool: tool, digest: digest, cleanup: os.RemoveAll, run: func(*exec.Cmd) error { t.Fatal("unexpected process invocation"); return nil }} + // v2.20.3 base.OptionsForTarget uses filepath.Abs for the actual hook .Path. + return root, []string{"linux", "amd64", filepath.Join(root, "dist/plugin"), "false"}, opt +} + +func nativeEnvironment(t *testing.T, cmd *exec.Cmd, root string) string { + t.Helper() + if cmd.Dir != root || cmd.Stdin != nil || cmd.Stdout != io.Discard || cmd.Stderr != io.Discard { + t.Fatal("cwd or standard streams changed") + } + values := map[string]string{} + for _, entry := range cmd.Env { + k, v, ok := strings.Cut(entry, "=") + if !ok || values[k] != "" { + t.Fatal("ambiguous child environment") + } + values[k] = v + } + if len(values) != 9 || values["PATH"] != "/usr/bin:/bin" || values["LANG"] != "C" || values["LC_ALL"] != "C" || values["WFCTL_DIFFCACHE"] != ":memory:" || values["GIT_CONFIG_NOSYSTEM"] != "1" || values["GIT_CONFIG_GLOBAL"] != "/dev/null" || values["GIT_TERMINAL_PROMPT"] != "0" { + t.Fatal("child environment is not the exact allowlist") + } + for _, name := range []string{"HOME", "TMPDIR"} { + st, e := os.Stat(values[name]) + if e != nil || !st.IsDir() || st.Mode().Perm() != 0700 { + t.Fatal("child private environment is not owned/private") + } + } + owned := filepath.Dir(values["HOME"]) + if filepath.Dir(values["TMPDIR"]) != owned || owned == root { + t.Fatal("child environment ownership changed") + } + return owned +} + +func TestNativeReleaseInvocationPolicy(t *testing.T) { + root, args, opt := nativeFixture(t) + calls, owned := 0, "" + opt.run = func(cmd *exec.Cmd) error { + calls++ + if cmd.Path != opt.tool || !reflect.DeepEqual(cmd.Args, []string{opt.tool, "plugin", "verify-capabilities", "--binary", filepath.Join(root, "dist/plugin"), root}) { + t.Fatal("exact verifier/artifact argv changed") + } + owned = nativeEnvironment(t, cmd, root) + _, _ = cmd.Stdout.Write([]byte("inert output marker")) + _, _ = cmd.Stderr.Write([]byte("inert diagnostic marker")) + return nil + } + result, e := checkNativeRelease(root, args, opt) + if e != nil || calls != 1 || !strings.Contains(result, "full capability parity not asserted") { + t.Fatalf("native policy crossing failed: %v", e) + } + if _, e = os.Lstat(owned); !os.IsNotExist(e) { + t.Fatal("owned child environment remains") + } + if nativeWfctlSHA != "0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8" { + t.Fatal("reviewed production authentication pin changed") + } +} + +func TestNativeReleaseRelativeArtifact(t *testing.T) { + root, args, opt := nativeFixture(t) + args[2] = "dist/plugin" + calls := 0 + opt.run = func(cmd *exec.Cmd) error { + calls++ + if cmd.Args[4] != filepath.Join(root, "dist/plugin") { + t.Fatal("relative artifact was not resolved to the exact source root") + } + return nil + } + if _, e := checkNativeRelease(root, args, opt); e != nil || calls != 1 { + t.Fatalf("relative artifact policy failed: %v", e) + } +} + +func TestNativeReleaseRefusals(t *testing.T) { + for _, name := range []string{"wrong-host", "unsupported-target", "invalid-snapshot", "extra-argument", "missing-tool", "relative-tool", "tool-symlink", "wrong-tool-digest", "tool-not-executable", "outside-artifact", "absolute-outside-artifact", "noncanonical-absolute-artifact", "manifest-as-artifact", "artifact-symlink", "artifact-parent-symlink", "artifact-not-executable", "manifest-symlink", "empty-manifest", "large-manifest"} { + t.Run(name, func(t *testing.T) { + root, args, opt := nativeFixture(t) + link := func(path, target string) { + t.Helper() + if e := os.Rename(path, target); e != nil { + t.Fatal(e) + } + if e := os.Symlink(target, path); e != nil { + t.Fatal(e) + } + } + switch name { + case "wrong-host": + opt.host = "darwin/arm64" + case "unsupported-target": + args[1] = "arm64" + case "invalid-snapshot": + args[3] = "TRUE" + case "extra-argument": + args = append(args, "inert-extra") + case "missing-tool": + opt.tool = filepath.Join(root, "missing") + case "relative-tool": + opt.tool = "verifier" + case "tool-symlink": + link(opt.tool, opt.tool+"-target") + case "wrong-tool-digest": + opt.digest = strings.Repeat("0", 64) + case "tool-not-executable": + if e := os.Chmod(opt.tool, 0600); e != nil { + t.Fatal(e) + } + case "outside-artifact": + args[2] = "../inert-outside" + case "absolute-outside-artifact": + args[2] = root + "-outside/dist/plugin" + case "noncanonical-absolute-artifact": + args[2] = root + "/dist/../dist/plugin" + case "manifest-as-artifact": + args[2] = filepath.Join(root, "plugin.json") + case "artifact-symlink": + p := filepath.Join(root, "dist/plugin") + link(p, p+"-target") + case "artifact-parent-symlink": + p := filepath.Join(root, "dist") + link(p, p+"-target") + case "artifact-not-executable": + if e := os.Chmod(filepath.Join(root, "dist/plugin"), 0600); e != nil { + t.Fatal(e) + } + case "manifest-symlink": + p := filepath.Join(root, "plugin.json") + link(p, p+"-target") + case "empty-manifest": + if e := os.WriteFile(filepath.Join(root, "plugin.json"), nil, 0600); e != nil { + t.Fatal(e) + } + case "large-manifest": + if e := os.WriteFile(filepath.Join(root, "plugin.json"), bytes.Repeat([]byte{'x'}, (64<<10)+1), 0600); e != nil { + t.Fatal(e) + } + } + if result, e := checkNativeRelease(root, args, opt); e == nil || result != "" { + t.Fatal("invalid input was accepted") + } + }) + } +} + +func TestNativeReleaseMutationAndFailure(t *testing.T) { + for _, name := range []string{"artifact", "manifest", "tool", "cleanup-after-success", "primary-and-cleanup"} { + t.Run(name, func(t *testing.T) { + root, args, opt := nativeFixture(t) + primary, cleanup := errors.New("inert primary"), errors.New("inert cleanup") + owned := "" + opt.run = func(cmd *exec.Cmd) error { + owned = nativeEnvironment(t, cmd, root) + if name == "primary-and-cleanup" { + return primary + } + if name == "cleanup-after-success" { + return nil + } + p := map[string]string{"artifact": "dist/plugin", "manifest": "plugin.json", "tool": "verifier"}[name] + return os.WriteFile(filepath.Join(root, p), []byte("inert changed bytes"), 0700) + } + if name == "primary-and-cleanup" || name == "cleanup-after-success" { + opt.cleanup = func(p string) error { + if e := os.RemoveAll(p); e != nil { + return e + } + return cleanup + } + } + result, e := checkNativeRelease(root, args, opt) + if e == nil || result != "" { + t.Fatal("changed input/failure accepted") + } + if name == "primary-and-cleanup" && (!errors.Is(e, primary) || !errors.Is(e, cleanup)) { + t.Fatal("primary or cleanup identity lost") + } + if name == "cleanup-after-success" && !errors.Is(e, cleanup) { + t.Fatal("cleanup failure did not fail closed") + } + if _, e = os.Lstat(owned); !os.IsNotExist(e) { + t.Fatal("owned child directory remains") + } + }) + } +} + +func TestNativeReleaseInertExecutable(t *testing.T) { + for _, code := range []string{"0", "7"} { + t.Run("exit-"+code, func(t *testing.T) { + root, args, opt := nativeFixture(t) + body := "#!/bin/sh\n[ \"$#\" = 5 ] || exit 11\n[ \"$1\" = plugin ] && [ \"$2\" = verify-capabilities ] && [ \"$3\" = --binary ] || exit 12\nprintf 'inert output discarded'\nprintf 'inert diagnostic discarded' >&2\nexit " + code + "\n" + if e := os.WriteFile(opt.tool, []byte(body), 0700); e != nil { + t.Fatal(e) + } + var e error + opt.digest, e = nativeDigest(opt.tool, 160<<20, true) + if e != nil { + t.Fatal(e) + } + owned := "" + opt.run = func(cmd *exec.Cmd) error { owned = nativeEnvironment(t, cmd, root); return cmd.Run() } + _, e = checkNativeRelease(root, args, opt) + if (code == "0") != (e == nil) { + t.Fatalf("finite inert invocation outcome: %v", e) + } + if code == "7" { + var exit *exec.ExitError + if !errors.As(e, &exit) || exit.ExitCode() != 7 { + t.Fatal("child exit identity lost") + } + } + if _, e = os.Lstat(owned); !os.IsNotExist(e) { + t.Fatal("finite child environment remains") + } + }) + } +} + +func TestNativeReleaseCLI(t *testing.T) { + root, args, opt := nativeFixture(t) + script, e := filepath.Abs("check-native-release.go") + if e != nil { + t.Fatal(e) + } + for _, tc := range []struct { + name string + args []string + want string + fail bool + }{ + {"snapshot", []string{"linux", "amd64", "unused", "true"}, "runtime check not performed", false}, + {"cross", []string{"darwin", "arm64", "unused", "false"}, "runtime check not performed", false}, + {"unsupported", []string{"linux", "arm64", "unused", "true"}, "unsupported release target", true}, + {"malformed", []string{"linux", "amd64", "unused", "TRUE"}, "expected OS ARCH ARTIFACT SNAPSHOT_BOOL", true}, + {"native-refusal", args, "", true}, + } { + t.Run(tc.name, func(t *testing.T) { + cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin/go"), append([]string{"run", script}, tc.args...)...) + cmd.Dir = root + cmd.Env = append(os.Environ(), "GO111MODULE=off", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOPROXY=off", "GOSUMDB=off", "GOVCS=*:off", "WFCTL_BIN="+opt.tool) + var out, errout bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &errout + e := cmd.Run() + want := tc.want + if tc.name == "native-refusal" { + want = "native release verification requires a linux/amd64 host" + if runtime.GOOS+"/"+runtime.GOARCH == "linux/amd64" { + want = "wfctl authentication failed" + } + } + if tc.fail { + var exit *exec.ExitError + if !errors.As(e, &exit) || exit.ExitCode() != 1 || out.Len() != 0 || !strings.Contains(errout.String(), want) { + t.Fatalf("actual CLI refusal changed: %v %q", e, errout.String()) + } + } else if e != nil || errout.Len() != 0 || !strings.Contains(out.String(), want) { + t.Fatalf("actual CLI skip scope changed: %v %q", e, errout.String()) + } + }) + } +} diff --git a/scripts/check-release-archives_test.go b/scripts/check-release-archives_test.go index 5d664fc..7c4b823 100644 --- a/scripts/check-release-archives_test.go +++ b/scripts/check-release-archives_test.go @@ -89,6 +89,15 @@ func TestArchiveReleaseEngineParity(t *testing.T) { "test -f \"$ENGINE_BIN\" && test ! -L \"$ENGINE_BIN\"", } { count := 1 + if name == "release.yml" && required == "shasum -a 256 --check --strict" { + // wfctl is authenticated independently too. Bind this assertion + // to the engine's exact guard, not a file-wide checksum count. + engineGuard := `printf '%s %s\n' 'd124b61b79baf6d7e2727bb018e7115c045c076df82c13795bb19f9ace4b612d' "$ENGINE_BIN" | shasum -a 256 --check --strict` + if strings.Count(string(b), engineGuard) != 1 { + t.Error("release must authenticate the exact engine path") + } + continue + } if name == "archive-qualification.yml" && (strings.HasPrefix(required, "d124") || strings.Contains(required, "shasum") || strings.HasPrefix(required, "test -f")) { count = 2 // pre-credential binding and pre-execution recheck } @@ -354,7 +363,7 @@ func TestArchiveInputAnchors(t *testing.T) { if err != nil { t.Fatal(err) } - for _, n := range []string{".goreleaser.yaml", "scripts/check-build-toolchain.go", "go.mod", "go.sum", "scripts/check-release-archives.go", "scripts/check-release-archives_test.go"} { + for _, n := range []string{".goreleaser.yaml", "scripts/check-build-toolchain.go", "go.mod", "go.sum", "scripts/check-release-archives.go", "scripts/check-release-archives_test.go", "scripts/check-native-release.go", "scripts/check-native-release_test.go"} { data, e := os.ReadFile(filepath.Join("..", n)) if e != nil { t.Fatal(e) @@ -365,6 +374,37 @@ func TestArchiveInputAnchors(t *testing.T) { } } +func TestNativeReleaseHookContract(t *testing.T) { + b, err := os.ReadFile("../.goreleaser.yaml") + if err != nil { + t.Fatal(err) + } + compiler := strings.Index(string(b), `go run ./scripts/check-build-toolchain.go "{{ .Path }}"`) + gate := strings.Index(string(b), `env GOOS= GOARCH= go run ./scripts/check-native-release.go "{{ .Os }}" "{{ .Arch }}" "{{ .Path }}" "{{ .IsSnapshot }}"`) + if compiler < 0 || gate <= compiler { + t.Fatal("native release check must be a real post-build hook after compiler validation") + } + b, err = os.ReadFile("../.github/workflows/release.yml") + if err != nil { + t.Fatal(err) + } + s := string(b) + for _, required := range []string{ + "0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8", + "WFCTL_BIN: ${{ runner.temp }}/wfctl-bin/wfctl", + "shasum -a 256 --check --strict", + } { + if !strings.Contains(s, required) { + t.Fatalf("release verifier authentication/input missing: %s", required) + } + } + digest := strings.Index(s, "0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8") + chmod := strings.Index(s, `chmod 500 "${RUNNER_TEMP}/wfctl-bin/wfctl"`) + if chmod <= digest || strings.Contains(s, "skipping verify-capabilities") || strings.Contains(s, "Verify capabilities (runtime truth-check)") { + t.Fatal("wfctl must be authenticated before chmod and checking must not remain after publication") + } +} + func fixtureGit(t *testing.T, root string, args ...string) string { t.Helper() c := exec.Command("git", append([]string{"-C", root, "-c", "core.hooksPath=/dev/null", "-c", "user.name=ArchiveFixture", "-c", "user.email=fixture@example.invalid"}, args...)...) From c7c9036449219217f1db9c893f1f7b5138273e12 Mon Sep 17 00:00:00 2001 From: Jon Langevin Date: Wed, 25 Nov 2026 20:32:33 -0500 Subject: [PATCH 4/8] Qualify Compute tag-mode archives without publication --- .github/workflows/archive-qualification.yml | 16 +- .github/workflows/tag-qualification.yml | 172 ++++++++ scripts/check-native-release.go | 68 ++- scripts/check-native-release_test.go | 97 +++++ scripts/check-release-archives.go | 295 ++++++++++++- scripts/check-release-archives_test.go | 453 ++++++++++++++++++++ scripts/install-release-engine.sh | 42 ++ scripts/qualify-tag-archives.go | 285 ++++++++++++ scripts/qualify-tag-archives_test.go | 239 +++++++++++ 9 files changed, 1654 insertions(+), 13 deletions(-) create mode 100644 .github/workflows/tag-qualification.yml create mode 100644 scripts/install-release-engine.sh create mode 100644 scripts/qualify-tag-archives.go create mode 100644 scripts/qualify-tag-archives_test.go diff --git a/.github/workflows/archive-qualification.yml b/.github/workflows/archive-qualification.yml index b8de1ff..e7c9037 100644 --- a/.github/workflows/archive-qualification.yml +++ b/.github/workflows/archive-qualification.yml @@ -49,10 +49,10 @@ jobs: 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum - c33b50d1a150abdae97a710ec8d4607528e00e87a164214945b16af29afab00a scripts/check-release-archives.go - c87a9f0af027d073abc719b93ca6b2f1ec51c759891e3c8583dc126faf593855 scripts/check-release-archives_test.go - 254ac8d98a27300226ad38c9a849a084dd252438eb1f1a9f7e97d44c8f02e2a4 scripts/check-native-release.go - ad5b7c651d394e79028a03f387afbca8ecbaedff6811f93e52ed7b00019a880e scripts/check-native-release_test.go + f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go + 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go + 79508cb83ac4c8512c19e4697bcc615ee7ef35fe011a258e97bf51c9235773c6 scripts/check-native-release.go + e6cde44d4d9fe8c72877aa420c70823e238e10281ef34363da0d2861afcc00a3 scripts/check-native-release_test.go INPUTS test "$(go version)" = 'go version go1.27.4 linux/amd64' ENGINE_BIN="$(command -v goreleaser)" @@ -120,10 +120,10 @@ jobs: 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum - c33b50d1a150abdae97a710ec8d4607528e00e87a164214945b16af29afab00a scripts/check-release-archives.go - c87a9f0af027d073abc719b93ca6b2f1ec51c759891e3c8583dc126faf593855 scripts/check-release-archives_test.go - 254ac8d98a27300226ad38c9a849a084dd252438eb1f1a9f7e97d44c8f02e2a4 scripts/check-native-release.go - ad5b7c651d394e79028a03f387afbca8ecbaedff6811f93e52ed7b00019a880e scripts/check-native-release_test.go + f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go + 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go + 79508cb83ac4c8512c19e4697bcc615ee7ef35fe011a258e97bf51c9235773c6 scripts/check-native-release.go + e6cde44d4d9fe8c72877aa420c70823e238e10281ef34363da0d2861afcc00a3 scripts/check-native-release_test.go INPUTS home="$(mktemp -d "$OWNED_ROOT/package-home.XXXXXXXX")" tmp="$(mktemp -d "$OWNED_ROOT/package-tmp.XXXXXXXX")" diff --git a/.github/workflows/tag-qualification.yml b/.github/workflows/tag-qualification.yml new file mode 100644 index 0000000..78c748a --- /dev/null +++ b/.github/workflows/tag-qualification.yml @@ -0,0 +1,172 @@ +name: Tag-mode qualification +on: + pull_request: + branches: [main, master] +permissions: + contents: read +jobs: + tag-archives: + # Existing same-repo private-dependency read boundary; workflow authors + # remain trusted. Execution never inherits the acquisition credentials. + if: >- + github.event.pull_request.head.repo.full_name == github.repository + && github.repository == 'GoCodeAlone/workflow-plugin-compute' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version: '1.27.4' + cache: false + - name: Bind immutable source and inputs + id: scratch + env: + EXPECTED_SHA: ${{ github.sha }} + PR_HEAD: ${{ github.event.pull_request.head.sha }} + PR_BASE: ${{ github.event.pull_request.base.sha }} + shell: bash --noprofile --norc -euo pipefail {0} + run: | + umask 077 + [[ "$EXPECTED_SHA" =~ ^[0-9a-f]{40}$ ]] + [[ "$PR_HEAD" =~ ^[0-9a-f]{40}$ && "$PR_BASE" =~ ^[0-9a-f]{40}$ ]] + test "$(git rev-parse HEAD)" = "$EXPECTED_SHA" + test "$(git rev-parse HEAD^1)" = "$PR_BASE" + test "$(git rev-parse HEAD^2)" = "$PR_HEAD" + test -z "$(git status --porcelain=v1 --untracked-files=all --ignored)" + test "$(go version)" = 'go version go1.27.4 linux/amd64' + for file in .goreleaser.yaml scripts/check-build-toolchain.go go.mod go.sum scripts/check-release-archives.go scripts/check-release-archives_test.go scripts/check-native-release.go scripts/check-native-release_test.go scripts/qualify-tag-archives.go scripts/qualify-tag-archives_test.go scripts/install-release-engine.sh; do + test -f "$file" && test ! -L "$file" + done + sha256sum --check --strict <<'INPUTS' + 8255a10418c3bcf015986e46a0bcf167fedbd80a66b81923d7095fd430653eff .goreleaser.yaml + 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go + de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod + 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum + f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go + 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go + 79508cb83ac4c8512c19e4697bcc615ee7ef35fe011a258e97bf51c9235773c6 scripts/check-native-release.go + e6cde44d4d9fe8c72877aa420c70823e238e10281ef34363da0d2861afcc00a3 scripts/check-native-release_test.go + 9851e70b4561fb13962ba466f78c78d6f2373291b5a747c79b8d2919969f0830 scripts/qualify-tag-archives.go + f1d93f6f9ba1f53131a5354f44dd1fde9fe0bc8cac2190dd75d6764764671883 scripts/qualify-tag-archives_test.go + 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh + INPUTS + root="$(mktemp -d "$RUNNER_TEMP/tag-qualification.XXXXXXXX")" + mkdir "$root/downloads" "$root/module-cache" "$root/build-cache" "$root/gopath" "$root/acquire-tmp" + printf 'root=%s\n' "$root" >> "$GITHUB_OUTPUT" + printf 'tree=%s\n' "$(git rev-parse 'HEAD^{tree}')" >> "$GITHUB_OUTPUT" + - name: Acquire public tool bytes without executing them + env: + OWNED_ROOT: ${{ steps.scratch.outputs.root }} + shell: bash --noprofile --norc -euo pipefail {0} + run: | + umask 077 + home="$(mktemp -d "$OWNED_ROOT/download-home.XXXXXXXX")" + env -i PATH=/usr/bin:/bin HOME="$home" curl --disable --fail --location --silent --show-error --proto '=https' --tlsv1.2 --max-time 120 --max-filesize 160000000 \ + --output "$OWNED_ROOT/downloads/engine.tar.gz" \ + https://github.com/goreleaser/goreleaser/releases/download/v2.20.3/goreleaser_Linux_x86_64.tar.gz + env -i PATH=/usr/bin:/bin HOME="$home" curl --disable --fail --location --silent --show-error --proto '=https' --tlsv1.2 --max-time 120 --max-filesize 160000000 \ + --output "$OWNED_ROOT/downloads/wfctl" \ + https://github.com/GoCodeAlone/workflow/releases/download/v0.78.2/wfctl-linux-amd64 + printf '%s %s\n' 'a36d5d7d07a5e538e052cef2a9f93f1cd4af493cf5a3712b9177c1ebe360f0e7' "$OWNED_ROOT/downloads/engine.tar.gz" | shasum -a 256 --check --strict + printf '%s %s\n' '0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8' "$OWNED_ROOT/downloads/wfctl" | shasum -a 256 --check --strict + - name: Acquire pinned dependencies + env: + RELEASES_TOKEN: ${{ secrets.RELEASES_TOKEN || github.token }} + OWNED_ROOT: ${{ steps.scratch.outputs.root }} + shell: bash --noprofile --norc -euo pipefail {0} + run: | + umask 077 + test -n "$RELEASES_TOKEN" + auth="$(mktemp -d "$OWNED_ROOT/auth.XXXXXXXX")" + trap 'rm -f -- "$auth/.gitconfig" "$OWNED_ROOT/acquire.stdout" "$OWNED_ROOT/acquire.stderr"' EXIT + git config --file "$auth/.gitconfig" url."https://x-access-token:${RELEASES_TOKEN}@github.com/GoCodeAlone/".insteadOf "https://github.com/GoCodeAlone/" + go_bin="$(command -v go)" + read_deps() { + env -i PATH="$(dirname "$go_bin"):/usr/bin:/bin" HOME="$auth" TMPDIR="$OWNED_ROOT/acquire-tmp" \ + GOTOOLCHAIN=local GOENV=off GOWORK=off GOPACKAGESDRIVER=off CGO_ENABLED=0 \ + GOFLAGS='-p=1 -mod=readonly' GOTELEMETRY=off GOMAXPROCS=2 GOMEMLIMIT=768MiB \ + GOPATH="$OWNED_ROOT/gopath" GOMODCACHE="$OWNED_ROOT/module-cache" GOCACHE="$OWNED_ROOT/build-cache" \ + GOPRIVATE='github.com/GoCodeAlone/*' GONOPROXY='github.com/GoCodeAlone/*' GONOSUMDB='github.com/GoCodeAlone/*' \ + GOPROXY=https://proxy.golang.org GOSUMDB=sum.golang.org \ + GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL="$auth/.gitconfig" GIT_TERMINAL_PROMPT=0 GIT_ALLOW_PROTOCOL=https \ + "$go_bin" "$@" + } + # Only pinned tool metadata/resolution: no project programs execute here. + status=0 + read_deps mod tidy -diff > "$OWNED_ROOT/acquire.stdout" 2> "$OWNED_ROOT/acquire.stderr" || status="$?" + if [ "$status" -ne 0 ]; then + echo "::error::pinned dependency tidy failed (exit $status); stopped without fallback; acquisition output withheld" + exit "$status" + fi + status=0 + read_deps list -deps -test ./... > "$OWNED_ROOT/acquire.stdout" 2> "$OWNED_ROOT/acquire.stderr" || status="$?" + if [ "$status" -ne 0 ]; then + echo "::error::pinned dependency closure failed (exit $status); stopped without fallback; acquisition output withheld" + exit "$status" + fi + rm -f -- "$auth/.gitconfig" + test ! -e "$auth/.gitconfig" + rm -f -- "$OWNED_ROOT/acquire.stdout" "$OWNED_ROOT/acquire.stderr" + # The token is supplied on stdin, never as a scanner argument. Scan + # only this task's owned inputs; matches or scan errors stop execution. + set +e + printf '%s\n' "$RELEASES_TOKEN" | grep -qrF -f /dev/stdin -- "$OWNED_ROOT" 2>/dev/null + scan_status="${PIPESTATUS[1]}" + set -e + if [ "$scan_status" -ne 1 ]; then + echo '::error::credential residue check failed; stopped before project execution' + exit 1 + fi + printf 'removed\n' > "$OWNED_ROOT/credentials-removed" + test "$(du -sk "$OWNED_ROOT" | cut -f1)" -lt 4194304 + - name: Execute tag qualification without credentials + env: + OWNED_ROOT: ${{ steps.scratch.outputs.root }} + EXPECTED_SHA: ${{ github.sha }} + EXPECTED_TREE: ${{ steps.scratch.outputs.tree }} + shell: bash --noprofile --norc -euo pipefail {0} + run: | + umask 077 + test -f "$OWNED_ROOT/credentials-removed" + for file in .goreleaser.yaml scripts/check-build-toolchain.go go.mod go.sum scripts/check-release-archives.go scripts/check-release-archives_test.go scripts/check-native-release.go scripts/check-native-release_test.go scripts/qualify-tag-archives.go scripts/qualify-tag-archives_test.go scripts/install-release-engine.sh; do + test -f "$file" && test ! -L "$file" + done + sha256sum --check --strict <<'INPUTS' + 8255a10418c3bcf015986e46a0bcf167fedbd80a66b81923d7095fd430653eff .goreleaser.yaml + 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go + de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod + 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum + f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go + 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go + 79508cb83ac4c8512c19e4697bcc615ee7ef35fe011a258e97bf51c9235773c6 scripts/check-native-release.go + e6cde44d4d9fe8c72877aa420c70823e238e10281ef34363da0d2861afcc00a3 scripts/check-native-release_test.go + 9851e70b4561fb13962ba466f78c78d6f2373291b5a747c79b8d2919969f0830 scripts/qualify-tag-archives.go + f1d93f6f9ba1f53131a5354f44dd1fde9fe0bc8cac2190dd75d6764764671883 scripts/qualify-tag-archives_test.go + 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh + INPUTS + mkdir "$OWNED_ROOT/execution-home" "$OWNED_ROOT/execution-tmp" + # Repository helpers run only after auth material/logs are removed. + env -i PATH=/usr/bin:/bin HOME="$OWNED_ROOT/execution-home" TMPDIR="$OWNED_ROOT/execution-tmp" \ + bash ./scripts/install-release-engine.sh linux-amd64 "$OWNED_ROOT/downloads/engine.tar.gz" "$OWNED_ROOT/engine" + printf '%s %s\n' '0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8' "$OWNED_ROOT/downloads/wfctl" | shasum -a 256 --check --strict + chmod 500 "$OWNED_ROOT/downloads/wfctl" + go_bin="$(command -v go)" + clean() { + env -i PATH="$(dirname "$go_bin"):/usr/bin:/bin" HOME="$OWNED_ROOT/execution-home" TMPDIR="$OWNED_ROOT/execution-tmp" \ + LANG=C LC_ALL=C GOTOOLCHAIN=local GOENV=off GOWORK=off GOAUTH=off GOTELEMETRY=off \ + GOPROXY=off GOSUMDB=off GOVCS='*:off' GOPACKAGESDRIVER=off CGO_ENABLED=0 GOFLAGS='-p=1' GOMAXPROCS=2 GOMEMLIMIT=768MiB \ + GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL=/dev/null GIT_TERMINAL_PROMPT=0 GIT_ALLOW_PROTOCOL=file GIT_NO_LAZY_FETCH=1 \ + GOPATH="$OWNED_ROOT/gopath" GOMODCACHE="$OWNED_ROOT/module-cache" GOCACHE="$OWNED_ROOT/build-cache" "$@" + } + (cd scripts && clean "$go_bin" test -count=1 -timeout=45s check-release-archives.go check-release-archives_test.go) + (cd scripts && clean "$go_bin" test -count=1 -timeout=45s check-native-release.go check-native-release_test.go) + (cd scripts && clean "$go_bin" test -count=1 -timeout=45s qualify-tag-archives.go qualify-tag-archives_test.go) + # Only this fixed driver may invoke the engine in this job. Successful + # stdout contains its validated public combined receipt, not raw logs. + clean "$go_bin" run ./scripts/qualify-tag-archives.go "$EXPECTED_SHA" "$EXPECTED_TREE" "$OWNED_ROOT" "$GITHUB_WORKSPACE" \ + "$OWNED_ROOT/engine/goreleaser" "$OWNED_ROOT/downloads/wfctl" "$go_bin" + test "$(du -sk "$OWNED_ROOT" | cut -f1)" -lt 4194304 diff --git a/scripts/check-native-release.go b/scripts/check-native-release.go index d89e87d..b52a453 100644 --- a/scripts/check-native-release.go +++ b/scripts/check-native-release.go @@ -7,6 +7,7 @@ package main import ( "crypto/sha256" + "encoding/json" "errors" "fmt" "io" @@ -26,10 +27,58 @@ const nativeWfctlSHA = "0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be88 // digest and real command/cleanup operations, without a runtime override. type nativeCheckOptions struct { host, tool, digest string + receipt string run func(*exec.Cmd) error cleanup func(string) error } +type nativeValidationReceipt struct { + Schema int `json:"schema"` + Scope string `json:"scope"` + Verdict string `json:"verdict"` + Target string `json:"target"` + Artifact string `json:"artifact_path"` + ArtifactSHA string `json:"artifact_sha256"` + ManifestSHA string `json:"manifest_sha256"` + VerifierSHA string `json:"verifier_sha256"` +} + +func nativeReceiptDestination(root, path string) error { + if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "\x00\r\n") { + return errors.New("receipt requires a fresh absolute owned path") + } + rel, err := filepath.Rel(root, path) + if err != nil || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))) { + return errors.New("receipt must remain outside source") + } + parent, err := os.Lstat(filepath.Dir(path)) + if err != nil || !parent.IsDir() || parent.Mode().Perm() != 0700 { + return errors.New("receipt parent must be a private owned directory") + } + if _, err = os.Lstat(path); !os.IsNotExist(err) { + return errors.New("receipt destination already exists or is unavailable") + } + return nil +} + +func writeNativeReceipt(path string, receipt nativeValidationReceipt) error { + b, err := json.Marshal(receipt) + if err != nil { + return err + } + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + return errors.New("cannot exclusively create native receipt") + } + _, writeErr := f.Write(b) + closeErr := f.Close() + if writeErr != nil || closeErr != nil { + removeErr := os.Remove(path) // Only the file just created above is owned. + return errors.Join(writeErr, closeErr, removeErr) + } + return nil +} + func nativeDigest(path string, limit int64, executable bool) (string, error) { st, err := os.Lstat(path) if err != nil || !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() > limit || (executable && st.Mode().Perm()&0111 == 0) { @@ -123,6 +172,11 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res if err != nil { return "", fmt.Errorf("manifest validation failed: %w", err) } + if opt.receipt != "" { + if err = nativeReceiptDestination(root, opt.receipt); err != nil { + return "", err + } + } owned, err := os.MkdirTemp("", "compute-native-check-") if err != nil { return "", errors.New("cannot create owned verifier directory") @@ -132,6 +186,17 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res err = errors.Join(err, fmt.Errorf("owned verifier cleanup failed: %w", e)) result = "" } + // A receipt is a success record only after the child joined, every + // input remained stable and owned temporary cleanup succeeded. + if err == nil && opt.receipt != "" { + rel, e := filepath.Rel(root, artifact) + if e == nil { + e = writeNativeReceipt(opt.receipt, nativeValidationReceipt{Schema: 1, Scope: "runtime-identity-version-declared-iac", Verdict: "pass", Target: "linux-amd64", Artifact: filepath.ToSlash(rel), ArtifactSHA: artifactSHA, ManifestSHA: manifestSHA, VerifierSHA: toolSHA}) + } + if e != nil { + err, result = fmt.Errorf("native receipt failed: %w", e), "" + } + } }() home, tmp := filepath.Join(owned, "home"), filepath.Join(owned, "tmp") if os.Mkdir(home, 0700) != nil || os.Mkdir(tmp, 0700) != nil { @@ -164,7 +229,8 @@ func main() { var result string result, err = checkNativeRelease(root, os.Args[1:], nativeCheckOptions{ host: runtime.GOOS + "/" + runtime.GOARCH, tool: os.Getenv("WFCTL_BIN"), digest: nativeWfctlSHA, - run: (*exec.Cmd).Run, cleanup: os.RemoveAll, + receipt: os.Getenv("NATIVE_CHECK_RECEIPT"), + run: (*exec.Cmd).Run, cleanup: os.RemoveAll, }) if err == nil { fmt.Println(result) diff --git a/scripts/check-native-release_test.go b/scripts/check-native-release_test.go index 374b2cc..545a115 100644 --- a/scripts/check-native-release_test.go +++ b/scripts/check-native-release_test.go @@ -6,6 +6,7 @@ package main import ( "bytes" + "encoding/json" "errors" "io" "os" @@ -111,6 +112,102 @@ func TestNativeReleaseRelativeArtifact(t *testing.T) { } } +func TestNativeReleaseReceipt(t *testing.T) { + for _, name := range []string{"success", "child-failure", "cleanup-failure", "existing", "source-path", "snapshot", "cross"} { + t.Run(name, func(t *testing.T) { + root, args, opt := nativeFixture(t) + receiptRoot := t.TempDir() + if e := os.Chmod(receiptRoot, 0700); e != nil { + t.Fatal(e) + } + opt.receipt = filepath.Join(receiptRoot, "native.json") + called, cleaned := 0, false + opt.run = func(cmd *exec.Cmd) error { + called++ + nativeEnvironment(t, cmd, root) + for _, e := range cmd.Env { + if strings.HasPrefix(e, "NATIVE_CHECK_RECEIPT=") { + t.Fatal("receipt destination leaked to plugin environment") + } + } + if _, e := os.Lstat(opt.receipt); !os.IsNotExist(e) { + t.Fatal("receipt exists before native check completes") + } + if name == "child-failure" { + return errors.New("inert verifier failure") + } + return nil + } + opt.cleanup = func(path string) error { + cleaned = true + if e := os.RemoveAll(path); e != nil { + return e + } + if name == "cleanup-failure" { + return errors.New("inert cleanup failure") + } + return nil + } + switch name { + case "existing": + if e := os.WriteFile(opt.receipt, []byte("preserve"), 0600); e != nil { + t.Fatal(e) + } + case "source-path": + opt.receipt = filepath.Join(root, "receipt.json") + case "snapshot": + args[3] = "true" + case "cross": + args[0], args[1] = "darwin", "arm64" + } + _, e := checkNativeRelease(root, args, opt) + if name == "success" { + if e != nil || called != 1 || !cleaned { + t.Fatalf("receipt producer failed: %v", e) + } + b, e := os.ReadFile(opt.receipt) + if e != nil { + t.Fatal(e) + } + var record nativeValidationReceipt + if e = json.Unmarshal(b, &record); e != nil { + t.Fatal(e) + } + a, _ := nativeDigest(filepath.Join(root, "dist/plugin"), 128<<20, true) + m, _ := nativeDigest(filepath.Join(root, "plugin.json"), 64<<10, false) + if record.Schema != 1 || record.Scope != "runtime-identity-version-declared-iac" || record.Verdict != "pass" || record.Target != "linux-amd64" || record.Artifact != "dist/plugin" || record.ArtifactSHA != a || record.ManifestSHA != m || record.VerifierSHA != opt.digest { + t.Fatal("receipt not bound to actual invocation inputs") + } + st, _ := os.Stat(opt.receipt) + if st.Mode().Perm() != 0600 { + t.Fatal("receipt mode not private") + } + return + } + if name == "snapshot" || name == "cross" { + if e != nil || called != 0 { + t.Fatal("skip created runtime evidence") + } + } else if e == nil { + t.Fatal("invalid receipt path/failure accepted") + } + if name == "child-failure" || name == "cleanup-failure" { + if called != 1 || !cleaned { + t.Fatal("failure control did not reach the actual invocation/cleanup boundary") + } + } + if name == "existing" { + b, _ := os.ReadFile(opt.receipt) + if string(b) != "preserve" || called != 0 { + t.Fatal("existing receipt overwritten or verifier started") + } + } else if _, e := os.Lstat(opt.receipt); !os.IsNotExist(e) { + t.Fatal("failure or skip emitted success receipt") + } + }) + } +} + func TestNativeReleaseRefusals(t *testing.T) { for _, name := range []string{"wrong-host", "unsupported-target", "invalid-snapshot", "extra-argument", "missing-tool", "relative-tool", "tool-symlink", "wrong-tool-digest", "tool-not-executable", "outside-artifact", "absolute-outside-artifact", "noncanonical-absolute-artifact", "manifest-as-artifact", "artifact-symlink", "artifact-parent-symlink", "artifact-not-executable", "manifest-symlink", "empty-manifest", "large-manifest"} { t.Run(name, func(t *testing.T) { diff --git a/scripts/check-release-archives.go b/scripts/check-release-archives.go index 2dfb123..22f4979 100644 --- a/scripts/check-release-archives.go +++ b/scripts/check-release-archives.go @@ -13,6 +13,7 @@ import ( "debug/elf" "debug/macho" "encoding/json" + "errors" "fmt" "io" "io/fs" @@ -354,6 +355,208 @@ type sourceState struct { // Store exact bytes: RawMessage is normalized by receipt JSON marshaling. Manifest []byte `json:"manifest"` } + +// Separate wire shape prevents snapshot/tag receipts from being reused across +// modes. Only deterministic disposable local qualification tags are admitted. +type tagSourceState struct { + Source *sourceState `json:"source"` + Tag string `json:"tag"` +} + +// Wire contract produced by the native post-hook, not a runtime attestation. +// The same-job owner controls these files; no hostile same-user isolation is +// implied. This consumer still binds every fact to current verified bytes. +type nativeValidationReceipt struct { + Schema int `json:"schema"` + Scope string `json:"scope"` + Verdict string `json:"verdict"` + Target string `json:"target"` + Artifact string `json:"artifact_path"` + ArtifactSHA string `json:"artifact_sha256"` + ManifestSHA string `json:"manifest_sha256"` + VerifierSHA string `json:"verifier_sha256"` +} + +// Reuse the full verifier, including current physical output inventory and +// archive bytes. A stored success report alone cannot attest to present bytes. +// The temporary extraction is owned here, never executed, and removed before +// returning success. This is not an adversarial concurrent-mutation boundary. +func revalidateTagArchiveReport(root, sha, tag string, report *archiveReport, rawReport []byte) (err error) { + // Resolve placement before creation: TMPDIR inside the source is refused, + // including directory symlinks that would redirect into the source tree. + source, e := filepath.EvalSymlinks(root) + if e != nil { + return fmt.Errorf("cannot resolve archive recheck source") + } + temp, e := filepath.EvalSymlinks(os.TempDir()) + if e != nil { + return fmt.Errorf("cannot resolve archive recheck temporary directory") + } + rel, e := filepath.Rel(source, temp) + if e != nil || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))) { + return fmt.Errorf("archive recheck temporary directory must be outside source") + } + owned, e := os.MkdirTemp(temp, "compute-tag-recheck-") + if e != nil { + return fmt.Errorf("cannot create owned archive recheck directory") + } + defer func() { + if e := os.RemoveAll(owned); e != nil { + err = errors.Join(err, fmt.Errorf("tag archive recheck cleanup failed: %w", e)) + } + }() + current, e := verifyArchives(root, sha, report.Source, filepath.Join(owned, "extracted"), tag) + if e != nil { + return fmt.Errorf("tag archive revalidation failed: %w", e) + } + currentJSON, e := json.Marshal(current) + if e != nil { + return fmt.Errorf("tag archive recheck report invalid") + } + currentValue, e := jsonValue(currentJSON) + if e != nil { + return fmt.Errorf("tag archive recheck report invalid") + } + // Parse original wire bytes directly. Re-marshaling the decoded report + // would filter supplied BuildInfo fields and hide unexpected differences. + previousValue, e := jsonValue(rawReport) + if e != nil || !reflect.DeepEqual(currentValue, previousValue) { + return fmt.Errorf("tag archive report changed") + } + return nil +} + +func bindNativeReceipt(root, sha, tree, tag, reportPath, nativePath string, out io.Writer) error { + if e := qualificationTagIdentity(root, sha, tree, tag); e != nil { + return e + } + read := func(path string) ([]byte, error) { + path = filepath.Clean(path) + return readRegular(filepath.Dir(path), filepath.Base(path), maxMetadata) + } + b, e := read(reportPath) + if e != nil { + return e + } + reportSHA := byteHash(b) + var report archiveReport + if e = decodeExact(b, &report); e != nil { + return e + } + if report.Mode != "local-tag" || report.Commit != sha || report.Tree != tree || report.Tag != tag || report.TagVersion != strings.TrimPrefix(tag, "v") || report.Version != "" || report.Compiler != archiveCompiler || report.Source == nil || len(report.Archives) != 2 { + return fmt.Errorf("tag archive report binding mismatch") + } + if e = revalidateTagArchiveReport(root, sha, tag, &report, b); e != nil { + return e + } + manifest, e := verifySource(root, sha, report.TagVersion, report.Source) + if e != nil { + return e + } + if byteHash(manifest) != report.FinalManifestSHA { + return fmt.Errorf("tag manifest report mismatch") + } + b, e = read(nativePath) + if e != nil { + return e + } + nativeSHA := byteHash(b) + var native nativeValidationReceipt + if e = decodeExact(b, &native); e != nil { + return e + } + if native.Schema != 1 || native.Scope != "runtime-identity-version-declared-iac" || native.Verdict != "pass" || native.Target != "linux-amd64" || native.VerifierSHA != "0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8" || !sumSHA.MatchString(native.ArtifactSHA) || native.ManifestSHA != report.FinalManifestSHA { + return fmt.Errorf("native receipt contract mismatch") + } + b, e = readRegular(root, "dist/artifacts.json", maxMetadata) + if e != nil { + return e + } + if byteHash(b) != report.IndexSHA { + return fmt.Errorf("artifact index changed since tag verification") + } + var index []releaseArtifact + if e = decodeExact(b, &index); e != nil { + return e + } + count := 0 + for _, a := range index { + if a.Type == "Binary" && a.Internal == 4 && a.OS == "linux" && a.Arch == "amd64" { + count++ + if a.Name != archivePlugin || a.Path != native.Artifact { + return fmt.Errorf("native artifact path/index mismatch") + } + } + } + if count != 1 { + return fmt.Errorf("native artifact index is ambiguous") + } + data, e := readRegular(root, native.Artifact, maxBinary) + if e != nil { + return e + } + if byteHash(data) != native.ArtifactSHA { + return fmt.Errorf("native artifact bytes changed") + } + if _, e = inspectArchiveBinary(data, "linux-amd64", sha, report.TagVersion); e != nil { + return e + } + seen := map[string]bool{} + for _, a := range report.Archives { + if seen[a.Target] || (a.Target != "linux-amd64" && a.Target != "darwin-arm64") || !sumSHA.MatchString(a.BinarySHA) || !sumSHA.MatchString(a.ArchiveSHA) { + return fmt.Errorf("tag archive target report mismatch") + } + seen[a.Target] = true + if a.Target == "linux-amd64" && a.BinarySHA != native.ArtifactSHA { + return fmt.Errorf("native artifact/archive digest mismatch") + } + } + if e = qualificationTagIdentity(root, sha, tree, tag); e != nil { + return e + } + // Public validated facts only; no source paths, dependency lists, process + // output, environment or linker arguments enter the job log. + return json.NewEncoder(out).Encode(struct { + Scope string `json:"scope"` + Commit string `json:"commit"` + Tree string `json:"tree"` + Tag string `json:"tag"` + Target string `json:"target"` + BinarySHA string `json:"binary_sha256"` + ManifestSHA string `json:"manifest_sha256"` + VerifierSHA string `json:"verifier_sha256"` + ArchiveReceiptSHA string `json:"archive_receipt_sha256"` + NativeReceiptSHA string `json:"native_receipt_sha256"` + }{"local-tag-native-identity-version-declared-iac; no publication or full capability parity", sha, tree, tag, native.Target, native.ArtifactSHA, native.ManifestSHA, native.VerifierSHA, reportSHA, nativeSHA}) +} + +func qualificationTagIdentity(root, sha, tree, tag string) error { + if !fullSHA.MatchString(sha) || !fullSHA.MatchString(tree) || tag != "v0.0.0-qualification.g"+sha { + return fmt.Errorf("qualification tag/source mismatch") + } + for _, key := range []string{"GORELEASER_CURRENT_TAG", "GORELEASER_PREVIOUS_TAG"} { + if _, present := os.LookupEnv(key); present { + return fmt.Errorf("qualification tag override environment") + } + } + actualTree, e := sourceIdentity(root, sha) + if e != nil || actualTree != tree { + return fmt.Errorf("qualification source/tree mismatch") + } + ref := "refs/tags/" + tag + b, e := localGit(root, "for-each-ref", "--format=%(refname)%00%(symref)%00%(objectname)%00%(objecttype)", ref) + // An exact row requires the fully qualified direct, unsigned/lightweight + // commit ref. Annotated, symbolic and prefix-matching extra refs fail. + if e != nil || string(b) != ref+"\x00\x00"+sha+"\x00commit\n" { + return fmt.Errorf("qualification tag ref mismatch") + } + b, e = localGit(root, "tag", "--points-at", sha) + if e != nil || strings.TrimSpace(string(b)) != tag { + return fmt.Errorf("ambiguous qualification tag") + } + return nil +} + type boundedOutput struct { b bytes.Buffer overflow bool @@ -669,7 +872,10 @@ type archiveReport struct { Compiler string `json:"compiler"` Commit string `json:"commit"` Tree string `json:"tree"` - Version string `json:"snapshot_version"` + Version string `json:"snapshot_version,omitempty"` + TagVersion string `json:"tag_version,omitempty"` + Tag string `json:"tag,omitempty"` + Mode string `json:"verification_mode,omitempty"` Source *sourceState `json:"original_source"` FinalManifestSHA string `json:"final_manifest_sha256"` Archives []verifiedArchive `json:"archives"` @@ -739,6 +945,18 @@ func verifyDistInventory(root string, artifacts []releaseArtifact) error { } func verifySnapshot(root, sha string, before *sourceState, extract string) (*archiveReport, error) { + return verifyArchives(root, sha, before, extract, "") +} + +func verifyArchives(root, sha string, before *sourceState, extract, tag string) (*archiveReport, error) { + if before == nil { + return nil, fmt.Errorf("source receipt missing") + } + if tag != "" { + if e := qualificationTagIdentity(root, sha, before.Tree, tag); e != nil { + return nil, e + } + } b, e := readRegular(root, "dist/metadata.json", maxMetadata) if e != nil { return nil, e @@ -751,8 +969,12 @@ func verifySnapshot(root, sha string, before *sourceState, extract string) (*arc if meta.Project != archivePlugin || meta.Commit != sha || meta.Runtime.OS != runtime.GOOS || meta.Runtime.Arch != runtime.GOARCH { return nil, fmt.Errorf("release metadata source/host mismatch") } - if e = checkSnapshotVersion(meta.Version, sha); e != nil { - return nil, e + if tag == "" { + if e = checkSnapshotVersion(meta.Version, sha); e != nil { + return nil, e + } + } else if meta.Tag != tag || meta.Version != strings.TrimPrefix(tag, "v") { + return nil, fmt.Errorf("tag metadata version/source mismatch") } manifest, e := verifySource(root, sha, meta.Version, before) if e != nil { @@ -847,6 +1069,10 @@ func verifySnapshot(root, sha string, before *sourceState, extract string) (*arc } }() report := &archiveReport{Scope: "snapshot archives only; no binary execution or official release acceptance", Compiler: runtime.Version(), Commit: sha, Tree: before.Tree, Version: meta.Version, Source: before, FinalManifestSHA: byteHash(manifest)} + if tag != "" { + report.Scope = "local synthetic tag-mode archives only; no binary execution or official release acceptance" + report.Version, report.TagVersion, report.Tag, report.Mode = "", meta.Version, tag, "local-tag" + } report.EffectiveConfig = string(effective) report.EffectiveConfigSHA = byteHash(effective) report.MetadataSHA = metadataSHA @@ -891,6 +1117,13 @@ func verifySnapshot(root, sha string, before *sourceState, extract string) (*arc if _, e = verifySource(root, sha, meta.Version, before); e != nil { return nil, e } + if tag != "" { + // Keep this inside the owned extraction cleanup boundary: no success + // receipt or leftover output if the source/tag binding has changed. + if e = qualificationTagIdentity(root, sha, before.Tree, tag); e != nil { + return nil, e + } + } success = true return report, nil } @@ -913,13 +1146,67 @@ func runArchiveCheck(args []string, out io.Writer) error { return fmt.Errorf("archive verifier requires %s and GOTOOLCHAIN=local", archiveCompiler) } if len(args) < 3 || !fullSHA.MatchString(args[1]) { - return fmt.Errorf("usage: check-release-archives capture SHA STATE | verify SHA STATE EXTRACT") + return fmt.Errorf("usage: check-release-archives capture SHA STATE | verify SHA STATE EXTRACT | capture-tag SHA TREE TAG STATE | verify-tag SHA TREE TAG STATE EXTRACT | bind-native SHA TREE TAG REPORT NATIVE") } root, e := os.Getwd() if e != nil { return e } switch args[0] { + case "bind-native": + if len(args) != 6 { + return fmt.Errorf("bind-native requires SHA TREE TAG REPORT NATIVE") + } + return bindNativeReceipt(root, args[1], args[2], args[3], args[4], args[5], out) + case "capture-tag": + if len(args) != 5 { + return fmt.Errorf("capture-tag requires SHA TREE TAG STATE") + } + if e = qualificationTagIdentity(root, args[1], args[2], args[3]); e != nil { + return e + } + state, e := captureSource(root, args[1]) + if e != nil { + return e + } + if state.Tree != args[2] { + return fmt.Errorf("qualification source/tree mismatch") + } + if e = qualificationTagIdentity(root, args[1], args[2], args[3]); e != nil { + return e + } + b, e := json.Marshal(tagSourceState{Source: state, Tag: args[3]}) + if e != nil { + return e + } + if len(b) > maxMetadata { + return fmt.Errorf("source receipt limit") + } + return writeExclusive(args[4], b) + case "verify-tag": + if len(args) != 6 { + return fmt.Errorf("verify-tag requires SHA TREE TAG STATE EXTRACT") + } + if !fullSHA.MatchString(args[2]) || args[3] != "v0.0.0-qualification.g"+args[1] { + return fmt.Errorf("qualification tag/source mismatch") + } + statePath := filepath.Clean(args[4]) + b, e := readRegular(filepath.Dir(statePath), filepath.Base(statePath), maxMetadata) + if e != nil { + return e + } + var state tagSourceState + if e = decodeExact(b, &state); e != nil { + return e + } + if state.Source == nil || state.Tag != args[3] || state.Source.Commit != args[1] || state.Source.Tree != args[2] { + return fmt.Errorf("tag source receipt mismatch") + } + report, e := verifyArchives(root, args[1], state.Source, args[5], args[3]) + if e != nil { + return e + } + return json.NewEncoder(out).Encode(report) case "capture": if len(args) != 3 { return fmt.Errorf("capture arguments") diff --git a/scripts/check-release-archives_test.go b/scripts/check-release-archives_test.go index 7c4b823..6d01d69 100644 --- a/scripts/check-release-archives_test.go +++ b/scripts/check-release-archives_test.go @@ -405,6 +405,36 @@ func TestNativeReleaseHookContract(t *testing.T) { } } +func TestTagPRQualificationWorkflow(t *testing.T) { + b, err := os.ReadFile("../.github/workflows/tag-qualification.yml") + if err != nil { + t.Fatalf("read-only tag qualification execution path missing: %v", err) + } + s := string(b) + for _, required := range []string{" pull_request:", " contents: read", "persist-credentials: false", "cache: false", "github.event.pull_request.head.repo.full_name == github.repository", "qualify-tag-archives.go", "Acquire pinned dependencies", "env -i", "GOTOOLCHAIN=local", "GOAUTH=off", "GOPROXY=off", "GOVCS='*:off'", "install-release-engine.sh", "0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8"} { + if !strings.Contains(s, required) { + t.Fatalf("tag job contract missing %s", required) + } + } + for _, forbidden := range []string{"contents: write", "pull_request_target:", "workflow_dispatch:", "repository_dispatch:", " push:", "upload-artifact", "packages:", "id-token:", "goreleaser-action", "--snapshot", "--skip=validate"} { + if strings.Contains(s, forbidden) { + t.Fatalf("tag job contains forbidden operation %s", forbidden) + } + } + if strings.Count(s, "secrets.RELEASES_TOKEN") != 1 { + t.Fatal("tag job changes dependency credential scope") + } + a, z := strings.Index(s, " - name: Acquire pinned dependencies"), strings.Index(s, " - name: Execute tag qualification without credentials") + if a < 0 || z <= a { + t.Fatal("tag job acquisition/execution boundary missing") + } + for _, forbidden := range []string{"go run", "go test", "scripts/", "wfctl ", "goreleaser "} { + if strings.Contains(s[a:z], forbidden) { + t.Fatal("project code executes during credential acquisition") + } + } +} + func fixtureGit(t *testing.T, root string, args ...string) string { t.Helper() c := exec.Command("git", append([]string{"-C", root, "-c", "core.hooksPath=/dev/null", "-c", "user.name=ArchiveFixture", "-c", "user.email=fixture@example.invalid"}, args...)...) @@ -680,6 +710,390 @@ func TestCaptureRawSource(t *testing.T) { } } +func TestTagModeCaptureCLI(t *testing.T) { + root, sha, before := newSourceFixture(t) + tag := "v0.0.0-qualification.g" + sha + // This is an unsigned, disposable local ref; no signing or remote operation. + fixtureGit(t, root, "tag", "--no-sign", tag, sha) + script, e := filepath.Abs("check-release-archives.go") + if e != nil { + t.Fatal(e) + } + state := filepath.Join(t.TempDir(), "tag-source.json") + fixtureTool(t, root, []string{"GO111MODULE=off"}, "run", script, "capture-tag", sha, before.Tree, tag, state) + b, e := os.ReadFile(state) + if e != nil { + t.Fatal(e) + } + var receipt struct { + Source *sourceState `json:"source"` + Tag string `json:"tag"` + } + if e = decodeExact(b, &receipt); e != nil || receipt.Source == nil || receipt.Tag != tag || receipt.Source.Commit != sha || receipt.Source.Tree != before.Tree || !bytes.Equal(receipt.Source.Manifest, before.Manifest) { + t.Fatalf("actual tag capture did not bind exact source/tree/tag/raw manifest: %v", e) + } +} + +// Tag-mode verifier proof uses genuine local Git tags and compiler metadata, +// not an engine invocation, native plugin execution or publication. +func TestTagModeArchiveCLI(t *testing.T) { + root, sha, before := newSourceFixture(t) + tag := "v0.0.0-qualification.g" + sha + version := strings.TrimPrefix(tag, "v") + fixtureGit(t, root, "tag", "--no-sign", tag, sha) + script, e := filepath.Abs("check-release-archives.go") + if e != nil { + t.Fatal(e) + } + owned := t.TempDir() + state, legacy := filepath.Join(owned, "tag-state.json"), filepath.Join(owned, "snapshot-state.json") + fixtureTool(t, root, []string{"GO111MODULE=off"}, "run", script, "capture-tag", sha, before.Tree, tag, state) + fixtureTool(t, root, []string{"GO111MODULE=off"}, "run", script, "capture", sha, legacy) + manifest := bytes.Replace(before.Manifest, []byte("0.1.10"), []byte(version), 1) + writeFixture(t, filepath.Join(root, "plugin.json"), manifest) + var artifacts []releaseArtifact + checksums := "" + binaries, packed := map[string][]byte{}, map[string][]byte{} + for _, target := range targets { + parts := strings.Split(target, "-") + rel := "dist/" + target + "/" + archivePlugin + bin := filepath.Join(root, filepath.FromSlash(rel)) + fixtureTool(t, root, []string{"GOOS=" + parts[0], "GOARCH=" + parts[1]}, "build", "-p=1", "-mod=readonly", "-buildvcs=true", "-ldflags=-s -w -X "+archiveModule+"/internal.Version="+version, "-o", bin, "./cmd/workflow-plugin-compute") + binaries[target], e = os.ReadFile(bin) + if e != nil { + t.Fatal(e) + } + packed[target] = packFixture(t, binaries[target], manifest) + writeFixture(t, filepath.Join(root, "dist", archiveName(target)), packed[target]) + checksums += checksumBytes(packed[target]) + " " + archiveName(target) + "\n" + artifacts = append(artifacts, releaseArtifact{Name: archivePlugin, Path: rel, OS: parts[0], Arch: parts[1], Type: "Binary", Internal: 4}, releaseArtifact{Name: archiveName(target), Path: "dist/" + archiveName(target), OS: parts[0], Arch: parts[1], Type: "Archive", Internal: 1}) + } + meta := releaseMetadata{Project: archivePlugin, Tag: tag, Version: version, Commit: sha, Date: "2000-01-01T00:00:00Z"} + meta.Runtime.OS, meta.Runtime.Arch = runtime.GOOS, runtime.GOARCH + metadata, _ := json.Marshal(meta) + writeFixture(t, filepath.Join(root, "dist/metadata.json"), metadata) + writeFixture(t, filepath.Join(root, "dist/config.yaml"), []byte("# Synthetic tag-mode fixture; no engine invocation.\nversion: 2\n")) + writeFixture(t, filepath.Join(root, "dist/checksums.txt"), []byte(checksums)) + artifacts = append(artifacts, releaseArtifact{Name: "checksums.txt", Path: "dist/checksums.txt", Type: "Checksum", Internal: 12}, releaseArtifact{Name: "metadata.json", Path: "dist/metadata.json", Type: "Metadata", Internal: 36}) + index, _ := json.Marshal(artifacts) + writeFixture(t, filepath.Join(root, "dist/artifacts.json"), index) + verifyArgs := []string{"verify-tag", sha, before.Tree, tag, state} + output := fixtureTool(t, root, []string{"GO111MODULE=off"}, append([]string{"run", script}, append(append([]string{}, verifyArgs...), filepath.Join(owned, "extracted"))...)...) + var report archiveReport + if e = decodeExact(output, &report); e != nil || report.Tree != before.Tree || report.Commit != sha || len(report.Archives) != 2 { + t.Fatalf("tag-mode CLI rejected genuine synthetic binding: %v", e) + } + var envelope map[string]json.RawMessage + if e = json.Unmarshal(output, &envelope); e != nil { + t.Fatal(e) + } + for key, want := range map[string]string{"tag": tag, "tag_version": version, "verification_mode": "local-tag"} { + var got string + if e = json.Unmarshal(envelope[key], &got); e != nil || got != want { + t.Fatalf("tag report field %s not bound", key) + } + } + if _, ok := envelope["snapshot_version"]; ok { + t.Fatal("tag report was mislabeled snapshot") + } + for _, a := range report.Archives { + if a.BinarySHA != checksumBytes(binaries[a.Target]) { + t.Fatal("tag-mode binary hash not bound to compiled artifact") + } + } + + reject := func(t *testing.T, name string, args, env []string, diagnostic string) { + t.Helper() + extract := filepath.Join(owned, "refusal-"+name) + argv := append([]string{"run", script}, append(append([]string{}, args...), extract)...) + cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin/go"), argv...) + cmd.Dir = root + cmd.Env = append(os.Environ(), append([]string{"GO111MODULE=off", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOPROXY=off", "GOSUMDB=off", "GOVCS=*:off", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null"}, env...)...) + var out, errout boundedOutput + cmd.Stdout, cmd.Stderr = &out, &errout + err := cmd.Run() + exit, ok := err.(*exec.ExitError) + if !ok || exit.ExitCode() != 1 || out.b.Len() != 0 || out.overflow || errout.overflow || !strings.Contains(errout.b.String(), diagnostic) { + t.Fatalf("actual tag-mode refusal %s missing: %v %q", name, err, errout.b.String()) + } + if _, e := os.Lstat(extract); !os.IsNotExist(e) { + t.Fatal("tag refusal left extraction output") + } + } + for _, name := range []string{"wrong-tree", "wrong-tag", "legacy-receipt", "nil-source", "wrong-receipt-tag", "snapshot-command", "current-tag-env", "previous-tag-env"} { + t.Run(name, func(t *testing.T) { + args := append([]string{}, verifyArgs...) + env := []string{} + want := "tag source receipt mismatch" + switch name { + case "wrong-tree": + args[2] = strings.Repeat("0", 40) + case "wrong-tag": + args[3] = tag + ".extra" + want = "qualification tag/source mismatch" + case "legacy-receipt": + args[4] = legacy + want = "unknown field" + case "nil-source", "wrong-receipt-tag": + b, e := os.ReadFile(state) + if e != nil { + t.Fatal(e) + } + var bad map[string]json.RawMessage + if e = json.Unmarshal(b, &bad); e != nil { + t.Fatal(e) + } + if name == "nil-source" { + bad["source"] = json.RawMessage("null") + } else { + bad["tag"], _ = json.Marshal(tag + ".extra") + } + b, e = json.Marshal(bad) + if e != nil { + t.Fatal(e) + } + args[4] = filepath.Join(owned, name+".json") + writeFixture(t, args[4], b) + case "snapshot-command": + args = []string{"verify", sha, state} + want = "unknown field" + case "current-tag-env": + env = []string{"GORELEASER_CURRENT_TAG="} + want = "qualification tag override environment" + case "previous-tag-env": + env = []string{"GORELEASER_PREVIOUS_TAG="} + want = "qualification tag override environment" + } + reject(t, name, args, env, want) + }) + } + ref := "refs/tags/" + tag + t.Run("missing-ref", func(t *testing.T) { + fixtureGit(t, root, "update-ref", "-d", ref, sha) + defer fixtureGit(t, root, "tag", "--no-sign", tag, sha) + reject(t, "missing-ref", verifyArgs, nil, "qualification tag ref mismatch") + }) + t.Run("moved-ref", func(t *testing.T) { + other := fixtureGit(t, root, "commit-tree", before.Tree, "-p", sha, "-m", "inert other commit") + fixtureGit(t, root, "update-ref", ref, other, sha) + defer fixtureGit(t, root, "update-ref", ref, sha, other) + reject(t, "moved-ref", verifyArgs, nil, "qualification tag ref mismatch") + }) + t.Run("annotated-ref", func(t *testing.T) { + fixtureGit(t, root, "update-ref", "-d", ref, sha) + fixtureGit(t, root, "tag", "--no-sign", "-a", tag, "-m", "inert annotation", sha) + defer func() { fixtureGit(t, root, "tag", "-d", tag); fixtureGit(t, root, "tag", "--no-sign", tag, sha) }() + reject(t, "annotated-ref", verifyArgs, nil, "qualification tag ref mismatch") + }) + t.Run("symbolic-ref", func(t *testing.T) { + fixtureGit(t, root, "symbolic-ref", ref, "refs/heads/main") + defer func() { + fixtureGit(t, root, "symbolic-ref", "--delete", ref) + fixtureGit(t, root, "tag", "--no-sign", tag, sha) + }() + reject(t, "symbolic-ref", verifyArgs, nil, "qualification tag ref mismatch") + }) + t.Run("extra-annotated-ref", func(t *testing.T) { + extra := tag + ".extra" + fixtureGit(t, root, "tag", "--no-sign", "-a", extra, "-m", "inert additional annotation", sha) + defer fixtureGit(t, root, "tag", "-d", extra) + reject(t, "extra-annotated-ref", verifyArgs, nil, "ambiguous qualification tag") + }) + for _, name := range []string{"metadata-tag", "metadata-snapshot-version", "checksum", "wire-type", "extra-output"} { + t.Run(name, func(t *testing.T) { + want := "tag metadata version/source mismatch" + switch name { + case "metadata-tag", "metadata-snapshot-version": + bad := meta + if name == "metadata-tag" { + bad.Tag = tag + ".extra" + } else { + bad.Version = "0.1.15-SNAPSHOT-" + sha[:7] + } + b, _ := json.Marshal(bad) + writeFixture(t, filepath.Join(root, "dist/metadata.json"), b) + defer writeFixture(t, filepath.Join(root, "dist/metadata.json"), metadata) + case "checksum": + writeFixture(t, filepath.Join(root, "dist/checksums.txt"), []byte(strings.Repeat("0", 64)+checksums[64:])) + defer writeFixture(t, filepath.Join(root, "dist/checksums.txt"), []byte(checksums)) + want = "archive checksum mismatch" + case "wire-type": + bad := append([]releaseArtifact{}, artifacts...) + bad[len(bad)-1].Internal = 35 + b, _ := json.Marshal(bad) + writeFixture(t, filepath.Join(root, "dist/artifacts.json"), b) + defer writeFixture(t, filepath.Join(root, "dist/artifacts.json"), index) + want = "artifact wire type mismatch" + case "extra-output": + p := filepath.Join(root, "dist/unlisted") + writeFixture(t, p, []byte("inert")) + defer os.Remove(p) + want = "unindexed or nonregular dist output" + } + reject(t, name, verifyArgs, nil, want) + }) + } + t.Run("native-receipt-binding-synthetic-facts", func(t *testing.T) { + // Only receipt-consumer proof. These synthetic success facts do not + // establish a wfctl/plugin invocation; hosted CI must produce them. + reportPath, nativePath := filepath.Join(owned, "tag-report.json"), filepath.Join(owned, "native-facts.json") + writeFixture(t, reportPath, output) + native := nativeValidationReceipt{Schema: 1, Scope: "runtime-identity-version-declared-iac", Verdict: "pass", Target: "linux-amd64", Artifact: "dist/linux-amd64/" + archivePlugin, ArtifactSHA: checksumBytes(binaries["linux-amd64"]), ManifestSHA: checksumBytes(manifest), VerifierSHA: "0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8"} + good, _ := json.Marshal(native) + writeFixture(t, nativePath, good) + args := []string{"run", script, "bind-native", sha, before.Tree, tag, reportPath, nativePath} + bound := fixtureTool(t, root, []string{"GO111MODULE=off"}, args...) + var facts map[string]json.RawMessage + if e := json.Unmarshal(bound, &facts); e != nil { + t.Fatal(e) + } + for key, want := range map[string]string{"binary_sha256": native.ArtifactSHA, "manifest_sha256": native.ManifestSHA, "verifier_sha256": native.VerifierSHA, "archive_receipt_sha256": checksumBytes(output), "native_receipt_sha256": checksumBytes(good)} { + var got string + if e := json.Unmarshal(facts[key], &got); e != nil || got != want { + t.Fatalf("combined receipt %s not bound", key) + } + } + for _, name := range []string{"scope", "verdict", "schema", "tool", "artifact", "manifest", "binary", "unknown"} { + t.Run(name, func(t *testing.T) { + var bad map[string]any + if e := json.Unmarshal(good, &bad); e != nil { + t.Fatal(e) + } + want := "native receipt contract mismatch" + switch name { + case "scope": + bad["scope"] = "full-capability-parity" + case "verdict": + bad["verdict"] = "fail" + case "schema": + bad["schema"] = 2 + case "tool": + bad["verifier_sha256"] = strings.Repeat("0", 64) + case "artifact": + bad["artifact_path"] = "dist/darwin-arm64/" + archivePlugin + want = "native artifact path/index mismatch" + case "manifest": + bad["manifest_sha256"] = strings.Repeat("0", 64) + case "binary": + bad["artifact_sha256"] = strings.Repeat("0", 64) + want = "native artifact bytes changed" + case "unknown": + bad["unrecognized_private_marker"] = true + want = "unknown field" + } + b, _ := json.Marshal(bad) + writeFixture(t, nativePath, b) + defer writeFixture(t, nativePath, good) + cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin/go"), args...) + cmd.Dir = root + cmd.Env = append(os.Environ(), "GO111MODULE=off", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOPROXY=off", "GOSUMDB=off", "GOVCS=*:off") + var out, errout boundedOutput + cmd.Stdout, cmd.Stderr = &out, &errout + e := cmd.Run() + exit, ok := e.(*exec.ExitError) + if !ok || exit.ExitCode() != 1 || out.b.Len() != 0 || out.overflow || errout.overflow || !strings.Contains(errout.b.String(), want) { + t.Fatalf("binder refusal %s missing: %v %q", name, e, errout.b.String()) + } + }) + } + + for _, name := range []string{"report-extra-dependency", "report-extra-main-version", "report-extra-setting"} { + t.Run(name, func(t *testing.T) { + var raw map[string]any + if e := json.Unmarshal(output, &raw); e != nil { + t.Fatal(e) + } + info := raw["archives"].([]any)[0].(map[string]any)["build_info"].(map[string]any) + switch name { + case "report-extra-dependency": + info["Deps"] = []any{map[string]any{"Path": "inert-extra-module"}} + case "report-extra-main-version": + info["Main"].(map[string]any)["Version"] = "inert-extra-version" + case "report-extra-setting": + info["Settings"] = append(info["Settings"].([]any), map[string]any{"Key": "inert-extra-setting", "Value": "inert-extra-value"}) + } + b, _ := json.Marshal(raw) + writeFixture(t, reportPath, b) + defer writeFixture(t, reportPath, output) + cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin/go"), args...) + cmd.Dir = root + cmd.Env = append(os.Environ(), "GO111MODULE=off", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOPROXY=off", "GOSUMDB=off", "GOVCS=*:off") + var out, errout boundedOutput + cmd.Stdout, cmd.Stderr = &out, &errout + e := cmd.Run() + exit, ok := e.(*exec.ExitError) + if !ok || exit.ExitCode() != 1 || out.b.Len() != 0 || out.overflow || errout.overflow || !strings.Contains(errout.b.String(), "tag archive report changed") { + t.Fatalf("raw report difference was lost: %v %q", e, errout.b.String()) + } + }) + } + + for _, name := range []string{"stale-linux-archive", "stale-darwin-archive", "missing-linux-archive", "missing-darwin-archive", "changed-metadata", "changed-checksum-order", "changed-effective-config", "unindexed-output"} { + t.Run(name, func(t *testing.T) { + path := "dist/" + archiveName("linux-amd64") + want := "tag archive revalidation failed" + switch name { + case "stale-darwin-archive", "missing-darwin-archive": + path = "dist/" + archiveName("darwin-arm64") + case "changed-metadata": + path, want = "dist/metadata.json", "tag archive report changed" + case "changed-checksum-order": + path, want = "dist/checksums.txt", "tag archive report changed" + case "changed-effective-config": + path, want = "dist/config.yaml", "tag archive report changed" + case "unindexed-output": + path = "dist/unindexed-inert" + } + p := filepath.Join(root, path) + original, e := os.ReadFile(p) + if name == "unindexed-output" { + if !os.IsNotExist(e) { + t.Fatal("unexpected preexisting fixture output") + } + writeFixture(t, p, []byte("inert extra output")) + defer os.Remove(p) + } else { + if e != nil { + t.Fatal(e) + } + defer writeFixture(t, p, original) + switch name { + case "missing-linux-archive", "missing-darwin-archive": + if e := os.Remove(p); e != nil { + t.Fatal(e) + } + case "changed-metadata": + var m map[string]any + if e := json.Unmarshal(original, &m); e != nil { + t.Fatal(e) + } + m["date"] = "2000-01-02T00:00:00Z" + b, _ := json.Marshal(m) + writeFixture(t, p, b) + case "changed-checksum-order": + lines := strings.Split(string(original), "\n") + writeFixture(t, p, []byte(lines[1]+"\n"+lines[0]+"\n")) + default: + writeFixture(t, p, append(append([]byte(nil), original...), '\n')) + } + } + cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin/go"), args...) + cmd.Dir = root + cmd.Env = append(os.Environ(), "GO111MODULE=off", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOPROXY=off", "GOSUMDB=off", "GOVCS=*:off") + var out, errout boundedOutput + cmd.Stdout, cmd.Stderr = &out, &errout + e = cmd.Run() + exit, ok := e.(*exec.ExitError) + if !ok || exit.ExitCode() != 1 || out.b.Len() != 0 || out.overflow || errout.overflow || !strings.Contains(errout.b.String(), want) { + t.Fatalf("stale physical-output binder refusal %s missing: %v %q", name, e, errout.b.String()) + } + }) + } + + }) + t.Logf("local synthetic tag=%s source=%s tree=%s; real compiler/archive bytes; no engine or plugin execution", tag, sha, before.Tree) +} + func TestJSONAndPathRefusals(t *testing.T) { for _, b := range []string{`{"x":1,"x":2}`, `{"x":{"y":1,"y":2}}`, `{} {}`, `[`, strings.Repeat("[", 34) + strings.Repeat("]", 34)} { if _, e := jsonValue([]byte(b)); e == nil { @@ -872,6 +1286,21 @@ func TestRealArchiveProvenance(t *testing.T) { if e = decodeExact(output, &report); e != nil || len(report.Archives) != 2 || report.Commit != sha { t.Fatalf("actual CLI refused synthetic producer bytes: %v", e) } + t.Run("legacy-snapshot-report-shape", func(t *testing.T) { + var fields map[string]json.RawMessage + if e := json.Unmarshal(output, &fields); e != nil { + t.Fatal(e) + } + var got string + if e := json.Unmarshal(fields["snapshot_version"], &got); e != nil || got != version { + t.Fatal("legacy snapshot version wire field changed") + } + for _, key := range []string{"tag", "tag_version", "verification_mode"} { + if _, ok := fields[key]; ok { + t.Fatal("tag fields leaked into legacy snapshot report") + } + } + }) for _, tc := range []struct { name, diagnostic string mutate func(map[string]any) @@ -1052,3 +1481,27 @@ func TestRealArchiveProvenance(t *testing.T) { } t.Logf("synthetic source=%s tree=%s; real clean and dirty VCS metadata, Linux/amd64 and Darwin/arm64, actual validator CLI; zero archived execution", sha, before.Tree) } + +func TestTagRecheckTemporaryPlacement(t *testing.T) { + for _, child := range []bool{false, true} { + t.Run(map[bool]string{false: "source-root", true: "inside-source"}[child], func(t *testing.T) { + root := t.TempDir() + temp := root + if child { + temp = filepath.Join(root, "inside") + if e := os.Mkdir(temp, 0700); e != nil { + t.Fatal(e) + } + } + t.Setenv("TMPDIR", temp) + e := revalidateTagArchiveReport(root, strings.Repeat("1", 40), "inert", &archiveReport{}, nil) + if e == nil || !strings.Contains(e.Error(), "temporary directory must be outside source") { + t.Fatalf("source-local temporary placement accepted: %v", e) + } + entries, e := os.ReadDir(temp) + if e != nil || len(entries) != 0 { + t.Fatal("refused placement created source output") + } + }) + } +} diff --git a/scripts/install-release-engine.sh b/scripts/install-release-engine.sh new file mode 100644 index 0000000..30400fd --- /dev/null +++ b/scripts/install-release-engine.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Offline v2.20.3 extractor for tag qualification; never executes the engine. +# Archive pins were checked against checksums.txt authenticated with Sigstore +# identity https://github.com/goreleaser/goreleaser/.github/workflows/release.yml@refs/tags/v2.20.3 +# and issuer https://token.actions.githubusercontent.com. +# The caller supplies owned, nonconcurrently modified paths. This does not +# download, execute the engine, or establish an adversarial race boundary. +set -euo pipefail +umask 077 + +fail() { printf '%s\n' "$1" >&2; exit 1; } +test "$#" -eq 3 || fail 'usage: install-release-engine TARGET ABSOLUTE_ARCHIVE FRESH_ABSOLUTE_DIRECTORY' +target=$1 +archive=$2 +destination=$3 +case "$target" in + linux-amd64) + archive_sha=a36d5d7d07a5e538e052cef2a9f93f1cd4af493cf5a3712b9177c1ebe360f0e7 + binary_sha=d124b61b79baf6d7e2727bb018e7115c045c076df82c13795bb19f9ace4b612d + ;; + darwin-arm64) + archive_sha=e2c896685fcdb3ec255ce30e86ab073d56f3c02eb539061e749e98d9be1fc2b6 + binary_sha=d582cd4ff47eac803718c957ff6781d33367cdf865db2948d529b39d60b9767e + ;; + *) fail 'unsupported release engine target' ;; +esac +case "$archive" in /*) ;; *) fail 'archive must be absolute' ;; esac +case "$destination" in /*) ;; *) fail 'destination must be absolute' ;; esac +test -f "$archive" && test ! -L "$archive" || fail 'archive must be a regular non-symlink file' +test ! -e "$destination" && test ! -L "$destination" || fail 'destination must not exist' + +# No archive parsing or destination creation happens before authentication. +actual=$(shasum -a 256 "$archive") +test "${actual%% *}" = "$archive_sha" || fail 'release engine archive digest mismatch' +mkdir "$destination" +# Retain this exclusively owned directory on failure. Never remove a +# caller-supplied path, and never grant execute permission to failed output. +set -C +tar -xzOf "$archive" goreleaser > "$destination/goreleaser" +actual=$(shasum -a 256 "$destination/goreleaser") +test "${actual%% *}" = "$binary_sha" || fail 'release engine binary digest mismatch' +chmod 500 "$destination/goreleaser" diff --git a/scripts/qualify-tag-archives.go b/scripts/qualify-tag-archives.go new file mode 100644 index 0000000..ed71297 --- /dev/null +++ b/scripts/qualify-tag-archives.go @@ -0,0 +1,285 @@ +//go:build ignore + +// Read-only PR qualification driver. No configurable engine argv, publishing +// credentials, remote tags or artifact uploads. Real tag-mode execution is +// qualified only when this exact command runs on the hosted Linux runner. +package main + +import ( + "bytes" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" +) + +const tagEngineSHA = "d124b61b79baf6d7e2727bb018e7115c045c076df82c13795bb19f9ace4b612d" +const tagWfctlSHA = "0d41f3050b535e2bc7c1d6a5537ab2a60938e0b49c4c4f12ece1be883762dfc8" + +var tagFullSHA = regexp.MustCompile(`^[0-9a-f]{40}$`) + +type tagQualification struct { + sha, tree, root, source, engine, wfctl, goBin string + run func(string, []string, []string) ([]byte, error) +} + +func fixedTagRelease(engine string) []string { + return []string{engine, "release", "--config=.goreleaser.yaml", "--clean", "--skip=publish,announce,sign,notarize,sbom,docker,ko,changelog", "--parallelism=1", "--timeout=10m"} +} + +func tagFileHash(path string, max int64, executable bool) (string, error) { + if !filepath.IsAbs(path) || filepath.Clean(path) != path { + return "", errors.New("noncanonical tool path") + } + st, e := os.Lstat(path) + if e != nil || !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() > max || (executable && st.Mode().Perm()&0111 == 0) { + return "", errors.New("invalid qualification file") + } + f, e := os.Open(path) + if e != nil { + return "", errors.New("qualification file unreadable") + } + defer f.Close() + h := sha256.New() + n, e := io.Copy(h, io.LimitReader(f, max+1)) + if e != nil || n != st.Size() || n > max { + return "", errors.New("qualification file changed/oversized") + } + return fmt.Sprintf("%x", h.Sum(nil)), nil +} + +func (q tagQualification) environment(native bool) []string { + e := []string{"PATH=" + filepath.Dir(q.goBin) + ":" + filepath.Dir(q.engine) + ":/usr/bin:/bin", "HOME=" + filepath.Join(q.root, "execution-home"), "TMPDIR=" + filepath.Join(q.root, "execution-tmp"), "LANG=C", "LC_ALL=C", "GOTOOLCHAIN=local", "GOENV=off", "GOWORK=off", "GOAUTH=off", "GOTELEMETRY=off", "GOPROXY=off", "GOSUMDB=off", "GOVCS=*:off", "GOPACKAGESDRIVER=off", "CGO_ENABLED=0", "GOFLAGS=-p=1", "GOMAXPROCS=2", "GOMEMLIMIT=768MiB", "GOPATH=" + filepath.Join(q.root, "gopath"), "GOMODCACHE=" + filepath.Join(q.root, "module-cache"), "GOCACHE=" + filepath.Join(q.root, "build-cache"), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_TERMINAL_PROMPT=0", "GIT_ALLOW_PROTOCOL=file", "GIT_NO_LAZY_FETCH=1"} + if native { + e = append(e, "WFCTL_BIN="+q.wfctl, "NATIVE_CHECK_RECEIPT="+filepath.Join(q.root, "native.json")) + } + return e +} + +func tagGit(dir string, args ...string) []string { + return append([]string{"/usr/bin/git", "-c", "core.hooksPath=/dev/null", "-c", "protocol.allow=never", "-c", "protocol.file.allow=always", "-c", "submodule.recurse=false", "-C", dir}, args...) +} + +// Each child is sequentially joined. Raw output is bounded and withheld; +// no private dependency paths or arbitrary diagnostics are logged. +func runTagChild(dir string, env, argv []string) ([]byte, error) { + cmd := exec.Command(argv[0], argv[1:]...) + cmd.Dir = dir + cmd.Env = env + var out, errout tagBoundedOutput + cmd.Stdout, cmd.Stderr = &out, &errout + e := cmd.Run() + if e != nil { + if exit, ok := e.(*exec.ExitError); ok { + return nil, fmt.Errorf("qualification subprocess failed (exit %d); output withheld", exit.ExitCode()) + } + return nil, errors.New("qualification subprocess could not start; output withheld") + } + if out.overflow || errout.overflow { + return nil, errors.New("qualification subprocess output limit exceeded; output withheld") + } + return out.Bytes(), nil +} + +type tagBoundedOutput struct { + bytes.Buffer + overflow bool +} + +func (w *tagBoundedOutput) Write(p []byte) (int, error) { + n := len(p) + left := (1 << 20) - w.Len() + if left > 0 { + w.Buffer.Write(p[:min(left, n)]) + } + if n > left { + w.overflow = true + } + return n, nil +} + +func tagWrite(path string, data []byte) error { + f, e := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if e != nil { + return errors.New("qualification receipt already exists/unavailable") + } + _, we := f.Write(data) + ce := f.Close() + return errors.Join(we, ce) +} + +func (q tagQualification) prepareClone() (string, error) { + env := q.environment(false) + src := filepath.Join(q.root, "source") + if _, e := os.Lstat(src); !os.IsNotExist(e) { + return "", errors.New("owned source destination must be fresh") + } + // --no-local uses a fresh file-transport pack, not shared objects/hardlinks. + if _, e := q.run(q.source, env, tagGit(q.source, "clone", "--no-local", "--no-hardlinks", "--no-tags", "--no-checkout", q.source, src)); e != nil { + return "", e + } + if _, e := os.Lstat(filepath.Join(src, ".git/objects/info/alternates")); !os.IsNotExist(e) { + return "", errors.New("clone has unsupported alternates") + } + if _, e := q.run(src, env, tagGit(src, "checkout", "--detach", q.sha)); e != nil { + return "", e + } + head, e := os.ReadFile(filepath.Join(src, ".git/HEAD")) + if e != nil || string(head) != q.sha+"\n" { + return "", errors.New("owned checkout must be detached") + } + b, e := q.run(src, env, tagGit(src, "rev-parse", "HEAD", "HEAD^{tree}")) + if e != nil || string(b) != q.sha+"\n"+q.tree+"\n" { + return "", errors.New("owned checkout source/tree mismatch") + } + b, e = q.run(src, env, tagGit(src, "tag", "--list")) + if e != nil || len(bytes.TrimSpace(b)) != 0 { + return "", errors.New("owned checkout must not import tags") + } + // Canonical public metadata is needed by SCM defaults. It is not fetched; + // all Git transports except local file remain disabled, and push is inert. + if _, e = q.run(src, env, tagGit(src, "remote", "set-url", "origin", "https://github.com/GoCodeAlone/workflow-plugin-compute.git")); e != nil { + return "", e + } + if _, e = q.run(src, env, tagGit(src, "config", "remote.origin.pushurl", "disabled://qualification")); e != nil { + return "", e + } + if _, e = q.run(src, env, tagGit(src, "tag", "--no-sign", "v0.0.0-qualification.g"+q.sha, q.sha)); e != nil { + return "", e + } + return src, nil +} + +func (q tagQualification) execute(out io.Writer) error { + if !tagFullSHA.MatchString(q.sha) || !tagFullSHA.MatchString(q.tree) { + return errors.New("invalid expected source identity") + } + for _, p := range []string{q.root, q.source, q.engine, q.wfctl, q.goBin} { + if !filepath.IsAbs(p) || filepath.Clean(p) != p { + return errors.New("qualification paths must be canonical/absolute") + } + } + st, e := os.Lstat(q.root) + if e != nil || !st.IsDir() || st.Mode().Perm() != 0700 { + return errors.New("qualification root must be private and owned") + } + for _, name := range []string{"execution-home", "execution-tmp", "module-cache", "build-cache", "gopath"} { + st, e := os.Lstat(filepath.Join(q.root, name)) + if e != nil || !st.IsDir() || st.Mode()&os.ModeSymlink != 0 { + return errors.New("qualification directories missing/redirected") + } + } + for _, name := range []string{"before.json", "native.json", "archives.json", "combined.json"} { + if _, e := os.Lstat(filepath.Join(q.root, name)); !os.IsNotExist(e) { + return errors.New("qualification receipts must be fresh") + } + } + markerPath := filepath.Join(q.root, "credentials-removed") + if _, e := tagFileHash(markerPath, 16, false); e != nil { + return errors.New("credential-removal prerequisite missing") + } + marker, e := os.ReadFile(markerPath) + if e != nil || string(marker) != "removed\n" { + return errors.New("credential-removal prerequisite missing") + } + authConfigs, e := filepath.Glob(filepath.Join(q.root, "auth.*", ".gitconfig")) + if e != nil || len(authConfigs) != 0 { + return errors.New("acquisition credential files remain") + } + for _, name := range []string{"github_token", "gitlab_token", "gitea_token"} { + if _, e := os.Lstat(filepath.Join(q.root, "execution-home/.config/goreleaser", name)); !os.IsNotExist(e) { + return errors.New("execution HOME contains credential material") + } + } + if h, e := tagFileHash(q.engine, 128<<20, true); e != nil || h != tagEngineSHA { + return errors.New("engine authentication failed") + } + if h, e := tagFileHash(q.wfctl, 160<<20, true); e != nil || h != tagWfctlSHA { + return errors.New("wfctl authentication failed") + } + if _, e := tagFileHash(q.goBin, 128<<20, true); e != nil { + return errors.New("Go tool unavailable") + } + b, e := q.run(q.source, q.environment(false), []string{q.goBin, "version"}) + if e != nil || string(b) != "go version go1.27.4 linux/amd64\n" { + return errors.New("unexpected Go toolchain") + } + b, e = q.run(q.source, q.environment(false), tagGit(q.source, "rev-parse", "HEAD", "HEAD^{tree}")) + if e != nil || string(b) != q.sha+"\n"+q.tree+"\n" { + return errors.New("input source/tree mismatch") + } + src, e := q.prepareClone() + if e != nil { + return fmt.Errorf("owned checkout preparation failed: %w", e) + } + tag := "v0.0.0-qualification.g" + q.sha + checker := filepath.Join(src, "scripts/check-release-archives.go") + goCheck := func(args ...string) ([]byte, error) { + return q.run(src, q.environment(false), append([]string{q.goBin, "run", checker}, args...)) + } + if _, e = goCheck("capture-tag", q.sha, q.tree, tag, filepath.Join(q.root, "before.json")); e != nil { + return fmt.Errorf("tag source capture failed: %w", e) + } + for _, phase := range []struct { + name string + argv []string + }{ + {"configuration check", []string{q.engine, "check", "--config=.goreleaser.yaml"}}, + {"nonpublishing tag build", fixedTagRelease(q.engine)}, + } { + if h, e := tagFileHash(q.engine, 128<<20, true); e != nil || h != tagEngineSHA { + return errors.New("engine changed before execution") + } + if _, e = q.run(src, q.environment(true), phase.argv); e != nil { + return fmt.Errorf("%s failed: %w", phase.name, e) + } + } + b, e = goCheck("verify-tag", q.sha, q.tree, tag, filepath.Join(q.root, "before.json"), filepath.Join(q.root, "extracted")) + if e != nil { + return fmt.Errorf("tag archive verification failed: %w", e) + } + if e = tagWrite(filepath.Join(q.root, "archives.json"), b); e != nil { + return e + } + b, e = goCheck("bind-native", q.sha, q.tree, tag, filepath.Join(q.root, "archives.json"), filepath.Join(q.root, "native.json")) + if e != nil { + return fmt.Errorf("native/archive receipt binding failed: %w", e) + } + if !json.Valid(b) { + return errors.New("combined receipt is not JSON") + } + if e = tagWrite(filepath.Join(q.root, "combined.json"), b); e != nil { + return e + } + _, e = out.Write(b) + return e +} + +func main() { + if len(os.Args) != 8 { + fmt.Fprintln(os.Stderr, "usage: qualify-tag-archives SHA TREE OWNED_ROOT SOURCE ENGINE WFCTL GO") + os.Exit(1) + } + for _, key := range []string{"GITHUB_TOKEN", "GH_TOKEN", "RELEASES_TOKEN", "ACTIONS_RUNTIME_TOKEN", "SSH_AUTH_SOCK", "GORELEASER_CURRENT_TAG", "GORELEASER_PREVIOUS_TAG"} { + if _, ok := os.LookupEnv(key); ok { + fmt.Fprintln(os.Stderr, "tag qualification: credential/tag override environment refused") + os.Exit(1) + } + } + if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" || runtime.Version() != "go1.27.4" || os.Getenv("GOTOOLCHAIN") != "local" { + fmt.Fprintln(os.Stderr, "tag qualification: requires local Go1.27.4 linux/amd64") + os.Exit(1) + } + a := os.Args[1:] + q := tagQualification{sha: a[0], tree: a[1], root: a[2], source: a[3], engine: a[4], wfctl: a[5], goBin: a[6], run: runTagChild} + if e := q.execute(os.Stdout); e != nil { + fmt.Fprintln(os.Stderr, "tag qualification:", e) + os.Exit(1) + } +} diff --git a/scripts/qualify-tag-archives_test.go b/scripts/qualify-tag-archives_test.go new file mode 100644 index 0000000..27ca059 --- /dev/null +++ b/scripts/qualify-tag-archives_test.go @@ -0,0 +1,239 @@ +//go:build ignore + +// Inert policy/entry-point and genuine file-only Git preparation controls. +// No test substitutes a successful engine or creates fake engine archives. +package main + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" +) + +func TestFixedTagReleaseBoundary(t *testing.T) { + want := []string{"/owned/engine", "release", "--config=.goreleaser.yaml", "--clean", "--skip=publish,announce,sign,notarize,sbom,docker,ko,changelog", "--parallelism=1", "--timeout=10m"} + if !reflect.DeepEqual(fixedTagRelease("/owned/engine"), want) { + t.Fatal("fixed nonpublishing argv changed") + } + q := tagQualification{root: "/owned", goBin: "/go/bin/go", engine: "/owned/engine", wfctl: "/owned/wfctl"} + for _, native := range []bool{false, true} { + env := map[string]string{} + for _, v := range q.environment(native) { + k, v, _ := strings.Cut(v, "=") + if _, ok := env[k]; ok { + t.Fatal("duplicate execution environment") + } + env[k] = v + } + for _, key := range []string{"GITHUB_TOKEN", "GH_TOKEN", "RELEASES_TOKEN", "ACTIONS_RUNTIME_TOKEN", "SSH_AUTH_SOCK", "GORELEASER_CURRENT_TAG", "GORELEASER_PREVIOUS_TAG"} { + if _, ok := env[key]; ok { + t.Fatal("credential/tag override propagated") + } + } + for k, v := range map[string]string{"GOTOOLCHAIN": "local", "GOAUTH": "off", "GOPROXY": "off", "GOVCS": "*:off", "GIT_ALLOW_PROTOCOL": "file", "GIT_NO_LAZY_FETCH": "1", "GIT_CONFIG_GLOBAL": "/dev/null"} { + if env[k] != v { + t.Fatalf("execution boundary %s changed", k) + } + } + if (env["NATIVE_CHECK_RECEIPT"] != "") != native || (env["WFCTL_BIN"] != "") != native { + t.Fatal("native inputs leaked to other phases") + } + } +} + +func tagTestGit(t *testing.T, dir string, args ...string) string { + t.Helper() + env := []string{"PATH=/usr/bin:/bin", "HOME=" + t.TempDir(), "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_TERMINAL_PROMPT=0", "GIT_AUTHOR_DATE=2000-01-01T00:00:00Z", "GIT_COMMITTER_DATE=2000-01-01T00:00:00Z"} + argv := tagGit(dir, append([]string{"-c", "user.name=QualificationFixture", "-c", "user.email=fixture@example.invalid"}, args...)...) + b, e := runTagChild(dir, env, argv) + if e != nil { + t.Fatalf("owned Git fixture: %v", e) + } + return strings.TrimSpace(string(b)) +} + +func TestOwnedTagCheckout(t *testing.T) { + for _, name := range []string{"exact", "detached", "wrong-tree"} { + t.Run(name, func(t *testing.T) { + wrong := name == "wrong-tree" + source := t.TempDir() + if e := os.WriteFile(filepath.Join(source, "source.txt"), []byte("inert owned source\n"), 0600); e != nil { + t.Fatal(e) + } + tagTestGit(t, source, "init", "-q", "-b", "main") + tagTestGit(t, source, "add", "source.txt") + tagTestGit(t, source, "commit", "-qm", "inert source") + branch := tagTestGit(t, source, "rev-parse", "refs/heads/main") + if name == "detached" { + tagTestGit(t, source, "checkout", "--detach", "HEAD") + if e := os.WriteFile(filepath.Join(source, "detached.txt"), []byte("inert detached candidate\n"), 0600); e != nil { + t.Fatal(e) + } + tagTestGit(t, source, "add", "detached.txt") + tagTestGit(t, source, "commit", "-qm", "inert detached candidate") + } + sha, tree := tagTestGit(t, source, "rev-parse", "HEAD"), tagTestGit(t, source, "rev-parse", "HEAD^{tree}") + root := t.TempDir() + for _, n := range []string{"execution-home", "execution-tmp"} { + if e := os.Mkdir(filepath.Join(root, n), 0700); e != nil { + t.Fatal(e) + } + } + q := tagQualification{sha: sha, tree: tree, root: root, source: source, engine: "/usr/bin/false", goBin: filepath.Join(runtime.GOROOT(), "bin/go"), run: runTagChild} + if wrong { + q.tree = strings.Repeat("0", 40) + } + dest, e := q.prepareClone() + if wrong { + if e == nil { + t.Fatal("wrong clone tree accepted") + } + return + } + if e != nil { + t.Fatal(e) + } + if tagTestGit(t, source, "rev-parse", "refs/heads/main") != branch || tagTestGit(t, source, "rev-parse", "HEAD") != sha { + t.Fatal("original source refs changed") + } + if tagTestGit(t, source, "tag", "--list") != "" { + t.Fatal("original checkout tags mutated") + } + if got := tagTestGit(t, dest, "tag", "--list"); got != "v0.0.0-qualification.g"+sha { + t.Fatal("owned qualification tag not exact") + } + if tagTestGit(t, dest, "rev-parse", "HEAD") != sha || tagTestGit(t, dest, "rev-parse", "HEAD^{tree}") != tree { + t.Fatal("owned source identity changed") + } + if tagTestGit(t, dest, "remote", "get-url", "origin") != "https://github.com/GoCodeAlone/workflow-plugin-compute.git" || tagTestGit(t, dest, "config", "--get", "remote.origin.pushurl") != "disabled://qualification" { + t.Fatal("canonical metadata/inert push binding changed") + } + if _, e := os.Lstat(filepath.Join(dest, ".git/objects/info/alternates")); !os.IsNotExist(e) { + t.Fatal("shared alternates present") + } + b, e := os.ReadFile(filepath.Join(dest, "source.txt")) + if e != nil || string(b) != "inert owned source\n" { + t.Fatal("clone raw source differs") + } + }) + } +} + +func TestTagChildFailureWithholdsOutput(t *testing.T) { + _, e := runTagChild(t.TempDir(), []string{"PATH=/usr/bin:/bin"}, []string{"/bin/sh", "-c", "printf 'inert-sensitive-output'; printf 'inert-sensitive-error' >&2; exit 7"}) + if e == nil || !strings.Contains(e.Error(), "exit 7") || strings.Contains(e.Error(), "inert-sensitive") { + t.Fatal("failed child output disclosed") + } + var w tagBoundedOutput + b := bytes.Repeat([]byte{'x'}, (1<<20)+1) + n, e := w.Write(b) + if e != nil || n != len(b) || w.Len() != 1<<20 || !w.overflow { + t.Fatal("bounded accepting output changed") + } +} + +func TestTagToolAuthenticationStopsBeforeExecution(t *testing.T) { + root := t.TempDir() + if e := os.Chmod(root, 0700); e != nil { + t.Fatal(e) + } + for _, name := range []string{"execution-home", "execution-tmp", "module-cache", "build-cache", "gopath"} { + if e := os.Mkdir(filepath.Join(root, name), 0700); e != nil { + t.Fatal(e) + } + } + if e := os.WriteFile(filepath.Join(root, "credentials-removed"), []byte("removed\n"), 0600); e != nil { + t.Fatal(e) + } + tool := filepath.Join(root, "inert-tool") + if e := os.WriteFile(tool, []byte("inert tool, never executed"), 0700); e != nil { + t.Fatal(e) + } + q := tagQualification{sha: strings.Repeat("1", 40), tree: strings.Repeat("2", 40), root: root, source: root, engine: tool, wfctl: tool, goBin: filepath.Join(runtime.GOROOT(), "bin/go"), run: func(string, []string, []string) ([]byte, error) { + t.Fatal("unauthenticated tool executed") + return nil, nil + }} + if e := q.execute(&bytes.Buffer{}); e == nil || !strings.Contains(e.Error(), "engine authentication failed") { + t.Fatalf("authentication boundary did not reach expected engine refusal: %v", e) + } +} + +func TestOwnedCredentialResidueBoundary(t *testing.T) { + b, e := os.ReadFile("../.github/workflows/tag-qualification.yml") + if e != nil { + t.Fatal(e) + } + s := string(b) + a := strings.Index(s, " set +e\n") + if a < 0 { + t.Fatal("residue boundary missing") + } + z := strings.Index(s[a:], " test \"$(du -sk") + if z < 0 { + t.Fatal("residue boundary missing") + } + block := s[a : a+z] + for _, present := range []bool{false, true} { + t.Run(map[bool]string{false: "clean", true: "residue"}[present], func(t *testing.T) { + root := t.TempDir() + value := "harmless input" + if present { + value = "inert-residue-marker" + } + if e := os.WriteFile(filepath.Join(root, "input"), []byte(value), 0600); e != nil { + t.Fatal(e) + } + cmd := exec.Command("/bin/bash", "--noprofile", "--norc", "-euo", "pipefail", "-c", block) + cmd.Env = []string{"PATH=/usr/bin:/bin", "OWNED_ROOT=" + root, "RELEASES_TOKEN=inert-residue-marker"} + var out, errout bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &errout + e := cmd.Run() + if (e != nil) != present || strings.Contains(out.String()+errout.String(), "inert-residue-marker") { + t.Fatalf("owned residue guard failed: %v", e) + } + _, e = os.Lstat(filepath.Join(root, "credentials-removed")) + if present && !os.IsNotExist(e) { + t.Fatal("residue created execution marker") + } + if !present && e != nil { + t.Fatal("clean input did not permit execution") + } + }) + } +} + +func TestTagQualificationCLIRefusals(t *testing.T) { + script, e := filepath.Abs("qualify-tag-archives.go") + if e != nil { + t.Fatal(e) + } + for _, cred := range []bool{false, true} { + t.Run(map[bool]string{false: "unadmitted-runtime", true: "credential"}[cred], func(t *testing.T) { + args := []string{"run", script, strings.Repeat("1", 40), strings.Repeat("2", 40), "inert", "inert", "inert", "inert", "inert"} + cmd := exec.Command(filepath.Join(runtime.GOROOT(), "bin/go"), args...) + cmd.Env = append(os.Environ(), "GO111MODULE=off", "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOPROXY=off", "GOSUMDB=off", "GOVCS=*:off") + if cred { + cmd.Env = append(cmd.Env, "GITHUB_TOKEN=inert-fixture") + } + var out, errout bytes.Buffer + cmd.Stdout, cmd.Stderr = &out, &errout + e := cmd.Run() + exit, ok := e.(*exec.ExitError) + want := "qualification paths must be canonical/absolute" + if runtime.GOOS != "linux" || runtime.GOARCH != "amd64" { + want = "requires local Go1.27.4 linux/amd64" + } + if cred { + want = "credential/tag override environment refused" + } + if !ok || exit.ExitCode() != 1 || out.Len() != 0 || !strings.Contains(errout.String(), want) || strings.Contains(errout.String(), "inert-fixture") { + t.Fatalf("actual orchestration entry-point refusal changed: %v %q", e, errout.String()) + } + }) + } +} From f9ff4acac608e7e23bb4c206f1e8e11548587c90 Mon Sep 17 00:00:00 2001 From: Jon Langevin Date: Wed, 25 Nov 2026 20:55:04 -0500 Subject: [PATCH 5/8] Report bounded diagnostics for tag qualification failures --- .github/workflows/archive-qualification.yml | 8 +- .github/workflows/tag-qualification.yml | 16 +- scripts/check-native-release.go | 99 ++++++++++- scripts/check-native-release_test.go | 184 ++++++++++++++++++++ scripts/qualify-tag-archives.go | 111 +++++++++++- scripts/qualify-tag-archives_test.go | 131 ++++++++++++++ 6 files changed, 531 insertions(+), 18 deletions(-) diff --git a/.github/workflows/archive-qualification.yml b/.github/workflows/archive-qualification.yml index e7c9037..14f76fe 100644 --- a/.github/workflows/archive-qualification.yml +++ b/.github/workflows/archive-qualification.yml @@ -51,8 +51,8 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 79508cb83ac4c8512c19e4697bcc615ee7ef35fe011a258e97bf51c9235773c6 scripts/check-native-release.go - e6cde44d4d9fe8c72877aa420c70823e238e10281ef34363da0d2861afcc00a3 scripts/check-native-release_test.go + 84a2952559c853257d714f0f821858941b506469c376454bc5c3b52526a7ab5d scripts/check-native-release.go + 0f08ca658f13ce9177092e7d36689dbcb1248d187390ffcd7375fd251948d902 scripts/check-native-release_test.go INPUTS test "$(go version)" = 'go version go1.27.4 linux/amd64' ENGINE_BIN="$(command -v goreleaser)" @@ -122,8 +122,8 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 79508cb83ac4c8512c19e4697bcc615ee7ef35fe011a258e97bf51c9235773c6 scripts/check-native-release.go - e6cde44d4d9fe8c72877aa420c70823e238e10281ef34363da0d2861afcc00a3 scripts/check-native-release_test.go + 84a2952559c853257d714f0f821858941b506469c376454bc5c3b52526a7ab5d scripts/check-native-release.go + 0f08ca658f13ce9177092e7d36689dbcb1248d187390ffcd7375fd251948d902 scripts/check-native-release_test.go INPUTS home="$(mktemp -d "$OWNED_ROOT/package-home.XXXXXXXX")" tmp="$(mktemp -d "$OWNED_ROOT/package-tmp.XXXXXXXX")" diff --git a/.github/workflows/tag-qualification.yml b/.github/workflows/tag-qualification.yml index 78c748a..d6bf2eb 100644 --- a/.github/workflows/tag-qualification.yml +++ b/.github/workflows/tag-qualification.yml @@ -48,10 +48,10 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 79508cb83ac4c8512c19e4697bcc615ee7ef35fe011a258e97bf51c9235773c6 scripts/check-native-release.go - e6cde44d4d9fe8c72877aa420c70823e238e10281ef34363da0d2861afcc00a3 scripts/check-native-release_test.go - 9851e70b4561fb13962ba466f78c78d6f2373291b5a747c79b8d2919969f0830 scripts/qualify-tag-archives.go - f1d93f6f9ba1f53131a5354f44dd1fde9fe0bc8cac2190dd75d6764764671883 scripts/qualify-tag-archives_test.go + 84a2952559c853257d714f0f821858941b506469c376454bc5c3b52526a7ab5d scripts/check-native-release.go + 0f08ca658f13ce9177092e7d36689dbcb1248d187390ffcd7375fd251948d902 scripts/check-native-release_test.go + fe2c2ca977ea7a913e3b7482f9ab185cc0ab89c97b8a273241491bada7ab08b4 scripts/qualify-tag-archives.go + fc31789161cef0182eaa3b9fc93a26a1de798df416fed96e079f4179fcbe52e2 scripts/qualify-tag-archives_test.go 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh INPUTS root="$(mktemp -d "$RUNNER_TEMP/tag-qualification.XXXXXXXX")" @@ -142,10 +142,10 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 79508cb83ac4c8512c19e4697bcc615ee7ef35fe011a258e97bf51c9235773c6 scripts/check-native-release.go - e6cde44d4d9fe8c72877aa420c70823e238e10281ef34363da0d2861afcc00a3 scripts/check-native-release_test.go - 9851e70b4561fb13962ba466f78c78d6f2373291b5a747c79b8d2919969f0830 scripts/qualify-tag-archives.go - f1d93f6f9ba1f53131a5354f44dd1fde9fe0bc8cac2190dd75d6764764671883 scripts/qualify-tag-archives_test.go + 84a2952559c853257d714f0f821858941b506469c376454bc5c3b52526a7ab5d scripts/check-native-release.go + 0f08ca658f13ce9177092e7d36689dbcb1248d187390ffcd7375fd251948d902 scripts/check-native-release_test.go + fe2c2ca977ea7a913e3b7482f9ab185cc0ab89c97b8a273241491bada7ab08b4 scripts/qualify-tag-archives.go + fc31789161cef0182eaa3b9fc93a26a1de798df416fed96e079f4179fcbe52e2 scripts/qualify-tag-archives_test.go 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh INPUTS mkdir "$OWNED_ROOT/execution-home" "$OWNED_ROOT/execution-tmp" diff --git a/scripts/check-native-release.go b/scripts/check-native-release.go index b52a453..2c0dbed 100644 --- a/scripts/check-native-release.go +++ b/scripts/check-native-release.go @@ -43,6 +43,30 @@ type nativeValidationReceipt struct { VerifierSHA string `json:"verifier_sha256"` } +// Failure diagnostics are deliberately distinct from an accepted native +// receipt: fixed facts only, with no paths, child output or error strings. +type nativeFailureDiagnostic struct { + Schema int `json:"schema"` + Scope string `json:"scope"` + PrimaryPhase string `json:"primary_phase"` + VerifierResult string `json:"verifier_result"` + Joined bool `json:"joined"` + Exit *int `json:"exit,omitempty"` + Cleanup string `json:"cleanup"` + TmpBytes *int `json:"tmpdir_bytes,omitempty"` +} + +func writeNativeFailureDiagnostic(path string, diagnostic nativeFailureDiagnostic) error { + b, e := json.Marshal(diagnostic) + if e != nil { + return e + } + if len(b) > 512 { + return errors.New("native diagnostic exceeded bound") + } + return writeNativeRecord(path, b) +} + func nativeReceiptDestination(root, path string) error { if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "\x00\r\n") { return errors.New("receipt requires a fresh absolute owned path") @@ -55,6 +79,18 @@ func nativeReceiptDestination(root, path string) error { if err != nil || !parent.IsDir() || parent.Mode().Perm() != 0700 { return errors.New("receipt parent must be a private owned directory") } + canonicalRoot, e := filepath.EvalSymlinks(root) + if e != nil { + return errors.New("cannot resolve receipt source") + } + canonicalParent, e := filepath.EvalSymlinks(filepath.Dir(path)) + if e != nil { + return errors.New("cannot resolve receipt parent") + } + rel, e = filepath.Rel(canonicalRoot, canonicalParent) + if e != nil || (rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))) { + return errors.New("receipt must remain outside source") + } if _, err = os.Lstat(path); !os.IsNotExist(err) { return errors.New("receipt destination already exists or is unavailable") } @@ -66,6 +102,10 @@ func writeNativeReceipt(path string, receipt nativeValidationReceipt) error { if err != nil { return err } + return writeNativeRecord(path, b) +} + +func writeNativeRecord(path string, b []byte) error { f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) if err != nil { return errors.New("cannot exclusively create native receipt") @@ -152,11 +192,36 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res if err != nil { return "", errors.New("cannot resolve project root") } + phase := "artifact" + diagnostic := nativeFailureDiagnostic{Schema: 1, Scope: "native-hook-diagnostic", VerifierResult: "not-invoked", Cleanup: "not-created"} + if opt.receipt != "" { + // Both names must be fresh before installing reporting. Resolve parent + // placement so neither receipt can redirect into the source tree. + if err = nativeReceiptDestination(root, opt.receipt); err != nil { + return "", err + } + if err = nativeReceiptDestination(root, opt.receipt+".status"); err != nil { + return "", err + } + defer func() { + if err == nil { + return + } + if diagnostic.PrimaryPhase == "" { + diagnostic.PrimaryPhase = phase + } + if e := writeNativeFailureDiagnostic(opt.receipt+".status", diagnostic); e != nil { + err = errors.Join(err, fmt.Errorf("native diagnostic failed: %w", e)) + result = "" + } + }() + } artifact, err := nativeArtifactPath(root, args[2]) if err != nil { return "", err } manifest := filepath.Join(root, "plugin.json") + phase = "tool" if !filepath.IsAbs(opt.tool) || filepath.Clean(opt.tool) != opt.tool { return "", errors.New("WFCTL_BIN must be an absolute verifier path") } @@ -164,25 +229,36 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res if err != nil || toolSHA != opt.digest { return "", errors.New("wfctl authentication failed") } + phase = "artifact" artifactSHA, err := nativeDigest(artifact, 128<<20, true) if err != nil { return "", fmt.Errorf("artifact validation failed: %w", err) } + phase = "manifest" manifestSHA, err := nativeDigest(manifest, 64<<10, false) if err != nil { return "", fmt.Errorf("manifest validation failed: %w", err) } + phase = "receipt-destination" if opt.receipt != "" { if err = nativeReceiptDestination(root, opt.receipt); err != nil { return "", err } } + phase = "workspace" owned, err := os.MkdirTemp("", "compute-native-check-") if err != nil { return "", errors.New("cannot create owned verifier directory") } defer func() { + // Preserve the primary phase even if cleanup independently fails. + diagnostic.PrimaryPhase = "none" + if err != nil { + diagnostic.PrimaryPhase = phase + } + diagnostic.Cleanup = "removed" if e := opt.cleanup(owned); e != nil { + diagnostic.Cleanup = "failed" err = errors.Join(err, fmt.Errorf("owned verifier cleanup failed: %w", e)) result = "" } @@ -194,6 +270,7 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res e = writeNativeReceipt(opt.receipt, nativeValidationReceipt{Schema: 1, Scope: "runtime-identity-version-declared-iac", Verdict: "pass", Target: "linux-amd64", Artifact: filepath.ToSlash(rel), ArtifactSHA: artifactSHA, ManifestSHA: manifestSHA, VerifierSHA: toolSHA}) } if e != nil { + diagnostic.PrimaryPhase = "receipt" err, result = fmt.Errorf("native receipt failed: %w", e), "" } } @@ -207,9 +284,25 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=" + home, "TMPDIR=" + tmp, "LANG=C", "LC_ALL=C", "WFCTL_DIFFCACHE=:memory:", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_TERMINAL_PROMPT=0"} // No raw plugin output or inherited stdin: only fixed gate diagnostics. cmd.Stdout, cmd.Stderr = io.Discard, io.Discard - if e := opt.run(cmd); e != nil { - return "", fmt.Errorf("runtime identity/version/declared-IaC verifier failed: %w", e) - } + phase = "verifier" + n := len(tmp) + diagnostic.TmpBytes = &n // Exactly the TMPDIR supplied above. + runErr := opt.run(cmd) + switch { + case cmd.ProcessState != nil: + diagnostic.VerifierResult = "exited" + diagnostic.Joined = true + code := cmd.ProcessState.ExitCode() + diagnostic.Exit = &code + case cmd.Process == nil: + diagnostic.VerifierResult = "not-started" + default: + diagnostic.VerifierResult = "state-unavailable" + } + if runErr != nil { + return "", fmt.Errorf("runtime identity/version/declared-IaC verifier failed: %w", runErr) + } + phase = "postcheck" for _, input := range []struct { path, before string limit int64 diff --git a/scripts/check-native-release_test.go b/scripts/check-native-release_test.go index 545a115..4143830 100644 --- a/scripts/check-native-release_test.go +++ b/scripts/check-native-release_test.go @@ -396,3 +396,187 @@ func TestNativeReleaseCLI(t *testing.T) { }) } } + +// Real native checker function and, for the verifier cases, a finite harmless +// shell helper. No wfctl/plugin, sockets or encryption is invoked. +func TestNativeFailureDiagnostics(t *testing.T) { + for _, name := range []string{"tool", "verifier", "verifier-and-cleanup", "cleanup", "postcheck", "receipt", "existing-status"} { + t.Run(name, func(t *testing.T) { + root, args, opt := nativeFixture(t) + dir := t.TempDir() + if e := os.Chmod(dir, 0700); e != nil { + t.Fatal(e) + } + opt.receipt = filepath.Join(dir, "native.json") + path := opt.receipt + ".status" + calls := 0 + opt.run = func(*exec.Cmd) error { calls++; return nil } + cleanupFailure := errors.New("inert-cleanup-private-marker") + primary := "tool" + cleanup := "not-created" + joined := false + switch name { + case "tool": + opt.digest = strings.Repeat("0", 64) + case "verifier", "verifier-and-cleanup": + if e := os.WriteFile(opt.tool, []byte("#!/bin/sh\nprintf inert-private-output\nprintf inert-private-error >&2\nexit 7\n"), 0700); e != nil { + t.Fatal(e) + } + opt.digest, _ = nativeDigest(opt.tool, 160<<20, true) + opt.run = func(c *exec.Cmd) error { calls++; return c.Run() } + primary, cleanup, joined = "verifier", "removed", true + case "cleanup": + primary, cleanup = "none", "failed" + case "postcheck": + primary, cleanup = "postcheck", "removed" + opt.run = func(*exec.Cmd) error { + calls++ + return os.WriteFile(filepath.Join(root, "dist/plugin"), []byte("inert changed artifact"), 0700) + } + case "receipt": + primary, cleanup = "receipt", "removed" + opt.run = func(*exec.Cmd) error { calls++; return os.WriteFile(opt.receipt, []byte("preserve inert file"), 0600) } + case "existing-status": + if e := os.WriteFile(path, []byte("preserve inert status"), 0600); e != nil { + t.Fatal(e) + } + } + if name == "cleanup" || name == "verifier-and-cleanup" { + if name == "verifier-and-cleanup" { + cleanup = "failed" + } + opt.cleanup = func(p string) error { + if e := os.RemoveAll(p); e != nil { + return e + } + return cleanupFailure + } + } + suppliedTmpBytes := 0 + run := opt.run + opt.run = func(c *exec.Cmd) error { + for _, v := range c.Env { + if strings.HasPrefix(v, "TMPDIR=") { + suppliedTmpBytes = len(strings.TrimPrefix(v, "TMPDIR=")) + } + } + return run(c) + } + result, e := checkNativeRelease(root, args, opt) + if name == "existing-status" { + b, _ := os.ReadFile(path) + if e == nil || calls != 0 || string(b) != "preserve inert status" { + t.Fatal("preexisting diagnostic did not stop before invocation") + } + return + } + if e == nil || result != "" { + t.Fatal("failed gate did not fail") + } + if name == "cleanup" || name == "verifier-and-cleanup" { + if !errors.Is(e, cleanupFailure) { + t.Fatal("cleanup error identity lost") + } + } + b, readErr := os.ReadFile(path) + if readErr != nil { + t.Fatalf("fixed failure diagnostic missing: %v", readErr) + } + if len(b) > 512 || bytes.Contains(b, []byte("private")) || bytes.Contains(b, []byte(root)) || bytes.Contains(b, []byte(opt.tool)) { + t.Fatal("diagnostic disclosed raw input/output or exceeded bound") + } + var d map[string]any + if e := json.Unmarshal(b, &d); e != nil { + t.Fatal(e) + } + if d["schema"] != float64(1) || d["scope"] != "native-hook-diagnostic" || d["primary_phase"] != primary || d["cleanup"] != cleanup || d["joined"] != joined { + t.Fatalf("incorrect fixed diagnostic facts: %s", b) + } + if joined { + var exited *exec.ExitError + if !errors.As(e, &exited) || exited.ExitCode() != 7 { + t.Fatal("primary exit identity lost") + } + if d["exit"] != float64(7) || d["verifier_result"] != "exited" { + t.Fatal("actual joined exit missing") + } + } else if _, ok := d["exit"]; ok { + t.Fatal("exit fabricated without completed command state") + } + if name == "tool" { + if _, ok := d["tmpdir_bytes"]; ok { + t.Fatal("TMPDIR length fabricated before construction") + } + } else if n, ok := d["tmpdir_bytes"].(float64); !ok || n != float64(suppliedTmpBytes) || n <= 0 || n > 4096 { + t.Fatal("exact child temporary path length missing") + } + st, statErr := os.Stat(path) + if statErr != nil || st.Mode().Perm() != 0600 { + t.Fatal("diagnostic file is not private") + } + if name == "verifier" { + t.Logf("NATIVE_DIAGNOSTIC_FIXTURE:%s", b) + } + if name != "receipt" { + if _, e := os.Lstat(opt.receipt); !os.IsNotExist(e) { + t.Fatal("failed gate emitted success receipt") + } + } + }) + } +} + +func TestNativeDiagnosticWriteFailurePreservesPrimary(t *testing.T) { + root, args, opt := nativeFixture(t) + dir := t.TempDir() + if e := os.Chmod(dir, 0700); e != nil { + t.Fatal(e) + } + opt.receipt = filepath.Join(dir, "native.json") + if e := os.WriteFile(opt.tool, []byte("#!/bin/sh\nexit 7\n"), 0700); e != nil { + t.Fatal(e) + } + opt.digest, _ = nativeDigest(opt.tool, 160<<20, true) + var primaryErr error + opt.run = func(c *exec.Cmd) error { + if e := os.WriteFile(opt.receipt+".status", []byte("preserve inert record"), 0600); e != nil { + t.Fatal(e) + } + primaryErr = c.Run() + return primaryErr + } + _, e := checkNativeRelease(root, args, opt) + var exit *exec.ExitError + if primaryErr == nil || !errors.Is(e, primaryErr) || !errors.As(e, &exit) || exit.ExitCode() != 7 || !strings.Contains(e.Error(), "native diagnostic failed") { + t.Fatal("diagnostic write failure swallowed primary exit") + } + b, _ := os.ReadFile(opt.receipt + ".status") + if string(b) != "preserve inert record" { + t.Fatal("diagnostic overwrote a competing record") + } + if _, e := os.Lstat(opt.receipt); !os.IsNotExist(e) { + t.Fatal("failure emitted accepted receipt") + } +} + +func TestNativeReceiptResolvedSourceRefusal(t *testing.T) { + root, args, opt := nativeFixture(t) + parent := t.TempDir() + if e := os.Mkdir(filepath.Join(root, "inside"), 0700); e != nil { + t.Fatal(e) + } + if e := os.Symlink(root, filepath.Join(parent, "owned-alias")); e != nil { + t.Fatal(e) + } + opt.receipt = filepath.Join(parent, "owned-alias", "inside", "native.json") + calls := 0 + opt.run = func(*exec.Cmd) error { calls++; return nil } + _, e := checkNativeRelease(root, args, opt) + if e == nil || !strings.Contains(e.Error(), "outside source") || calls != 0 { + t.Fatal("resolved source-local destination accepted") + } + entries, e := os.ReadDir(filepath.Join(root, "inside")) + if e != nil || len(entries) != 0 { + t.Fatal("refused destination changed source") + } +} diff --git a/scripts/qualify-tag-archives.go b/scripts/qualify-tag-archives.go index ed71297..853783e 100644 --- a/scripts/qualify-tag-archives.go +++ b/scripts/qualify-tag-archives.go @@ -77,9 +77,9 @@ func runTagChild(dir string, env, argv []string) ([]byte, error) { e := cmd.Run() if e != nil { if exit, ok := e.(*exec.ExitError); ok { - return nil, fmt.Errorf("qualification subprocess failed (exit %d); output withheld", exit.ExitCode()) + return nil, fmt.Errorf("qualification subprocess failed (exit %d); output withheld%s", exit.ExitCode(), tagNativeDiagnostic(dir, env)) } - return nil, errors.New("qualification subprocess could not start; output withheld") + return nil, fmt.Errorf("qualification subprocess could not start; output withheld%s", tagNativeDiagnostic(dir, env)) } if out.overflow || errout.overflow { return nil, errors.New("qualification subprocess output limit exceeded; output withheld") @@ -87,6 +87,111 @@ func runTagChild(dir string, env, argv []string) ([]byte, error) { return out.Bytes(), nil } +// Diagnostic-only wire. It never authorizes an artifact or changes failure. +type tagNativeStatus struct { + Schema int `json:"schema"` + Scope string `json:"scope"` + PrimaryPhase string `json:"primary_phase"` + VerifierResult string `json:"verifier_result"` + Joined bool `json:"joined"` + Exit *int `json:"exit,omitempty"` + Cleanup string `json:"cleanup"` + TmpBytes *int `json:"tmpdir_bytes,omitempty"` +} + +func tagNativeDiagnostic(source string, env []string) string { + receipt := "" + count := 0 + for _, v := range env { + if bytes.HasPrefix([]byte(v), []byte("NATIVE_CHECK_RECEIPT=")) { + receipt = v[len("NATIVE_CHECK_RECEIPT="):] + count++ + } + } + if count == 0 { + return "" + } + prefix := `; native diagnostic=` + unusable := prefix + `{"observation":"unusable"}` + if count != 1 || !filepath.IsAbs(receipt) || filepath.Clean(receipt) != receipt { + return unusable + } + parent := filepath.Dir(receipt) + st, e := os.Lstat(parent) + if e != nil || !st.IsDir() || st.Mode().Perm() != 0700 { + return unusable + } + resolved, e := filepath.EvalSymlinks(parent) + if e != nil { + return unusable + } + canonicalSource, e := filepath.EvalSymlinks(source) + if e != nil { + return unusable + } + rel, e := filepath.Rel(canonicalSource, resolved) + if e != nil || (rel != ".." && !bytes.HasPrefix([]byte(rel), []byte(".."+string(filepath.Separator)))) { + return unusable + } + path := receipt + ".status" + st, e = os.Lstat(path) + if os.IsNotExist(e) { + return prefix + `{"observation":"not-observed"}` + } + if e != nil || !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() > 512 { + return unusable + } + f, e := os.Open(path) + if e != nil { + return unusable + } + b, e := io.ReadAll(io.LimitReader(f, 513)) + closeErr := f.Close() + if e != nil || closeErr != nil || int64(len(b)) != st.Size() || len(b) > 512 { + return unusable + } + var d tagNativeStatus + decoder := json.NewDecoder(bytes.NewReader(b)) + decoder.DisallowUnknownFields() + if decoder.Decode(&d) != nil { + return unusable + } + canonical, e := json.Marshal(d) + if e != nil || !bytes.Equal(bytes.TrimSpace(b), canonical) { + return unusable + } // Also rejects duplicate keys/trailing data. + phases := map[string]bool{"none": true, "artifact": true, "tool": true, "manifest": true, "receipt-destination": true, "workspace": true, "verifier": true, "postcheck": true, "receipt": true} + cleanups := map[string]bool{"not-created": true, "removed": true, "failed": true} + if d.Schema != 1 || d.Scope != "native-hook-diagnostic" || !phases[d.PrimaryPhase] || !cleanups[d.Cleanup] || (d.PrimaryPhase == "none" && d.Cleanup != "failed") { + return unusable + } + if d.TmpBytes != nil && (*d.TmpBytes <= 0 || *d.TmpBytes > 4096) { + return unusable + } + switch d.VerifierResult { + case "not-invoked": + if d.Joined || d.Exit != nil || d.TmpBytes != nil { + return unusable + } + case "not-started", "state-unavailable": + if d.Joined || d.Exit != nil || d.TmpBytes == nil { + return unusable + } + case "exited": + if !d.Joined || d.Exit == nil || *d.Exit < -1 || *d.Exit > 255 || d.TmpBytes == nil { + return unusable + } + default: + return unusable + } + // All values here have been validated against fixed enums/integer bounds. + out, _ := json.Marshal(struct { + Observation string `json:"observation"` + Facts tagNativeStatus `json:"facts"` + }{"refused", d}) + return prefix + string(out) +} + type tagBoundedOutput struct { bytes.Buffer overflow bool @@ -175,7 +280,7 @@ func (q tagQualification) execute(out io.Writer) error { return errors.New("qualification directories missing/redirected") } } - for _, name := range []string{"before.json", "native.json", "archives.json", "combined.json"} { + for _, name := range []string{"before.json", "native.json", "native.json.status", "archives.json", "combined.json"} { if _, e := os.Lstat(filepath.Join(q.root, name)); !os.IsNotExist(e) { return errors.New("qualification receipts must be fresh") } diff --git a/scripts/qualify-tag-archives_test.go b/scripts/qualify-tag-archives_test.go index 27ca059..a6d39a2 100644 --- a/scripts/qualify-tag-archives_test.go +++ b/scripts/qualify-tag-archives_test.go @@ -237,3 +237,134 @@ func TestTagQualificationCLIRefusals(t *testing.T) { }) } } + +// Exercise the real subprocess failure entry boundary with finite harmless +// exit7 and owned wire fixtures; never execute a release engine. +func TestTagChildFixedNativeDiagnostics(t *testing.T) { + good := `{"schema":1,"scope":"native-hook-diagnostic","primary_phase":"verifier","verifier_result":"exited","joined":true,"exit":7,"cleanup":"removed","tmpdir_bytes":99}` + for _, name := range []string{"valid", "missing", "unknown", "malformed", "oversize", "bad-phase", "bad-number", "bad-schema", "bad-cleanup", "bad-result", "bad-joined", "bad-length", "duplicate", "symlink"} { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + if e := os.Chmod(dir, 0700); e != nil { + t.Fatal(e) + } + receipt := filepath.Join(dir, "native.json") + path := receipt + ".status" + wire, want := good, `"observation":"refused"` + switch name { + case "missing": + want = `"observation":"not-observed"` + case "unknown": + wire = strings.TrimSuffix(good, "}") + `,"inert-private-marker":"inert-private-value"}` + want = `"observation":"unusable"` + case "malformed": + wire = "inert-private-malformed" + want = `"observation":"unusable"` + case "oversize": + wire = strings.Repeat("x", 513) + want = `"observation":"unusable"` + case "bad-phase": + wire = strings.Replace(good, `"primary_phase":"verifier"`, `"primary_phase":"inert-private-phase"`, 1) + want = `"observation":"unusable"` + case "bad-number": + wire = strings.Replace(good, `"exit":7`, `"exit":7.5`, 1) + want = `"observation":"unusable"` + case "bad-schema": + wire = strings.Replace(good, `"schema":1`, `"schema":2`, 1) + want = `"observation":"unusable"` + case "bad-cleanup": + wire = strings.Replace(good, `"cleanup":"removed"`, `"cleanup":"inert-private-cleanup"`, 1) + want = `"observation":"unusable"` + case "bad-result": + wire = strings.Replace(good, `"verifier_result":"exited"`, `"verifier_result":"inert-private-result"`, 1) + want = `"observation":"unusable"` + case "bad-joined": + wire = strings.Replace(good, `"joined":true`, `"joined":false`, 1) + want = `"observation":"unusable"` + case "bad-length": + wire = strings.Replace(good, `"tmpdir_bytes":99`, `"tmpdir_bytes":4097`, 1) + want = `"observation":"unusable"` + case "duplicate": + wire = strings.TrimSuffix(good, "}") + `,"exit":7}` + want = `"observation":"unusable"` + case "symlink": + want = `"observation":"unusable"` + } + if name != "missing" { + dest := path + if name == "symlink" { + dest = filepath.Join(dir, "inert-target") + } + if e := os.WriteFile(dest, []byte(wire), 0600); e != nil { + t.Fatal(e) + } + if name == "symlink" { + if e := os.Symlink(dest, path); e != nil { + t.Fatal(e) + } + } + } + _, e := runTagChild(t.TempDir(), []string{"PATH=/usr/bin:/bin", "NATIVE_CHECK_RECEIPT=" + receipt}, []string{"/bin/sh", "-c", "printf inert-private-output; printf inert-private-error >&2; exit 7"}) + if e == nil || !strings.Contains(e.Error(), "exit 7") || !strings.Contains(e.Error(), want) || strings.Contains(e.Error(), "private") || strings.Contains(e.Error(), dir) { + t.Fatalf("fixed diagnostic boundary missing: %v", e) + } + }) + } +} + +// Actual native producer function -> its exact wire bytes -> actual driver +// subprocess-error consumer. Only the verifier is a finite inert shell helper; +// this is not a release engine/wfctl/plugin invocation or native acceptance. +func TestTagNativeDiagnosticProducerCrossing(t *testing.T) { + argv := []string{filepath.Join(runtime.GOROOT(), "bin/go"), "test", "-v", "-count=1", "-p=1", "-timeout=30s", "-run", "^TestNativeFailureDiagnostics/verifier$", "check-native-release.go", "check-native-release_test.go"} + b, e := runTagChild(".", os.Environ(), argv) + if e != nil { + t.Fatal(e) + } + var wire string + for _, line := range strings.Split(string(b), "\n") { + if _, v, ok := strings.Cut(line, "NATIVE_DIAGNOSTIC_FIXTURE:"); ok { + if wire != "" { + t.Fatal("ambiguous producer fixture") + } + wire = v + } + } + if wire == "" { + t.Fatal("actual native diagnostic producer not observed") + } + dir := t.TempDir() + if e := os.Chmod(dir, 0700); e != nil { + t.Fatal(e) + } + receipt := filepath.Join(dir, "native.json") + if e := os.WriteFile(receipt+".status", []byte(wire), 0600); e != nil { + t.Fatal(e) + } + _, e = runTagChild(t.TempDir(), []string{"PATH=/usr/bin:/bin", "NATIVE_CHECK_RECEIPT=" + receipt}, []string{"/bin/sh", "-c", "exit 7"}) + if e == nil || !strings.Contains(e.Error(), `"observation":"refused"`) || !strings.Contains(e.Error(), `"primary_phase":"verifier"`) || !strings.Contains(e.Error(), `"joined":true`) { + t.Fatalf("actual wire did not cross strict consumer: %v", e) + } +} + +func TestTagDiagnosticFreshnessBeforeExecution(t *testing.T) { + root := t.TempDir() + if e := os.Chmod(root, 0700); e != nil { + t.Fatal(e) + } + for _, n := range []string{"execution-home", "execution-tmp", "module-cache", "build-cache", "gopath"} { + if e := os.Mkdir(filepath.Join(root, n), 0700); e != nil { + t.Fatal(e) + } + } + if e := os.WriteFile(filepath.Join(root, "native.json.status"), []byte("inert preexisting status"), 0600); e != nil { + t.Fatal(e) + } + q := tagQualification{sha: strings.Repeat("1", 40), tree: strings.Repeat("2", 40), root: root, source: root, engine: "/inert/engine", wfctl: "/inert/wfctl", goBin: filepath.Join(runtime.GOROOT(), "bin/go"), run: func(string, []string, []string) ([]byte, error) { + t.Fatal("stale diagnostic reached execution") + return nil, nil + }} + if e := q.execute(&bytes.Buffer{}); e == nil || !strings.Contains(e.Error(), "receipts must be fresh") { + t.Fatalf("stale diagnostic not refused before execution: %v", e) + } +} From 000f5e4931eabe40135271f490bf3e3e4f468ca8 Mon Sep 17 00:00:00 2001 From: Jon Langevin Date: Wed, 25 Nov 2026 21:24:34 -0500 Subject: [PATCH 6/8] Classify bounded native verifier failure hints --- .github/workflows/archive-qualification.yml | 8 +- .github/workflows/tag-qualification.yml | 16 ++-- scripts/check-native-release.go | 88 +++++++++++++++++- scripts/check-native-release_test.go | 98 ++++++++++++++++++++- scripts/qualify-tag-archives.go | 17 ++++ scripts/qualify-tag-archives_test.go | 74 ++++++++++++++++ 6 files changed, 287 insertions(+), 14 deletions(-) diff --git a/.github/workflows/archive-qualification.yml b/.github/workflows/archive-qualification.yml index 14f76fe..bef1f56 100644 --- a/.github/workflows/archive-qualification.yml +++ b/.github/workflows/archive-qualification.yml @@ -51,8 +51,8 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 84a2952559c853257d714f0f821858941b506469c376454bc5c3b52526a7ab5d scripts/check-native-release.go - 0f08ca658f13ce9177092e7d36689dbcb1248d187390ffcd7375fd251948d902 scripts/check-native-release_test.go + 9fe612289e89d68fee1758bfbe4bb10e865474bf74ce83ce6336f2cdfac67e0c scripts/check-native-release.go + 4f840be2cd14577133d7f524ef3015c6dd58b3af7102efface925c44213e8192 scripts/check-native-release_test.go INPUTS test "$(go version)" = 'go version go1.27.4 linux/amd64' ENGINE_BIN="$(command -v goreleaser)" @@ -122,8 +122,8 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 84a2952559c853257d714f0f821858941b506469c376454bc5c3b52526a7ab5d scripts/check-native-release.go - 0f08ca658f13ce9177092e7d36689dbcb1248d187390ffcd7375fd251948d902 scripts/check-native-release_test.go + 9fe612289e89d68fee1758bfbe4bb10e865474bf74ce83ce6336f2cdfac67e0c scripts/check-native-release.go + 4f840be2cd14577133d7f524ef3015c6dd58b3af7102efface925c44213e8192 scripts/check-native-release_test.go INPUTS home="$(mktemp -d "$OWNED_ROOT/package-home.XXXXXXXX")" tmp="$(mktemp -d "$OWNED_ROOT/package-tmp.XXXXXXXX")" diff --git a/.github/workflows/tag-qualification.yml b/.github/workflows/tag-qualification.yml index d6bf2eb..366a07a 100644 --- a/.github/workflows/tag-qualification.yml +++ b/.github/workflows/tag-qualification.yml @@ -48,10 +48,10 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 84a2952559c853257d714f0f821858941b506469c376454bc5c3b52526a7ab5d scripts/check-native-release.go - 0f08ca658f13ce9177092e7d36689dbcb1248d187390ffcd7375fd251948d902 scripts/check-native-release_test.go - fe2c2ca977ea7a913e3b7482f9ab185cc0ab89c97b8a273241491bada7ab08b4 scripts/qualify-tag-archives.go - fc31789161cef0182eaa3b9fc93a26a1de798df416fed96e079f4179fcbe52e2 scripts/qualify-tag-archives_test.go + 9fe612289e89d68fee1758bfbe4bb10e865474bf74ce83ce6336f2cdfac67e0c scripts/check-native-release.go + 4f840be2cd14577133d7f524ef3015c6dd58b3af7102efface925c44213e8192 scripts/check-native-release_test.go + 3c1d05b6ba0fb93e9b03061e45bfb9b4ae0b7f5055c086261342fb40cc713955 scripts/qualify-tag-archives.go + b6a3123bb11c5774585fb59bc4325958cf0651d69d3acc10a55dab973e8c79fd scripts/qualify-tag-archives_test.go 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh INPUTS root="$(mktemp -d "$RUNNER_TEMP/tag-qualification.XXXXXXXX")" @@ -142,10 +142,10 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 84a2952559c853257d714f0f821858941b506469c376454bc5c3b52526a7ab5d scripts/check-native-release.go - 0f08ca658f13ce9177092e7d36689dbcb1248d187390ffcd7375fd251948d902 scripts/check-native-release_test.go - fe2c2ca977ea7a913e3b7482f9ab185cc0ab89c97b8a273241491bada7ab08b4 scripts/qualify-tag-archives.go - fc31789161cef0182eaa3b9fc93a26a1de798df416fed96e079f4179fcbe52e2 scripts/qualify-tag-archives_test.go + 9fe612289e89d68fee1758bfbe4bb10e865474bf74ce83ce6336f2cdfac67e0c scripts/check-native-release.go + 4f840be2cd14577133d7f524ef3015c6dd58b3af7102efface925c44213e8192 scripts/check-native-release_test.go + 3c1d05b6ba0fb93e9b03061e45bfb9b4ae0b7f5055c086261342fb40cc713955 scripts/qualify-tag-archives.go + b6a3123bb11c5774585fb59bc4325958cf0651d69d3acc10a55dab973e8c79fd scripts/qualify-tag-archives_test.go 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh INPUTS mkdir "$OWNED_ROOT/execution-home" "$OWNED_ROOT/execution-tmp" diff --git a/scripts/check-native-release.go b/scripts/check-native-release.go index 2c0dbed..a940b6a 100644 --- a/scripts/check-native-release.go +++ b/scripts/check-native-release.go @@ -6,6 +6,7 @@ package main import ( + "bytes" "crypto/sha256" "encoding/json" "errors" @@ -14,8 +15,11 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "runtime" + "strconv" "strings" + "unicode/utf8" ) // Immutable official Workflow release v0.78.2, asset 442231027. This binds the @@ -54,6 +58,8 @@ type nativeFailureDiagnostic struct { Exit *int `json:"exit,omitempty"` Cleanup string `json:"cleanup"` TmpBytes *int `json:"tmpdir_bytes,omitempty"` + ReasonHint string `json:"reason_hint,omitempty"` + SocketBytes *int `json:"socket_path_bytes,omitempty"` } func writeNativeFailureDiagnostic(path string, diagnostic nativeFailureDiagnostic) error { @@ -283,7 +289,8 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res cmd.Dir = root cmd.Env = []string{"PATH=/usr/bin:/bin", "HOME=" + home, "TMPDIR=" + tmp, "LANG=C", "LC_ALL=C", "WFCTL_DIFFCACHE=:memory:", "GIT_CONFIG_NOSYSTEM=1", "GIT_CONFIG_GLOBAL=/dev/null", "GIT_TERMINAL_PROMPT=0"} // No raw plugin output or inherited stdin: only fixed gate diagnostics. - cmd.Stdout, cmd.Stderr = io.Discard, io.Discard + var reported nativeReportedOutput + cmd.Stdout, cmd.Stderr = io.Discard, &reported phase = "verifier" n := len(tmp) diagnostic.TmpBytes = &n // Exactly the TMPDIR supplied above. @@ -299,6 +306,9 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res default: diagnostic.VerifierResult = "state-unavailable" } + if runErr != nil && diagnostic.Joined && diagnostic.Exit != nil && *diagnostic.Exit > 0 { + diagnostic.ReasonHint, diagnostic.SocketBytes = classifyNativeReportedError(reported.String(), tmp, reported.overflow) + } if runErr != nil { return "", fmt.Errorf("runtime identity/version/declared-IaC verifier failed: %w", runErr) } @@ -334,3 +344,79 @@ func main() { os.Exit(1) } } + +// The classifier consumes untrusted reported text, not kernel evidence. The +// exact authenticated wfctl can embed plugin stderr. Only fixed hints and a +// validated byte count are retained; no capture bytes ever enter diagnostics. +type nativeReportedOutput struct { + bytes.Buffer + overflow bool +} + +func (w *nativeReportedOutput) Write(p []byte) (int, error) { + n := len(p) + left := (16 << 10) - w.Len() + if left > 0 { + w.Buffer.Write(p[:min(left, n)]) + } + if n > left { + w.overflow = true + } + return n, nil +} + +func classifyNativeReportedError(text, tmp string, overflow bool) (string, *int) { + unknown := func() (string, *int) { return "unclassified", nil } + if overflow || !utf8.ValidString(text) || strings.ContainsRune(text, '\x00') || !filepath.IsAbs(tmp) || strings.ContainsAny(tmp, "\r\n\x00") { + return unknown() + } + // These prefixes come from pinned wfctl v0.78.2. Expected wrapper nesting + // is recognized; conflicting independent categories remain unclassified. + patterns := []struct{ pattern, kind string }{ + {`(?m)^(?:error: |wfctl: )?(?:plugin dial:|timeout waiting for plugin handshake)`, "reported-plugin-handshake"}, + {`(?m)^(?:error: |wfctl: )?plugin[.]json parse:`, "reported-manifest-parse"}, + {`(?m)^(?:error: |wfctl: )?plugin[.]json validate:`, "reported-manifest-validation"}, + {`(?m)^(?:error: |wfctl: )?GetManifest RPC:`, "reported-manifest-rpc"}, + {`(?m)^(?:error: |wfctl: )?GetContractRegistry RPC:`, "reported-contract-rpc"}, + {`(?m)^(?:error: |wfctl: )?verify-capabilities: [1-9][0-9]{0,3} mismatch[(]es[)]:`, "reported-manifest-mismatch"}, + } + kind := "" + matches := 0 + for _, p := range patterns { + n := len(regexp.MustCompile(p.pattern).FindAllStringIndex(text, -1)) + if n > 0 { + kind = p.kind + matches += n + } + } + if matches > 1 { + return unknown() + } + if strings.Contains(text, "listen unix ") { + if strings.Count(text, "listen unix ") != 1 { + return unknown() + } + pattern := `(?:^|[ \t\r\n"(=:])listen unix (` + regexp.QuoteMeta(tmp+"/plugin") + `([0-9]{1,10})): bind: invalid argument(?:$|[\r\n" )])` + m := regexp.MustCompile(pattern).FindStringSubmatch(text) + if len(m) != 3 { + return unknown() + } + n, e := strconv.ParseUint(m[2], 10, 32) + if e != nil || strconv.FormatUint(n, 10) != m[2] { + return unknown() + } + // Linux/amd64 RawSockaddrUnix.Path is108bytes, including the required + // terminator for this non-abstract pathname. No socket syscall occurs here. + if len(m[1]) > 107 { + if kind != "" && kind != "reported-plugin-handshake" { + return unknown() + } + size := len(m[1]) + return "reported-unix-socket-path-length", &size + } + } + if kind != "" { + return kind, nil + } + return unknown() +} diff --git a/scripts/check-native-release_test.go b/scripts/check-native-release_test.go index 4143830..de4881c 100644 --- a/scripts/check-native-release_test.go +++ b/scripts/check-native-release_test.go @@ -44,9 +44,13 @@ func nativeFixture(t *testing.T) (string, []string, nativeCheckOptions) { func nativeEnvironment(t *testing.T, cmd *exec.Cmd, root string) string { t.Helper() - if cmd.Dir != root || cmd.Stdin != nil || cmd.Stdout != io.Discard || cmd.Stderr != io.Discard { + if cmd.Dir != root || cmd.Stdin != nil || cmd.Stdout != io.Discard || cmd.Stderr == nil || cmd.Stderr == io.Discard { t.Fatal("cwd or standard streams changed") } + capture, ok := cmd.Stderr.(interface{ Len() int }) + if !ok || capture.Len() != 0 { + t.Fatal("stderr is not a fresh bounded private capture") + } values := map[string]string{} for _, entry := range cmd.Env { k, v, ok := strings.Cut(entry, "=") @@ -580,3 +584,95 @@ func TestNativeReceiptResolvedSourceRefusal(t *testing.T) { t.Fatal("refused destination changed source") } } + +// Pure source-bound pathname arithmetic and synthetic reported text only. +// No test binds, connects to or probes a socket. +func TestNativeReportedReasonBoundaries(t *testing.T) { + tmp99 := "/" + strings.Repeat("a", 98) + tmp90 := "/" + strings.Repeat("b", 89) + for _, tc := range []struct { + name, tmp, text, want string + overflow bool + size int + }{ + {"107-fits", tmp99, "plugin dial: listen unix " + tmp99 + "/plugin0: bind: invalid argument", "reported-plugin-handshake", false, 0}, + {"108-overflows", tmp99, "plugin dial: listen unix " + tmp99 + "/plugin10: bind: invalid argument", "reported-unix-socket-path-length", false, 108}, + {"116-upper-bound", tmp99, "plugin dial: listen unix " + tmp99 + "/plugin4294967295: bind: invalid argument", "reported-unix-socket-path-length", false, 116}, + {"short-worst-case-fits", tmp90, "plugin dial: listen unix " + tmp90 + "/plugin4294967295: bind: invalid argument", "reported-plugin-handshake", false, 0}, + {"leading-zero", tmp99, "plugin dial: listen unix " + tmp99 + "/plugin042: bind: invalid argument", "unclassified", false, 0}, + {"uint32-overflow", tmp99, "plugin dial: listen unix " + tmp99 + "/plugin4294967296: bind: invalid argument", "unclassified", false, 0}, + {"wrong-tmp", tmp99, "plugin dial: listen unix /inert-other/plugin42: bind: invalid argument", "unclassified", false, 0}, + {"wrong-errno", tmp99, "plugin dial: listen unix " + tmp99 + "/plugin42: bind: permission denied", "unclassified", false, 0}, + {"ambiguous", tmp99, strings.Repeat("plugin dial: listen unix "+tmp99+"/plugin42: bind: invalid argument\n", 2), "unclassified", false, 0}, + {"conflicting", tmp99, "plugin dial: listen unix " + tmp99 + "/plugin42: bind: invalid argument\nGetManifest RPC: inert-private-value", "unclassified", false, 0}, + {"truncated", tmp99, "plugin dial: listen unix " + tmp99 + "/plugin42: bind: invalid argument", "unclassified", true, 0}, + {"manifest-parse", tmp99, "wfctl: plugin.json parse: inert-private-value", "reported-manifest-parse", false, 0}, + {"manifest-validation", tmp99, "wfctl: plugin.json validate: inert-private-value", "reported-manifest-validation", false, 0}, + {"manifest-rpc", tmp99, "wfctl: GetManifest RPC: inert-private-value", "reported-manifest-rpc", false, 0}, + {"contract-rpc", tmp99, "wfctl: GetContractRegistry RPC: inert-private-value", "reported-contract-rpc", false, 0}, + {"manifest-mismatch", tmp99, "wfctl: verify-capabilities: 2 mismatch(es): inert-private-value", "reported-manifest-mismatch", false, 0}, + {"misleading-socket-substring", tmp99, "inertnotlisten unix " + tmp99 + "/plugin42: bind: invalid argument", "unclassified", false, 0}, + {"misleading-substring", tmp99, "inertnotplugin dial: inert-private-value", "unclassified", false, 0}, + } { + t.Run(tc.name, func(t *testing.T) { + got, n := classifyNativeReportedError(tc.text, tc.tmp, tc.overflow) + if got != tc.want || (n == nil) != (tc.size == 0) || (n != nil && *n != tc.size) { + t.Fatal("reported-text category or bounded length differs from source contract") + } + }) + } +} + +func TestNativeReportedReasonActualFunction(t *testing.T) { + // Explicit owned long directory: the test must not rely on an ambient + // Mac/CI path length. Only regular files and finite shell output are used. + longTemp := filepath.Join(t.TempDir(), strings.Repeat("x", 120)) + if e := os.Mkdir(longTemp, 0700); e != nil { + t.Fatal(e) + } + t.Setenv("TMPDIR", longTemp) + root, args, opt := nativeFixture(t) + dir := t.TempDir() + if e := os.Chmod(dir, 0700); e != nil { + t.Fatal(e) + } + opt.receipt = filepath.Join(dir, "native.json") + body := []byte("#!/bin/sh\nprintf 'plugin dial: listen unix %s/plugin42: bind: invalid argument\n' \"$TMPDIR\" >&2\nexit 1\n") + if e := os.WriteFile(opt.tool, body, 0700); e != nil { + t.Fatal(e) + } + opt.digest, _ = nativeDigest(opt.tool, 160<<20, true) + opt.run = func(c *exec.Cmd) error { return c.Run() } + _, e := checkNativeRelease(root, args, opt) + var exit *exec.ExitError + if !errors.As(e, &exit) || exit.ExitCode() != 1 { + t.Fatal("reported text changed actual failure") + } + b, readErr := os.ReadFile(opt.receipt + ".status") + if readErr != nil { + t.Fatal("failure diagnostic missing") + } + var d map[string]any + if e := json.Unmarshal(b, &d); e != nil { + t.Fatal(e) + } + if d["reason_hint"] != "reported-unix-socket-path-length" || d["socket_path_bytes"] != d["tmpdir_bytes"].(float64)+9 { + t.Fatal("real function did not classify finite synthetic helper output") + } + t.Logf("NATIVE_REPORTED_REASON_FIXTURE:%s", b) + if bytes.Contains(b, []byte("listen unix")) || bytes.Contains(b, []byte(root)) || len(b) > 512 { + t.Fatal("raw reported text escaped diagnostic") + } +} + +func TestNativeReportedCaptureBound(t *testing.T) { + var w nativeReportedOutput + payload := bytes.Repeat([]byte{'x'}, (16<<10)+1) + n, e := w.Write(payload) + if e != nil || n != len(payload) || w.Len() != 16<<10 || !w.overflow { + t.Fatal("capture is not bounded and accepting") + } + if hint, size := classifyNativeReportedError(w.String(), "/inert", w.overflow); hint != "unclassified" || size != nil { + t.Fatal("truncated capture was classified") + } +} diff --git a/scripts/qualify-tag-archives.go b/scripts/qualify-tag-archives.go index 853783e..ca7107a 100644 --- a/scripts/qualify-tag-archives.go +++ b/scripts/qualify-tag-archives.go @@ -97,6 +97,8 @@ type tagNativeStatus struct { Exit *int `json:"exit,omitempty"` Cleanup string `json:"cleanup"` TmpBytes *int `json:"tmpdir_bytes,omitempty"` + ReasonHint string `json:"reason_hint,omitempty"` + SocketBytes *int `json:"socket_path_bytes,omitempty"` } func tagNativeDiagnostic(source string, env []string) string { @@ -184,6 +186,21 @@ func tagNativeDiagnostic(source string, env []string) string { default: return unusable } + hints := map[string]bool{"unclassified": true, "reported-unix-socket-path-length": true, "reported-plugin-handshake": true, "reported-manifest-parse": true, "reported-manifest-validation": true, "reported-manifest-rpc": true, "reported-contract-rpc": true, "reported-manifest-mismatch": true} + if d.ReasonHint != "" { + if !hints[d.ReasonHint] || d.PrimaryPhase != "verifier" || !d.Joined || d.Exit == nil || *d.Exit <= 0 || d.VerifierResult != "exited" { + return unusable + } + if d.ReasonHint == "reported-unix-socket-path-length" { + if d.SocketBytes == nil || d.TmpBytes == nil || *d.SocketBytes <= 107 || *d.SocketBytes < *d.TmpBytes+8 || *d.SocketBytes > *d.TmpBytes+17 { + return unusable + } + } else if d.SocketBytes != nil { + return unusable + } + } else if d.SocketBytes != nil { + return unusable + } // All values here have been validated against fixed enums/integer bounds. out, _ := json.Marshal(struct { Observation string `json:"observation"` diff --git a/scripts/qualify-tag-archives_test.go b/scripts/qualify-tag-archives_test.go index a6d39a2..8ee0811 100644 --- a/scripts/qualify-tag-archives_test.go +++ b/scripts/qualify-tag-archives_test.go @@ -368,3 +368,77 @@ func TestTagDiagnosticFreshnessBeforeExecution(t *testing.T) { t.Fatalf("stale diagnostic not refused before execution: %v", e) } } + +func TestTagReportedReasonWire(t *testing.T) { + good := `{"schema":1,"scope":"native-hook-diagnostic","primary_phase":"verifier","verifier_result":"exited","joined":true,"exit":1,"cleanup":"removed","tmpdir_bytes":99,"reason_hint":"reported-unix-socket-path-length","socket_path_bytes":108}` + for _, name := range []string{"valid", "unknown-hint", "fits-budget", "wrong-length", "wrong-hint-shape", "not-joined", "exit-zero", "wrong-phase", "hint-absent"} { + t.Run(name, func(t *testing.T) { + dir := t.TempDir() + if e := os.Chmod(dir, 0700); e != nil { + t.Fatal(e) + } + receipt := filepath.Join(dir, "native.json") + wire := good + want := `"observation":"unusable"` + switch name { + case "valid": + want = `"observation":"refused"` + case "unknown-hint": + wire = strings.Replace(good, "reported-unix-socket-path-length", "inert-private-cause", 1) + case "fits-budget": + wire = strings.Replace(good, `"socket_path_bytes":108`, `"socket_path_bytes":107`, 1) + case "wrong-length": + wire = strings.Replace(good, `"socket_path_bytes":108`, `"socket_path_bytes":117`, 1) + case "wrong-hint-shape": + wire = strings.Replace(good, "reported-unix-socket-path-length", "reported-plugin-handshake", 1) + case "not-joined": + wire = strings.Replace(good, `"joined":true`, `"joined":false`, 1) + case "exit-zero": + wire = strings.Replace(good, `"exit":1`, `"exit":0`, 1) + case "wrong-phase": + wire = strings.Replace(good, `"primary_phase":"verifier"`, `"primary_phase":"postcheck"`, 1) + case "hint-absent": + wire = strings.Replace(good, `,"reason_hint":"reported-unix-socket-path-length"`, "", 1) + } + if e := os.WriteFile(receipt+".status", []byte(wire), 0600); e != nil { + t.Fatal(e) + } + _, e := runTagChild(t.TempDir(), []string{"PATH=/usr/bin:/bin", "NATIVE_CHECK_RECEIPT=" + receipt}, []string{"/bin/sh", "-c", "exit 1"}) + if e == nil || !strings.Contains(e.Error(), want) || strings.Contains(e.Error(), "private") { + t.Fatal("strict consumer accepted or disclosed malformed reported hint") + } + }) + } +} + +func TestTagReportedReasonProducerCrossing(t *testing.T) { + argv := []string{filepath.Join(runtime.GOROOT(), "bin/go"), "test", "-v", "-count=1", "-p=1", "-timeout=30s", "-run", "^TestNativeReportedReasonActualFunction$", "check-native-release.go", "check-native-release_test.go"} + b, e := runTagChild(".", os.Environ(), argv) + if e != nil { + t.Fatal("finite actual producer fixture failed") + } + var wire string + for _, line := range strings.Split(string(b), "\n") { + if _, v, ok := strings.Cut(line, "NATIVE_REPORTED_REASON_FIXTURE:"); ok { + if wire != "" { + t.Fatal("ambiguous producer fixture") + } + wire = v + } + } + if wire == "" { + t.Fatal("actual reported-text producer was not observed") + } + dir := t.TempDir() + if e := os.Chmod(dir, 0700); e != nil { + t.Fatal(e) + } + receipt := filepath.Join(dir, "native.json") + if e := os.WriteFile(receipt+".status", []byte(wire), 0600); e != nil { + t.Fatal(e) + } + _, e = runTagChild(t.TempDir(), []string{"PATH=/usr/bin:/bin", "NATIVE_CHECK_RECEIPT=" + receipt}, []string{"/bin/sh", "-c", "exit 1"}) + if e == nil || !strings.Contains(e.Error(), `"observation":"refused"`) || !strings.Contains(e.Error(), `"reason_hint":"reported-unix-socket-path-length"`) { + t.Fatal("actual reported-text wire did not cross strict consumer") + } +} From 672c413c33732d1cad1c57166089e93ecd5dc3c7 Mon Sep 17 00:00:00 2001 From: GoCodeAlone Automation Date: Wed, 25 Nov 2026 22:44:32 -0500 Subject: [PATCH 7/8] Keep native verifier socket path within Unix limits --- .github/workflows/archive-qualification.yml | 8 +- .github/workflows/tag-qualification.yml | 12 +- scripts/check-native-release.go | 200 ++++++++++++- scripts/check-native-release_test.go | 297 +++++++++++++++++++- scripts/qualify-tag-archives_test.go | 27 +- 5 files changed, 518 insertions(+), 26 deletions(-) diff --git a/.github/workflows/archive-qualification.yml b/.github/workflows/archive-qualification.yml index bef1f56..a9baca8 100644 --- a/.github/workflows/archive-qualification.yml +++ b/.github/workflows/archive-qualification.yml @@ -51,8 +51,8 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 9fe612289e89d68fee1758bfbe4bb10e865474bf74ce83ce6336f2cdfac67e0c scripts/check-native-release.go - 4f840be2cd14577133d7f524ef3015c6dd58b3af7102efface925c44213e8192 scripts/check-native-release_test.go + 83c9c3f02e603e3ef0a9b3318a8be43d9e09483b943137e8169ca12551e3476f scripts/check-native-release.go + a942283a5cd2fad447507261aecfefe45fe9c7e97c75284e0664d18ba5edf472 scripts/check-native-release_test.go INPUTS test "$(go version)" = 'go version go1.27.4 linux/amd64' ENGINE_BIN="$(command -v goreleaser)" @@ -122,8 +122,8 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 9fe612289e89d68fee1758bfbe4bb10e865474bf74ce83ce6336f2cdfac67e0c scripts/check-native-release.go - 4f840be2cd14577133d7f524ef3015c6dd58b3af7102efface925c44213e8192 scripts/check-native-release_test.go + 83c9c3f02e603e3ef0a9b3318a8be43d9e09483b943137e8169ca12551e3476f scripts/check-native-release.go + a942283a5cd2fad447507261aecfefe45fe9c7e97c75284e0664d18ba5edf472 scripts/check-native-release_test.go INPUTS home="$(mktemp -d "$OWNED_ROOT/package-home.XXXXXXXX")" tmp="$(mktemp -d "$OWNED_ROOT/package-tmp.XXXXXXXX")" diff --git a/.github/workflows/tag-qualification.yml b/.github/workflows/tag-qualification.yml index 366a07a..4e49ba9 100644 --- a/.github/workflows/tag-qualification.yml +++ b/.github/workflows/tag-qualification.yml @@ -48,10 +48,10 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 9fe612289e89d68fee1758bfbe4bb10e865474bf74ce83ce6336f2cdfac67e0c scripts/check-native-release.go - 4f840be2cd14577133d7f524ef3015c6dd58b3af7102efface925c44213e8192 scripts/check-native-release_test.go + 83c9c3f02e603e3ef0a9b3318a8be43d9e09483b943137e8169ca12551e3476f scripts/check-native-release.go + a942283a5cd2fad447507261aecfefe45fe9c7e97c75284e0664d18ba5edf472 scripts/check-native-release_test.go 3c1d05b6ba0fb93e9b03061e45bfb9b4ae0b7f5055c086261342fb40cc713955 scripts/qualify-tag-archives.go - b6a3123bb11c5774585fb59bc4325958cf0651d69d3acc10a55dab973e8c79fd scripts/qualify-tag-archives_test.go + 484c9d6acb7bb5f49f9b2ddf128d37c6ece4f890a66f8319e923e407ab2cabf9 scripts/qualify-tag-archives_test.go 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh INPUTS root="$(mktemp -d "$RUNNER_TEMP/tag-qualification.XXXXXXXX")" @@ -142,10 +142,10 @@ jobs: 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go - 9fe612289e89d68fee1758bfbe4bb10e865474bf74ce83ce6336f2cdfac67e0c scripts/check-native-release.go - 4f840be2cd14577133d7f524ef3015c6dd58b3af7102efface925c44213e8192 scripts/check-native-release_test.go + 83c9c3f02e603e3ef0a9b3318a8be43d9e09483b943137e8169ca12551e3476f scripts/check-native-release.go + a942283a5cd2fad447507261aecfefe45fe9c7e97c75284e0664d18ba5edf472 scripts/check-native-release_test.go 3c1d05b6ba0fb93e9b03061e45bfb9b4ae0b7f5055c086261342fb40cc713955 scripts/qualify-tag-archives.go - b6a3123bb11c5774585fb59bc4325958cf0651d69d3acc10a55dab973e8c79fd scripts/qualify-tag-archives_test.go + 484c9d6acb7bb5f49f9b2ddf128d37c6ece4f890a66f8319e923e407ab2cabf9 scripts/qualify-tag-archives_test.go 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh INPUTS mkdir "$OWNED_ROOT/execution-home" "$OWNED_ROOT/execution-tmp" diff --git a/scripts/check-native-release.go b/scripts/check-native-release.go index a940b6a..bae3ce1 100644 --- a/scripts/check-native-release.go +++ b/scripts/check-native-release.go @@ -7,7 +7,9 @@ package main import ( "bytes" + "crypto/rand" "crypto/sha256" + "encoding/base64" "encoding/json" "errors" "fmt" @@ -19,6 +21,7 @@ import ( "runtime" "strconv" "strings" + "syscall" "unicode/utf8" ) @@ -33,7 +36,8 @@ type nativeCheckOptions struct { host, tool, digest string receipt string run func(*exec.Cmd) error - cleanup func(string) error + afterCleanup func(string) error + workspace func() (*nativeWorkspace, error) } type nativeValidationReceipt struct { @@ -252,10 +256,16 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res } } phase = "workspace" - owned, err := os.MkdirTemp("", "compute-native-check-") - if err != nil { - return "", errors.New("cannot create owned verifier directory") + makeWorkspace := opt.workspace + if makeWorkspace == nil { + makeWorkspace = newNativeWorkspace + } + workspace, err := makeWorkspace() + if err != nil || workspace == nil { + return "", errors.Join(errors.New("cannot create owned short verifier directory"), err) } + owned := workspace.path + defer func() { // Preserve the primary phase even if cleanup independently fails. diagnostic.PrimaryPhase = "none" @@ -263,7 +273,13 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res diagnostic.PrimaryPhase = phase } diagnostic.Cleanup = "removed" - if e := opt.cleanup(owned); e != nil { + cleanupErr := workspace.cleanup() + // Optional synthetic post-cleanup check; production never substitutes + // the mandatory identity-bound cleanup with a caller-supplied remover. + if cleanupErr == nil && opt.afterCleanup != nil { + cleanupErr = opt.afterCleanup(owned) + } + if e := cleanupErr; e != nil { diagnostic.Cleanup = "failed" err = errors.Join(err, fmt.Errorf("owned verifier cleanup failed: %w", e)) result = "" @@ -281,9 +297,16 @@ func checkNativeRelease(root string, args []string, opt nativeCheckOptions) (res } } }() - home, tmp := filepath.Join(owned, "home"), filepath.Join(owned, "tmp") - if os.Mkdir(home, 0700) != nil || os.Mkdir(tmp, 0700) != nil { - return "", errors.New("cannot prepare owned verifier environment") + home, tmp := filepath.Join(owned, "h"), owned + if e := workspace.parent.Mkdir(workspace.name+"/h", 0700); e != nil { + return "", fmt.Errorf("cannot prepare owned verifier HOME: %w", e) + } + homeInfo, e := workspace.parent.Lstat(workspace.name + "/h") + if e != nil { + return "", fmt.Errorf("cannot verify owned verifier HOME: %w", e) + } + if e = nativePrivateDirectory(homeInfo, os.Geteuid()); e != nil { + return "", e } cmd := exec.Command(opt.tool, "plugin", "verify-capabilities", "--binary", artifact, root) cmd.Dir = root @@ -333,7 +356,7 @@ func main() { result, err = checkNativeRelease(root, os.Args[1:], nativeCheckOptions{ host: runtime.GOOS + "/" + runtime.GOARCH, tool: os.Getenv("WFCTL_BIN"), digest: nativeWfctlSHA, receipt: os.Getenv("NATIVE_CHECK_RECEIPT"), - run: (*exec.Cmd).Run, cleanup: os.RemoveAll, + run: (*exec.Cmd).Run, workspace: newNativeWorkspace, }) if err == nil { fmt.Println(result) @@ -420,3 +443,162 @@ func classifyNativeReportedError(text, tmp string, overflow bool) (string, *int) } return unknown() } + +// A single private root is the exact TMPDIR handed to wfctl. The default +// go-plugin Unix basename is /plugin plus at most ten uint32 decimal digits. +const nativeSocketSuffixMax = len("/plugin") + 10 + +type nativeWorkspace struct { + parent *os.Root + name, path string + identity os.FileInfo + closed bool + cleanupErr error +} + +func nativeWorkspacePath(parent, name string) (string, error) { + if !filepath.IsAbs(parent) || filepath.Clean(parent) != parent || !regexp.MustCompile(`^nc-[A-Za-z0-9_-]{22}$`).MatchString(name) { + return "", errors.New("noncanonical native workspace name") + } + path := filepath.Join(parent, name) + if len(path)+nativeSocketSuffixMax > 107 { + return "", errors.New("native workspace exceeds Linux Unix-socket byte budget") + } + return path, nil +} + +func nativeDirectoryOwner(info os.FileInfo) (int, error) { + if info == nil || !info.IsDir() || info.Mode()&os.ModeSymlink != 0 { + return 0, errors.New("native workspace is not a directory") + } + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return 0, errors.New("native directory ownership unavailable") + } + return int(stat.Uid), nil +} +func nativePrivateDirectory(info os.FileInfo, uid int) error { + owner, e := nativeDirectoryOwner(info) + if e != nil { + return e + } + if owner != uid || info.Mode().Perm() != 0700 { + return errors.New("native workspace must be owned and mode0700") + } + return nil +} +func nativeTempParent(info os.FileInfo, uid int) error { + owner, e := nativeDirectoryOwner(info) + if e != nil { + return e + } + if owner == uid && info.Mode().Perm() == 0700 { + return nil + } + if owner != 0 || (info.Mode().Perm()&0022 != 0 && info.Mode()&os.ModeSticky == 0) { + return errors.New("native temp parent lacks trusted ownership/isolation") + } + return nil +} + +func newNativeWorkspace() (*nativeWorkspace, error) { return newNativeWorkspaceAt("/tmp", rand.Reader) } + +// The path/entropy parameters are private test seams. main always selects the +// fixed /tmp factory and crypto/rand; there is no environment/CLI override. +func newNativeWorkspaceAt(base string, entropy io.Reader) (workspace *nativeWorkspace, err error) { + canonical, e := filepath.EvalSymlinks(base) + if e != nil { + return nil, fmt.Errorf("cannot resolve native temp parent: %w", e) + } + canonical, e = filepath.Abs(canonical) + if e != nil { + return nil, e + } + anchor, e := os.OpenRoot(canonical) + if e != nil { + return nil, fmt.Errorf("cannot open native temp parent: %w", e) + } + transferred := false + defer func() { + if !transferred { + err = errors.Join(err, anchor.Close()) + } + }() + info, e := anchor.Lstat(".") + if e != nil { + return nil, e + } + if e = nativeTempParent(info, os.Geteuid()); e != nil { + return nil, e + } + byPath, e := os.Lstat(canonical) + if e != nil || !os.SameFile(info, byPath) { + return nil, errors.New("native temp parent path/descriptor mismatch") + } + if _, e = nativeWorkspacePath(canonical, "nc-"+strings.Repeat("A", 22)); e != nil { + return nil, e + } + for attempt := 0; attempt < 8; attempt++ { + var nonce [16]byte + if _, e = io.ReadFull(entropy, nonce[:]); e != nil { + return nil, fmt.Errorf("native workspace entropy failed: %w", e) + } + name := "nc-" + base64.RawURLEncoding.EncodeToString(nonce[:]) + path, e := nativeWorkspacePath(canonical, name) + if e != nil { + return nil, e + } + if e = anchor.Mkdir(name, 0700); os.IsExist(e) { + continue + } else if e != nil { + return nil, fmt.Errorf("native workspace creation failed: %w", e) + } + child, e := anchor.Lstat(name) + owner, ownerErr := nativeDirectoryOwner(child) + if e != nil || ownerErr != nil || owner != os.Geteuid() { + // No identity was admitted: close the capability and retain the entry + // rather than deleting an entry that might no longer be ours. + return nil, errors.Join(errors.New("new native workspace identity unavailable; possible residue retained"), e, ownerErr) + } + workspace = &nativeWorkspace{parent: anchor, name: name, path: path, identity: child} + transferred = true + admissionErr := nativePrivateDirectory(child, os.Geteuid()) + actual, pathErr := os.Lstat(path) + if pathErr != nil || !os.SameFile(child, actual) { + admissionErr = errors.Join(admissionErr, errors.New("native child path/descriptor mismatch"), pathErr) + } + if admissionErr != nil { + return nil, errors.Join(admissionErr, workspace.cleanup()) + } + return workspace, nil + } + return nil, errors.New("native workspace collision budget exhausted") +} + +func (w *nativeWorkspace) cleanup() (err error) { + if w.closed { + return w.cleanupErr + } + w.closed = true + defer func() { err = errors.Join(err, w.parent.Close()); w.cleanupErr = err }() + current, e := w.parent.Lstat(w.name) + if e != nil || !os.SameFile(w.identity, current) { + return errors.New("native workspace identity changed; cleanup refused, residue retained") + } + owner, e := nativeDirectoryOwner(current) + if e != nil || owner != os.Geteuid() { + return errors.New("native workspace owner changed; cleanup refused, residue retained") + } + byPath, e := os.Lstat(w.path) + if e != nil || !os.SameFile(current, byPath) { + return errors.New("native workspace path changed; cleanup refused, residue retained") + } + privacyErr := nativePrivateDirectory(current, os.Geteuid()) + if e = w.parent.RemoveAll(w.name); e != nil { + return errors.Join(privacyErr, fmt.Errorf("native owned removal failed: %w", e)) + } + if _, e = w.parent.Lstat(w.name); !os.IsNotExist(e) { + return errors.Join(privacyErr, errors.New("native workspace remains after cleanup")) + } + return privacyErr +} diff --git a/scripts/check-native-release_test.go b/scripts/check-native-release_test.go index de4881c..22363a9 100644 --- a/scripts/check-native-release_test.go +++ b/scripts/check-native-release_test.go @@ -15,6 +15,7 @@ import ( "reflect" "runtime" "strings" + "syscall" "testing" ) @@ -37,7 +38,19 @@ func nativeFixture(t *testing.T) (string, []string, nativeCheckOptions) { if e != nil { t.Fatal(e) } - opt := nativeCheckOptions{host: "linux/amd64", tool: tool, digest: digest, cleanup: os.RemoveAll, run: func(*exec.Cmd) error { t.Fatal("unexpected process invocation"); return nil }} + opt := nativeCheckOptions{host: "linux/amd64", tool: tool, digest: digest, afterCleanup: os.RemoveAll, run: func(*exec.Cmd) error { t.Fatal("unexpected process invocation"); return nil }} + opt.workspace = func() (*nativeWorkspace, error) { + w, e := newNativeWorkspace() + if e == nil { + t.Logf("OWNED_NATIVE_TMP:%s", w.path) + t.Cleanup(func() { + if _, e := os.Lstat(w.path); !os.IsNotExist(e) { + t.Error("owned native workspace leaked after command return") + } + }) + } + return w, e + } // v2.20.3 base.OptionsForTarget uses filepath.Abs for the actual hook .Path. return root, []string{"linux", "amd64", filepath.Join(root, "dist/plugin"), "false"}, opt } @@ -69,7 +82,7 @@ func nativeEnvironment(t *testing.T, cmd *exec.Cmd, root string) string { } } owned := filepath.Dir(values["HOME"]) - if filepath.Dir(values["TMPDIR"]) != owned || owned == root { + if values["TMPDIR"] != owned || owned == root { t.Fatal("child environment ownership changed") } return owned @@ -142,7 +155,7 @@ func TestNativeReleaseReceipt(t *testing.T) { } return nil } - opt.cleanup = func(path string) error { + opt.afterCleanup = func(path string) error { cleaned = true if e := os.RemoveAll(path); e != nil { return e @@ -301,7 +314,7 @@ func TestNativeReleaseMutationAndFailure(t *testing.T) { return os.WriteFile(filepath.Join(root, p), []byte("inert changed bytes"), 0700) } if name == "primary-and-cleanup" || name == "cleanup-after-success" { - opt.cleanup = func(p string) error { + opt.afterCleanup = func(p string) error { if e := os.RemoveAll(p); e != nil { return e } @@ -449,7 +462,7 @@ func TestNativeFailureDiagnostics(t *testing.T) { if name == "verifier-and-cleanup" { cleanup = "failed" } - opt.cleanup = func(p string) error { + opt.afterCleanup = func(p string) error { if e := os.RemoveAll(p); e != nil { return e } @@ -656,7 +669,7 @@ func TestNativeReportedReasonActualFunction(t *testing.T) { if e := json.Unmarshal(b, &d); e != nil { t.Fatal(e) } - if d["reason_hint"] != "reported-unix-socket-path-length" || d["socket_path_bytes"] != d["tmpdir_bytes"].(float64)+9 { + if d["reason_hint"] != "reported-plugin-handshake" || d["socket_path_bytes"] != nil || d["tmpdir_bytes"].(float64)+17 > 107 { t.Fatal("real function did not classify finite synthetic helper output") } t.Logf("NATIVE_REPORTED_REASON_FIXTURE:%s", b) @@ -676,3 +689,275 @@ func TestNativeReportedCaptureBound(t *testing.T) { t.Fatal("truncated capture was classified") } } + +// Real entry function, synthetic verifier callback, owned regular directories. +// The deliberately long ambient TMPDIR must not become the socket namespace. +func TestNativeShortTempEntry(t *testing.T) { + ambient := filepath.Join(t.TempDir(), strings.Repeat("a", 120)) + if e := os.Mkdir(ambient, 0700); e != nil { + t.Fatal(e) + } + t.Setenv("TMPDIR", ambient) + root, args, opt := nativeFixture(t) + var socketDir string + calls := 0 + opt.run = func(c *exec.Cmd) error { + calls++ + nativeEnvironment(t, c, root) + values := map[string]string{} + for _, v := range c.Env { + k, v, _ := strings.Cut(v, "=") + values[k] = v + } + socketDir = values["TMPDIR"] + if len(socketDir)+len("/plugin")+10 > 107 { + t.Error("native entry exceeded worst-case Linux socket byte budget") + } + if filepath.Dir(values["HOME"]) != socketDir { + t.Error("native entry did not use its single private root directly for socket temp") + } + if strings.HasPrefix(socketDir, ambient) { + t.Error("native socket namespace inherited long ambient temp path") + } + return nil + } + if _, e := checkNativeRelease(root, args, opt); e != nil || calls != 1 { + t.Fatalf("synthetic native entry failed: %v", e) + } + if socketDir != "" { + if _, e := os.Lstat(socketDir); !os.IsNotExist(e) { + t.Fatal("owned socket directory survived joined return") + } + } +} + +func nativeOwnedTestParent(t *testing.T) string { + t.Helper() + p, e := os.MkdirTemp("/tmp", "nt-") + if e != nil { + t.Fatal("cannot create owned native test parent") + } + p, e = filepath.EvalSymlinks(p) + if e != nil { + t.Fatal(e) + } + identity, e := os.Lstat(p) + if e != nil { + t.Fatal(e) + } + t.Logf("OWNED_NATIVE_PARENT:%s", p) + t.Cleanup(func() { + current, e := os.Lstat(p) + if e != nil || !os.SameFile(identity, current) { + t.Error("native test parent identity changed; teardown refused") + return + } + if e := os.RemoveAll(p); e != nil { + t.Error("owned native test parent teardown failed") + return + } + if _, e := os.Lstat(p); !os.IsNotExist(e) { + t.Error("owned native test parent survived teardown") + } + }) + return p +} + +type nativeSyntheticInfo struct { + os.FileInfo + mode os.FileMode + uid uint32 +} + +func (i nativeSyntheticInfo) Mode() os.FileMode { return i.mode } +func (i nativeSyntheticInfo) IsDir() bool { return i.mode.IsDir() } +func (i nativeSyntheticInfo) Sys() any { return &syscall.Stat_t{Uid: i.uid} } + +func TestNativeWorkspaceBudgetAndParentPolicy(t *testing.T) { + name := "nc-" + strings.Repeat("A", 22) + for _, tc := range []struct { + name, parent string + ok bool + }{ + {"parent64", "/" + strings.Repeat("p", 63), true}, + {"parent65", "/" + strings.Repeat("p", 64), false}, + {"byte-not-rune-budget", "/" + strings.Repeat("p", 62) + "é", false}, + } { + t.Run(tc.name, func(t *testing.T) { + path, e := nativeWorkspacePath(tc.parent, name) + if (e == nil) != tc.ok { + t.Fatal("native raw-byte path budget mismatch") + } + if e == nil && len(path)+17 > 107 { + t.Fatal("admitted path exceeded budget") + } + }) + } + if _, e := nativeWorkspacePath("/tmp", "../inert"); e == nil { + t.Fatal("native child traversal accepted") + } + info, e := os.Stat(t.TempDir()) + if e != nil { + t.Fatal(e) + } + for _, tc := range []struct { + name string + uid uint32 + mode os.FileMode + ok bool + }{ + {"private-actor", 12345, os.ModeDir | 0700, true}, + {"root-sticky", 0, os.ModeDir | os.ModeSticky | 0777, true}, + {"root-read-only-to-others", 0, os.ModeDir | 0755, true}, + {"root-unsafe", 0, os.ModeDir | 0777, false}, + {"foreign-owner", 23456, os.ModeDir | 0700, false}, + {"actor-public", 12345, os.ModeDir | 0777, false}, + {"not-directory", 12345, 0700, false}, + {"redirected", 12345, os.ModeDir | os.ModeSymlink | 0700, false}, + } { + t.Run(tc.name, func(t *testing.T) { + e := nativeTempParent(nativeSyntheticInfo{info, tc.mode, tc.uid}, 12345) + if (e == nil) != tc.ok { + t.Fatal("native temp parent ownership/isolation policy mismatch") + } + }) + } +} + +type nativeEntropyFailure struct{ err error } + +func (r nativeEntropyFailure) Read([]byte) (int, error) { return 0, r.err } + +func TestNativeWorkspaceAllocationAndCleanup(t *testing.T) { + parent := nativeOwnedTestParent(t) + if e := os.WriteFile(filepath.Join(parent, "sibling"), []byte("preserve public fixture"), 0600); e != nil { + t.Fatal(e) + } + w, e := newNativeWorkspaceAt(parent, bytes.NewReader(make([]byte, 16))) + if e != nil { + t.Fatal("owned workspace creation failed") + } + t.Logf("OWNED_NATIVE_TMP:%s", w.path) + info, e := os.Lstat(w.path) + if e != nil || !os.SameFile(w.identity, info) || nativePrivateDirectory(info, os.Geteuid()) != nil { + t.Fatal("native directory is not identity-bound/private") + } + if len(w.path)+17 > 107 || filepath.Dir(w.path) != parent { + t.Fatal("native directory violated containment/budget") + } + if e = w.parent.WriteFile(w.name+"/owned", []byte("inert owned child"), 0600); e != nil { + t.Fatal(e) + } + if e = w.cleanup(); e != nil { + t.Fatal("mandatory identity-bound cleanup failed") + } + if _, e = os.Lstat(w.path); !os.IsNotExist(e) { + t.Fatal("native directory survived cleanup") + } + b, e := os.ReadFile(filepath.Join(parent, "sibling")) + if e != nil || string(b) != "preserve public fixture" { + t.Fatal("cleanup touched unowned sibling") + } + if _, e = w.parent.Lstat("."); e == nil { + t.Fatal("parent capability was not closed") + } + if e = w.cleanup(); e != nil { + t.Fatal("completed cleanup was not idempotent") + } +} + +func TestNativeWorkspaceEntropyAndCollisionRefusals(t *testing.T) { + t.Run("entropy", func(t *testing.T) { + parent := nativeOwnedTestParent(t) + sentinel := errors.New("inert entropy failure") + w, e := newNativeWorkspaceAt(parent, nativeEntropyFailure{sentinel}) + if w != nil || !errors.Is(e, sentinel) { + t.Fatal("entropy failure did not fail closed with identity") + } + entries, e := os.ReadDir(parent) + if e != nil || len(entries) != 0 { + t.Fatal("entropy failure created output") + } + }) + t.Run("collisions", func(t *testing.T) { + parent := nativeOwnedTestParent(t) + name := "nc-" + strings.Repeat("A", 22) + path := filepath.Join(parent, name) + if e := os.Mkdir(path, 0700); e != nil { + t.Fatal(e) + } + if e := os.WriteFile(filepath.Join(path, "keep"), []byte("preserve"), 0600); e != nil { + t.Fatal(e) + } + before, e := os.Lstat(path) + if e != nil { + t.Fatal(e) + } + w, e := newNativeWorkspaceAt(parent, bytes.NewReader(make([]byte, 16*8))) + if w != nil || e == nil || !strings.Contains(e.Error(), "collision budget") { + t.Fatal("collision budget did not refuse") + } + after, e := os.Lstat(path) + b, readErr := os.ReadFile(filepath.Join(path, "keep")) + if e != nil || readErr != nil || !os.SameFile(before, after) || string(b) != "preserve" { + t.Fatal("collision removed/modified preexisting fixture") + } + }) +} + +func TestNativeWorkspaceIdentityMismatchRefusal(t *testing.T) { + parent := nativeOwnedTestParent(t) + w, e := newNativeWorkspaceAt(parent, bytes.NewReader(make([]byte, 16))) + if e != nil { + t.Fatal(e) + } + if e = w.parent.Rename(w.name, w.name+"-retained"); e != nil { + t.Fatal(e) + } + if e = w.parent.Mkdir(w.name, 0700); e != nil { + t.Fatal(e) + } + if e = w.parent.WriteFile(w.name+"/keep", []byte("replacement fixture"), 0600); e != nil { + t.Fatal(e) + } + if e = w.cleanup(); e == nil { + t.Fatal("changed native identity was removed") + } + b, e := os.ReadFile(filepath.Join(w.path, "keep")) + if e != nil || string(b) != "replacement fixture" { + t.Fatal("cleanup touched replacement fixture") + } + retained, e := os.Lstat(filepath.Join(parent, w.name+"-retained")) + if e != nil || !os.SameFile(retained, w.identity) { + t.Fatal("original retained identity changed") + } + if _, e = w.parent.Lstat("."); e == nil { + t.Fatal("refusal leaked parent capability") + } +} + +func TestNativeWorkspacePartialInitializationCleanup(t *testing.T) { + root, args, opt := nativeFixture(t) + factory := opt.workspace + var owned string + opt.workspace = func() (*nativeWorkspace, error) { + w, e := factory() + if e != nil { + return w, e + } + owned = w.path + if e := w.parent.Mkdir(w.name+"/h", 0700); e != nil { + t.Fatal(e) + } + return w, nil + } + calls := 0 + opt.run = func(*exec.Cmd) error { calls++; return nil } + _, e := checkNativeRelease(root, args, opt) + if !errors.Is(e, os.ErrExist) || calls != 0 { + t.Fatal("partial initialization failed to stop before verifier") + } + if _, e := os.Lstat(owned); !os.IsNotExist(e) { + t.Fatal("partial initialization left owned directory") + } +} diff --git a/scripts/qualify-tag-archives_test.go b/scripts/qualify-tag-archives_test.go index 8ee0811..6410e57 100644 --- a/scripts/qualify-tag-archives_test.go +++ b/scripts/qualify-tag-archives_test.go @@ -10,6 +10,7 @@ import ( "os/exec" "path/filepath" "reflect" + "regexp" "runtime" "strings" "testing" @@ -321,6 +322,7 @@ func TestTagNativeDiagnosticProducerCrossing(t *testing.T) { if e != nil { t.Fatal(e) } + recordNestedNativeWorkspaces(t, b) var wire string for _, line := range strings.Split(string(b), "\n") { if _, v, ok := strings.Cut(line, "NATIVE_DIAGNOSTIC_FIXTURE:"); ok { @@ -417,6 +419,7 @@ func TestTagReportedReasonProducerCrossing(t *testing.T) { if e != nil { t.Fatal("finite actual producer fixture failed") } + recordNestedNativeWorkspaces(t, b) var wire string for _, line := range strings.Split(string(b), "\n") { if _, v, ok := strings.Cut(line, "NATIVE_REPORTED_REASON_FIXTURE:"); ok { @@ -438,7 +441,29 @@ func TestTagReportedReasonProducerCrossing(t *testing.T) { t.Fatal(e) } _, e = runTagChild(t.TempDir(), []string{"PATH=/usr/bin:/bin", "NATIVE_CHECK_RECEIPT=" + receipt}, []string{"/bin/sh", "-c", "exit 1"}) - if e == nil || !strings.Contains(e.Error(), `"observation":"refused"`) || !strings.Contains(e.Error(), `"reason_hint":"reported-unix-socket-path-length"`) { + if e == nil || !strings.Contains(e.Error(), `"observation":"refused"`) || !strings.Contains(e.Error(), `"reason_hint":"reported-plugin-handshake"`) { t.Fatal("actual reported-text wire did not cross strict consumer") } } + +func recordNestedNativeWorkspaces(t *testing.T, b []byte) { + t.Helper() + parent, e := filepath.EvalSymlinks("/tmp") + if e != nil { + t.Fatal("cannot resolve native workspace ledger parent") + } + for _, line := range strings.Split(string(b), "\n") { + _, path, ok := strings.Cut(line, "OWNED_NATIVE_TMP:") + if !ok { + continue + } + path = strings.TrimSpace(path) + if filepath.Dir(path) != parent || !regexp.MustCompile(`^nc-[A-Za-z0-9_-]{22}$`).MatchString(filepath.Base(path)) { + t.Fatal("nested native ledger escaped fixed temp scope") + } + if _, e := os.Lstat(path); !os.IsNotExist(e) { + t.Fatal("nested producer left its owned native directory") + } + t.Logf("OWNED_NATIVE_TMP:%s", path) + } +} From 0d029b9e16bfefb9f6d6ffee4db6dd88f9653308 Mon Sep 17 00:00:00 2001 From: GoCodeAlone Automation Date: Wed, 25 Nov 2026 23:17:21 -0500 Subject: [PATCH 8/8] Use verifier-compatible local release rehearsal tags --- .github/workflows/archive-qualification.yml | 8 +-- .github/workflows/tag-qualification.yml | 16 ++--- scripts/check-release-archives.go | 27 +++++++- scripts/check-release-archives_test.go | 75 ++++++++++++++++++++- scripts/qualify-tag-archives.go | 32 ++++++++- scripts/qualify-tag-archives_test.go | 65 +++++++++++++++++- 6 files changed, 204 insertions(+), 19 deletions(-) diff --git a/.github/workflows/archive-qualification.yml b/.github/workflows/archive-qualification.yml index a9baca8..89c1c24 100644 --- a/.github/workflows/archive-qualification.yml +++ b/.github/workflows/archive-qualification.yml @@ -49,8 +49,8 @@ jobs: 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum - f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go - 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go + 4bab12314beb126e5733dcb147d54b2b11d90eba81aa1ccea4c2463f2e943fd3 scripts/check-release-archives.go + d5e31a5c4c9c9ecb5d3a440dffdef0b860ba58984f1c7b8d018b62abc858ce9d scripts/check-release-archives_test.go 83c9c3f02e603e3ef0a9b3318a8be43d9e09483b943137e8169ca12551e3476f scripts/check-native-release.go a942283a5cd2fad447507261aecfefe45fe9c7e97c75284e0664d18ba5edf472 scripts/check-native-release_test.go INPUTS @@ -120,8 +120,8 @@ jobs: 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum - f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go - 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go + 4bab12314beb126e5733dcb147d54b2b11d90eba81aa1ccea4c2463f2e943fd3 scripts/check-release-archives.go + d5e31a5c4c9c9ecb5d3a440dffdef0b860ba58984f1c7b8d018b62abc858ce9d scripts/check-release-archives_test.go 83c9c3f02e603e3ef0a9b3318a8be43d9e09483b943137e8169ca12551e3476f scripts/check-native-release.go a942283a5cd2fad447507261aecfefe45fe9c7e97c75284e0664d18ba5edf472 scripts/check-native-release_test.go INPUTS diff --git a/.github/workflows/tag-qualification.yml b/.github/workflows/tag-qualification.yml index 4e49ba9..4fb7435 100644 --- a/.github/workflows/tag-qualification.yml +++ b/.github/workflows/tag-qualification.yml @@ -46,12 +46,12 @@ jobs: 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum - f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go - 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go + 4bab12314beb126e5733dcb147d54b2b11d90eba81aa1ccea4c2463f2e943fd3 scripts/check-release-archives.go + d5e31a5c4c9c9ecb5d3a440dffdef0b860ba58984f1c7b8d018b62abc858ce9d scripts/check-release-archives_test.go 83c9c3f02e603e3ef0a9b3318a8be43d9e09483b943137e8169ca12551e3476f scripts/check-native-release.go a942283a5cd2fad447507261aecfefe45fe9c7e97c75284e0664d18ba5edf472 scripts/check-native-release_test.go - 3c1d05b6ba0fb93e9b03061e45bfb9b4ae0b7f5055c086261342fb40cc713955 scripts/qualify-tag-archives.go - 484c9d6acb7bb5f49f9b2ddf128d37c6ece4f890a66f8319e923e407ab2cabf9 scripts/qualify-tag-archives_test.go + 7b33ef466f782d6a39a4184e3dbaf45deff7e39a260866d0b216104314b2b28a scripts/qualify-tag-archives.go + 681d29149bb646f18d40a581b7bdea01ae1ffd0fc45e80a19080aed659a37e39 scripts/qualify-tag-archives_test.go 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh INPUTS root="$(mktemp -d "$RUNNER_TEMP/tag-qualification.XXXXXXXX")" @@ -140,12 +140,12 @@ jobs: 68afa214265e8668c77bdd63db95f60e987d7f7cd82bb3df7d82a25618d4e732 scripts/check-build-toolchain.go de865e63ef12058b46d3e1bba849c80213ef2219bcd827b4b8fbdd6b7d363078 go.mod 97f7baac3309f1b0889b30516fe3dcb581c0ba099130f7904e51d11963f534c4 go.sum - f7587c98b2032584cc7361e7f68f90f445d4162b3856c2e01f41d61424ff243b scripts/check-release-archives.go - 6bb5844033c697ed57c44614df06dc0164f5af79c6e02436fd05b4bbae08ff26 scripts/check-release-archives_test.go + 4bab12314beb126e5733dcb147d54b2b11d90eba81aa1ccea4c2463f2e943fd3 scripts/check-release-archives.go + d5e31a5c4c9c9ecb5d3a440dffdef0b860ba58984f1c7b8d018b62abc858ce9d scripts/check-release-archives_test.go 83c9c3f02e603e3ef0a9b3318a8be43d9e09483b943137e8169ca12551e3476f scripts/check-native-release.go a942283a5cd2fad447507261aecfefe45fe9c7e97c75284e0664d18ba5edf472 scripts/check-native-release_test.go - 3c1d05b6ba0fb93e9b03061e45bfb9b4ae0b7f5055c086261342fb40cc713955 scripts/qualify-tag-archives.go - 484c9d6acb7bb5f49f9b2ddf128d37c6ece4f890a66f8319e923e407ab2cabf9 scripts/qualify-tag-archives_test.go + 7b33ef466f782d6a39a4184e3dbaf45deff7e39a260866d0b216104314b2b28a scripts/qualify-tag-archives.go + 681d29149bb646f18d40a581b7bdea01ae1ffd0fc45e80a19080aed659a37e39 scripts/qualify-tag-archives_test.go 9c1ce84cca15098821f4597fcc7fda12a65bcaffce47e31636f43516f51af083 scripts/install-release-engine.sh INPUTS mkdir "$OWNED_ROOT/execution-home" "$OWNED_ROOT/execution-tmp" diff --git a/scripts/check-release-archives.go b/scripts/check-release-archives.go index 22f4979..98fa995 100644 --- a/scripts/check-release-archives.go +++ b/scripts/check-release-archives.go @@ -24,6 +24,7 @@ import ( "regexp" "runtime" "runtime/debug" + "strconv" "strings" "unicode/utf8" ) @@ -531,7 +532,8 @@ func bindNativeReceipt(root, sha, tree, tag, reportPath, nativePath string, out } func qualificationTagIdentity(root, sha, tree, tag string) error { - if !fullSHA.MatchString(sha) || !fullSHA.MatchString(tree) || tag != "v0.0.0-qualification.g"+sha { + wanted, e := numericQualificationTag(sha) + if e != nil || !fullSHA.MatchString(tree) || tag != wanted { return fmt.Errorf("qualification tag/source mismatch") } for _, key := range []string{"GORELEASER_CURRENT_TAG", "GORELEASER_PREVIOUS_TAG"} { @@ -1187,7 +1189,8 @@ func runArchiveCheck(args []string, out io.Writer) error { if len(args) != 6 { return fmt.Errorf("verify-tag requires SHA TREE TAG STATE EXTRACT") } - if !fullSHA.MatchString(args[2]) || args[3] != "v0.0.0-qualification.g"+args[1] { + wanted, tagErr := numericQualificationTag(args[1]) + if tagErr != nil || !fullSHA.MatchString(args[2]) || args[3] != wanted { return fmt.Errorf("qualification tag/source mismatch") } statePath := filepath.Clean(args[4]) @@ -1253,3 +1256,23 @@ func main() { os.Exit(1) } } + +// numericQualificationTag is only for unsigned local qualification refs. +// Encode all160 SHA bits as56/52/52-bit canonical decimal components: the +// released wfctl v0.78.2 parser accepts three signed64-bit numeric components, +// but refuses prerelease syntax. Keep these large versions out of releases. +func numericQualificationTag(sha string) (string, error) { + if !regexp.MustCompile(`^[0-9a-f]{40}$`).MatchString(sha) || sha == "0000000000000000000000000000000000000000" { + return "", fmt.Errorf("invalid qualification source") + } + chunks := []string{sha[:14], sha[14:27], sha[27:]} + var values [3]uint64 + for i, chunk := range chunks { + n, e := strconv.ParseUint(chunk, 16, 64) + if e != nil { + return "", fmt.Errorf("invalid qualification source") + } + values[i] = n + } + return fmt.Sprintf("v%d.%d.%d", values[0], values[1], values[2]), nil +} diff --git a/scripts/check-release-archives_test.go b/scripts/check-release-archives_test.go index 6d01d69..56a09db 100644 --- a/scripts/check-release-archives_test.go +++ b/scripts/check-release-archives_test.go @@ -12,11 +12,13 @@ import ( "encoding/binary" "encoding/json" "fmt" + "math/big" "os" "os/exec" "path/filepath" "runtime" "runtime/debug" + "strconv" "strings" "testing" "time" @@ -712,7 +714,7 @@ func TestCaptureRawSource(t *testing.T) { func TestTagModeCaptureCLI(t *testing.T) { root, sha, before := newSourceFixture(t) - tag := "v0.0.0-qualification.g" + sha + tag := qualificationTagReference(t, sha) // This is an unsigned, disposable local ref; no signing or remote operation. fixtureGit(t, root, "tag", "--no-sign", tag, sha) script, e := filepath.Abs("check-release-archives.go") @@ -738,7 +740,7 @@ func TestTagModeCaptureCLI(t *testing.T) { // not an engine invocation, native plugin execution or publication. func TestTagModeArchiveCLI(t *testing.T) { root, sha, before := newSourceFixture(t) - tag := "v0.0.0-qualification.g" + sha + tag := qualificationTagReference(t, sha) version := strings.TrimPrefix(tag, "v") fixtureGit(t, root, "tag", "--no-sign", tag, sha) script, e := filepath.Abs("check-release-archives.go") @@ -1505,3 +1507,72 @@ func TestTagRecheckTemporaryPlacement(t *testing.T) { }) } } + +func qualificationTagReference(t *testing.T, sha string) string { + t.Helper() + n, ok := new(big.Int).SetString(sha, 16) + if !ok { + t.Fatal("reference SHA parse") + } + mask := new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 52), big.NewInt(1)) + patch := new(big.Int).And(new(big.Int).Set(n), mask) + minor := new(big.Int).And(new(big.Int).Rsh(new(big.Int).Set(n), 52), mask) + major := new(big.Int).Rsh(new(big.Int).Set(n), 104) + return "v" + major.String() + "." + minor.String() + "." + patch.String() +} +func TestNumericQualificationTag(t *testing.T) { + vectors := []struct{ sha, tag string }{ + {"0000000000000000000000000008000000000000", "v0.0.2251799813685248"}, + {"0000000000000000000000000020000000000000", "v0.2.0"}, + {"0000000000000080000000000000000000000000", "v0.2251799813685248.0"}, + {"0000000000000200000000000000000000000000", "v2.0.0"}, + + {"0000000000000000000000000000000000000001", "v0.0.1"}, + {"0000000000000000000000000010000000000000", "v0.1.0"}, + {"0000000000000100000000000000000000000000", "v1.0.0"}, + {"8000000000000000000000000000000000000000", "v36028797018963968.0.0"}, + {"ffffffffffffffffffffffffffffffffffffffff", "v72057594037927935.4503599627370495.4503599627370495"}, + {"672c413c33732d1cad1c57166089e93ecd5dc3c7", "v29040581295698733.504477286229512.2789730733114311"}, + } + for _, tc := range vectors { + tag, e := numericQualificationTag(tc.sha) + if e != nil || tag != tc.tag || tag != qualificationTagReference(t, tc.sha) { + t.Fatal("qualification tag differs from independent full-SHA numeric contract") + } + parts := strings.Split(strings.TrimPrefix(tag, "v"), ".") + if len(parts) != 3 { + t.Fatal("numeric qualification tag is not legacy-compatible") + } + n := new(big.Int) + for index, p := range parts { + value, e := strconv.ParseUint(p, 10, 63) + if e != nil || strconv.FormatUint(value, 10) != p { + t.Fatal("component exceeds signed64 or is noncanonical") + } + if _, e := strconv.Atoi(p); e != nil { + t.Fatal("released legacy parser's integer operation rejects component") + } + if index > 0 { + n.Lsh(n, 52) + } + n.Add(n, new(big.Int).SetUint64(value)) + } + if fmt.Sprintf("%040x", n) != tc.sha { + t.Fatal("numeric tag lost or reordered SHA bits") + } + } + for _, bad := range []string{"", strings.Repeat("0", 40), strings.Repeat("A", 40), strings.Repeat("f", 39), strings.Repeat("f", 41), strings.Repeat("g", 40)} { + if _, e := numericQualificationTag(bad); e == nil { + t.Fatal("invalid or sentinel source accepted") + } + } +} + +func TestQualificationRejectsLegacyPrereleaseTag(t *testing.T) { + root, sha, before := newSourceFixture(t) + legacy := "v0.0.0-qualification.g" + sha + fixtureGit(t, root, "tag", "--no-sign", legacy, sha) + if e := qualificationTagIdentity(root, sha, before.Tree, legacy); e == nil { + t.Fatal("legacy incompatible qualification tag accepted") + } +} diff --git a/scripts/qualify-tag-archives.go b/scripts/qualify-tag-archives.go index ca7107a..fe2959f 100644 --- a/scripts/qualify-tag-archives.go +++ b/scripts/qualify-tag-archives.go @@ -17,6 +17,7 @@ import ( "path/filepath" "regexp" "runtime" + "strconv" ) const tagEngineSHA = "d124b61b79baf6d7e2727bb018e7115c045c076df82c13795bb19f9ace4b612d" @@ -237,6 +238,10 @@ func tagWrite(path string, data []byte) error { } func (q tagQualification) prepareClone() (string, error) { + tag, e := numericQualificationTag(q.sha) + if e != nil { + return "", e + } env := q.environment(false) src := filepath.Join(q.root, "source") if _, e := os.Lstat(src); !os.IsNotExist(e) { @@ -272,7 +277,7 @@ func (q tagQualification) prepareClone() (string, error) { if _, e = q.run(src, env, tagGit(src, "config", "remote.origin.pushurl", "disabled://qualification")); e != nil { return "", e } - if _, e = q.run(src, env, tagGit(src, "tag", "--no-sign", "v0.0.0-qualification.g"+q.sha, q.sha)); e != nil { + if _, e = q.run(src, env, tagGit(src, "tag", "--no-sign", tag, q.sha)); e != nil { return "", e } return src, nil @@ -282,6 +287,10 @@ func (q tagQualification) execute(out io.Writer) error { if !tagFullSHA.MatchString(q.sha) || !tagFullSHA.MatchString(q.tree) { return errors.New("invalid expected source identity") } + tag, e := numericQualificationTag(q.sha) + if e != nil { + return e + } for _, p := range []string{q.root, q.source, q.engine, q.wfctl, q.goBin} { if !filepath.IsAbs(p) || filepath.Clean(p) != p { return errors.New("qualification paths must be canonical/absolute") @@ -340,7 +349,6 @@ func (q tagQualification) execute(out io.Writer) error { if e != nil { return fmt.Errorf("owned checkout preparation failed: %w", e) } - tag := "v0.0.0-qualification.g" + q.sha checker := filepath.Join(src, "scripts/check-release-archives.go") goCheck := func(args ...string) ([]byte, error) { return q.run(src, q.environment(false), append([]string{q.goBin, "run", checker}, args...)) @@ -405,3 +413,23 @@ func main() { os.Exit(1) } } + +// numericQualificationTag is only for unsigned local qualification refs. +// Encode all160 SHA bits as56/52/52-bit canonical decimal components: the +// released wfctl v0.78.2 parser accepts three signed64-bit numeric components, +// but refuses prerelease syntax. Keep these large versions out of releases. +func numericQualificationTag(sha string) (string, error) { + if !regexp.MustCompile(`^[0-9a-f]{40}$`).MatchString(sha) || sha == "0000000000000000000000000000000000000000" { + return "", fmt.Errorf("invalid qualification source") + } + chunks := []string{sha[:14], sha[14:27], sha[27:]} + var values [3]uint64 + for i, chunk := range chunks { + n, e := strconv.ParseUint(chunk, 16, 64) + if e != nil { + return "", fmt.Errorf("invalid qualification source") + } + values[i] = n + } + return fmt.Sprintf("v%d.%d.%d", values[0], values[1], values[2]), nil +} diff --git a/scripts/qualify-tag-archives_test.go b/scripts/qualify-tag-archives_test.go index 6410e57..5b90c24 100644 --- a/scripts/qualify-tag-archives_test.go +++ b/scripts/qualify-tag-archives_test.go @@ -6,12 +6,15 @@ package main import ( "bytes" + "fmt" + "math/big" "os" "os/exec" "path/filepath" "reflect" "regexp" "runtime" + "strconv" "strings" "testing" ) @@ -105,7 +108,7 @@ func TestOwnedTagCheckout(t *testing.T) { if tagTestGit(t, source, "tag", "--list") != "" { t.Fatal("original checkout tags mutated") } - if got := tagTestGit(t, dest, "tag", "--list"); got != "v0.0.0-qualification.g"+sha { + if got := tagTestGit(t, dest, "tag", "--list"); got != qualificationTagReference(t, sha) { t.Fatal("owned qualification tag not exact") } if tagTestGit(t, dest, "rev-parse", "HEAD") != sha || tagTestGit(t, dest, "rev-parse", "HEAD^{tree}") != tree { @@ -467,3 +470,63 @@ func recordNestedNativeWorkspaces(t *testing.T, b []byte) { t.Logf("OWNED_NATIVE_TMP:%s", path) } } + +func qualificationTagReference(t *testing.T, sha string) string { + t.Helper() + n, ok := new(big.Int).SetString(sha, 16) + if !ok { + t.Fatal("reference SHA parse") + } + mask := new(big.Int).Sub(new(big.Int).Lsh(big.NewInt(1), 52), big.NewInt(1)) + patch := new(big.Int).And(new(big.Int).Set(n), mask) + minor := new(big.Int).And(new(big.Int).Rsh(new(big.Int).Set(n), 52), mask) + major := new(big.Int).Rsh(new(big.Int).Set(n), 104) + return "v" + major.String() + "." + minor.String() + "." + patch.String() +} +func TestNumericQualificationTag(t *testing.T) { + vectors := []struct{ sha, tag string }{ + {"0000000000000000000000000008000000000000", "v0.0.2251799813685248"}, + {"0000000000000000000000000020000000000000", "v0.2.0"}, + {"0000000000000080000000000000000000000000", "v0.2251799813685248.0"}, + {"0000000000000200000000000000000000000000", "v2.0.0"}, + + {"0000000000000000000000000000000000000001", "v0.0.1"}, + {"0000000000000000000000000010000000000000", "v0.1.0"}, + {"0000000000000100000000000000000000000000", "v1.0.0"}, + {"8000000000000000000000000000000000000000", "v36028797018963968.0.0"}, + {"ffffffffffffffffffffffffffffffffffffffff", "v72057594037927935.4503599627370495.4503599627370495"}, + {"672c413c33732d1cad1c57166089e93ecd5dc3c7", "v29040581295698733.504477286229512.2789730733114311"}, + } + for _, tc := range vectors { + tag, e := numericQualificationTag(tc.sha) + if e != nil || tag != tc.tag || tag != qualificationTagReference(t, tc.sha) { + t.Fatal("qualification tag differs from independent full-SHA numeric contract") + } + parts := strings.Split(strings.TrimPrefix(tag, "v"), ".") + if len(parts) != 3 { + t.Fatal("numeric qualification tag is not legacy-compatible") + } + n := new(big.Int) + for index, p := range parts { + value, e := strconv.ParseUint(p, 10, 63) + if e != nil || strconv.FormatUint(value, 10) != p { + t.Fatal("component exceeds signed64 or is noncanonical") + } + if _, e := strconv.Atoi(p); e != nil { + t.Fatal("released legacy parser's integer operation rejects component") + } + if index > 0 { + n.Lsh(n, 52) + } + n.Add(n, new(big.Int).SetUint64(value)) + } + if fmt.Sprintf("%040x", n) != tc.sha { + t.Fatal("numeric tag lost or reordered SHA bits") + } + } + for _, bad := range []string{"", strings.Repeat("0", 40), strings.Repeat("A", 40), strings.Repeat("f", 39), strings.Repeat("f", 41), strings.Repeat("g", 40)} { + if _, e := numericQualificationTag(bad); e == nil { + t.Fatal("invalid or sentinel source accepted") + } + } +}