package mac import ( "context" "errors" "os" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // userTempFixture is a stand-in for /private/var/folders with one // user's T in it, 0700 and this test's own. func userTempFixture(t *testing.T) (prefix, temp string) { t.Helper() prefix, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { t.Fatal(err) } temp = filepath.Join(prefix, "4m", "abc123_def", "T") if err := os.MkdirAll(temp, 0700); err != nil { t.Fatal(err) } return prefix, temp } func getconf(out string, err error) Exec { return func(_ context.Context, name string, args ...string) (string, error) { if name != "/usr/bin/getconf" || strings.Join(args, " ") != "DARWIN_USER_TEMP_DIR" { return "", errors.New("not getconf") } return out, err } } // T is getconf's answer with its symlinks resolved and no trailing // slash, and only when it is the runner user's own 0700 directory // under the system's user folders; otherwise why, in words. func TestUserTemp(t *testing.T) { prefix, temp := userTempFixture(t) uid := os.Getuid() // macOS names it through /var, a symlink to /private/var. link := filepath.Join(t.TempDir(), "var-T") if err := os.Symlink(temp, link); err != nil { t.Fatal(err) } if got, err := UserTemp(context.Background(), getconf(link+"/\n", nil), uid, prefix); err != nil || got != temp { t.Fatalf("resolved %q %v, want %q", got, err, temp) } refused := func(name, why string, x Exec, uid int) { t.Helper() got, err := UserTemp(context.Background(), x, uid, prefix) var e *UserTempError if got != "" || !errors.Is(err, ErrUserTemp) || !errors.As(err, &e) || e.Why != why || strings.Contains(e.Why, "/") { t.Fatalf("%s: %q %v", name, got, err) } } refused("another owner", "another user owns it", getconf(temp, nil), uid+1) refused("getconf failed", "getconf did not name it", getconf("", errors.New("exit 1")), uid) refused("relative", "getconf did not name it", getconf("T/", nil), uid) refused("missing", "it does not exist", getconf(temp+"-gone", nil), uid) refused("the prefix itself", "it is not under the system's user folders", getconf(prefix, nil), uid) elsewhere := t.TempDir() if err := os.Chmod(elsewhere, 0700); err != nil { t.Fatal(err) } refused("outside the user folders", "it is not under the system's user folders", getconf(elsewhere, nil), uid) // A link inside the user folders that leads out of them. if err := os.Symlink(elsewhere, filepath.Join(prefix, "out")); err != nil { t.Fatal(err) } refused("linked out", "it is not under the system's user folders", getconf(filepath.Join(prefix, "out"), nil), uid) file := filepath.Join(prefix, "file") if err := os.WriteFile(file, nil, 0700); err != nil { t.Fatal(err) } refused("a file", "it is not a directory", getconf(file, nil), uid) if err := os.Chmod(temp, 0755); err != nil { t.Fatal(err) } refused("readable by others", "its mode is not 0700", getconf(temp, nil), uid) } // tempTree writes what T holds before an attempt: a file, a folder, // TemporaryItems with one entry, and a folder outside T. func tempTree(t *testing.T, temp string) (outside string) { t.Helper() for _, d := range []string{"keepdir", "TemporaryItems/old", "shared"} { if err := os.MkdirAll(filepath.Join(temp, d), 0700); err != nil { t.Fatal(err) } } for _, f := range []string{"keep", "shared/a"} { if err := os.WriteFile(filepath.Join(temp, f), []byte("before"), 0600); err != nil { t.Fatal(err) } } outside = t.TempDir() if err := os.WriteFile(filepath.Join(outside, "precious"), []byte("x"), 0600); err != nil { t.Fatal(err) } return outside } func exists(p string) bool { _, err := os.Lstat(p); return err == nil } // Once a sandboxed run is proven over, what appeared in T and in // T/TemporaryItems goes and what was there stays, even rewritten; a // symlink goes as itself, never what it leads to. func TestGateCleansUserTemp(t *testing.T) { g, dir := gateFixture(t, true) _, temp := userTempFixture(t) outside := tempTree(t, temp) g.UserTemp = temp script := `T=` + quote(temp) + ` echo after > "$T/keep" mkdir -p "$T/new/deep" "$T/swbuild.tmp.1" "$T/TemporaryItems/NSIRD_xcodebuild_1" && touch "$T/new/deep/f" "$T/TemporaryDirectory.2" ln -s ` + quote(outside) + ` "$T/link" ln -s ` + quote(outside) + ` "$T/TemporaryItems/NSIRD_link"` if res, _ := run(g, dir, "checks-t-1", time.Minute, script); res.Code != 0 || !res.Terminated { t.Fatalf("%+v", res) } for _, kept := range []string{"keep", "keepdir", "shared/a", "TemporaryItems", "TemporaryItems/old"} { if !exists(filepath.Join(temp, kept)) { t.Fatalf("%s was there before and is gone", kept) } } for _, gone := range []string{"new", "swbuild.tmp.1", "TemporaryDirectory.2", "link", "TemporaryItems/NSIRD_xcodebuild_1", "TemporaryItems/NSIRD_link"} { if exists(filepath.Join(temp, gone)) { t.Fatalf("%s appeared during the run and is left", gone) } } if !exists(filepath.Join(outside, "precious")) { t.Fatal("the cleanup followed a symlink out of T") } } // TemporaryItems swapped for a symlink to a folder that was in T before: // the link goes, the folder and what it held stay. func TestGateCleanupKeepsASwappedTemporaryItemsTarget(t *testing.T) { g, dir := gateFixture(t, true) _, temp := userTempFixture(t) tempTree(t, temp) g.UserTemp = temp // Relative, so it stays inside T, where os.Root would follow it. script := `T=` + quote(temp) + `; rm -rf "$T/TemporaryItems" && ln -s shared "$T/TemporaryItems"` if res, _ := run(g, dir, "checks-t-2", time.Minute, script); res.Code != 0 || !res.Terminated { t.Fatalf("%+v", res) } if exists(filepath.Join(temp, "TemporaryItems")) || !exists(filepath.Join(temp, "shared/a")) { t.Fatal("a swapped TemporaryItems was followed, or left") } } // A run whose end is not proven may still be writing T: nothing is // removed then; by that attempt's own proof (Verify), never by the next // gate's turn. func TestGateCleanupWaitsForTheProvenEnd(t *testing.T) { g, dir := gateFixture(t, true) _, temp := userTempFixture(t) g.UserTemp, g.Settle, g.Turns = temp, 500*time.Millisecond, NewTurns(filepath.Join(t.TempDir(), "lock")) g.procs = withPhantom() quieted := 0 g.QuietSimulators = func(context.Context) { quieted++ } res, id := run(g, dir, "checks-t-3", time.Minute, `touch `+quote(filepath.Join(temp, "late"))) if res.Terminated || !exists(filepath.Join(temp, "late")) || quieted != 0 { t.Fatalf("cleaned before the end was proven: %+v", res) } // The next gate's turn neither finishes it nor runs. g.procs = nil if res, _ := run(g, dir, "checks-t-3b", time.Minute, `touch `+quote(filepath.Join(temp, "next"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "next")) || !exists(filepath.Join(temp, "late")) || !g.Turns.Pending() { t.Fatalf("another turn finished or ran past the cleanup: %+v", res) } // Its own proof finishes it; then gates run again. if !g.Verify(id) || exists(filepath.Join(temp, "late")) || g.Turns.Pending() { t.Fatal("the attempt's proof did not finish its cleanup") } res, _ = run(g, dir, "checks-t-3c", time.Minute, `ls `+quote(temp)+`; touch `+quote(filepath.Join(temp, "next"))) if !res.Terminated || strings.Contains(res.Output, "late") || exists(filepath.Join(temp, "next")) || exists(g.Turns.pending()) { t.Fatalf("not run, or not cleaned, after the proof: %+v", res) } // One that cannot be finished (T is no longer a folder of this // user's): its proof says not over, and nothing runs. g.procs = withPhantom() _, id = run(g, dir, "checks-t-3d", time.Minute, `true`) g.procs = nil if err := os.Chmod(temp, 0755); err != nil { t.Fatal(err) } if g.Verify(id) { t.Fatal("proven over with its cleanup not done") } if res, _ := run(g, dir, "checks-t-3e", time.Minute, `touch `+quote(filepath.Join(temp, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran")) { t.Fatalf("ran with a cleanup left that cannot be finished: %+v", res) } if err := os.Chmod(temp, 0700); err != nil { t.Fatal(err) } if !g.Verify(id) || g.Turns.Pending() { t.Fatal("the cleanup was not finished once it could be") } // A T that cannot be listed: nothing runs. g.UserTemp = filepath.Join(temp, "gone") if res, _ := run(g, dir, "checks-t-4", time.Minute, `touch `+quote(filepath.Join(temp, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(temp, "ran")) { t.Fatalf("ran without a listing of T: %+v", res) } } // Gates sharing the Mac's turns never overlap, sandboxed or not, and one // waiting for its turn can be cancelled before anything of it runs. func TestGatesTakeTurns(t *testing.T) { // Two processes' turns over one lock file (the worker and // the probe command): as one. lock := filepath.Join(t.TempDir(), "lock") turns := NewTurns(lock) a, dirA := gateFixture(t, true) b, dirB := gateFixture(t, false) a.Turns, b.Turns = turns, NewTurns(lock) log := filepath.Join(t.TempDir(), "log") step := func(name string) string { return `echo ` + name + `-start >> ` + quote(log) + `; sleep 0.3; echo ` + name + `-end >> ` + quote(log) } var wg sync.WaitGroup for _, g := range []struct { g *Gate dir string name string }{{a, dirA, "a"}, {b, dirB, "b"}} { wg.Add(1) go func() { defer wg.Done() if res, _ := run(g.g, g.dir, "checks-turn-"+g.name, time.Minute, step(g.name)); res.Code != 0 { t.Errorf("%s: %+v", g.name, res) } }() } wg.Wait() raw, _ := os.ReadFile(log) lines := strings.Fields(string(raw)) if len(lines) != 4 || strings.TrimSuffix(lines[0], "-start") != strings.TrimSuffix(lines[1], "-end") { t.Fatalf("gates overlapped: %v", lines) } held, err := turns.Take(context.Background(), OpEngineering) if err != nil { t.Fatal(err) } if _, ok := b.Turns.TryTake(OpWarm); ok { t.Fatal("TryTake while another holds the turn") } ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() res := b.Run(ctx, "checks-turn-c", dirB, []string{"/bin/sh", "-c", "touch " + quote(log+".c")}, time.Minute, func(string) error { return nil }) held.Give() if res.Reason != "cancelled" || !res.Terminated || exists(log+".c") { t.Fatalf("ran without its turn: %+v", res) } } // P2 needs the user's T: refused, it says why (in words) and checks // wait for the sandbox. func TestP2NeedsTheUserTemp(t *testing.T) { f := newProbeFixture(t, allLines("denied")) f.h.Paths.UserTemp, f.h.Paths.UserTempWhy = "", "its mode is not 0700" p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)) if ran || p.Verdict != wire.ProbeUnavailable || p.Detail != "user_temp_refused" { t.Fatalf("%+v", p) } } // What the attempt made unreadable is still removed; a T replaced by a // symlink during the run is cleaned by the folder it was (never where // the link leads), and the next gate runs nothing. func TestGateCleanupHoldsT(t *testing.T) { g, dir := gateFixture(t, true) _, temp := userTempFixture(t) outside := tempTree(t, temp) g.UserTemp, g.Turns = temp, NewTurns(filepath.Join(t.TempDir(), "lock")) locked := `T=` + quote(temp) + `; mkdir -p "$T/left/deep" && touch "$T/left/deep/payload" && chmod 000 "$T/left/deep" "$T/left"` if res, _ := run(g, dir, "checks-t-5", time.Minute, locked); res.Code != 0 || exists(filepath.Join(temp, "left")) || exists(g.Turns.pending()) { t.Fatalf("a locked folder was left: %+v", res) } moved := filepath.Join(filepath.Dir(temp), "T-moved") swap := `T=` + quote(temp) + `; touch "$T/new" && mv "$T" ` + quote(moved) + ` && ln -s ` + quote(outside) + ` "$T"` if res, _ := run(g, dir, "checks-t-6", time.Minute, swap); res.Code != 0 || !res.Terminated { t.Fatalf("%+v", res) } if exists(filepath.Join(moved, "new")) || !exists(filepath.Join(moved, "keep")) || !exists(filepath.Join(outside, "precious")) { t.Fatal("the cleanup did not hold the T it listed") } if res, _ := run(g, dir, "checks-t-7", time.Minute, `touch `+quote(filepath.Join(outside, "ran"))); res.Reason != "checks_unavailable" || exists(filepath.Join(outside, "ran")) { t.Fatalf("ran with T a symlink: %+v", res) } } // The digest names a profile ChecksSettings makes, not a refusal. func TestProfileDigest(t *testing.T) { if _, err := ChecksSettings(digestInput()); err != nil { t.Fatal(err) } } // Simulators are shut down once the end is proven and before T is // cleaned (CoreSimulator's processes may still be writing it); however // long that takes, the cleanup then runs and the run's result stands. func TestGateQuietsSimulatorsBeforeCleaning(t *testing.T) { g, dir := gateFixture(t, true) _, temp := userTempFixture(t) g.UserTemp = temp var saw []bool g.QuietSimulators = func(context.Context) { saw = append(saw, exists(filepath.Join(temp, "new"))) time.Sleep(300 * time.Millisecond) } res, _ := run(g, dir, "checks-t-8", time.Minute, `touch `+quote(filepath.Join(temp, "new"))) if len(saw) != 1 || !saw[0] || exists(filepath.Join(temp, "new")) || res.Code != 0 || res.Reason != "" || !res.Terminated { t.Fatalf("quieted %v before cleaning, result %+v", saw, res) } } // The cleanup is on record before anything of an attempt starts: a // runner killed mid-run leaves it to the next gate (any process), which // first proves that attempt over, then cleans T, then runs. Not proven, // unreadable or unrecordable: nothing runs. func TestGatePendingCleanupSurvivesTheRunner(t *testing.T) { g, dir := gateFixture(t, true) _, temp := userTempFixture(t) tempTree(t, temp) lock := filepath.Join(t.TempDir(), "lock") g.UserTemp, g.Turns, g.Settle = temp, NewTurns(lock), 500*time.Millisecond // The killed runner's attempt: its record, then what it left. s, err := openTemp(temp, nil) if err != nil { t.Fatal(err) } if err := g.Turns.writePending(pendingRecord{Attempt: "checks-dead", Before: s.before}); err != nil { t.Fatal(err) } s.close() if err := os.WriteFile(filepath.Join(temp, "leftover"), nil, 0600); err != nil { t.Fatal(err) } // Still running (a process with its marker): nothing runs, nothing goes. g.procs = withPhantom("checks-dead") ran := filepath.Join(t.TempDir(), "ran") if res, _ := run(g, dir, "checks-p-1", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) || !exists(filepath.Join(temp, "leftover")) { t.Fatalf("ran beside an unproven attempt: %+v", res) } // Over: its leftovers go before the next gate runs, and the record. g.procs = nil quieted := 0 g.QuietSimulators = func(context.Context) { quieted++ } res, _ := run(g, dir, "checks-p-2", time.Minute, `ls `+quote(temp)) if res.Code != 0 || strings.Contains(res.Output, "leftover") || exists(filepath.Join(temp, "leftover")) || exists(g.Turns.pending()) || quieted != 2 { t.Fatalf("pending cleanup not finished first (quieted %d): %+v", quieted, res) } // A record that cannot be read, or written: nothing runs. if err := os.WriteFile(g.Turns.pending(), []byte("{"), 0600); err != nil { t.Fatal(err) } if res, _ := run(g, dir, "checks-p-3", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) || !g.Turns.Pending() { t.Fatalf("ran past an unreadable record: %+v", res) } if err := os.Remove(g.Turns.pending()); err != nil { t.Fatal(err) } if err := os.Mkdir(g.Turns.pending()+".new", 0700); err != nil { t.Fatal(err) } if res, _ := run(g, dir, "checks-p-4", time.Minute, `touch `+quote(ran)); res.Reason != "checks_unavailable" || exists(ran) { t.Fatalf("ran without its cleanup on record: %+v", res) } }