package equipotest import ( "crypto/sha256" "encoding/json" "fmt" "os" "os/exec" "path/filepath" "reflect" "regexp" "strings" "testing" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/release" ) func TestRunnerReleaseContract(t *testing.T) { raw, err := os.ReadFile("../release/manifest.json") executionMust(t, err) var manifest release.Manifest if err = json.Unmarshal(raw, &manifest); err != nil { t.Fatal(err) } if !reflect.DeepEqual(manifest, release.BuildManifest()) { t.Fatal("manifest differs from embedded build") } if manifest.Schema != 3 || manifest.Codex != "0.165.0" || manifest.BwrapVersion != "0.11.0" { t.Fatal("unpinned dependencies") } // The source pins the four programs this repository does not build. // The tool proxy is never typed in: a release build records it. names := []string{} for _, b := range manifest.Binaries { names = append(names, b.Name) } if !reflect.DeepEqual(names, []string{"claude", "codex", "codex-code-mode-host", "bwrap"}) || manifest.Installable() { t.Fatalf("source manifest pins %v", names) } unit, err := os.ReadFile("../../packaging/equipo-runner.service") if err != nil { t.Fatal(err) } for _, value := range []string{"Type=simple", "Restart=on-failure", "TimeoutStopSec=45", "KillMode=control-group", "EnvironmentFile=%h/.config/equipo-runner/runner.env", "ExecStart=%h/.local/lib/equipo-runner/equipo-runner run"} { if !strings.Contains(string(unit), value) { t.Fatalf("missing service contract: %s", value) } } for _, value := range []string{"0.0.0.0", "sudo ", "ExecStartPost=", "enrol"} { if strings.Contains(string(unit), value) { t.Fatalf("unsafe unit %s", value) } } } func TestRunnerReleaseContractPackaging(t *testing.T) { runnerPackagingScenarios(t, "release-runner", []string{"clean", "dirty", "untracked", "codex", "copy", "helper", "digest"}) } // A release is refused unless the pinned programs agree everywhere (the // manifest, the provider packages, this machine) and reviewed copy is in. // A clean one records what it built: no digest in it is typed in. func TestReleasePinsAndProvenance(t *testing.T) { for _, target := range []string{"release", "release-runner"} { t.Run(target, func(t *testing.T) { runnerPackagingScenarios(t, target, []string{"clean", "fake_cli", "manifest_pin", "tool_proxy_pinned", "old_schema", "bwrap", "copy", "pending_plan3_docs", "missing_plan3_inventory"}) }) } } // make release builds in a tree of its own, a checkout of one commit, and // records provenance only for what that commit built: a tree that was // dirty before, changed during the build, or a binary whose own build // information names another commit or a modified tree, records nothing // and leaves nothing in releases/. func TestReleaseBuildsFromOneCommit(t *testing.T) { runnerPackagingScenarios(t, "release", []string{"dirty", "untracked", "changed_during_build", "vcs_revision", "vcs_modified", "vcs_missing"}) } func runnerPackagingScenarios(t *testing.T, target string, scenarios []string) { for _, scenario := range scenarios { t.Run(scenario, func(t *testing.T) { root := t.TempDir() bin := filepath.Join(root, "bin") executionMust(t, os.Mkdir(bin, 0700)) copyReleaseTrackedTree(t, root) scripts := map[string]string{ // git: one commit, abc1234. A clone of it is a copy of this tree. "git": "#!/bin/sh\ncase \"$1\" in diff) [ \"$SCENARIO\" != dirty ];; rev-parse) echo abc1234;; ls-files) if [ \"$SCENARIO\" = untracked ]; then echo unsafe.go; fi;; status) if [ \"$SCENARIO\" = dirty ]; then echo ' M tracked'; fi; if [ \"$SCENARIO\" = untracked ]; then echo '?? unsafe.go'; fi; if [ -e changed-during-build ]; then echo '?? changed-during-build'; fi;; clone) for a; do last=$a; done; mkdir -p \"$last\" && cp -R . \"$last\";; esac\n", // Each build writes its own bytes, so every artifact has its own digest. // go version -m reports the commit a binary says it was built from. "go": "#!/bin/sh\ncase \"$1\" in env) echo go1.26.11;; version) rev=abc1234; mod=false; if [ \"$SCENARIO\" = vcs_revision ]; then rev=def5678; fi; if [ \"$SCENARIO\" = vcs_modified ]; then mod=true; fi; if [ \"$SCENARIO\" != vcs_missing ]; then printf '%s: go1.26.11\\n\\tpath\\tfixture\\n\\tbuild\\tvcs.revision=%s\\n\\tbuild\\tvcs.modified=%s\\n' \"$3\" \"$rev\" \"$mod\"; fi;; test) [ \"$SCENARIO\" != copy ];; build) if [ \"$SCENARIO\" = changed_during_build ]; then touch changed-during-build; fi; if [ \"$GOOS/$GOARCH\" = linux/arm64 ]; then test -f internal/release/bundled/install-manifest.json || exit 97; test ! -e internal/release/bundled/renderer.tar.gz || exit 96; fi; printf '%s\\n' \"$GOOS/$GOARCH\" \"$@\" >> \"$CAPTURE\"; while [ $# -gt 0 ]; do if [ \"$1\" = -o ]; then shift; printf 'built %s for %s\\n' \"$1\" \"$GOOS/$GOARCH\" > \"$1\"; fi; shift; done;; esac\n", "codex": "#!/bin/sh\n[ \"$SCENARIO\" != codex ] && echo 'codex-cli 0.165.0'\n", "bwrap": "#!/bin/sh\nif [ \"$SCENARIO\" = bwrap ]; then echo 'bubblewrap 0.10.0'; else echo 'bubblewrap 0.11.0'; fi\n", "systemctl": "#!/bin/sh\nexit 98\n", "carlos": "#!/bin/sh\nexit 99\n", } scripts["go"] = strings.Replace(scripts["go"], "version) rev=abc1234;", `version) case "$3" in */gitleaks) printf '\tmod\tgithub.com/zricethezav/gitleaks/v8\tv8.30.1\th1:fixture\n'; exit 0;; esac; rev=abc1234;`, 1) scripts["../scripts/build-renderer-tree.py"] = "import gzip, hashlib, io, sys, tarfile\nassert sys.argv[1] == 'internal/release/renderer.json' and sys.argv[2].endswith('-abc1234/renderer.tar.gz')\nm = b'dir usr\\n'\nwith gzip.open(sys.argv[2], 'wb') as g, tarfile.open(fileobj=g, mode='w|') as t:\n i = tarfile.TarInfo('MANIFEST'); i.size = len(m); t.addfile(i, io.BytesIO(m))\nopen(sys.argv[2].rsplit('/', 1)[0] + '/SOURCES', 'w').write('sources\\n')\nprint(hashlib.sha256(m).hexdigest())\n" // a tree of one directory, and its SOURCES: the script itself is tested in internal/release for name, script := range scripts { executionMust(t, os.WriteFile(filepath.Join(bin, name), []byte(script), 0700)) } installed := releasePinsFixture(t, root, bin, scenario) if scenario == "codex" { executionMust(t, os.WriteFile(filepath.Join(bin, "codex"), []byte("changed executable"), 0700)) } if scenario == "helper" { executionMust(t, os.Remove(filepath.Join(bin, "codex-code-mode-host"))) } if scenario == "digest" { executionMust(t, os.WriteFile(filepath.Join(bin, "claude"), []byte("changed"), 0700)) } capture := filepath.Join(root, "build.args") cmd := exec.Command("make", "--no-print-directory", target) cmd.Dir = root cmd.Env = []string{"PATH=" + bin + ":/usr/bin:/bin", "SCENARIO=" + scenario, "CAPTURE=" + capture, "TMPDIR=" + t.TempDir()} cmd.Env = append(cmd.Env, installed...) out, err := cmd.CombinedOutput() if scenario != "clean" { if err == nil { t.Fatalf("unsafe release accepted %s: %s", scenario, out) } // These are caught after the build, in its own tree: nothing // of it reaches releases/, and no provenance is recorded. if after := scenario == "changed_during_build" || strings.HasPrefix(scenario, "vcs_"); after { if _, err = os.Stat(filepath.Join(root, "releases")); !os.IsNotExist(err) { t.Fatalf("a refused build left artifacts in releases/: %s", out) } } else if _, err = os.Stat(capture); !os.IsNotExist(err) { t.Fatal("built before release guards") } return } if err != nil { t.Fatalf("release: %v %s", err, out) } raw, err := os.ReadFile(capture) executionMust(t, err) wantTarget := "linux/amd64" if target == "release" { wantTarget = "linux/arm64" } if !strings.Contains(string(raw), wantTarget) || !strings.Contains(string(raw), "BuildVersion=abc1234") { t.Fatalf("wrong stamped build: %s", raw) } // No build turns off the commit a binary records about itself. if strings.Contains(string(raw), "buildvcs") { t.Fatalf("a release build hides its commit: %s", raw) } dir := filepath.Join(root, "releases/equipo-runner-linux-amd64-abc1234") digest := func(path string) string { t.Helper() b, err := os.ReadFile(path) executionMust(t, err) return fmt.Sprintf("%x", sha256.Sum256(b)) } size := func(path string) int64 { t.Helper() info, err := os.Stat(path) executionMust(t, err) return info.Size() } proxy := digest(filepath.Join(dir, "equipo-tool-proxy")) // The tool proxy is built first, plainly; both runners are then // linked with the digest of that build (Mac runners spec ยง3.1: // the Mac worker is built beside the Linux runner, stamped the same). flags := "-s -w -X amadan.net/rastrillo/rastrillo.BuildVersion=abc1234 -X amadan.net/oficina/equipo/internal/release.toolProxySHA256=" + proxy for _, build := range []string{ "linux/amd64\nbuild\n-trimpath\n-ldflags\n-s -w\n-o\nreleases/equipo-runner-linux-amd64-abc1234/equipo-tool-proxy\n./cmd/equipo-tool-proxy\n", "linux/amd64\nbuild\n-trimpath\n-ldflags\n" + flags + " -X amadan.net/oficina/equipo/internal/release.gitleaksSHA256=" + digest(filepath.Join(dir, "gitleaks")) + " -X amadan.net/oficina/equipo/internal/release.rendererSHA256=" + fmt.Sprintf("%x", sha256.Sum256([]byte("dir usr\n"))) + // The archive the runner fetches from the forge: its digest, // size and the tag its digest names. " -X amadan.net/oficina/equipo/internal/release.rendererArchiveSHA256=" + digest(filepath.Join(dir, "renderer.tar.gz")) + " -X amadan.net/oficina/equipo/internal/release.rendererArchiveSize=" + fmt.Sprint(size(filepath.Join(dir, "renderer.tar.gz"))) + " -X amadan.net/oficina/equipo/internal/release.rendererTag=renderer-" + digest(filepath.Join(dir, "renderer.tar.gz"))[:12] + "\n-o\nreleases/equipo-runner-linux-amd64-abc1234/equipo-runner\n", "darwin/arm64\nbuild\n-trimpath\n-ldflags\n" + flags + " -X amadan.net/oficina/equipo/internal/release.gitleaksSHA256=" + digest(filepath.Join(dir, "darwin-arm64", "gitleaks")) + "\n-o\nreleases/equipo-runner-linux-amd64-abc1234/darwin-arm64/equipo-runner\n", } { if !strings.Contains(string(raw), build) { t.Fatalf("missing build %q in: %s", build, raw) } } if strings.Index(string(raw), "./cmd/equipo-tool-proxy") > strings.Index(string(raw), "./cmd/equipo-runner") { t.Fatalf("a runner was built before the tool proxy it records: %s", raw) } // A Mac worker has no tool proxy. if strings.Contains(string(raw), "darwin-arm64/equipo-tool-proxy") { t.Fatalf("a Mac tool proxy built: %s", raw) } // The shipped manifest is the source's pins plus the proxy this // build made, and the install manifest names the same bytes. var source, shipped release.Manifest readJSON := func(path string, into any) { t.Helper() b, err := os.ReadFile(path) executionMust(t, err) executionMust(t, json.Unmarshal(b, into)) } readJSON(filepath.Join(root, "internal/release/manifest.json"), &source) readJSON(filepath.Join(dir, "manifest.json"), &shipped) source.Binaries = append(source.Binaries, release.BinaryDigest{Name: "equipo-tool-proxy", Version: source.LauncherVersion, SHA256: proxy}) if !reflect.DeepEqual(source, shipped) || !shipped.Installable() { t.Fatalf("shipped manifest %+v", shipped) } var install release.InstallManifest readJSON(filepath.Join(dir, "install-manifest.json"), &install) runner, mac := digest(filepath.Join(dir, "equipo-runner")), digest(filepath.Join(dir, "darwin-arm64/equipo-runner")) if install.Validate("abc1234") != nil || !reflect.DeepEqual(install.Release, shipped) || install.RunnerSHA256 != runner || !reflect.DeepEqual(install.Targets, map[string]release.InstallTarget{release.TargetLinux: {RunnerSHA256: runner, ToolProxySHA256: proxy, GitleaksSHA256: digest(filepath.Join(dir, "gitleaks")), RendererSHA256: fmt.Sprintf("%x", sha256.Sum256([]byte("dir usr\n"))), RendererArchiveSHA256: digest(filepath.Join(dir, "renderer.tar.gz")), RendererArchiveSize: size(filepath.Join(dir, "renderer.tar.gz"))}, release.TargetDarwin: {RunnerSHA256: mac, GitleaksSHA256: digest(filepath.Join(dir, "darwin-arm64", "gitleaks"))}}) { t.Fatalf("install manifest %+v", install) } if _, err := os.Stat(filepath.Join(dir, "evidence")); !os.IsNotExist(err) { t.Fatal("a release ships live-gate evidence") } if target != "release" { return } // The instance is linked with the same digest, and the provenance // manifest records every artifact of the build at its commit. instance := filepath.Join(root, "releases/equipo-linux-arm64-abc1234") if !strings.Contains(string(raw), "linux/arm64\nbuild\n-tags\nrunnerassets\n-trimpath\n-ldflags\n"+flags+"\n-o\nreleases/equipo-linux-arm64-abc1234\n./cmd/equipo\n") { t.Fatalf("the instance is not linked with its build's tool proxy: %s", raw) } var made struct { Version, Commit, Go string Release release.Manifest SHA256 map[string]string } readJSON(instance+".manifest.json", &made) if made.Version != "abc1234" || made.Commit != "abc1234" || made.Go != "go1.26.11" || !reflect.DeepEqual(made.Release, shipped) || !reflect.DeepEqual(made.SHA256, map[string]string{"instance": digest(instance), "runner": runner, "tool_proxy": proxy, "darwin_runner": mac, "gitleaks": digest(filepath.Join(dir, "gitleaks")), "darwin_gitleaks": digest(filepath.Join(dir, "darwin-arm64", "gitleaks")), "renderer_archive": digest(filepath.Join(dir, "renderer.tar.gz")), "renderer_sources": digest(filepath.Join(dir, "SOURCES")), "install_manifest": digest(filepath.Join(dir, "install-manifest.json"))}) { t.Fatalf("provenance manifest %+v", made) } if _, err := os.Stat(instance + ".evidence"); !os.IsNotExist(err) { t.Fatal("a release ships live-gate evidence") } // What was just built verifies; one changed byte does not. verify := func() error { cmd := exec.Command("python3", "scripts/staged-artifacts.py", "verify", "abc1234") cmd.Dir = root return cmd.Run() } executionMust(t, verify()) executionMust(t, os.WriteFile(filepath.Join(dir, "equipo-tool-proxy"), []byte("another tool proxy"), 0700)) if verify() == nil { t.Fatal("a tool proxy the release did not build verified") } }) } } // A store that is given no verified tuples, as production's is, treats // no report as verified for anyone but its owner. func TestRunnerReleaseContractUnlistedReport(t *testing.T) { f := connectionStore(t) f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock)) executionMust(t, f.s.ReportConnections(connectionContext, f.principal, f.reports)) rows, err := f.s.Connections(connectionContext, ownerActor) executionMust(t, err) for _, row := range rows { for _, r := range row.Reports { if r.ReadIsolation { t.Fatal("unlisted report changed build eligibility") } } } f.choice(t, "") f.denied(t, "engineering", "") } // releasePinsFixture gives an isolated copy of the tree fake provider // programs and pins that name them: the manifest, the provider packages // and the programs agree, as a release needs. A scenario breaks one of // them. It returns the EQUIPO_*_PATH variables for the release check. // Only this copy receives synthetic reviewed copy and pins; production // documents, pins and pending markers are never rewritten. func releasePinsFixture(t *testing.T, root, bin, scenario string) []string { t.Helper() write := func(name string, data []byte, mode os.FileMode) { t.Helper() executionMust(t, os.WriteFile(filepath.Join(root, name), data, mode)) } for _, name := range []string{"internal/equipo/copy.go", "docs/api/equipo-v1.md", "docs/plan-3-acceptance.md", "docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md"} { write(name, []byte("reviewed packaging fixture only\n"), 0600) } if scenario == "pending_plan3_docs" { write("docs/api/equipo-v1.md", []byte("COPY REVIEW REQUIRED\n"), 0600) } if scenario == "missing_plan3_inventory" { executionMust(t, os.Remove(filepath.Join(root, "docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md"))) } var fixture release.Manifest raw, err := os.ReadFile(filepath.Join(root, "internal/release/manifest.json")) executionMust(t, err) executionMust(t, json.Unmarshal(raw, &fixture)) var installed []string hashes := map[string]string{} for i, b := range fixture.Binaries { path := filepath.Join(bin, b.Name) if b.Name != "codex" && b.Name != "bwrap" { executionMust(t, os.WriteFile(path, []byte("#!/bin/sh\n# "+b.Name+"\nexit 0\n"), 0700)) } data, err := os.ReadFile(path) executionMust(t, err) hashes[b.Name] = fmt.Sprintf("%x", sha256.Sum256(data)) fixture.Binaries[i].SHA256 = hashes[b.Name] variable := map[string]string{"claude": "EQUIPO_CLAUDE_PATH", "codex": "EQUIPO_CODEX_PATH", "codex-code-mode-host": "EQUIPO_CODEX_CODE_MODE_HOST_PATH", "bwrap": "EQUIPO_BWRAP_PATH"}[b.Name] installed = append(installed, variable+"="+path) } // fake_cli leaves the production pins in the provider packages: they // must refuse the same fake programs the manifest now names. if scenario != "fake_cli" { for _, name := range []string{"claude", "codex"} { path := filepath.Join("internal/runner/provider", name, "launcher.go") data, err := os.ReadFile(filepath.Join(root, path)) executionMust(t, err) lines := strings.Split(string(data), "\n") for i, line := range lines { if strings.HasPrefix(line, "const ExecutableSHA256 =") { lines[i] = fmt.Sprintf("const ExecutableSHA256 = %q", hashes[name]) } if strings.HasPrefix(line, "const CodeModeHostSHA256 =") { lines[i] = fmt.Sprintf("const CodeModeHostSHA256 = %q", hashes["codex-code-mode-host"]) } } write(path, []byte(strings.Join(lines, "\n")), 0600) } // On an arm64 machine the prerequisites check reads the arm64 pin. path := "internal/runner/provider/codex/pins.go" data, err := os.ReadFile(filepath.Join(root, path)) executionMust(t, err) arm := regexp.MustCompile(`(ExecutableSHA256Arm64\s+= )"[a-f0-9]{64}"`) write(path, arm.ReplaceAll(data, []byte(`${1}"`+hashes["codex"]+`"`)), 0600) } switch scenario { case "manifest_pin": // The manifest names other bytes than the provider package pins. fixture.Binaries[0].SHA256 = strings.Repeat("c", 64) case "tool_proxy_pinned": // A tool proxy digest typed into the source is never accepted. fixture.Binaries = append(fixture.Binaries, release.BinaryDigest{Name: "equipo-tool-proxy", Version: fixture.LauncherVersion, SHA256: strings.Repeat("d", 64)}) case "old_schema": fixture.Schema = 2 } data, err := json.Marshal(fixture) executionMust(t, err) write("internal/release/manifest.json", data, 0600) return installed }