package checks import ( "os" "os/exec" "path/filepath" "slices" "strings" "testing" "golang.org/x/mod/module" modzip "golang.org/x/mod/zip" ) const ( toolchainRefused = "go: golang.org/toolchain@v0.0.1-go1.26.5.linux-amd64: verifying module: checksum database disabled by GOSUMDB=off" moduleRefused = "go: amadan.net/oficina/home/handoff@v0.0.0-20261120140933-17cdcaff3345: module lookup disabled by GOPROXY=off" ) // TestNeedsNetworkNeedsTheDependencyStage: only Equipo's own dependency // stage can say a gate needed the network: it failed, and everything Go // printed there is its refusal to download a module or a Go release // offline. The gate's output is the candidate's: read whole, as it is // produced, it can only keep a failure a failure, and evidence that is // not complete keeps it a failure too (Astra, reviews of f03d79bb and // 4e0d2497). func TestNeedsNetworkNeedsTheDependencyStage(t *testing.T) { run := func(code int, out string) Run { return Run{Code: code, Output: out, Evidence: Scan(out)} } offline := run(1, moduleRefused+"\n"+toolchainRefused+"\n") deps := "go mod download in . failed (the hub's git rate limit?); retrying in 5s\napp.go:32:2: module lookup disabled by GOPROXY=off\nx.go:3:8: mkdir /opt/go-mod/cache/download/example.invalid: read-only file system\nFAIL\tamadan.net/oficina/home [setup failed]\nFAIL\nmake: *** [Makefile:82: deps] Error 1\n" gateDeps := run(2, deps) if !NeedsNetwork(offline, gateDeps) { t.Fatal("an offline dependency stage and a gate failing on dependencies is not needs-network") } noise := strings.Repeat("noise\n", 5000) for name, tc := range map[string]struct{ stage, gate Run }{ "checksum mismatch": {run(1, "verifying example.com/m@v1.0.0: checksum mismatch\n\tdownloaded: h1:aaa=\n\tgo.sum: h1:bbb=\n\nSECURITY ERROR\nThis download does NOT match an earlier download recorded in go.sum.\n"), gateDeps}, "corrupt archive": {run(1, "go: golang.org/toolchain@v0.0.1-go1.26.5.linux-amd64: zip: not a valid zip file\n"), gateDeps}, "quoted diagnostic": {run(0, ""), run(1, " door_test.go:12: got \""+toolchainRefused+"\"\n"+toolchainRefused+"\n"+moduleRefused+"\nFAIL\n")}, "stage passed": {run(0, toolchainRefused), gateDeps}, "mixed test": {offline, run(1, deps+"--- FAIL: TestDoorPages (0.01s)\n")}, "mixed compile": {offline, run(1, deps+"./calma.go:12:2: undefined: doorView\n")}, "mixed panic": {offline, run(1, deps+"panic: runtime error: index out of range\n")}, "mixed other write": {offline, run(1, deps+"x.go:3:8: open /workspace/gen.go: read-only file system\n")}, "json test failure": {offline, run(1, deps+`{"Time":"2026-11-23T10:00:00Z","Action":"fail","Package":"example.com/x","Test":"TestDoor","Elapsed":0}`+"\n")}, "json build failure": {offline, run(1, deps+`{"ImportPath":"example.com/x","Action":"build-fail"}`+"\n")}, "failure beyond tail": {offline, run(1, "--- FAIL: TestDoor (0.00s)\n"+noise+deps)}, "stage other line": {run(1, moduleRefused+"\nbash: cd: handoff: No such file or directory\n"), gateDeps}, "stage refusal beyond tail": {run(1, "bash: cd: handoff: No such file or directory\n"+strings.Repeat(moduleRefused+"\n", 500)), gateDeps}, "stage empty": {run(1, ""), gateDeps}, "stage only progress": {run(1, "go: no module dependencies to download\n"), gateDeps}, "gate passed": {offline, run(0, "")}, "newer go.mod": {run(1, "go: go.mod requires go >= 1.27.0 (running go 1.26.10; GOTOOLCHAIN=local)\n"), gateDeps}, "no gate evidence": {offline, Run{Code: 2, Output: deps}}, "no stage evidence": {Run{Code: 1, Output: moduleRefused}, gateDeps}, } { if NeedsNetwork(tc.stage, tc.gate) { t.Errorf("%s: counted as needs-network", name) } } // Incomplete evidence is a failure: a stream never finished, one cut // short, or a line too long to read whole. incomplete := map[string]func() *Evidence{ "stream never closed": func() *Evidence { e, w := NewEvidence(2) w[0].Write([]byte(deps)) w[0].Close() return e }, "stream cut short": func() *Evidence { e, w := NewEvidence(1) w[0].Write([]byte(deps)) w[0].Abort() return e }, "line too long": func() *Evidence { e, w := NewEvidence(1) w[0].Write([]byte(deps + strings.Repeat("x", 1<<20) + "\n")) w[0].Close() return e }, } for name, ev := range incomplete { if NeedsNetwork(offline, Run{Code: 2, Output: deps, Evidence: ev()}) { t.Errorf("%s: counted as needs-network", name) } } stageEv, stageW := NewEvidence(2) stageW[0].Write([]byte(moduleRefused + "\n")) stageW[0].Close() if NeedsNetwork(Run{Code: 1, Evidence: stageEv}, gateDeps) { t.Error("an unfinished dependency stage counted as needs-network") } // Written in pieces, from two streams at once, the same lines read the same. e, w := NewEvidence(2) for _, piece := range strings.SplitAfter(deps, "o") { w[0].Write([]byte(piece)) w[1].Write([]byte(piece)) } w[0].Close() w[1].Close() if !NeedsNetwork(offline, Run{Code: 2, Evidence: e}) { t.Fatal("streamed evidence read differently") } } // TestGoRequirement: the runner's Go must meet what the base's own // go.mod files and gate files ask. go and toolchain directives are // minimums; a release a Makefile pins is honoured by the same minor // release at that patch or newer (make runs with GOTOOLCHAIN=local); a // release any other gate file pins is honoured only exactly. func TestGoRequirement(t *testing.T) { home := map[string]string{"go.mod": "module amadan.net/oficina/home\n\ngo 1.26.0\n\ntoolchain go1.26.5\n", "handoff/go.mod": "module x\n\ngo 1.25.0\n", "Makefile": "export GOTOOLCHAIN := go1.26.5\nbuild:\n\tgo build ./...\n"} for _, tc := range []struct { name string files map[string]string met bool }{ {"home", home, true}, {"newer go directive", map[string]string{"go.mod": "module x\n\ngo 1.27.0\n"}, false}, {"newer toolchain directive", map[string]string{"go.mod": "module x\n\ngo 1.26.0\ntoolchain go1.27.1\n"}, false}, {"newer submodule", map[string]string{"go.mod": "module x\n\ngo 1.26.0\n", "tools/go.mod": "module y\n\ngo 1.26.11\n"}, false}, {"vendored go.mod ignored", map[string]string{"go.mod": "module x\n\ngo 1.26.0\n", "vendor/example.com/y/go.mod": "module y\n\ngo 1.30\n", "internal/testdata/go.mod": "module z\n\ngo 1.30\n"}, true}, {"make pins an older minor", map[string]string{"Makefile": "export GOTOOLCHAIN := go1.25.4\n"}, false}, {"make pins a newer patch", map[string]string{"build/go.mk": "GOTOOLCHAIN ?= go1.26.11\n"}, false}, {"make pins a minimum", map[string]string{"GNUmakefile": "export GOTOOLCHAIN=go1.26.3+auto\n"}, true}, {"make pins a newer minimum", map[string]string{"Makefile": "export GOTOOLCHAIN = go1.27.0+auto\n"}, false}, {"make asks for local", map[string]string{"Makefile": "export GOTOOLCHAIN := local\n"}, true}, {"script pins another patch", map[string]string{".amadan/ci.d/10-vet": "#!/bin/sh\nexport GOTOOLCHAIN=go1.26.5\nexec go vet ./...\n"}, false}, {"script pins this release", map[string]string{".amadan/ci": "GOTOOLCHAIN='go1.26.10' go test ./...\n"}, true}, {"no Go", map[string]string{"package.json": "{}"}, true}, } { files := map[string][]byte{} for name, body := range tc.files { if !GoRequirementFile(name) && name != "package.json" && name != "vendor/example.com/y/go.mod" && name != "internal/testdata/go.mod" { t.Fatalf("%s: %s not read", tc.name, name) } if GoRequirementFile(name) { files[name] = []byte(body) } } if got := ReadGoRequirement(files).Unmet("go1.26.10"); got == tc.met { t.Errorf("%s: unmet=%v", tc.name, got) } } } func TestRunnerGoVersion(t *testing.T) { root := t.TempDir() if _, err := RunnerGoVersion(root); err == nil { t.Fatal("missing VERSION accepted") } os.WriteFile(filepath.Join(root, "VERSION"), []byte("go1.26.10\ntime 2026-11-05T00:00:00Z\n"), 0o600) if v, err := RunnerGoVersion(root); err != nil || v != "go1.26.10" { t.Fatalf("%q %v", v, err) } os.WriteFile(filepath.Join(root, "VERSION"), []byte("devel +abc\n"), 0o600) if _, err := RunnerGoVersion(root); err == nil { t.Fatal("unversioned toolchain accepted") } } // TestDependencyStage: the stage downloads each module's dependencies // from the read-only cache, in Go's own words, and leaves the tree's // go.mod and go.sum exactly as the candidate wrote them. func TestDependencyStage(t *testing.T) { goBin, err := exec.LookPath("go") if err != nil { t.Skip("go is not installed") } // Create child state first so cleanup removes it after the source tree. state := t.TempDir() for _, dir := range []string{"home", "tmp", "mod", "cache"} { if err := os.MkdirAll(filepath.Join(state, dir), 0o700); err != nil { t.Fatal(err) } } // Go ignores GOTELEMETRY as a setting: its mode file controls the // detached sidecar. Reuse the sandbox's off configuration and Go's // test-directory override so this is also hermetic on macOS. xdg, err := telemetryOffConfig(state) if err != nil { t.Fatal(err) } tree := t.TempDir() write := func(name, body string) { p := filepath.Join(tree, name) os.MkdirAll(filepath.Dir(p), 0o700) if err := os.WriteFile(p, []byte(body), 0o600); err != nil { t.Fatal(err) } } write("go.mod", "module example.com/app\n\ngo 1.21\n") write("app.go", "package app\n") write("dep/go.mod", "module example.com/dep\n\ngo 1.21\n\nrequire example.invalid/missing v1.0.0\n") write("dep/go.sum", "") write("vendored/go.mod", "module example.com/vendored\n\ngo 1.21\n\nrequire example.invalid/v v1.0.0\n") write("vendored/vendor/modules.txt", "# example.invalid/v v1.0.0\n") for _, skipped := range []string{"vendor/x/go.mod", "testdata/go.mod", ".hidden/go.mod", "_old/go.mod"} { write(skipped, "module skipped\n") } dirs := GoModuleDirs(tree) if !slices.Equal(dirs, []string{".", "dep"}) { t.Fatalf("module dirs %q", dirs) } proxy := "off" run := func(dirs []string) Run { argv := DependencyStage(dirs) cmd := exec.Command(argv[0], argv[1:]...) cmd.Dir = tree cmd.Env = []string{"PATH=" + filepath.Dir(goBin) + ":/usr/bin:/bin", "HOME=" + filepath.Join(state, "home"), "TMPDIR=" + filepath.Join(state, "tmp"), "GOMODCACHE=" + filepath.Join(state, "mod"), "GOCACHE=" + filepath.Join(state, "cache"), "GOPROXY=" + proxy, "GOSUMDB=off", "GOTOOLCHAIN=local", "GOFLAGS=-modcacherw", "GOWORK=off", "GOENV=off", "GOTELEMETRY=off", "TEST_TELEMETRY_DIR=" + filepath.Join(xdg, "go", "telemetry")} // An environment variable alone does not set Go's telemetry mode. // Check the actual child configuration before it can spawn a sidecar. mode := exec.Command(goBin, "env", "GOTELEMETRY") mode.Env = cmd.Env if out, err := mode.CombinedOutput(); err != nil || strings.TrimSpace(string(out)) != "off" { t.Fatalf("dependency child telemetry: %q, %v", out, err) } out, err := cmd.CombinedOutput() if err != nil { t.Logf("dependency stage: %v", err) } return Run{Code: cmd.ProcessState.ExitCode(), Output: string(out), Evidence: Scan(string(out))} } if res := run([]string{"."}); res.Code != 0 { t.Fatalf("a module with nothing to download failed: %+v", res) } res := run(dirs) if res.Code == 0 || !NeedsNetwork(res, Run{Code: 1, Evidence: Scan("make: *** [ci] Error 1\n")}) { t.Fatalf("missing module not refused offline in Go's words: %+v", res) } // A download that succeeds (from a local proxy here) records its sums // in the stage's copy, never in the candidate's go.sum. dir := t.TempDir() lib := filepath.Join(dir, "lib") os.MkdirAll(lib, 0o700) os.WriteFile(filepath.Join(lib, "go.mod"), []byte("module example.com/lib\n\ngo 1.21\n"), 0o600) os.WriteFile(filepath.Join(lib, "lib.go"), []byte("package lib\n"), 0o600) at := filepath.Join(dir, "proxy/example.com/lib/@v") os.MkdirAll(at, 0o700) os.WriteFile(filepath.Join(at, "list"), []byte("v1.0.0\n"), 0o600) os.WriteFile(filepath.Join(at, "v1.0.0.info"), []byte(`{"Version":"v1.0.0"}`), 0o600) os.WriteFile(filepath.Join(at, "v1.0.0.mod"), []byte("module example.com/lib\n\ngo 1.21\n"), 0o600) z, err := os.Create(filepath.Join(at, "v1.0.0.zip")) if err != nil { t.Fatal(err) } if err := modzip.CreateFromDir(z, module.Version{Path: "example.com/lib", Version: "v1.0.0"}, lib); err != nil { t.Fatal(err) } z.Close() write("uses/go.mod", "module example.com/uses\n\ngo 1.21\n\nrequire example.com/lib v1.0.0\n") write("uses/go.sum", "") write("uses/uses.go", "package uses\n\nimport _ \"example.com/lib\"\n") proxy = "file://" + filepath.Join(dir, "proxy") if res := run([]string{"uses"}); res.Code != 0 { t.Fatalf("download from the proxy failed: %+v", res) } for _, name := range []string{"dep/go.sum", "uses/go.sum"} { if raw, _ := os.ReadFile(filepath.Join(tree, name)); len(raw) != 0 { t.Fatalf("the stage wrote the candidate's %s: %q", name, raw) } } }