package mac import ( "bytes" "context" "crypto/sha256" "encoding/hex" "errors" "io" "io/fs" "net/http" "os" "path/filepath" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/wire" ) // fakeClaude stands in for the 276 MB darwin binary: the tests check the // pin's handling, so a test CLI carries its own digest (claudeFor). func fakeClaude() []byte { return bytes.Repeat([]byte("#!/bin/sh\necho fake claude 2.1.312\n"), 1024) } func digest(b []byte) string { s := sha256.Sum256(b) return hex.EncodeToString(s[:]) } // claudeFor is the pinned CLI under installDir, pinned to body's digest. // Its home is installDir's parent (a test's own temporary directory); // both are made 0700, as a umask of 002 leaves t.TempDir's group-writable. func claudeFor(installDir string, body []byte) ClaudeCLI { for _, d := range []string{filepath.Dir(installDir), installDir} { if err := os.Chmod(d, 0700); err != nil { panic(err) } } c := NewClaudeCLI(filepath.Dir(installDir), installDir) c.pin = digest(body) return c } // serve answers every fetch with body and records the URLs asked. func serve(body []byte, urls *[]string) ClaudeFetch { return func(_ context.Context, url string) (io.ReadCloser, error) { if urls != nil { *urls = append(*urls, url) } return io.NopCloser(bytes.NewReader(body)), nil } } func noFetch(t *testing.T) ClaudeFetch { return func(context.Context, string) (io.ReadCloser, error) { t.Fatal("fetched although the pinned CLI is in place") return nil, errors.New("no") } } // watched calls atEOF once, when the download has been read to its end: // what is on disk then is what the provisioner wrote before it decided. type watched struct { r io.Reader atEOF func() n int64 } func (w *watched) Read(p []byte) (int, error) { n, err := w.r.Read(p) w.n += int64(n) if err == io.EOF && w.atEOF != nil { w.atEOF() w.atEOF = nil } return n, err } func (w *watched) Close() error { return nil } // entries are the names under dir and their modes ("" for dir itself); a // missing dir has none. func entries(t *testing.T, dir string) map[string]fs.FileMode { t.Helper() out := map[string]fs.FileMode{} err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { if errors.Is(err, fs.ErrNotExist) && path == dir { return fs.SkipDir } if err != nil { return err } if path == dir { return nil } info, err := os.Lstat(path) if err != nil { return err } rel, _ := filepath.Rel(dir, path) out[filepath.ToSlash(rel)] = info.Mode() return nil }) if err != nil { t.Fatal(err) } return out } // The Mac's pin is the official 2.1.312 darwin-arm64 binary (task 1, S1): // nothing else on darwin has one, and the Linux pins did not move. func TestClaudePinDarwin(t *testing.T) { const want = "6b5ec691195e551b02c41df9f7d723f4ea61eaa03c2df90acefe3736f1aeb620" if claude.ExecutableSHA256DarwinArm64 != want { t.Fatalf("darwin pin %q", claude.ExecutableSHA256DarwinArm64) } if pin, ok := claude.ReleasePinFor("darwin", "arm64"); !ok || pin != want { t.Fatalf("darwin/arm64: %q %v", pin, ok) } for _, arch := range []string{"amd64", "386", "riscv64", ""} { if pin, ok := claude.ReleasePinFor("darwin", arch); ok || pin != "" { t.Fatalf("darwin/%s has a pin %q", arch, pin) } } for _, p := range []struct{ goos, goarch, pin string }{{"linux", "amd64", claude.ExecutableSHA256}, {"linux", "arm64", claude.ExecutableSHA256Arm64}} { if pin, ok := claude.ReleasePinFor(p.goos, p.goarch); !ok || pin != p.pin { t.Fatalf("%s/%s: %q %v", p.goos, p.goarch, pin, ok) } } if _, ok := claude.ReleasePinFor("windows", "amd64"); ok { t.Fatal("windows has a pin") } // The Mac worker's CLI checks against exactly that pin. if got := NewClaudeCLI("/Users/u", "/Users/u/.local/lib/equipo-runner"); got.pin != want || got.home != "/Users/u" || got.installDir != "/Users/u/.local/lib/equipo-runner" { t.Fatalf("NewClaudeCLI %+v", got) } } // One changed byte is refused before the file is ever executable, and the // refused download leaves nothing behind. func TestProvisionChecksDigestBeforeExec(t *testing.T) { dir := t.TempDir() body := fakeClaude() bad := slices.Clone(body) bad[len(bad)/2] ^= 1 cli := claudeFor(dir, body) for _, try := range [][]byte{bad, body} { var during map[string]fs.FileMode fetch := func(context.Context, string) (io.ReadCloser, error) { return &watched{r: bytes.NewReader(try), atEOF: func() { during = entries(t, ClaudeDir(dir)) }}, nil } err := cli.Provision(context.Background(), fetch) if len(during) != 1 { t.Fatalf("the download was not staged as one file: %v", during) } for name, mode := range during { if mode.Perm()&0111 != 0 || !mode.IsRegular() { t.Fatalf("%s is %v while it downloads, before its digest is known", name, mode) } } if bytes.Equal(try, bad) { if !errors.Is(err, ErrClaudeRefused) { t.Fatalf("one changed byte: %v", err) } if left := entries(t, ClaudeDir(dir)); len(left) != 0 { t.Fatalf("a refused download left %v", left) } if _, err := cli.Verify(); err == nil { t.Fatal("verified after a refused download") } continue } if err != nil { t.Fatalf("the pinned bytes: %v", err) } path, err := cli.Verify() if err != nil { t.Fatal(err) } info, err := os.Lstat(path) if err != nil || info.Mode().Perm() != 0700 { t.Fatalf("placed %v %v", info.Mode(), err) } } } // A 512 MB bound; written only at tools/claude-2.1.312/claude under the // install dir, mode 0700, through no symlink; a wrong file in place is // replaced, a right one is kept. func TestProvisionBoundsAndPlace(t *testing.T) { if MaxClaudeBinary != 512<<20 { t.Fatalf("bound %d", MaxClaudeBinary) } if got := NewClaudeCLI("/", "/i").bound(); got != MaxClaudeBinary { t.Fatalf("the worker's bound is %d", got) } ctx := context.Background() body := fakeClaude() t.Run("bound", func(t *testing.T) { dir := t.TempDir() cli := claudeFor(dir, body) cli.limit = int64(len(body)) - 1 w := &watched{r: io.MultiReader(bytes.NewReader(body), bytes.NewReader(make([]byte, 1<<20)))} if err := cli.Provision(ctx, func(context.Context, string) (io.ReadCloser, error) { return w, nil }); !errors.Is(err, ErrClaudeRefused) { t.Fatalf("over the bound: %v", err) } if w.n > cli.limit+1 { t.Fatalf("read %d bytes past a %d bound", w.n, cli.limit) } if left := entries(t, ClaudeDir(dir)); len(left) != 0 { t.Fatalf("left %v", left) } cli.limit = int64(len(body)) if err := cli.Provision(ctx, serve(body, nil)); err != nil { t.Fatalf("at the bound: %v", err) } }) t.Run("place", func(t *testing.T) { dir := t.TempDir() cli := claudeFor(dir, body) if err := cli.Provision(ctx, serve(body, nil)); err != nil { t.Fatal(err) } want := filepath.Join(dir, "tools", "claude-2.1.312", "claude") if ClaudeDir(dir) != filepath.Dir(want) { t.Fatalf("ClaudeDir %q", ClaudeDir(dir)) } if path, err := cli.Verify(); err != nil || path != want { t.Fatalf("Verify %q %v", path, err) } got := entries(t, dir) wantModes := map[string]fs.FileMode{"tools": fs.ModeDir | 0700, "tools/claude-2.1.312": fs.ModeDir | 0700, "tools/claude-2.1.312/claude": 0700} if len(got) != len(wantModes) { t.Fatalf("wrote %v", got) } for name, mode := range wantModes { if got[name] != mode { t.Fatalf("%s is %v, want %v (all: %v)", name, got[name], mode, got) } } // In place and right: kept, nothing fetched. if err := cli.Provision(ctx, noFetch(t)); err != nil { t.Fatal(err) } // In place and wrong: replaced. if err := os.WriteFile(want, append(slices.Clone(body), '\n'), 0700); err != nil { t.Fatal(err) } var urls []string if err := cli.Provision(ctx, serve(body, &urls)); err != nil || len(urls) != 1 { t.Fatalf("a wrong file: %v %v", err, urls) } if raw, _ := os.ReadFile(want); !bytes.Equal(raw, body) { t.Fatal("the wrong file was not replaced") } // A download a crash left behind goes. stale := filepath.Join(ClaudeDir(dir), ".claude-download-stale") if err := os.WriteFile(stale, []byte("half"), 0600); err != nil { t.Fatal(err) } if err := cli.Provision(ctx, noFetch(t)); err != nil { t.Fatal(err) } if _, err := os.Lstat(stale); !errors.Is(err, fs.ErrNotExist) { t.Fatalf("a stale download is still there: %v", err) } }) t.Run("tools is a symlink", func(t *testing.T) { dir, outside := t.TempDir(), t.TempDir() if err := os.Symlink(outside, filepath.Join(dir, "tools")); err != nil { t.Fatal(err) } cli := claudeFor(dir, body) if err := cli.Provision(ctx, serve(body, nil)); err == nil { t.Fatal("provisioned through a symlinked tools directory") } if left := entries(t, outside); len(left) != 0 { t.Fatalf("wrote through the link: %v", left) } }) // os.Root alone refuses a link that leaves it; these stay inside, so // only the provisioner's own refusal stops them. t.Run("tools is a symlink inside the install dir", func(t *testing.T) { dir := t.TempDir() elsewhere := filepath.Join(dir, "elsewhere") if err := os.Mkdir(elsewhere, 0700); err != nil { t.Fatal(err) } if err := os.Symlink("elsewhere", filepath.Join(dir, "tools")); err != nil { t.Fatal(err) } cli := claudeFor(dir, body) if err := cli.Provision(ctx, serve(body, nil)); err == nil { t.Fatal("provisioned through a symlinked tools directory") } if left := entries(t, elsewhere); len(left) != 0 { t.Fatalf("wrote through the link: %v", left) } }) t.Run("the version directory is a symlink", func(t *testing.T) { dir := t.TempDir() elsewhere := filepath.Join(dir, "tools", "elsewhere") if err := os.MkdirAll(elsewhere, 0700); err != nil { t.Fatal(err) } if err := os.Symlink("elsewhere", ClaudeDir(dir)); err != nil { t.Fatal(err) } cli := claudeFor(dir, body) if err := cli.Provision(ctx, serve(body, nil)); err == nil { t.Fatal("provisioned through a symlinked version directory") } if left := entries(t, elsewhere); len(left) != 0 { t.Fatalf("wrote through the link: %v", left) } if _, err := cli.Verify(); err == nil { t.Fatal("verified through a symlinked version directory") } }) t.Run("the binary is a symlink", func(t *testing.T) { dir := t.TempDir() cli := claudeFor(dir, body) if err := cli.Provision(ctx, serve(body, nil)); err != nil { t.Fatal(err) } // A link to a right copy beside it: never verified, replaced by a // real file, the copy untouched. path := ClaudePath(dir) real := filepath.Join(ClaudeDir(dir), "claude.real") if err := os.Rename(path, real); err != nil { t.Fatal(err) } if err := os.Symlink("claude.real", path); err != nil { t.Fatal(err) } if _, err := cli.Verify(); !errors.Is(err, ErrClaudeUnpinned) { t.Fatalf("a symlink verified: %v", err) } var urls []string if err := cli.Provision(ctx, serve(body, &urls)); err != nil || len(urls) != 1 { t.Fatalf("a symlink in place: %v %v", err, urls) } if info, err := os.Lstat(path); err != nil || !info.Mode().IsRegular() { t.Fatalf("still a link: %v %v", info, err) } if raw, err := os.ReadFile(real); err != nil || !bytes.Equal(raw, body) { t.Fatalf("the link's target changed: %v", err) } }) } // roundTrip stands in for the network: nothing in a test leaves the // machine. type roundTrip func(*http.Request) (*http.Response, error) func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } // The URL comes from the version and platform constants; the official // source is an HTTPS GET of it that follows no redirect; a local file // stands in only in a test build. func TestProvisionOnlyFromTheOfficialURL(t *testing.T) { const official = "https://downloads.claude.ai/claude-code-releases/2.1.312/darwin-arm64/claude" if ClaudeURL() != official || ClaudeURL() != ClaudeReleaseBase+"/"+provider.ClaudeVersion+"/"+ClaudePlatform+"/claude" { t.Fatalf("ClaudeURL %q", ClaudeURL()) } ctx := context.Background() body := fakeClaude() var urls []string if err := claudeFor(t.TempDir(), body).Provision(ctx, serve(body, &urls)); err != nil || !slices.Equal(urls, []string{official}) { t.Fatalf("asked %v: %v", urls, err) } defer func(was http.RoundTripper) { claudeTransport = was }(claudeTransport) var asked []string status, location := http.StatusOK, "" claudeTransport = roundTrip(func(r *http.Request) (*http.Response, error) { asked = append(asked, r.Method+" "+r.URL.String()) h, code := http.Header{}, status if r.URL.String() != official { // A redirect's target answers, so a client that follows one // shows here as a second request rather than looping. code = http.StatusOK } else if location != "" { h.Set("Location", location) } return &http.Response{StatusCode: code, Header: h, Body: io.NopCloser(bytes.NewReader(body)), Request: r}, nil }) local := filepath.Join(t.TempDir(), "claude") if err := os.WriteFile(local, body, 0600); err != nil { t.Fatal(err) } getenv := func(k string) string { if k == ClaudeStandInEnv { return local } return "" } if err := claudeFor(t.TempDir(), body).Provision(ctx, OfficialClaude(getenv)); err != nil { t.Fatal(err) } if claudeStandInBuild { if len(asked) != 0 { t.Fatalf("a test build with a stand-in fetched %v", asked) } } else if !slices.Equal(asked, []string{"GET " + official}) { t.Fatalf("a release build asked %v, the stand-in must be ignored", asked) } // The official source itself: no redirect followed, 200 only. none := func(string) string { return "" } asked, status, location = nil, http.StatusFound, "https://elsewhere.example/claude" if err := claudeFor(t.TempDir(), body).Provision(ctx, OfficialClaude(none)); err == nil || !slices.Equal(asked, []string{"GET " + official}) { t.Fatalf("a redirect: %v %v", err, asked) } asked, status, location = nil, http.StatusNotFound, "" if err := claudeFor(t.TempDir(), body).Provision(ctx, OfficialClaude(none)); err == nil || len(asked) != 1 { t.Fatalf("a 404: %v %v", err, asked) } } // The launcher hashes the CLI again before each launch: a file swapped // after a launch stops the next one with engineering_unavailable, and // nothing starts. func TestVerifyBeforeEveryLaunch(t *testing.T) { dir := t.TempDir() body := fakeClaude() cli := claudeFor(dir, body) if err := cli.Provision(context.Background(), serve(body, nil)); err != nil { t.Fatal(err) } var started [][]string start := func(_ context.Context, argv []string) error { started = append(started, argv) return nil } for range 2 { if err := cli.Launch(context.Background(), start, "-p", "--output-format", "stream-json"); err != nil { t.Fatal(err) } } want := []string{ClaudePath(dir), "-p", "--output-format", "stream-json"} if len(started) != 2 || !slices.Equal(started[0], want) || !slices.Equal(started[1], want) { t.Fatalf("started %v", started) } unavailable := func(err error) bool { var u *ClaudeUnavailable return errors.As(err, &u) && u.Reason() == wire.ReasonEngineeringUnavailable } // Swapped in place, same size and mode, one byte changed. swapped := slices.Clone(body) swapped[0] ^= 1 next := ClaudePath(dir) + ".next" if err := os.WriteFile(next, swapped, 0700); err != nil { t.Fatal(err) } if err := os.Rename(next, ClaudePath(dir)); err != nil { t.Fatal(err) } if err := cli.Launch(context.Background(), start); !unavailable(err) { t.Fatalf("a swapped CLI: %v", err) } // None in place at all, or no CLI configured: the same stop. if err := os.Remove(ClaudePath(dir)); err != nil { t.Fatal(err) } if err := cli.Launch(context.Background(), start); !unavailable(err) { t.Fatalf("a missing CLI: %v", err) } if err := (ClaudeCLI{}).Launch(context.Background(), start); !unavailable(err) { t.Fatalf("no CLI: %v", err) } if len(started) != 2 { t.Fatalf("started an unverified CLI: %v", started) } } // The capability report runs no claude at all: it states the pinned // version only while the pinned file verifies. func TestDiscoveryNeverRunsUnpinnedClaude(t *testing.T) { dir := t.TempDir() body := fakeClaude() cli := claudeFor(dir, body) var ran []string x := func(ctx context.Context, name string, args ...string) (string, error) { ran = append(ran, strings.Join(append([]string{name}, args...), " ")) return recordedExec(t)(ctx, name, args...) } tools := Tools{Xcodebuild: "xcodebuild", Xcrun: "xcrun", Swift: "swift", Node: "node", SRT: "srt", Claude: cli} if c := Capabilities(context.Background(), x, tools); c.Harness.Claude != "" { t.Fatalf("claimed %q with nothing provisioned", c.Harness.Claude) } if err := cli.Provision(context.Background(), serve(body, nil)); err != nil { t.Fatal(err) } c := Capabilities(context.Background(), x, tools) if c.Harness.Claude != provider.ClaudeVersion || slices.Contains(c.Tags, wire.TagClaude) { t.Fatalf("verified: harness %q tags %v", c.Harness.Claude, c.Tags) } if err := os.WriteFile(ClaudePath(dir), append(slices.Clone(body), 0), 0700); err != nil { t.Fatal(err) } if c := Capabilities(context.Background(), x, tools); c.Harness.Claude != "" { t.Fatalf("claimed %q for a changed file", c.Harness.Claude) } if len(ran) == 0 { t.Fatal("the recorder saw nothing") } for _, cmd := range ran { if strings.Contains(cmd, "claude") { t.Fatalf("discovery ran %q", cmd) } } } // The worker keeps the pinned CLI itself: fetched from the official URL // only, again after a failure (warned, nothing claimed), refreshed when // it starts verifying, fetched anew when it is swapped, never run. func TestKeepClaude(t *testing.T) { defer func(r, c time.Duration) { ClaudeRetry, ClaudeRecheck = r, c }(ClaudeRetry, ClaudeRecheck) ClaudeRetry, ClaudeRecheck = time.Millisecond, time.Millisecond dir := t.TempDir() body := fakeClaude() cli := claudeFor(dir, body) ctx, cancel := context.WithCancel(context.Background()) defer cancel() var urls, warned, versions []string fetch := func(_ context.Context, url string) (io.ReadCloser, error) { urls = append(urls, url) switch len(urls) { case 1, 2: if v := cli.Version(); v != "" { t.Errorf("claimed %q before any fetch succeeded", v) } return nil, errors.New("offline") case 4: cancel() } return io.NopCloser(bytes.NewReader(body)), nil } refresh := func() { versions = append(versions, cli.Version()) // Swapped once it verified: found at the next check. if err := os.WriteFile(ClaudePath(dir), append(slices.Clone(body), 1), 0700); err != nil { t.Error(err) } } done := make(chan struct{}) go func() { KeepClaude(ctx, cli, fetch, refresh, func(msg string, _ ...any) { warned = append(warned, msg) }) close(done) }() select { case <-done: case <-time.After(10 * time.Second): t.Fatal("KeepClaude did not stop with its context") } if len(urls) != 4 || slices.ContainsFunc(urls, func(u string) bool { return u != ClaudeURL() }) { t.Fatalf("asked %v", urls) } if len(warned) != 2 || !slices.Equal(versions, []string{provider.ClaudeVersion}) { t.Fatalf("warned %v versions %v", warned, versions) } if cli.Version() != provider.ClaudeVersion { t.Fatal("the swapped CLI was not fetched again") } } // Env-gated, run on docs-t1 with task 1's download (never executed: it // is a darwin binary): the official 2.1.312 darwin-arm64 build matches // the compiled pin and provisions as the Mac would. func TestClaudeDarwinBinaryMatchesPin(t *testing.T) { path := os.Getenv("EQUIPO_CLAUDE_DARWIN_BINARY") if path == "" { t.Skip("EQUIPO_CLAUDE_DARWIN_BINARY not set") } f, err := os.Open(path) if err != nil { t.Fatal(err) } defer f.Close() h := sha256.New() if _, err := io.Copy(h, f); err != nil { t.Fatal(err) } if got := hex.EncodeToString(h.Sum(nil)); got != claude.ExecutableSHA256DarwinArm64 { t.Fatalf("%s is %s, the pin is %s", path, got, claude.ExecutableSHA256DarwinArm64) } home, dir := install(t) cli := NewClaudeCLI(home, dir) var urls []string fetch := func(_ context.Context, url string) (io.ReadCloser, error) { urls = append(urls, url) return os.Open(path) } if err := cli.Provision(context.Background(), fetch); err != nil || !slices.Equal(urls, []string{ClaudeURL()}) { t.Fatalf("provision: %v %v", err, urls) } if cli.Version() != "2.1.312" { t.Fatal("the provisioned binary does not verify") } }