package mac import ( "context" "encoding/json" "errors" "net" "os" "path/filepath" "slices" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/wire" ) // fakeXcodebuild plays xcodebuild for the fixture: it really reads the // targets file the probe wrote, prints the report lines a scenario // gives (the plugin's while the test target builds), and with // FAKE_CONNECT connects to the test's loopback port while saying // "denied" (the probe's listener must catch the lie). FAKE_NOISE prints // what a real build does: far more than the gate's last 200 lines. // FAKE_*_FAIL fails a step the way it fails on a Mac. A call that would // write Xcode's derived data, package checkouts or package caches // anywhere but the gate's TMPDIR fails as the Studio's P2 did under srt // (exit 65, the PIF cache's "workspace" folder not writable); an action // without its result bundle there fails as the default bundle in // DARWIN_USER_TEMP_DIR did, and a resolve whose SwiftPM config folder // ($XDG_CONFIG_HOME, else ~/.swiftpm) is not in TMPDIR as ~/.swiftpm // did (exit 74). const fakeXcodebuild = `#!/bin/bash [ -n "$FAKE_HANG" ] && { trap '' TERM; exec sleep 600; } noise() { [ -n "$FAKE_NOISE" ] && for i in $(seq 1 300); do echo "CompileSwift normal arm64 step $i"; done; true; } for f in -derivedDataPath -clonedSourcePackagesDirPath -packageCachePath; do case " $* " in *" $f $TMPDIR/"*) ;; *) echo "error: Could not compute dependency graph: Error Domain=NSCocoaErrorDomain Code=513 (no permission to save in the folder workspace; $f not in TMPDIR)"; echo "** BUILD FAILED **"; exit 65 ;; esac done case " $* " in *" -list "*|*" -resultBundlePath $TMPDIR/Results/"*) ;; *) echo "xcodebuild[1] Error saving log: Error Domain=NSCocoaErrorDomain Code=513 (ResultBundle in DARWIN_USER_TEMP_DIR: Operation not permitted)"; echo "** BUILD FAILED **"; exit 65 ;; esac case "$*" in *-resolvePackageDependencies*) case "$XDG_CONFIG_HOME" in "$TMPDIR"/*) ;; *) echo "xcodebuild: error: Could not resolve package dependencies:"; echo " .swiftpm/security: Operation not permitted"; exit 74 ;; esac ;; esac case "$*" in *-list*) echo " Schemes:"; echo " Hostile-Package"; exit 0 ;; *HostileScript*) [ -r ../equipo-targets.txt ] || { echo "no targets"; exit 3; } case "$TMPDIR" in "$FAKE_DIR"/scratch/*) ;; *) echo "error: unable to create directory $TMPDIR/sym (Permission denied)"; echo "** BUILD FAILED **"; exit 65 ;; esac [ -n "$FAKE_BUILD_FAIL" ] && { echo "Sandbox: deny(1) mach-lookup com.apple.dt.example"; echo "** BUILD FAILED **"; exit 65; } [ -n "$FAKE_LINES_THEN_FAIL" ] && { cat "$FAKE_DIR/script.out"; echo "** BUILD FAILED **"; exit 65; } cat "$FAKE_DIR/script.out"; noise; echo "** BUILD SUCCEEDED **"; exit 0 ;; *-resolvePackageDependencies*) [ -n "$FAKE_RESOLVE_FAIL" ] && { echo "xcodebuild: error: Could not resolve package dependencies:"; echo " sandbox-exec: sandbox_apply: Operation not permitted"; exit 74; } echo "resolved source packages:"; exit 0 ;; *build-for-testing*) [ -n "$FAKE_TEST_BUILD_FAIL" ] && { printf '%s\n' "$FAKE_TEST_BUILD_FAIL"; echo "** TEST BUILD FAILED **"; exit 65; } cat "$FAKE_DIR/plugin.out"; noise; echo "** TEST BUILD SUCCEEDED **"; exit 0 ;; *testHostile*) case "$*" in *test-without-building*"platform=iOS Simulator,id="*) ;; *) echo "testHostile not on an iOS simulator"; exit 70 ;; esac [ -n "$FAKE_RUN_FAIL" ] && { echo "xcodebuild: error: Failed to establish communication with the test runner."; echo "** TEST EXECUTE FAILED **"; exit 65; } t=../equipo-targets.txt if [ -n "$FAKE_READ_STATE" ] && cat "$(sed -n 's/^state=//p' $t)" >/dev/null 2>&1; then echo "EQUIPO-PROBE test state allowed"; fi if [ -n "$FAKE_READ_TOKEN" ] && [ "$(cat "$(sed -n 's/^token_file=//p' $t)")" = "$(sed -n 's/^token=//p' $t)" ]; then echo "EQUIPO-PROBE test tokenfile allowed"; fi if [ -n "$FAKE_CONNECT" ]; then exec 3<>"/dev/tcp/127.0.0.1/$(sed -n 's/^port_test=//p' $t)"; fi cat "$FAKE_DIR/test.out"; noise; echo "** TEST EXECUTE SUCCEEDED **"; exit 0 ;; *testWait*) echo "EQUIPO-PROBE wait started"; exec sleep 600 ;; esac exit 64 ` // fakeXcrun plays xcrun simctl bootstatus for P2's simulator boot. const fakeXcrun = `#!/bin/bash [ "$1 $2 $4" = "simctl bootstatus -b" ] || exit 64 [ -n "$FAKE_BOOT_FAIL" ] && { echo "An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405):"; echo "Unable to boot device: error: launchd_sim failed"; exit 149; } echo "Device already booted, nothing to do." ` func allLines(result string) map[string]string { out := map[string]string{} for _, place := range []string{"script", "plugin", "test"} { var b strings.Builder for _, what := range []string{"state", "home", "tcp", "dns", "keychain", "tokenfile", "tokenlink", "tokenenv", "tokenargs", "tokenlaunchd", "tokenfd"} { b.WriteString("warning: EQUIPO-PROBE " + place + " " + what + " " + result + "\n") } out[place] = b.String() } return out } type probeFixture struct { h ProbeHost dir string execLog []string } func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *probeFixture { t.Helper() root := t.TempDir() f := &probeFixture{dir: root} xb := filepath.Join(root, "xcodebuild") srt := filepath.Join(root, "srt") xcrun := filepath.Join(root, "xcrun") for p, body := range map[string]string{xb: fakeXcodebuild, srt: fakeSRT, xcrun: fakeXcrun} { if err := os.WriteFile(p, []byte(body), 0700); err != nil { t.Fatal(err) } } // The script and plugin places print through the build log: the // script's in the project's build, the plugin's in the test build. for name, place := range map[string]string{"script.out": "script", "plugin.out": "plugin", "test.out": "test"} { if err := os.WriteFile(filepath.Join(root, name), []byte(lines[place]), 0600); err != nil { t.Fatal(err) } } state := filepath.Join(root, "state") if err := os.MkdirAll(state, 0700); err != nil { t.Fatal(err) } pm := "Battery Power:\n sleep 1\nAC Power:\n Sleep On Power Button 1\n sleep 0\n displaysleep 10\n" execs := map[string]string{ xb + " -version": "Xcode 16.2\nBuild version 16C5032a\n", "/usr/sbin/scutil --get ComputerName": "Tito Studio\n", "node --version": "v22.12.0\n", "rg --version": "ripgrep 14.1.1\n", srt + " --version": "0.0.81\n", "/usr/bin/pmset -g custom": pm, "/bin/ps -x -o comm=": "/bin/zsh\n", "/bin/launchctl print gui/501/io.amadan.equipo-runner": "gui/501/io.amadan.equipo-runner = {\n", } sims, _ := os.ReadFile("testdata/simctl-devices.json") exec := func(ctx context.Context, name string, args ...string) (string, error) { key := strings.Join(append([]string{name}, args...), " ") f.execLog = append(f.execLog, key) switch { case key == xcrun+" simctl list -j devices available": return string(sims), nil case strings.HasPrefix(key, "/usr/bin/security "): return "", nil case strings.HasPrefix(key, srt+" --settings "): return "", nil } if out, ok := execs[key]; ok { return out, nil } return "", errors.New("not recorded: " + key) } base := []string{"PATH=/usr/bin:/bin", "HOME=" + root, "FAKE_DIR=" + root, "FAKE_SRT_SEEN=" + filepath.Join(root, "seen.json")} f.h = ProbeHost{Exec: exec, Tools: Tools{Xcodebuild: xb, Xcrun: xcrun, Node: "node", SRT: srt, RG: "rg"}, Paths: Paths{Home: root, StateDir: state, AccountsRoot: filepath.Join(root, "accounts"), OtherHomes: []string{"/Users/Shared", "/Users/paul"}, UserTemp: "/private/var/folders/4m/abc123_def/T"}, Scratch: filepath.Join(root, "scratch"), UID: 501, Version: "abc1234", Gate: func(sandboxed bool) *Gate { g := &Gate{Env: append(append([]string{}, base...), env...), Grace: 300 * time.Millisecond, Settle: 5 * time.Second, Lines: 200, Sandbox: wire.SandboxNone} if sandboxed { g.SRT, g.Sandbox = srt, wire.SandboxSeatbelt g.Settings = func(tree, attempt string) ([]byte, error) { return []byte("{}"), nil } } return g }, Resolve: func(context.Context, string) bool { return true }, Exposed: func(string) bool { return false }, Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }, Wait: 30 * time.Second, } return f } // The whole probe run against a fake Mac whose fixture reports every // attempt denied: P2 denied, the report valid as a capability report. func TestRunProbesAllDenied(t *testing.T) { f := newProbeFixture(t, allLines("denied")) r := RunProbes(context.Background(), f.h) if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil { t.Fatalf("report outside the capability rules: %v %+v", err, r.Probes) } var ids []string for _, p := range r.Probes { ids = append(ids, p.ID) } if !slices.Equal(ids, wire.ProbeIDs) { t.Fatalf("probes %v", ids) } if !r.Sandboxed() || !r.SRTRanXcode || r.Version != "abc1234" || r.Profile != ProfileDigest() { t.Fatalf("P2 %+v srt=%v", r.Probe("P2"), r.SRTRanXcode) } if p := r.Probe("P2"); p.Detail != "unix_only:script.home plugin.home test.home;srt_ran_xcode" { t.Fatalf("P2 detail %q", p.Detail) } for id, want := range map[string]string{"P1": wire.ProbePassed, "P3": wire.ProbeSkipped, "P4": wire.ProbePassed, "P5": wire.ProbeSkipped, "P6": wire.ProbePassed, "P7": wire.ProbePassed} { if p := r.Probe(id); p.Verdict != want { t.Fatalf("%s %+v", id, p) } } if r.Probe("P1").Detail != "xcode:16.2,16C5032a;ios_simulators:5;computer:Tito Studio" || !strings.Contains(r.Probe("P6").Detail, "marked_left:0") || !strings.Contains(r.Probe("P6").Detail, "tree_removed") { t.Fatalf("details %+v", r.Probes) } // The sentinel and the Keychain item are gone, the copies too. if left, _ := filepath.Glob(filepath.Join(f.h.Paths.StateDir, "probe-sentinel-*")); len(left) != 0 { t.Fatalf("sentinel left %v", left) } if left, _ := filepath.Glob(filepath.Join(f.h.Scratch, "*")); len(left) != 0 { t.Fatalf("scratch left %v", left) } added, deleted := false, false for _, l := range f.execLog { added = added || strings.HasPrefix(l, "/usr/bin/security add-generic-password -a equipo-probe -s io.amadan.equipo.probe.") && strings.HasSuffix(l, " -A -U") deleted = deleted || strings.HasPrefix(l, "/usr/bin/security delete-generic-password -a equipo-probe -s io.amadan.equipo.probe.") } if !added || !deleted { t.Fatalf("keychain sentinel not added and removed: %v", f.execLog) } raw, _ := json.Marshal(r) if strings.Contains(string(raw), f.h.Paths.StateDir) || strings.Contains(string(raw), "/Users/") { t.Fatalf("a path left the machine: %s", raw) } } // Anything short of every attempt denied is not P2's pass: an attempt // that got through (here the fixture really reads the sentinel, outside // any sandbox), a lie the loopback listener catches, a missing line, a // DNS control that failed outside, a fixture that did not build. func TestP2IsDeniedOnlyWhenEverythingIs(t *testing.T) { f := newProbeFixture(t, allLines("denied"), "FAKE_READ_STATE=1") if p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "allowed:test.state") { t.Fatalf("sentinel read: %+v", p) } f = newProbeFixture(t, allLines("denied"), "FAKE_CONNECT=1") if p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "allowed:test.tcp") { t.Fatalf("connection behind a denied line: %+v", p) } lines := allLines("denied") lines["plugin"] = strings.Replace(lines["plugin"], "warning: EQUIPO-PROBE plugin keychain denied\n", "", 1) f = newProbeFixture(t, lines) if p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "not_shown_denied:plugin.keychain") { t.Fatalf("missing line: %+v", p) } f = newProbeFixture(t, allLines("denied")) f.h.Resolve = func(context.Context, string) bool { return false } if p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeFailed { t.Fatalf("DNS control failed outside: %+v", p) } f = newProbeFixture(t, allLines("denied"), "FAKE_BUILD_FAIL=1") if p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); ran || p.Verdict != wire.ProbeFailed || !strings.HasSuffix(p.Detail, "srt_failed:script build exit 65") { t.Fatalf("the fixture did not build under srt: %+v ran=%v", p, ran) } f = newProbeFixture(t, allLines("denied")) f.h.Tools.SRT = "" if p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeUnavailable || ran { t.Fatalf("no srt: %+v", p) } } func TestJudgeP2(t *testing.T) { got := ParseAttempts(allLines("denied")["script"] + allLines("denied")["plugin"] + allLines("denied")["test"] + "EQUIPO-PROBE test dns allowed\n") if got["test.dns"] != "denied" || len(got) != 33 { t.Fatalf("the first line for an attempt counts: %v", got) } facts := P2Facts{Home: true, DNS: true, Keychain: true, Token: true, Accepted: map[string]bool{}} if v, g := JudgeP2(got, facts); v != wire.ProbeDenied || len(g) != 0 { t.Fatalf("%s %v", v, g) } facts.Keychain = false if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 3 { t.Fatalf("keychain control: %s %v", v, g) } facts = P2Facts{Home: false, DNS: true, Keychain: true, Token: true, Accepted: map[string]bool{"plugin": true}} if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || !slices.Equal(g["allowed"], []string{"plugin.tcp"}) { t.Fatalf("accepted: %s %v", v, g) } } func TestACSleepAndNode(t *testing.T) { if n, ok := ACSleep("Battery Power:\n sleep 1\nAC Power:\n sleep 0\n"); !ok || n != 0 { t.Fatal("AC sleep 0") } if n, ok := ACSleep("AC Power:\n sleep 30\n"); !ok || n != 30 { t.Fatal("AC sleep 30") } if _, ok := ACSleep("Battery Power:\n sleep 1\n"); ok { t.Fatal("battery taken for AC") } if n, ok := ACSleep(" standby 0\n sleep 0 (sleep prevented by powerd)\n"); !ok || n != 0 { t.Fatal("a desktop Mac's one set of settings") } for v, want := range map[string]bool{"v22.12.0": true, "v24.1.0": true, "v22.11.9": false, "v20.18.0": false, "22.12.0": false} { if NodeSupported(v) != want { t.Fatalf("%s", v) } } } // What P4 finds: a readable home, the agent not loaded, the Mac that // sleeps are each a failed P4, said in words without a path. func TestP4(t *testing.T) { f := newProbeFixture(t, nil) f.h.Exposed = func(p string) bool { return p == "/Users/paul" } p := probeP4(context.Background(), f.h) if p.Verdict != wire.ProbeFailed || p.Detail != "homes_readable:paul;agent_loaded;sleep_off" { t.Fatalf("%+v", p) } f.h.Paths.HomesUnknown = true if p := probeP4(context.Background(), f.h); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "homes_unchecked") { t.Fatalf("unknown homes: %+v", p) } } // The fixture ships whole: what P2 and P6 run is in the binary. func TestFixtureShips(t *testing.T) { root, err := CopyFixture(t.TempDir()) if err != nil { t.Fatal(err) } for _, f := range []string{"package/Package.swift", "package/Plugins/HostilePlugin/HostilePlugin.swift", "package/Tests/HostileTests/HostileTests.swift", "project/Hostile.xcodeproj/project.pbxproj", "project/hostile.sh"} { raw, err := os.ReadFile(filepath.Join(root, f)) if err != nil || len(raw) == 0 { t.Fatalf("%s: %v", f, err) } } pbx, _ := os.ReadFile(filepath.Join(root, "project/Hostile.xcodeproj/project.pbxproj")) if strings.Count(string(pbx), "ENABLE_USER_SCRIPT_SANDBOXING = NO;") != 2 { t.Fatal("the script phase must turn Xcode's own script sandbox off, as a hostile repository would") } tests, _ := os.ReadFile(filepath.Join(root, "package/Tests/HostileTests/HostileTests.swift")) wait := string(tests[strings.Index(string(tests), "func testWait"):]) if strings.Contains(wait, "Thread.sleep") || !strings.Contains(wait, "write(to:") || !strings.Contains(string(tests), "keychain_file") { t.Fatal("P6's test must work while it is killed, and P2's must try the host keychain file from the simulator") } if info, _ := os.Stat(filepath.Join(root, "project/hostile.sh")); info.Mode().Perm() != 0700 { t.Fatal("hostile.sh not executable") } for _, f := range []string{"package/Plugins/HostilePlugin/HostilePlugin.swift", "package/Tests/HostileTests/HostileTests.swift", "project/hostile.sh"} { raw, _ := os.ReadFile(filepath.Join(root, f)) for _, what := range []string{"state", "home", "tcp", "dns", "keychain"} { if !strings.Contains(string(raw), what) { t.Fatalf("%s does not try %s", f, what) } } } } // P2 runs its hostile test on an iOS simulator, as checks do (the fake // xcodebuild fails it anywhere else), and is denied only for a run whose // end was proven: a marked process left makes it failed, whatever the // lines say. Without an iOS simulator P2 cannot say. func TestP2NeedsTheSimulatorAndAProvenEnd(t *testing.T) { f := newProbeFixture(t, allLines("denied")) caps := Capabilities(context.Background(), f.h.Exec, f.h.Tools) if p, ran, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeDenied || !ran { t.Fatalf("on the simulator: %+v", p) } gate := f.h.Gate f.h.Gate = func(sandboxed bool) *Gate { g := gate(sandboxed) g.Settle = 300 * time.Millisecond g.procs = withPhantom() return g } if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "end_unproven") { t.Fatalf("end not proven: %+v", p) } f.h.Gate = gate // Every line says denied, but the hostile build did not complete: // not a pass. f = newProbeFixture(t, allLines("denied"), "FAKE_LINES_THEN_FAIL=1") if p, ran, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || ran { t.Fatalf("incomplete run: %+v", p) } caps.Simulators = nil if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeUnavailable || p.Detail != "no_simulator" { t.Fatalf("no simulator: %+v", p) } } // A wait nothing else bounds (a command that ignores its context) ends // at the run's limit: the report has every probe, the ones not finished // not proven and listed, and stays a valid capability report. func TestRunProbesLimit(t *testing.T) { stuck := make(chan struct{}) t.Cleanup(func() { close(stuck) }) h := ProbeHost{Version: "abc1234", UID: 501, Paths: Paths{HomesUnknown: true}, Exposed: func(string) bool { return false }, Limit: 300 * time.Millisecond, Exec: func(ctx context.Context, name string, args ...string) (string, error) { if name == "/bin/launchctl" { <-stuck } return "", errors.New("not recorded") }} got := make(chan Report, 1) go func() { got <- RunProbes(context.Background(), h) }() var r Report select { case r = <-got: case <-time.After(5 * time.Second): t.Fatal("the probe run outlived its limit") } if !slices.Equal(r.Unfinished, []string{"P4", "P5", "P6", "P7"}) { t.Fatalf("unfinished %v %+v", r.Unfinished, r.Probes) } for _, id := range r.Unfinished { if p := r.Probe(id); p.Verdict != wire.ProbeUnavailable || p.Detail != "probe_limit:300ms" { t.Fatalf("%s %+v", id, p) } } if p := r.Probe("P1"); p.Verdict != wire.ProbeFailed { t.Fatalf("P1 finished before the limit: %+v", p) } if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil { t.Fatalf("report outside the capability rules: %v", err) } } // #1: a probe run that reaches its limit reports at once, but keeps the // Mac's turn until its gates have stopped (here one that ignores SIGTERM // for its grace): nothing else takes the turn meanwhile, and it is free // once they have. func TestProbeLimitHoldsTheTurnUntilItsGateEnds(t *testing.T) { f := newProbeFixture(t, allLines("denied"), "FAKE_HANG=1") turns := NewTurns(filepath.Join(t.TempDir(), "lock")) inner := f.h.Gate f.h.Gate = func(sandboxed bool) *Gate { g := inner(sandboxed); g.Grace = 900 * time.Millisecond; return g } f.h.Turns, f.h.Limit = turns, 400*time.Millisecond done := make(chan Report, 1) go func() { done <- RunProbes(context.Background(), f.h) }() select { case <-done: case <-time.After(5 * time.Second): t.Fatal("no report at the run's limit") } time.Sleep(200 * time.Millisecond) if u, ok := turns.TryTake(OpCheck); ok { u.Give() t.Fatal("another operation took the turn while the probe's gate was still stopping") } for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(50 * time.Millisecond) { if u, ok := turns.TryTake(OpCheck); ok { u.Give() return } if time.Now().After(deadline) { t.Fatal("the turn was never given back") } } } // #11: a probe run that cannot take the Mac's turn says so by a code // the instance words, not by English of its own. func TestRunProbesWithoutTheTurn(t *testing.T) { f := newProbeFixture(t, allLines("denied")) turns := NewTurns("") held, err := turns.Take(context.Background(), OpEngineering) if err != nil { t.Fatal(err) } defer held.Give() f.h.Turns, f.h.Limit = turns, 200*time.Millisecond rep := RunProbes(context.Background(), f.h) for _, p := range rep.Probes { if p.Verdict != wire.ProbeUnavailable || p.Detail != wire.ProbeDetailTurnBusy { t.Fatalf("%+v", p) } } }