| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "slices" |
| 14 | "strings" |
| 15 | "sync/atomic" |
| 16 | "testing" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/oficina/equipo/internal/release" |
| 20 | "amadan.net/oficina/equipo/internal/runner" |
| 21 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 22 | "amadan.net/oficina/equipo/internal/wire" |
| 23 | ) |
| 24 | |
| 25 | // A worker's report says how its checks were confined, and a tree whose |
| 26 | // gate cannot be chosen (two schemes, no simulator) is checks that |
| 27 | // cannot run, never a pass; the gate waits until the probes are done. |
| 28 | func TestWorkerMacReports(t *testing.T) { |
| 29 | x := newWorkerRig(t) |
| 30 | x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") |
| 31 | x.gate.sandbox = wire.SandboxNone |
| 32 | if rep := x.run(); rep.Checks != wire.ChecksPassed || rep.ChecksSandbox != wire.SandboxNone { |
| 33 | t.Fatalf("label %+v", rep) |
| 34 | } |
| 35 | x.r.Attempt = 2 |
| 36 | h := x.header() |
| 37 | h.ID = "tr_2" |
| 38 | x.chunk(t, "c2", h, x.pack, 0, 1, "") |
| 39 | x.w.Find = func(string) (gate, string, bool) { return gate{}, "checks_unavailable", true } |
| 40 | if rep := x.run(); rep.State != wire.StepDone || rep.Checks != wire.ChecksCannotRun || rep.Reason != "checks_unavailable" || len(x.gate.ran) != 1 { |
| 41 | t.Fatalf("unchosen gate %+v ran %v", rep, x.gate.ran) |
| 42 | } |
| 43 | x.w.Find = nil |
| 44 | x.w.Ready = func(ctx context.Context) error { return context.Canceled } |
| 45 | if rep := x.run(); rep.State != wire.StepCancelled || len(x.gate.ran) != 1 { |
| 46 | t.Fatalf("ran before the probes were done: %+v", rep) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | // probeRig is a macProbes whose run, fingerprint and clock a test sets. |
| 51 | type probeRig struct { |
| 52 | p *macProbes |
| 53 | runs atomic.Int32 |
| 54 | verdict string |
| 55 | pinned bool |
| 56 | now time.Time |
| 57 | } |
| 58 | |
| 59 | func newProbeRig(t *testing.T) *probeRig { |
| 60 | x := &probeRig{verdict: wire.ProbeDenied, pinned: true, now: time.Now()} |
| 61 | x.p = newMacProbes("v1", filepath.Join(t.TempDir(), "probe-request"), func(context.Context) mac.Report { |
| 62 | x.runs.Add(1) |
| 63 | return mac.Report{Version: "v1", Profile: mac.ProfileDigest(), At: x.now, Probes: probesAll(x.verdict), SRTRanXcode: true} |
| 64 | }, func() bool { return x.pinned }) |
| 65 | x.p.now = func() time.Time { return x.now } |
| 66 | return x |
| 67 | } |
| 68 | |
| 69 | func (x *probeRig) started(t *testing.T) { |
| 70 | t.Helper() |
| 71 | x.p.start(t.Context(), func() {}) |
| 72 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 73 | defer cancel() |
| 74 | if err := x.p.wait(ctx); err != nil { |
| 75 | t.Fatal(err) |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | // Each attempt's gate follows the report this process made and still |
| 80 | // trusts: srt and seatbelt only when P2 denied; srt labelled none when |
| 81 | // the fixture built under srt; otherwise outside the sandbox, labelled |
| 82 | // none. No srt, no sandbox, whatever the report says. |
| 83 | func TestMacChecksPick(t *testing.T) { |
| 84 | x := newProbeRig(t) |
| 85 | 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}} |
| 86 | if m.pick() != m.bare { |
| 87 | t.Fatal("no report: not bare") |
| 88 | } |
| 89 | x.verdict = wire.ProbeFailed |
| 90 | x.started(t) |
| 91 | if m.pick() != m.unproven || m.Sandbox() != wire.SandboxNone { |
| 92 | t.Fatal("srt ran xcodebuild, P2 failed: not srt labelled none") |
| 93 | } |
| 94 | y := newProbeRig(t) |
| 95 | y.started(t) |
| 96 | m.probes = y.p |
| 97 | if m.pick() != m.sandboxed || m.Sandbox() != wire.SandboxSeatbelt { |
| 98 | t.Fatal("P2 denied: not seatbelt") |
| 99 | } |
| 100 | m.srt = "" |
| 101 | if m.pick() != m.bare { |
| 102 | t.Fatal("no srt: not bare") |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | // Repository code cannot forge the verdict: nothing on disk is read back |
| 107 | // as one (a probes.json saying denied changes nothing), and a report is |
| 108 | // trusted only for this version, with the srt, Node and ripgrep on disk |
| 109 | // now, for a day. Otherwise checks run as not verified and the probes |
| 110 | // run again; the request file only asks for that. |
| 111 | func TestMacProbesTrust(t *testing.T) { |
| 112 | x := newProbeRig(t) |
| 113 | state := filepath.Dir(x.p.request) |
| 114 | forged, _ := json.Marshal(mac.Report{Version: "v1", Profile: mac.ProfileDigest(), At: time.Now(), Probes: probesAll(wire.ProbeDenied), SRT: srtPinned}) |
| 115 | for _, name := range []string{"probes.json", "probe-request"} { |
| 116 | if err := os.WriteFile(filepath.Join(state, name), forged, 0600); err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | } |
| 120 | if _, ok := x.p.trusted(); ok { |
| 121 | t.Fatal("a report this process did not make is trusted") |
| 122 | } |
| 123 | x.started(t) |
| 124 | if r, ok := x.p.trusted(); !ok || !r.Sandboxed() { |
| 125 | t.Fatal("its own fresh report not trusted") |
| 126 | } |
| 127 | x.pinned = false |
| 128 | if _, ok := x.p.trusted(); ok { |
| 129 | t.Fatal("trusted after srt, Node or ripgrep stopped matching their pins") |
| 130 | } |
| 131 | x.pinned = true |
| 132 | x.now = x.now.Add(probeTrust + time.Minute) |
| 133 | if _, ok := x.p.trusted(); ok { |
| 134 | t.Fatal("trusted a day later") |
| 135 | } |
| 136 | deadline := time.Now().Add(5 * time.Second) |
| 137 | for x.runs.Load() < 2 && time.Now().Before(deadline) { |
| 138 | time.Sleep(20 * time.Millisecond) |
| 139 | } |
| 140 | if x.runs.Load() < 2 { |
| 141 | t.Fatal("an untrusted report did not probe again") |
| 142 | } |
| 143 | other := newProbeRig(t) |
| 144 | other.p.version = "v2" |
| 145 | other.started(t) |
| 146 | if _, ok := other.p.trusted(); ok { |
| 147 | t.Fatal("another version's report trusted") |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | func probesAll(p2 string) []wire.Probe { |
| 152 | var out []wire.Probe |
| 153 | for _, id := range wire.ProbeIDs { |
| 154 | v := wire.ProbePassed |
| 155 | if id == "P2" { |
| 156 | v = p2 |
| 157 | } |
| 158 | out = append(out, wire.Probe{ID: id, Verdict: v}) |
| 159 | } |
| 160 | return out |
| 161 | } |
| 162 | |
| 163 | // A Mac finds the repository's own gate first (with macOS's bash), and |
| 164 | // gives an Xcode project without one xcodebuild test. |
| 165 | func TestMacFind(t *testing.T) { |
| 166 | sims := []wire.Simulator{{Name: "iPhone 16 Pro", Runtime: "iOS 18.2", UDID: "5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3", State: "Shutdown"}} |
| 167 | h := &macHost{caps: func(context.Context) wire.Capabilities { return wire.Capabilities{Simulators: sims} }} |
| 168 | tree := t.TempDir() |
| 169 | scheme := filepath.Join(tree, "Woodstar.xcodeproj/xcshareddata/xcschemes/Woodstar.xcscheme") |
| 170 | if err := os.MkdirAll(filepath.Dir(scheme), 0700); err != nil { |
| 171 | t.Fatal(err) |
| 172 | } |
| 173 | if err := os.WriteFile(scheme, []byte("<Scheme/>"), 0600); err != nil { |
| 174 | t.Fatal(err) |
| 175 | } |
| 176 | g, reason, ok := h.find(tree) |
| 177 | if !ok || reason != "" || g.name != "xcodebuild test" || !strings.Contains(g.argv[2], "-scheme 'Woodstar' -destination 'platform=iOS Simulator,id=5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3'") { |
| 178 | t.Fatalf("%+v %q", g, reason) |
| 179 | } |
| 180 | if err := os.MkdirAll(filepath.Join(tree, ".amadan/ci.d"), 0700); err != nil { |
| 181 | t.Fatal(err) |
| 182 | } |
| 183 | if err := os.WriteFile(filepath.Join(tree, ".amadan/ci.d/10-test"), []byte("#!/bin/sh\nmake test\n"), 0700); err != nil { |
| 184 | t.Fatal(err) |
| 185 | } |
| 186 | if g, _, ok := h.find(tree); !ok || g.name != ".amadan/ci.d" || g.argv[0] != "/bin/bash" { |
| 187 | t.Fatalf("own gate %+v", g) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | // The worker updates itself to its instance's release: the darwin |
| 192 | // runner of that release's manifest, verified, swapped while no step |
| 193 | // runs, then it stops to be restarted. A digest mismatch replaces |
| 194 | // nothing; its own release or no release asks for nothing. |
| 195 | func TestMacUpdater(t *testing.T) { |
| 196 | newBin := []byte("#!new runner\n") |
| 197 | sum := sha256.Sum256(newBin) |
| 198 | digest := hex.EncodeToString(sum[:]) |
| 199 | var served atomic.Int32 |
| 200 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 201 | served.Add(1) |
| 202 | switch r.URL.Path { |
| 203 | case "/releases/bbb2222/install-manifest.json": |
| 204 | _ = json.NewEncoder(w).Encode(release.InstallManifest{Version: "bbb2222", Targets: map[string]release.InstallTarget{release.TargetDarwin: {RunnerSHA256: digest}}}) |
| 205 | case "/releases/ccc3333/install-manifest.json": |
| 206 | _ = json.NewEncoder(w).Encode(release.InstallManifest{Version: "ccc3333", Targets: map[string]release.InstallTarget{release.TargetDarwin: {RunnerSHA256: strings.Repeat("0", 64)}}}) |
| 207 | case "/releases/bbb2222/darwin-arm64/equipo-runner", "/releases/ccc3333/darwin-arm64/equipo-runner": |
| 208 | _, _ = w.Write(newBin) |
| 209 | default: |
| 210 | http.NotFound(w, r) |
| 211 | } |
| 212 | })) |
| 213 | defer srv.Close() |
| 214 | binary := filepath.Join(t.TempDir(), "equipo-runner") |
| 215 | if err := os.WriteFile(binary, []byte("#!old runner\n"), 0700); err != nil { |
| 216 | t.Fatal(err) |
| 217 | } |
| 218 | try := func(rel string) (held, stopped bool, err error) { |
| 219 | u := &macUpdater{origin: srv.URL, version: "aaa1111", binary: binary, fetch: fetchLimited} |
| 220 | u.offer(wire.Welcome{Release: rel}, func() func() { held = true; return func() {} }, func() { stopped = true }, nil) |
| 221 | if u.done == nil { |
| 222 | return held, stopped, nil |
| 223 | } |
| 224 | err = <-u.done |
| 225 | return held, stopped, err |
| 226 | } |
| 227 | for _, rel := range []string{"", "aaa1111", "dev", "../x"} { |
| 228 | if _, stopped, _ := try(rel); stopped || served.Load() != 0 { |
| 229 | t.Fatalf("release %q fetched or stopped", rel) |
| 230 | } |
| 231 | } |
| 232 | if _, stopped, err := try("ccc3333"); err == nil || stopped { |
| 233 | t.Fatal("a runner whose digest does not match was taken") |
| 234 | } |
| 235 | if raw, _ := os.ReadFile(binary); string(raw) != "#!old runner\n" { |
| 236 | t.Fatal("binary replaced by an unverified download") |
| 237 | } |
| 238 | held, stopped, err := try("bbb2222") |
| 239 | if err != nil || !held || !stopped { |
| 240 | t.Fatalf("update: %v held=%v stopped=%v", err, held, stopped) |
| 241 | } |
| 242 | if raw, _ := os.ReadFile(binary); string(raw) != string(newBin) { |
| 243 | t.Fatal("binary not replaced") |
| 244 | } |
| 245 | if info, _ := os.Stat(binary); info.Mode().Perm() != 0700 { |
| 246 | t.Fatal("new binary not private and executable") |
| 247 | } |
| 248 | left, _ := filepath.Glob(filepath.Join(filepath.Dir(binary), ".equipo-runner-update-*")) |
| 249 | if len(left) != 0 { |
| 250 | t.Fatalf("left %v", left) |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | // The Mac host keeps every tree the checks profile must let a gate |
| 255 | // write (attempt trees, the probes' fixture copies) under the scratch |
| 256 | // root, outside the state dir the profile denies. |
| 257 | func TestMacHostPaths(t *testing.T) { |
| 258 | root := t.TempDir() |
| 259 | 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")} |
| 260 | 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")} |
| 261 | for _, p := range tools { |
| 262 | if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil { |
| 263 | t.Fatal(err) |
| 264 | } |
| 265 | if err := os.WriteFile(p, []byte("#!/bin/sh\n"), 0700); err != nil { |
| 266 | t.Fatal(err) |
| 267 | } |
| 268 | } |
| 269 | users := filepath.Join(root, "Users") |
| 270 | if err := os.MkdirAll(filepath.Join(users, "paul"), 0700); err != nil { |
| 271 | t.Fatal(err) |
| 272 | } |
| 273 | was, wasTemp := macUsers, macUserTemp |
| 274 | macUsers = users |
| 275 | const temp = "/private/var/folders/4m/abc123_def/T" |
| 276 | macUserTemp = func(context.Context, mac.Exec) (string, error) { return temp, nil } |
| 277 | defer func() { macUsers, macUserTemp = was, wasTemp }() |
| 278 | // The tools come from the runner's own environment (its env file), |
| 279 | // not the process's. |
| 280 | h, err := newMacHost(c, OptionsFromEnv(func(k string) string { return tools[k] })) |
| 281 | if err != nil { |
| 282 | t.Fatal(err) |
| 283 | } |
| 284 | // The user's T: written by sandboxed gates and cleaned after each; |
| 285 | // every gate takes the one turn. |
| 286 | k := h.checks |
| 287 | 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 { |
| 288 | t.Fatalf("user temp %+v", h.paths) |
| 289 | } |
| 290 | 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") { |
| 291 | t.Fatalf("%+v", p) |
| 292 | } |
| 293 | settings := h.checks.sandboxed.Settings |
| 294 | if settings == nil || h.checks.bare.Settings != nil || h.checks.sandboxed.Sandbox != wire.SandboxSeatbelt || h.checks.unproven.Sandbox != wire.SandboxNone { |
| 295 | t.Fatal("gates") |
| 296 | } |
| 297 | key := filepath.Join(c.ScratchRoot, "worker-steps", "k") |
| 298 | if _, err := settings(filepath.Join(key, "tree"), filepath.Join(key, "attempt-1")); err != nil { |
| 299 | t.Fatalf("a worker tree refused: %v", err) |
| 300 | } |
| 301 | if _, err := settings(filepath.Join(c.StateDir, "worker", "steps", "k", "tree"), filepath.Join(key, "attempt-1")); err == nil { |
| 302 | t.Fatal("a tree in the state dir accepted") |
| 303 | } |
| 304 | // srt starts through `env node` and looks for rg on the PATH: the |
| 305 | // runner's own Node and ripgrep come first, for the runner and its gates. |
| 306 | t.Setenv("PATH", "/usr/bin:/bin") |
| 307 | out, err := h.run(context.Background(), "/bin/sh", "-c", "echo $PATH") |
| 308 | path := strings.Split(strings.TrimSpace(out), ":") |
| 309 | if err != nil || !slices.Contains(path[:2], filepath.Dir(tools["EQUIPO_NODE_PATH"])) || !slices.Contains(path[:2], filepath.Dir(tools["EQUIPO_RG_PATH"])) { |
| 310 | t.Fatalf("a tool's PATH %v %v", path, err) |
| 311 | } |
| 312 | if !strings.Contains(strings.Join(h.env, " "), "PATH="+filepath.Dir(tools["EQUIPO_RG_PATH"])+":"+filepath.Dir(tools["EQUIPO_NODE_PATH"])+":") { |
| 313 | t.Fatalf("gate env %v", h.env) |
| 314 | } |
| 315 | // The runner user's HOME stays (CoreSimulator's device set is found |
| 316 | // from it); Xcode's writes go to scratch by mac.XcodeWrites instead. |
| 317 | home, _ := os.UserHomeDir() |
| 318 | 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 { |
| 319 | t.Fatalf("gate env %v", h.env) |
| 320 | } |
| 321 | // A refused T: why, in words, and no checks profile. |
| 322 | macUserTemp = func(context.Context, mac.Exec) (string, error) { |
| 323 | return "", &mac.UserTempError{Why: "another user owns it"} |
| 324 | } |
| 325 | 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" { |
| 326 | t.Fatalf("refused T: %+v %v", h.paths, err) |
| 327 | } |
| 328 | if _, err := h.checks.sandboxed.Settings(filepath.Join(key, "tree"), filepath.Join(key, "attempt-1")); err == nil { |
| 329 | t.Fatal("a checks profile without the user's T") |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | // Xcode's plugin cache is warmed outside the sandbox with -showsdks, |
| 334 | // once per Xcode version and build: again after a failure, and not |
| 335 | // while a gate holds the turn. |
| 336 | func TestMacWarmsThePluginCacheOncePerXcode(t *testing.T) { |
| 337 | dir := t.TempDir() |
| 338 | xb, log, fail := filepath.Join(dir, "xcodebuild"), filepath.Join(dir, "log"), filepath.Join(dir, "fail") |
| 339 | if err := os.WriteFile(xb, []byte("#!/bin/sh\necho \"$*\" >> "+log+"\n[ ! -e "+fail+" ]\n"), 0700); err != nil { |
| 340 | t.Fatal(err) |
| 341 | } |
| 342 | h := &macHost{tools: mac.Tools{Xcodebuild: xb}, turns: mac.NewTurns(filepath.Join(dir, "lock"))} |
| 343 | b52, b60 := wire.Xcode{Version: "27.2", Build: "27B52"}, wire.Xcode{Version: "27.2", Build: "27B60"} |
| 344 | other := mac.NewTurns(filepath.Join(dir, "lock")) |
| 345 | turn, ok := other.TryTake(mac.OpCheck) |
| 346 | if !ok { |
| 347 | t.Fatal("turn") |
| 348 | } |
| 349 | h.warm(context.Background(), b52) |
| 350 | turn.Give() |
| 351 | // Nor while an earlier attempt's cleanup is pending. |
| 352 | _ = os.WriteFile(filepath.Join(dir, "lock.pending"), nil, 0600) |
| 353 | h.warm(context.Background(), b52) |
| 354 | _ = os.Remove(filepath.Join(dir, "lock.pending")) |
| 355 | _ = os.WriteFile(fail, nil, 0600) |
| 356 | h.warm(context.Background(), b52) |
| 357 | _ = os.Remove(fail) |
| 358 | for _, x := range []wire.Xcode{b52, b52, {}, b60, b60} { |
| 359 | h.warm(context.Background(), x) |
| 360 | } |
| 361 | if raw, _ := os.ReadFile(log); string(raw) != strings.Repeat("-showsdks\n", 3) { |
| 362 | t.Fatalf("warmed %q", raw) |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | // A worker's attempt has its marker on record before it starts anything, |
| 367 | // and an attempt a crashed runner left with no record is never taken as |
| 368 | // ended: recovery asks the worker to settle it by its marker. |
| 369 | func TestWorkerRecordsBeforeRunning(t *testing.T) { |
| 370 | x := newWorkerRig(t) |
| 371 | x.chunk(t, "c1", x.header(), x.pack, 0, 1, "") |
| 372 | var seen string |
| 373 | x.w.Ready = func(context.Context) error { return nil } |
| 374 | gate := &recordingGate{stubGate: x.gate, before: func() { |
| 375 | _ = x.w.State.db.QueryRow("SELECT coalesce(ns_id, '') FROM steps WHERE step_id=?", x.r.StepID).Scan(&seen) |
| 376 | }} |
| 377 | x.w.Gate = gate |
| 378 | if err := x.w.State.AcceptDispatch(context.Background(), "d1", x.r.DispatchCommand); err != nil { |
| 379 | t.Fatal(err) |
| 380 | } |
| 381 | _ = x.run() |
| 382 | if seen != mac.RecordID(0, "checks/"+stepKey(x.r)) { |
| 383 | t.Fatalf("recorded before the gate: %q", seen) |
| 384 | } |
| 385 | if workerRecord(UnrecordedStep(x.r.key())) != mac.RecordID(0, "checks/"+stepKey(x.r)) { |
| 386 | t.Fatal("an unrecorded attempt is not settled by its marker") |
| 387 | } |
| 388 | if workerRecord("") != "" { |
| 389 | t.Fatal("empty record") |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | type recordingGate struct { |
| 394 | *stubGate |
| 395 | before func() |
| 396 | } |
| 397 | |
| 398 | func (g *recordingGate) Run(ctx context.Context, a, dir string, argv []string, l time.Duration, record func(string) error) gateResult { |
| 399 | g.before() |
| 400 | return g.stubGate.Run(ctx, a, dir, argv, l, record) |
| 401 | } |
| 402 | |
| 403 | // A counterfeit srt (or Node, or ripgrep) is caught by the pins |
| 404 | // compiled into the runner, before every probe run and every sandboxed |
| 405 | // check: asking for a new probe after replacing it makes a report that |
| 406 | // is never trusted, so checks run outside the sandbox and say so. |
| 407 | func TestMacCounterfeitSRT(t *testing.T) { |
| 408 | x := newProbeRig(t) |
| 409 | x.pinned = false |
| 410 | x.started(t) |
| 411 | if _, ok := x.p.trusted(); ok { |
| 412 | t.Fatal("a report made with counterfeit tools trusted") |
| 413 | } |
| 414 | 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}} |
| 415 | if m.pick() != m.bare { |
| 416 | t.Fatal("counterfeit srt used") |
| 417 | } |
| 418 | // The tools match again and a probe is asked for: trusted again only |
| 419 | // because nothing ran outside the sandbox meanwhile (see the taint). |
| 420 | x.pinned = true |
| 421 | x.p.probeSoon() |
| 422 | deadline := time.Now().Add(5 * time.Second) |
| 423 | for x.runs.Load() < 2 && time.Now().Before(deadline) { |
| 424 | time.Sleep(20 * time.Millisecond) |
| 425 | } |
| 426 | time.Sleep(50 * time.Millisecond) |
| 427 | if m.pick() != m.sandboxed { |
| 428 | t.Fatal("a clean probe after the tools were restored") |
| 429 | } |
| 430 | } |
| 431 | |
| 432 | // The taint is sticky: once a check ran outside the sandbox, no probe |
| 433 | // (asked for again, all denied) labels a check sandboxed; the file |
| 434 | // keeps it across restarts, and the instance's word (welcome) puts it |
| 435 | // back if the file is deleted. |
| 436 | func TestMacTaintIsSticky(t *testing.T) { |
| 437 | x := newProbeRig(t) |
| 438 | file := filepath.Join(t.TempDir(), "tainted") |
| 439 | 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"}}} |
| 440 | tree := filepath.Join(t.TempDir(), "tree") |
| 441 | if err := os.MkdirAll(tree, 0700); err != nil { |
| 442 | t.Fatal(err) |
| 443 | } |
| 444 | // No report yet: the check the person chose to run outside the |
| 445 | // sandbox runs there, which taints. |
| 446 | 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() { |
| 447 | t.Fatalf("%+v tainted=%v", res, m.taint.Tainted()) |
| 448 | } |
| 449 | if _, err := os.Stat(file); err != nil { |
| 450 | t.Fatal("taint not kept on disk") |
| 451 | } |
| 452 | x.started(t) |
| 453 | x.p.probeSoon() |
| 454 | if r, ok := x.p.trusted(); !ok || !r.Sandboxed() { |
| 455 | t.Fatal("rig: a fresh denied report") |
| 456 | } |
| 457 | if m.pick() == m.sandboxed || m.Sandbox() != wire.SandboxNone { |
| 458 | t.Fatal("sandboxed again after a check ran outside it") |
| 459 | } |
| 460 | if !loadTaint(file).Tainted() { |
| 461 | t.Fatal("taint lost on restart") |
| 462 | } |
| 463 | if err := os.Remove(file); err != nil { |
| 464 | t.Fatal(err) |
| 465 | } |
| 466 | again := loadTaint(file) |
| 467 | if again.Tainted() { |
| 468 | t.Fatal("rig") |
| 469 | } |
| 470 | again.Set() // the instance's welcome says tainted |
| 471 | if !again.Tainted() { |
| 472 | t.Fatal("the instance's taint not taken") |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | // Before a sandboxed attempt's T is cleaned, every simulator is shut |
| 477 | // down (`simctl shutdown all`, bounded): a hung shutdown is cut off, |
| 478 | // the cleanup still runs and the attempt keeps its result; simulator |
| 479 | // processes left are logged by name. |
| 480 | func TestMacQuietsSimulatorsBeforeCleaning(t *testing.T) { |
| 481 | dir := t.TempDir() |
| 482 | temp := filepath.Join(dir, "T") |
| 483 | if err := os.Mkdir(temp, 0700); err != nil { |
| 484 | t.Fatal(err) |
| 485 | } |
| 486 | xcrun, ps, log := filepath.Join(dir, "xcrun"), filepath.Join(dir, "ps"), filepath.Join(dir, "log") |
| 487 | // The shutdown notes that T still holds the attempt's file, then hangs. |
| 488 | if err := os.WriteFile(xcrun, []byte("#!/bin/sh\n[ -e "+temp+"/new ] && echo \"$*\" >> "+log+"\nexec sleep 30\n"), 0700); err != nil { |
| 489 | t.Fatal(err) |
| 490 | } |
| 491 | 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 { |
| 492 | t.Fatal(err) |
| 493 | } |
| 494 | limit, wasPS := simShutdownLimit, macPS |
| 495 | simShutdownLimit, macPS = 300*time.Millisecond, ps |
| 496 | defer func() { simShutdownLimit, macPS = limit, wasPS }() |
| 497 | var out strings.Builder |
| 498 | h := &macHost{tools: mac.Tools{Xcrun: xcrun}, log: slog.New(slog.NewTextHandler(&out, nil))} |
| 499 | tree := filepath.Join(dir, "tree") |
| 500 | if err := os.Mkdir(tree, 0700); err != nil { |
| 501 | t.Fatal(err) |
| 502 | } |
| 503 | g := &mac.Gate{Env: []string{"PATH=/usr/bin:/bin"}, UserTemp: temp, QuietSimulators: h.quietSimulators, Grace: time.Second, Settle: 5 * time.Second, Lines: 50} |
| 504 | start := time.Now() |
| 505 | res := g.Run(context.Background(), "checks-sim-1", tree, []string{"/bin/sh", "-c", "touch " + temp + "/new"}, time.Minute, func(string) error { return nil }) |
| 506 | if took := time.Since(start); took > 15*time.Second || res.Code != 0 || res.Reason != "" || !res.Terminated { |
| 507 | t.Fatalf("after %s: %+v", took, res) |
| 508 | } |
| 509 | if raw, _ := os.ReadFile(log); string(raw) != "simctl shutdown all\n" { |
| 510 | t.Fatalf("shutdown before the cleanup: %q", raw) |
| 511 | } |
| 512 | if _, err := os.Lstat(filepath.Join(temp, "new")); err == nil { |
| 513 | t.Fatal("T not cleaned after a hung shutdown") |
| 514 | } |
| 515 | if !strings.Contains(out.String(), `names="SimMetalHost launchd_sim"`) { |
| 516 | t.Fatalf("log %s", out.String()) |
| 517 | } |
| 518 | } |
| 519 | |