package thin import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "log/slog" "net/http" "net/http/httptest" "os" "path/filepath" "slices" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/wire" ) // A worker's report says how its checks were confined, and a tree whose // gate cannot be chosen (two schemes, no simulator) is checks that // cannot run, never a pass; the gate waits until the probes are done. func TestWorkerMacReports(t *testing.T) { x := newWorkerRig(t) x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") x.gate.sandbox = wire.SandboxNone if rep := x.run(); rep.Checks != wire.ChecksPassed || rep.ChecksSandbox != wire.SandboxNone { t.Fatalf("label %+v", rep) } x.r.Attempt = 2 h := x.header() h.ID = "tr_2" x.chunk(t, "c2", h, x.pack, 0, 1, "") x.w.Find = func(string) (gate, string, bool) { return gate{}, "checks_unavailable", true } if rep := x.run(); rep.State != wire.StepDone || rep.Checks != wire.ChecksCannotRun || rep.Reason != "checks_unavailable" || len(x.gate.ran) != 1 { t.Fatalf("unchosen gate %+v ran %v", rep, x.gate.ran) } x.w.Find = nil x.w.Ready = func(ctx context.Context) error { return context.Canceled } if rep := x.run(); rep.State != wire.StepCancelled || len(x.gate.ran) != 1 { t.Fatalf("ran before the probes were done: %+v", rep) } } // probeRig is a macProbes whose run, fingerprint and clock a test sets. type probeRig struct { p *macProbes runs atomic.Int32 verdict string pinned bool now time.Time } func newProbeRig(t *testing.T) *probeRig { x := &probeRig{verdict: wire.ProbeDenied, pinned: true, now: time.Now()} x.p = newMacProbes("v1", filepath.Join(t.TempDir(), "probe-request"), func(context.Context) mac.Report { x.runs.Add(1) return mac.Report{Version: "v1", Profile: mac.ProfileDigest(), At: x.now, Probes: probesAll(x.verdict), SRTRanXcode: true} }, func() bool { return x.pinned }) x.p.now = func() time.Time { return x.now } return x } func (x *probeRig) started(t *testing.T) { t.Helper() x.p.start(t.Context(), func() {}) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := x.p.wait(ctx); err != nil { t.Fatal(err) } } // Each attempt's gate follows the report this process made and still // trusts: srt and seatbelt only when P2 denied; srt labelled none when // the fixture built under srt; otherwise outside the sandbox, labelled // none. No srt, no sandbox, whatever the report says. func TestMacChecksPick(t *testing.T) { x := newProbeRig(t) m := &macChecks{probes: x.p, taint: loadTaint(filepath.Join(t.TempDir(), "tainted")), srt: "/x/srt", sandboxed: &mac.Gate{Sandbox: wire.SandboxSeatbelt}, unproven: &mac.Gate{SRT: "/x/srt", Sandbox: wire.SandboxNone}, bare: &mac.Gate{Sandbox: wire.SandboxNone}} if m.pick() != m.bare { t.Fatal("no report: not bare") } x.verdict = wire.ProbeFailed x.started(t) if m.pick() != m.unproven || m.Sandbox() != wire.SandboxNone { t.Fatal("srt ran xcodebuild, P2 failed: not srt labelled none") } y := newProbeRig(t) y.started(t) m.probes = y.p if m.pick() != m.sandboxed || m.Sandbox() != wire.SandboxSeatbelt { t.Fatal("P2 denied: not seatbelt") } m.srt = "" if m.pick() != m.bare { t.Fatal("no srt: not bare") } } // Repository code cannot forge the verdict: nothing on disk is read back // as one (a probes.json saying denied changes nothing), and a report is // trusted only for this version, with the srt, Node and ripgrep on disk // now, for a day. Otherwise checks run as not verified and the probes // run again; the request file only asks for that. func TestMacProbesTrust(t *testing.T) { x := newProbeRig(t) state := filepath.Dir(x.p.request) forged, _ := json.Marshal(mac.Report{Version: "v1", Profile: mac.ProfileDigest(), At: time.Now(), Probes: probesAll(wire.ProbeDenied), SRT: srtPinned}) for _, name := range []string{"probes.json", "probe-request"} { if err := os.WriteFile(filepath.Join(state, name), forged, 0600); err != nil { t.Fatal(err) } } if _, ok := x.p.trusted(); ok { t.Fatal("a report this process did not make is trusted") } x.started(t) if r, ok := x.p.trusted(); !ok || !r.Sandboxed() { t.Fatal("its own fresh report not trusted") } x.pinned = false if _, ok := x.p.trusted(); ok { t.Fatal("trusted after srt, Node or ripgrep stopped matching their pins") } x.pinned = true x.now = x.now.Add(probeTrust + time.Minute) if _, ok := x.p.trusted(); ok { t.Fatal("trusted a day later") } deadline := time.Now().Add(5 * time.Second) for x.runs.Load() < 2 && time.Now().Before(deadline) { time.Sleep(20 * time.Millisecond) } if x.runs.Load() < 2 { t.Fatal("an untrusted report did not probe again") } other := newProbeRig(t) other.p.version = "v2" other.started(t) if _, ok := other.p.trusted(); ok { t.Fatal("another version's report trusted") } } func probesAll(p2 string) []wire.Probe { var out []wire.Probe for _, id := range wire.ProbeIDs { v := wire.ProbePassed if id == "P2" { v = p2 } out = append(out, wire.Probe{ID: id, Verdict: v}) } return out } // A Mac finds the repository's own gate first (with macOS's bash), and // gives an Xcode project without one xcodebuild test. func TestMacFind(t *testing.T) { sims := []wire.Simulator{{Name: "iPhone 16 Pro", Runtime: "iOS 18.2", UDID: "5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3", State: "Shutdown"}} h := &macHost{caps: func(context.Context) wire.Capabilities { return wire.Capabilities{Simulators: sims} }} tree := t.TempDir() scheme := filepath.Join(tree, "Woodstar.xcodeproj/xcshareddata/xcschemes/Woodstar.xcscheme") if err := os.MkdirAll(filepath.Dir(scheme), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(scheme, []byte(""), 0600); err != nil { t.Fatal(err) } g, reason, ok := h.find(tree) if !ok || reason != "" || g.name != "xcodebuild test" || !strings.Contains(g.argv[2], "-scheme 'Woodstar' -destination 'platform=iOS Simulator,id=5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3'") { t.Fatalf("%+v %q", g, reason) } if err := os.MkdirAll(filepath.Join(tree, ".amadan/ci.d"), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(filepath.Join(tree, ".amadan/ci.d/10-test"), []byte("#!/bin/sh\nmake test\n"), 0700); err != nil { t.Fatal(err) } if g, _, ok := h.find(tree); !ok || g.name != ".amadan/ci.d" || g.argv[0] != "/bin/bash" { t.Fatalf("own gate %+v", g) } } // The worker updates itself to its instance's release: the darwin // runner of that release's manifest, verified, swapped while no step // runs, then it stops to be restarted. A digest mismatch replaces // nothing; its own release or no release asks for nothing. func TestMacUpdater(t *testing.T) { newBin := []byte("#!new runner\n") sum := sha256.Sum256(newBin) digest := hex.EncodeToString(sum[:]) var served atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { served.Add(1) switch r.URL.Path { case "/releases/bbb2222/install-manifest.json": _ = json.NewEncoder(w).Encode(release.InstallManifest{Version: "bbb2222", Targets: map[string]release.InstallTarget{release.TargetDarwin: {RunnerSHA256: digest}}}) case "/releases/ccc3333/install-manifest.json": _ = json.NewEncoder(w).Encode(release.InstallManifest{Version: "ccc3333", Targets: map[string]release.InstallTarget{release.TargetDarwin: {RunnerSHA256: strings.Repeat("0", 64)}}}) case "/releases/bbb2222/darwin-arm64/equipo-runner", "/releases/ccc3333/darwin-arm64/equipo-runner": _, _ = w.Write(newBin) default: http.NotFound(w, r) } })) defer srv.Close() binary := filepath.Join(t.TempDir(), "equipo-runner") if err := os.WriteFile(binary, []byte("#!old runner\n"), 0700); err != nil { t.Fatal(err) } try := func(rel string) (held, stopped bool, err error) { u := &macUpdater{origin: srv.URL, version: "aaa1111", binary: binary, fetch: fetchLimited} u.offer(wire.Welcome{Release: rel}, func() func() { held = true; return func() {} }, func() { stopped = true }, nil) if u.done == nil { return held, stopped, nil } err = <-u.done return held, stopped, err } for _, rel := range []string{"", "aaa1111", "dev", "../x"} { if _, stopped, _ := try(rel); stopped || served.Load() != 0 { t.Fatalf("release %q fetched or stopped", rel) } } if _, stopped, err := try("ccc3333"); err == nil || stopped { t.Fatal("a runner whose digest does not match was taken") } if raw, _ := os.ReadFile(binary); string(raw) != "#!old runner\n" { t.Fatal("binary replaced by an unverified download") } held, stopped, err := try("bbb2222") if err != nil || !held || !stopped { t.Fatalf("update: %v held=%v stopped=%v", err, held, stopped) } if raw, _ := os.ReadFile(binary); string(raw) != string(newBin) { t.Fatal("binary not replaced") } if info, _ := os.Stat(binary); info.Mode().Perm() != 0700 { t.Fatal("new binary not private and executable") } left, _ := filepath.Glob(filepath.Join(filepath.Dir(binary), ".equipo-runner-update-*")) if len(left) != 0 { t.Fatalf("left %v", left) } } // The Mac host keeps every tree the checks profile must let a gate // write (attempt trees, the probes' fixture copies) under the scratch // root, outside the state dir the profile denies. func TestMacHostPaths(t *testing.T) { root := t.TempDir() c := runner.Config{StateDir: filepath.Join(root, "share/state"), ScratchRoot: filepath.Join(root, "share/scratch"), WorkspaceRoot: filepath.Join(root, "share/work"), Executable: filepath.Join(root, "lib/equipo-runner")} tools := map[string]string{"EQUIPO_SRT_PATH": filepath.Join(root, "srt/node_modules/.bin/srt"), "EQUIPO_NODE_PATH": filepath.Join(root, "tools/node-v1/bin/node"), "EQUIPO_RG_PATH": filepath.Join(root, "tools/rg-1/rg")} for _, p := range tools { if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(p, []byte("#!/bin/sh\n"), 0700); err != nil { t.Fatal(err) } } users := filepath.Join(root, "Users") if err := os.MkdirAll(filepath.Join(users, "paul"), 0700); err != nil { t.Fatal(err) } was, wasTemp := macUsers, macUserTemp macUsers = users const temp = "/private/var/folders/4m/abc123_def/T" macUserTemp = func(context.Context, mac.Exec) (string, error) { return temp, nil } defer func() { macUsers, macUserTemp = was, wasTemp }() // The tools come from the runner's own environment (its env file), // not the process's. h, err := newMacHost(c, OptionsFromEnv(func(k string) string { return tools[k] })) if err != nil { t.Fatal(err) } // The user's T: written by sandboxed gates and cleaned after each; // every gate takes the one turn. k := h.checks if h.paths.UserTemp != temp || k.sandboxed.UserTemp != temp || k.unproven.UserTemp != temp || k.bare.UserTemp != "" || k.sandboxed.Turns == nil || k.sandboxed.Turns != k.bare.Turns || k.sandboxed.QuietSimulators == nil || k.bare.QuietSimulators != nil { t.Fatalf("user temp %+v", h.paths) } if p := h.probeHost("v1", nil); p.Scratch != filepath.Join(c.ScratchRoot, "probes") || p.Paths.StateDir != c.StateDir || p.Paths.InstallDir != filepath.Join(root, "lib") { t.Fatalf("%+v", p) } settings := h.checks.sandboxed.Settings if settings == nil || h.checks.bare.Settings != nil || h.checks.sandboxed.Sandbox != wire.SandboxSeatbelt || h.checks.unproven.Sandbox != wire.SandboxNone { t.Fatal("gates") } key := filepath.Join(c.ScratchRoot, "worker-steps", "k") if _, err := settings(filepath.Join(key, "tree"), filepath.Join(key, "attempt-1")); err != nil { t.Fatalf("a worker tree refused: %v", err) } if _, err := settings(filepath.Join(c.StateDir, "worker", "steps", "k", "tree"), filepath.Join(key, "attempt-1")); err == nil { t.Fatal("a tree in the state dir accepted") } // srt starts through `env node` and looks for rg on the PATH: the // runner's own Node and ripgrep come first, for the runner and its gates. t.Setenv("PATH", "/usr/bin:/bin") out, err := h.run(context.Background(), "/bin/sh", "-c", "echo $PATH") path := strings.Split(strings.TrimSpace(out), ":") if err != nil || !slices.Contains(path[:2], filepath.Dir(tools["EQUIPO_NODE_PATH"])) || !slices.Contains(path[:2], filepath.Dir(tools["EQUIPO_RG_PATH"])) { t.Fatalf("a tool's PATH %v %v", path, err) } if !strings.Contains(strings.Join(h.env, " "), "PATH="+filepath.Dir(tools["EQUIPO_RG_PATH"])+":"+filepath.Dir(tools["EQUIPO_NODE_PATH"])+":") { t.Fatalf("gate env %v", h.env) } // The runner user's HOME stays (CoreSimulator's device set is found // from it); Xcode's writes go to scratch by mac.XcodeWrites instead. home, _ := os.UserHomeDir() if want := []string{"HOME=" + home, h.env[1], "CI=1", "LANG=en_US.UTF-8"}; !slices.Equal(h.env[:min(4, len(h.env))], want) || len(h.env) > 4 && (len(h.env) > 5 || !strings.HasPrefix(h.env[4], "DEVELOPER_DIR=")) || h.checks.sandboxed.ScratchHome || h.checks.unproven.ScratchHome { t.Fatalf("gate env %v", h.env) } // A refused T: why, in words, and no checks profile. macUserTemp = func(context.Context, mac.Exec) (string, error) { return "", &mac.UserTempError{Why: "another user owns it"} } if h, err = newMacHost(c, OptionsFromEnv(func(k string) string { return tools[k] })); err != nil || h.paths.UserTemp != "" || h.paths.UserTempWhy != "another user owns it" { t.Fatalf("refused T: %+v %v", h.paths, err) } if _, err := h.checks.sandboxed.Settings(filepath.Join(key, "tree"), filepath.Join(key, "attempt-1")); err == nil { t.Fatal("a checks profile without the user's T") } } // Xcode's plugin cache is warmed outside the sandbox with -showsdks, // once per Xcode version and build: again after a failure, and not // while a gate holds the turn. func TestMacWarmsThePluginCacheOncePerXcode(t *testing.T) { dir := t.TempDir() xb, log, fail := filepath.Join(dir, "xcodebuild"), filepath.Join(dir, "log"), filepath.Join(dir, "fail") if err := os.WriteFile(xb, []byte("#!/bin/sh\necho \"$*\" >> "+log+"\n[ ! -e "+fail+" ]\n"), 0700); err != nil { t.Fatal(err) } h := &macHost{tools: mac.Tools{Xcodebuild: xb}, turns: mac.NewTurns(filepath.Join(dir, "lock"))} b52, b60 := wire.Xcode{Version: "27.2", Build: "27B52"}, wire.Xcode{Version: "27.2", Build: "27B60"} other := mac.NewTurns(filepath.Join(dir, "lock")) turn, ok := other.TryTake(mac.OpCheck) if !ok { t.Fatal("turn") } h.warm(context.Background(), b52) turn.Give() // Nor while an earlier attempt's cleanup is pending. _ = os.WriteFile(filepath.Join(dir, "lock.pending"), nil, 0600) h.warm(context.Background(), b52) _ = os.Remove(filepath.Join(dir, "lock.pending")) _ = os.WriteFile(fail, nil, 0600) h.warm(context.Background(), b52) _ = os.Remove(fail) for _, x := range []wire.Xcode{b52, b52, {}, b60, b60} { h.warm(context.Background(), x) } if raw, _ := os.ReadFile(log); string(raw) != strings.Repeat("-showsdks\n", 3) { t.Fatalf("warmed %q", raw) } } // A worker's attempt has its marker on record before it starts anything, // and an attempt a crashed runner left with no record is never taken as // ended: recovery asks the worker to settle it by its marker. func TestWorkerRecordsBeforeRunning(t *testing.T) { x := newWorkerRig(t) x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") var seen string x.w.Ready = func(context.Context) error { return nil } gate := &recordingGate{stubGate: x.gate, before: func() { _ = x.w.State.db.QueryRow("SELECT coalesce(ns_id, '') FROM steps WHERE step_id=?", x.r.StepID).Scan(&seen) }} x.w.Gate = gate if err := x.w.State.AcceptDispatch(context.Background(), "d1", x.r.DispatchCommand); err != nil { t.Fatal(err) } _ = x.run() if seen != mac.RecordID(0, "checks/"+stepKey(x.r)) { t.Fatalf("recorded before the gate: %q", seen) } if workerRecord(UnrecordedStep(x.r.key())) != mac.RecordID(0, "checks/"+stepKey(x.r)) { t.Fatal("an unrecorded attempt is not settled by its marker") } if workerRecord("") != "" { t.Fatal("empty record") } } type recordingGate struct { *stubGate before func() } func (g *recordingGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) gateResult { g.before() return g.stubGate.Run(ctx, a, dir, argv, l, record) } // A counterfeit srt (or Node, or ripgrep) is caught by the pins // compiled into the runner, before every probe run and every sandboxed // check: asking for a new probe after replacing it makes a report that // is never trusted, so checks run outside the sandbox and say so. func TestMacCounterfeitSRT(t *testing.T) { x := newProbeRig(t) x.pinned = false x.started(t) if _, ok := x.p.trusted(); ok { t.Fatal("a report made with counterfeit tools trusted") } m := &macChecks{probes: x.p, taint: loadTaint(filepath.Join(t.TempDir(), "tainted")), srt: "/x/srt", sandboxed: &mac.Gate{Sandbox: wire.SandboxSeatbelt}, unproven: &mac.Gate{SRT: "/x/srt", Sandbox: wire.SandboxNone}, bare: &mac.Gate{Sandbox: wire.SandboxNone}} if m.pick() != m.bare { t.Fatal("counterfeit srt used") } // The tools match again and a probe is asked for: trusted again only // because nothing ran outside the sandbox meanwhile (see the taint). x.pinned = true x.p.probeSoon() deadline := time.Now().Add(5 * time.Second) for x.runs.Load() < 2 && time.Now().Before(deadline) { time.Sleep(20 * time.Millisecond) } time.Sleep(50 * time.Millisecond) if m.pick() != m.sandboxed { t.Fatal("a clean probe after the tools were restored") } } // The taint is sticky: once a check ran outside the sandbox, no probe // (asked for again, all denied) labels a check sandboxed; the file // keeps it across restarts, and the instance's word (welcome) puts it // back if the file is deleted. func TestMacTaintIsSticky(t *testing.T) { x := newProbeRig(t) file := filepath.Join(t.TempDir(), "tainted") m := &macChecks{probes: x.p, taint: loadTaint(file), creds: holdsNothing(), srt: "/x/srt", sandboxed: &mac.Gate{Sandbox: wire.SandboxSeatbelt}, unproven: &mac.Gate{SRT: "/x/srt", Sandbox: wire.SandboxNone}, bare: &mac.Gate{Sandbox: wire.SandboxNone, Env: []string{"PATH=/usr/bin:/bin"}}} tree := filepath.Join(t.TempDir(), "tree") if err := os.MkdirAll(tree, 0700); err != nil { t.Fatal(err) } // No report yet: the check the person chose to run outside the // sandbox runs there, which taints. if res := m.Run(withUnsandboxed(context.Background(), true), "checks-t-1", tree, []string{"/bin/true"}, time.Minute, func(string) error { return nil }); res.sandbox != wire.SandboxNone || !m.taint.Tainted() { t.Fatalf("%+v tainted=%v", res, m.taint.Tainted()) } if _, err := os.Stat(file); err != nil { t.Fatal("taint not kept on disk") } x.started(t) x.p.probeSoon() if r, ok := x.p.trusted(); !ok || !r.Sandboxed() { t.Fatal("rig: a fresh denied report") } if m.pick() == m.sandboxed || m.Sandbox() != wire.SandboxNone { t.Fatal("sandboxed again after a check ran outside it") } if !loadTaint(file).Tainted() { t.Fatal("taint lost on restart") } if err := os.Remove(file); err != nil { t.Fatal(err) } again := loadTaint(file) if again.Tainted() { t.Fatal("rig") } again.Set() // the instance's welcome says tainted if !again.Tainted() { t.Fatal("the instance's taint not taken") } } // Before a sandboxed attempt's T is cleaned, every simulator is shut // down (`simctl shutdown all`, bounded): a hung shutdown is cut off, // the cleanup still runs and the attempt keeps its result; simulator // processes left are logged by name. func TestMacQuietsSimulatorsBeforeCleaning(t *testing.T) { dir := t.TempDir() temp := filepath.Join(dir, "T") if err := os.Mkdir(temp, 0700); err != nil { t.Fatal(err) } xcrun, ps, log := filepath.Join(dir, "xcrun"), filepath.Join(dir, "ps"), filepath.Join(dir, "log") // The shutdown notes that T still holds the attempt's file, then hangs. if err := os.WriteFile(xcrun, []byte("#!/bin/sh\n[ -e "+temp+"/new ] && echo \"$*\" >> "+log+"\nexec sleep 30\n"), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(ps, []byte("#!/bin/sh\necho /usr/bin/zsh\necho /Library/Developer/launchd_sim\necho SimMetalHost\necho SimMetalHost\n"), 0700); err != nil { t.Fatal(err) } limit, wasPS := simShutdownLimit, macPS simShutdownLimit, macPS = 300*time.Millisecond, ps defer func() { simShutdownLimit, macPS = limit, wasPS }() var out strings.Builder h := &macHost{tools: mac.Tools{Xcrun: xcrun}, log: slog.New(slog.NewTextHandler(&out, nil))} tree := filepath.Join(dir, "tree") if err := os.Mkdir(tree, 0700); err != nil { t.Fatal(err) } g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, UserTemp: temp, QuietSimulators: h.quietSimulators, Grace: time.Second, Settle: 5 * time.Second, Lines: 50} start := time.Now() res := g.Run(context.Background(), "checks-sim-1", tree, []string{"/bin/sh", "-c", "touch " + temp + "/new"}, time.Minute, func(string) error { return nil }) if took := time.Since(start); took > 15*time.Second || res.Code != 0 || res.Reason != "" || !res.Terminated { t.Fatalf("after %s: %+v", took, res) } if raw, _ := os.ReadFile(log); string(raw) != "simctl shutdown all\n" { t.Fatalf("shutdown before the cleanup: %q", raw) } if _, err := os.Lstat(filepath.Join(temp, "new")); err == nil { t.Fatal("T not cleaned after a hung shutdown") } if !strings.Contains(out.String(), `names="SimMetalHost launchd_sim"`) { t.Fatalf("log %s", out.String()) } }