oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package equipotest
2
3import (
4 "crypto/sha256"
5 "encoding/json"
6 "fmt"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "reflect"
11 "regexp"
12 "strings"
13 "testing"
14
15 "amadan.net/oficina/equipo/internal/equipo"
16 "amadan.net/oficina/equipo/internal/release"
17)
18
19func TestRunnerReleaseContract(t *testing.T) {
20 raw, err := os.ReadFile("../release/manifest.json")
21 executionMust(t, err)
22 var manifest release.Manifest
23 if err = json.Unmarshal(raw, &manifest); err != nil {
24 t.Fatal(err)
25 }
26 if !reflect.DeepEqual(manifest, release.BuildManifest()) {
27 t.Fatal("manifest differs from embedded build")
28 }
29 if manifest.Schema != 3 || manifest.Codex != "0.165.0" || manifest.BwrapVersion != "0.11.0" {
30 t.Fatal("unpinned dependencies")
31 }
32 // The source pins the four programs this repository does not build.
33 // The tool proxy is never typed in: a release build records it.
34 names := []string{}
35 for _, b := range manifest.Binaries {
36 names = append(names, b.Name)
37 }
38 if !reflect.DeepEqual(names, []string{"claude", "codex", "codex-code-mode-host", "bwrap"}) || manifest.Installable() {
39 t.Fatalf("source manifest pins %v", names)
40 }
41 unit, err := os.ReadFile("../../packaging/equipo-runner.service")
42 if err != nil {
43 t.Fatal(err)
44 }
45 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"} {
46 if !strings.Contains(string(unit), value) {
47 t.Fatalf("missing service contract: %s", value)
48 }
49 }
50 for _, value := range []string{"0.0.0.0", "sudo ", "ExecStartPost=", "enrol"} {
51 if strings.Contains(string(unit), value) {
52 t.Fatalf("unsafe unit %s", value)
53 }
54 }
55}
56
57func TestRunnerReleaseContractPackaging(t *testing.T) {
58 runnerPackagingScenarios(t, "release-runner", []string{"clean", "dirty", "untracked", "codex", "copy", "helper", "digest"})
59}
60
61// A release is refused unless the pinned programs agree everywhere (the
62// manifest, the provider packages, this machine) and reviewed copy is in.
63// A clean one records what it built: no digest in it is typed in.
64func TestReleasePinsAndProvenance(t *testing.T) {
65 for _, target := range []string{"release", "release-runner"} {
66 t.Run(target, func(t *testing.T) {
67 runnerPackagingScenarios(t, target, []string{"clean", "fake_cli", "manifest_pin", "tool_proxy_pinned", "old_schema", "bwrap", "copy", "pending_plan3_docs", "missing_plan3_inventory"})
68 })
69 }
70}
71
72// make release builds in a tree of its own, a checkout of one commit, and
73// records provenance only for what that commit built: a tree that was
74// dirty before, changed during the build, or a binary whose own build
75// information names another commit or a modified tree, records nothing
76// and leaves nothing in releases/.
77func TestReleaseBuildsFromOneCommit(t *testing.T) {
78 runnerPackagingScenarios(t, "release", []string{"dirty", "untracked", "changed_during_build", "vcs_revision", "vcs_modified", "vcs_missing"})
79}
80
81func runnerPackagingScenarios(t *testing.T, target string, scenarios []string) {
82 for _, scenario := range scenarios {
83 t.Run(scenario, func(t *testing.T) {
84 root := t.TempDir()
85 bin := filepath.Join(root, "bin")
86 executionMust(t, os.Mkdir(bin, 0700))
87 copyReleaseTrackedTree(t, root)
88 scripts := map[string]string{
89 // git: one commit, abc1234. A clone of it is a copy of this tree.
90 "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",
91 // Each build writes its own bytes, so every artifact has its own digest.
92 // go version -m reports the commit a binary says it was built from.
93 "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",
94 "codex": "#!/bin/sh\n[ \"$SCENARIO\" != codex ] && echo 'codex-cli 0.165.0'\n",
95 "bwrap": "#!/bin/sh\nif [ \"$SCENARIO\" = bwrap ]; then echo 'bubblewrap 0.10.0'; else echo 'bubblewrap 0.11.0'; fi\n",
96 "systemctl": "#!/bin/sh\nexit 98\n",
97 "carlos": "#!/bin/sh\nexit 99\n",
98 }
99 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)
100 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
101 for name, script := range scripts {
102 executionMust(t, os.WriteFile(filepath.Join(bin, name), []byte(script), 0700))
103 }
104 installed := releasePinsFixture(t, root, bin, scenario)
105 if scenario == "codex" {
106 executionMust(t, os.WriteFile(filepath.Join(bin, "codex"), []byte("changed executable"), 0700))
107 }
108 if scenario == "helper" {
109 executionMust(t, os.Remove(filepath.Join(bin, "codex-code-mode-host")))
110 }
111 if scenario == "digest" {
112 executionMust(t, os.WriteFile(filepath.Join(bin, "claude"), []byte("changed"), 0700))
113 }
114 capture := filepath.Join(root, "build.args")
115 cmd := exec.Command("make", "--no-print-directory", target)
116 cmd.Dir = root
117 cmd.Env = []string{"PATH=" + bin + ":/usr/bin:/bin", "SCENARIO=" + scenario, "CAPTURE=" + capture, "TMPDIR=" + t.TempDir()}
118 cmd.Env = append(cmd.Env, installed...)
119 out, err := cmd.CombinedOutput()
120 if scenario != "clean" {
121 if err == nil {
122 t.Fatalf("unsafe release accepted %s: %s", scenario, out)
123 }
124 // These are caught after the build, in its own tree: nothing
125 // of it reaches releases/, and no provenance is recorded.
126 if after := scenario == "changed_during_build" || strings.HasPrefix(scenario, "vcs_"); after {
127 if _, err = os.Stat(filepath.Join(root, "releases")); !os.IsNotExist(err) {
128 t.Fatalf("a refused build left artifacts in releases/: %s", out)
129 }
130 } else if _, err = os.Stat(capture); !os.IsNotExist(err) {
131 t.Fatal("built before release guards")
132 }
133 return
134 }
135 if err != nil {
136 t.Fatalf("release: %v %s", err, out)
137 }
138 raw, err := os.ReadFile(capture)
139 executionMust(t, err)
140 wantTarget := "linux/amd64"
141 if target == "release" {
142 wantTarget = "linux/arm64"
143 }
144 if !strings.Contains(string(raw), wantTarget) || !strings.Contains(string(raw), "BuildVersion=abc1234") {
145 t.Fatalf("wrong stamped build: %s", raw)
146 }
147 // No build turns off the commit a binary records about itself.
148 if strings.Contains(string(raw), "buildvcs") {
149 t.Fatalf("a release build hides its commit: %s", raw)
150 }
151 dir := filepath.Join(root, "releases/equipo-runner-linux-amd64-abc1234")
152 digest := func(path string) string {
153 t.Helper()
154 b, err := os.ReadFile(path)
155 executionMust(t, err)
156 return fmt.Sprintf("%x", sha256.Sum256(b))
157 }
158 size := func(path string) int64 {
159 t.Helper()
160 info, err := os.Stat(path)
161 executionMust(t, err)
162 return info.Size()
163 }
164 proxy := digest(filepath.Join(dir, "equipo-tool-proxy"))
165 // The tool proxy is built first, plainly; both runners are then
166 // linked with the digest of that build (Mac runners spec §3.1:
167 // the Mac worker is built beside the Linux runner, stamped the same).
168 flags := "-s -w -X amadan.net/rastrillo/rastrillo.BuildVersion=abc1234 -X amadan.net/oficina/equipo/internal/release.toolProxySHA256=" + proxy
169 for _, build := range []string{
170 "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",
171 "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"))) +
172 // The archive the runner fetches from the forge: its digest,
173 // size and the tag its digest names.
174 " -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",
175 "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",
176 } {
177 if !strings.Contains(string(raw), build) {
178 t.Fatalf("missing build %q in: %s", build, raw)
179 }
180 }
181 if strings.Index(string(raw), "./cmd/equipo-tool-proxy") > strings.Index(string(raw), "./cmd/equipo-runner") {
182 t.Fatalf("a runner was built before the tool proxy it records: %s", raw)
183 }
184 // A Mac worker has no tool proxy.
185 if strings.Contains(string(raw), "darwin-arm64/equipo-tool-proxy") {
186 t.Fatalf("a Mac tool proxy built: %s", raw)
187 }
188 // The shipped manifest is the source's pins plus the proxy this
189 // build made, and the install manifest names the same bytes.
190 var source, shipped release.Manifest
191 readJSON := func(path string, into any) {
192 t.Helper()
193 b, err := os.ReadFile(path)
194 executionMust(t, err)
195 executionMust(t, json.Unmarshal(b, into))
196 }
197 readJSON(filepath.Join(root, "internal/release/manifest.json"), &source)
198 readJSON(filepath.Join(dir, "manifest.json"), &shipped)
199 source.Binaries = append(source.Binaries, release.BinaryDigest{Name: "equipo-tool-proxy", Version: source.LauncherVersion, SHA256: proxy})
200 if !reflect.DeepEqual(source, shipped) || !shipped.Installable() {
201 t.Fatalf("shipped manifest %+v", shipped)
202 }
203 var install release.InstallManifest
204 readJSON(filepath.Join(dir, "install-manifest.json"), &install)
205 runner, mac := digest(filepath.Join(dir, "equipo-runner")), digest(filepath.Join(dir, "darwin-arm64/equipo-runner"))
206 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"))}}) {
207 t.Fatalf("install manifest %+v", install)
208 }
209 if _, err := os.Stat(filepath.Join(dir, "evidence")); !os.IsNotExist(err) {
210 t.Fatal("a release ships live-gate evidence")
211 }
212 if target != "release" {
213 return
214 }
215 // The instance is linked with the same digest, and the provenance
216 // manifest records every artifact of the build at its commit.
217 instance := filepath.Join(root, "releases/equipo-linux-arm64-abc1234")
218 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") {
219 t.Fatalf("the instance is not linked with its build's tool proxy: %s", raw)
220 }
221 var made struct {
222 Version, Commit, Go string
223 Release release.Manifest
224 SHA256 map[string]string
225 }
226 readJSON(instance+".manifest.json", &made)
227 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")),
228 "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"))}) {
229 t.Fatalf("provenance manifest %+v", made)
230 }
231 if _, err := os.Stat(instance + ".evidence"); !os.IsNotExist(err) {
232 t.Fatal("a release ships live-gate evidence")
233 }
234 // What was just built verifies; one changed byte does not.
235 verify := func() error {
236 cmd := exec.Command("python3", "scripts/staged-artifacts.py", "verify", "abc1234")
237 cmd.Dir = root
238 return cmd.Run()
239 }
240 executionMust(t, verify())
241 executionMust(t, os.WriteFile(filepath.Join(dir, "equipo-tool-proxy"), []byte("another tool proxy"), 0700))
242 if verify() == nil {
243 t.Fatal("a tool proxy the release did not build verified")
244 }
245 })
246 }
247}
248
249// A store that is given no verified tuples, as production's is, treats
250// no report as verified for anyone but its owner.
251func TestRunnerReleaseContractUnlistedReport(t *testing.T) {
252 f := connectionStore(t)
253 f.s = equipo.NewStore(f.d, equipo.WithRunnerClock(f.clock))
254 executionMust(t, f.s.ReportConnections(connectionContext, f.principal, f.reports))
255 rows, err := f.s.Connections(connectionContext, ownerActor)
256 executionMust(t, err)
257 for _, row := range rows {
258 for _, r := range row.Reports {
259 if r.ReadIsolation {
260 t.Fatal("unlisted report changed build eligibility")
261 }
262 }
263 }
264 f.choice(t, "")
265 f.denied(t, "engineering", "")
266}
267
268// releasePinsFixture gives an isolated copy of the tree fake provider
269// programs and pins that name them: the manifest, the provider packages
270// and the programs agree, as a release needs. A scenario breaks one of
271// them. It returns the EQUIPO_*_PATH variables for the release check.
272// Only this copy receives synthetic reviewed copy and pins; production
273// documents, pins and pending markers are never rewritten.
274func releasePinsFixture(t *testing.T, root, bin, scenario string) []string {
275 t.Helper()
276 write := func(name string, data []byte, mode os.FileMode) {
277 t.Helper()
278 executionMust(t, os.WriteFile(filepath.Join(root, name), data, mode))
279 }
280 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"} {
281 write(name, []byte("reviewed packaging fixture only\n"), 0600)
282 }
283 if scenario == "pending_plan3_docs" {
284 write("docs/api/equipo-v1.md", []byte("COPY REVIEW REQUIRED\n"), 0600)
285 }
286 if scenario == "missing_plan3_inventory" {
287 executionMust(t, os.Remove(filepath.Join(root, "docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md")))
288 }
289 var fixture release.Manifest
290 raw, err := os.ReadFile(filepath.Join(root, "internal/release/manifest.json"))
291 executionMust(t, err)
292 executionMust(t, json.Unmarshal(raw, &fixture))
293 var installed []string
294 hashes := map[string]string{}
295 for i, b := range fixture.Binaries {
296 path := filepath.Join(bin, b.Name)
297 if b.Name != "codex" && b.Name != "bwrap" {
298 executionMust(t, os.WriteFile(path, []byte("#!/bin/sh\n# "+b.Name+"\nexit 0\n"), 0700))
299 }
300 data, err := os.ReadFile(path)
301 executionMust(t, err)
302 hashes[b.Name] = fmt.Sprintf("%x", sha256.Sum256(data))
303 fixture.Binaries[i].SHA256 = hashes[b.Name]
304 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]
305 installed = append(installed, variable+"="+path)
306 }
307 // fake_cli leaves the production pins in the provider packages: they
308 // must refuse the same fake programs the manifest now names.
309 if scenario != "fake_cli" {
310 for _, name := range []string{"claude", "codex"} {
311 path := filepath.Join("internal/runner/provider", name, "launcher.go")
312 data, err := os.ReadFile(filepath.Join(root, path))
313 executionMust(t, err)
314 lines := strings.Split(string(data), "\n")
315 for i, line := range lines {
316 if strings.HasPrefix(line, "const ExecutableSHA256 =") {
317 lines[i] = fmt.Sprintf("const ExecutableSHA256 = %q", hashes[name])
318 }
319 if strings.HasPrefix(line, "const CodeModeHostSHA256 =") {
320 lines[i] = fmt.Sprintf("const CodeModeHostSHA256 = %q", hashes["codex-code-mode-host"])
321 }
322 }
323 write(path, []byte(strings.Join(lines, "\n")), 0600)
324 }
325 // On an arm64 machine the prerequisites check reads the arm64 pin.
326 path := "internal/runner/provider/codex/pins.go"
327 data, err := os.ReadFile(filepath.Join(root, path))
328 executionMust(t, err)
329 arm := regexp.MustCompile(`(ExecutableSHA256Arm64\s+= )"[a-f0-9]{64}"`)
330 write(path, arm.ReplaceAll(data, []byte(`${1}"`+hashes["codex"]+`"`)), 0600)
331 }
332 switch scenario {
333 case "manifest_pin":
334 // The manifest names other bytes than the provider package pins.
335 fixture.Binaries[0].SHA256 = strings.Repeat("c", 64)
336 case "tool_proxy_pinned":
337 // A tool proxy digest typed into the source is never accepted.
338 fixture.Binaries = append(fixture.Binaries, release.BinaryDigest{Name: "equipo-tool-proxy", Version: fixture.LauncherVersion, SHA256: strings.Repeat("d", 64)})
339 case "old_schema":
340 fixture.Schema = 2
341 }
342 data, err := json.Marshal(fixture)
343 executionMust(t, err)
344 write("internal/release/manifest.json", data, 0600)
345 return installed
346}
347