| 1 | package mac |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "net" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "slices" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | "time" |
| 14 | |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | ) |
| 17 | |
| 18 | // fakeXcodebuild plays xcodebuild for the fixture: it really reads the |
| 19 | // targets file the probe wrote, prints the report lines a scenario |
| 20 | // gives (the plugin's while the test target builds), and with |
| 21 | // FAKE_CONNECT connects to the test's loopback port while saying |
| 22 | // "denied" (the probe's listener must catch the lie). FAKE_NOISE prints |
| 23 | // what a real build does: far more than the gate's last 200 lines. |
| 24 | // FAKE_*_FAIL fails a step the way it fails on a Mac. A call that would |
| 25 | // write Xcode's derived data, package checkouts or package caches |
| 26 | // anywhere but the gate's TMPDIR fails as the Studio's P2 did under srt |
| 27 | // (exit 65, the PIF cache's "workspace" folder not writable); an action |
| 28 | // without its result bundle there fails as the default bundle in |
| 29 | // DARWIN_USER_TEMP_DIR did, and a resolve whose SwiftPM config folder |
| 30 | // ($XDG_CONFIG_HOME, else ~/.swiftpm) is not in TMPDIR as ~/.swiftpm |
| 31 | // did (exit 74). |
| 32 | const fakeXcodebuild = `#!/bin/bash |
| 33 | [ -n "$FAKE_HANG" ] && { trap '' TERM; exec sleep 600; } |
| 34 | noise() { [ -n "$FAKE_NOISE" ] && for i in $(seq 1 300); do echo "CompileSwift normal arm64 step $i"; done; true; } |
| 35 | for f in -derivedDataPath -clonedSourcePackagesDirPath -packageCachePath; do |
| 36 | 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 |
| 37 | done |
| 38 | 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 |
| 39 | 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 |
| 40 | case "$*" in |
| 41 | *-list*) echo " Schemes:"; echo " Hostile-Package"; exit 0 ;; |
| 42 | *HostileScript*) |
| 43 | [ -r ../equipo-targets.txt ] || { echo "no targets"; exit 3; } |
| 44 | case "$TMPDIR" in "$FAKE_DIR"/scratch/*) ;; *) echo "error: unable to create directory $TMPDIR/sym (Permission denied)"; echo "** BUILD FAILED **"; exit 65 ;; esac |
| 45 | [ -n "$FAKE_BUILD_FAIL" ] && { echo "Sandbox: deny(1) mach-lookup com.apple.dt.example"; echo "** BUILD FAILED **"; exit 65; } |
| 46 | [ -n "$FAKE_LINES_THEN_FAIL" ] && { cat "$FAKE_DIR/script.out"; echo "** BUILD FAILED **"; exit 65; } |
| 47 | cat "$FAKE_DIR/script.out"; noise; echo "** BUILD SUCCEEDED **"; exit 0 ;; |
| 48 | *-resolvePackageDependencies*) |
| 49 | [ -n "$FAKE_RESOLVE_FAIL" ] && { echo "xcodebuild: error: Could not resolve package dependencies:"; echo " sandbox-exec: sandbox_apply: Operation not permitted"; exit 74; } |
| 50 | echo "resolved source packages:"; exit 0 ;; |
| 51 | *build-for-testing*) |
| 52 | [ -n "$FAKE_TEST_BUILD_FAIL" ] && { printf '%s\n' "$FAKE_TEST_BUILD_FAIL"; echo "** TEST BUILD FAILED **"; exit 65; } |
| 53 | cat "$FAKE_DIR/plugin.out"; noise; echo "** TEST BUILD SUCCEEDED **"; exit 0 ;; |
| 54 | *testHostile*) |
| 55 | case "$*" in *test-without-building*"platform=iOS Simulator,id="*) ;; *) echo "testHostile not on an iOS simulator"; exit 70 ;; esac |
| 56 | [ -n "$FAKE_RUN_FAIL" ] && { echo "xcodebuild: error: Failed to establish communication with the test runner."; echo "** TEST EXECUTE FAILED **"; exit 65; } |
| 57 | t=../equipo-targets.txt |
| 58 | if [ -n "$FAKE_READ_STATE" ] && cat "$(sed -n 's/^state=//p' $t)" >/dev/null 2>&1; then echo "EQUIPO-PROBE test state allowed"; fi |
| 59 | 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 |
| 60 | if [ -n "$FAKE_CONNECT" ]; then exec 3<>"/dev/tcp/127.0.0.1/$(sed -n 's/^port_test=//p' $t)"; fi |
| 61 | cat "$FAKE_DIR/test.out"; noise; echo "** TEST EXECUTE SUCCEEDED **"; exit 0 ;; |
| 62 | *testWait*) echo "EQUIPO-PROBE wait started"; exec sleep 600 ;; |
| 63 | esac |
| 64 | exit 64 |
| 65 | ` |
| 66 | |
| 67 | // fakeXcrun plays xcrun simctl bootstatus for P2's simulator boot. |
| 68 | const fakeXcrun = `#!/bin/bash |
| 69 | [ "$1 $2 $4" = "simctl bootstatus -b" ] || exit 64 |
| 70 | [ -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; } |
| 71 | echo "Device already booted, nothing to do." |
| 72 | ` |
| 73 | |
| 74 | func allLines(result string) map[string]string { |
| 75 | out := map[string]string{} |
| 76 | for _, place := range []string{"script", "plugin", "test"} { |
| 77 | var b strings.Builder |
| 78 | for _, what := range []string{"state", "home", "tcp", "dns", "keychain", "tokenfile", "tokenlink", "tokenenv", "tokenargs", "tokenlaunchd", "tokenfd"} { |
| 79 | b.WriteString("warning: EQUIPO-PROBE " + place + " " + what + " " + result + "\n") |
| 80 | } |
| 81 | out[place] = b.String() |
| 82 | } |
| 83 | return out |
| 84 | } |
| 85 | |
| 86 | type probeFixture struct { |
| 87 | h ProbeHost |
| 88 | dir string |
| 89 | execLog []string |
| 90 | } |
| 91 | |
| 92 | func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *probeFixture { |
| 93 | t.Helper() |
| 94 | root := t.TempDir() |
| 95 | f := &probeFixture{dir: root} |
| 96 | xb := filepath.Join(root, "xcodebuild") |
| 97 | srt := filepath.Join(root, "srt") |
| 98 | xcrun := filepath.Join(root, "xcrun") |
| 99 | for p, body := range map[string]string{xb: fakeXcodebuild, srt: fakeSRT, xcrun: fakeXcrun} { |
| 100 | if err := os.WriteFile(p, []byte(body), 0700); err != nil { |
| 101 | t.Fatal(err) |
| 102 | } |
| 103 | } |
| 104 | // The script and plugin places print through the build log: the |
| 105 | // script's in the project's build, the plugin's in the test build. |
| 106 | for name, place := range map[string]string{"script.out": "script", "plugin.out": "plugin", "test.out": "test"} { |
| 107 | if err := os.WriteFile(filepath.Join(root, name), []byte(lines[place]), 0600); err != nil { |
| 108 | t.Fatal(err) |
| 109 | } |
| 110 | } |
| 111 | state := filepath.Join(root, "state") |
| 112 | if err := os.MkdirAll(state, 0700); err != nil { |
| 113 | t.Fatal(err) |
| 114 | } |
| 115 | pm := "Battery Power:\n sleep 1\nAC Power:\n Sleep On Power Button 1\n sleep 0\n displaysleep 10\n" |
| 116 | execs := map[string]string{ |
| 117 | xb + " -version": "Xcode 16.2\nBuild version 16C5032a\n", "/usr/sbin/scutil --get ComputerName": "Tito Studio\n", |
| 118 | "node --version": "v22.12.0\n", "rg --version": "ripgrep 14.1.1\n", srt + " --version": "0.0.81\n", |
| 119 | "/usr/bin/pmset -g custom": pm, "/bin/ps -x -o comm=": "/bin/zsh\n", |
| 120 | "/bin/launchctl print gui/501/io.amadan.equipo-runner": "gui/501/io.amadan.equipo-runner = {\n", |
| 121 | } |
| 122 | sims, _ := os.ReadFile("testdata/simctl-devices.json") |
| 123 | exec := func(ctx context.Context, name string, args ...string) (string, error) { |
| 124 | key := strings.Join(append([]string{name}, args...), " ") |
| 125 | f.execLog = append(f.execLog, key) |
| 126 | switch { |
| 127 | case key == xcrun+" simctl list -j devices available": |
| 128 | return string(sims), nil |
| 129 | case strings.HasPrefix(key, "/usr/bin/security "): |
| 130 | return "", nil |
| 131 | case strings.HasPrefix(key, srt+" --settings "): |
| 132 | return "", nil |
| 133 | } |
| 134 | if out, ok := execs[key]; ok { |
| 135 | return out, nil |
| 136 | } |
| 137 | return "", errors.New("not recorded: " + key) |
| 138 | } |
| 139 | base := []string{"PATH=/usr/bin:/bin", "HOME=" + root, "FAKE_DIR=" + root, "FAKE_SRT_SEEN=" + filepath.Join(root, "seen.json")} |
| 140 | f.h = ProbeHost{Exec: exec, Tools: Tools{Xcodebuild: xb, Xcrun: xcrun, Node: "node", SRT: srt, RG: "rg"}, |
| 141 | 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"}, |
| 142 | Scratch: filepath.Join(root, "scratch"), UID: 501, Version: "abc1234", |
| 143 | Gate: func(sandboxed bool) *Gate { |
| 144 | g := &Gate{Env: append(append([]string{}, base...), env...), Grace: 300 * time.Millisecond, Settle: 5 * time.Second, Lines: 200, Sandbox: wire.SandboxNone} |
| 145 | if sandboxed { |
| 146 | g.SRT, g.Sandbox = srt, wire.SandboxSeatbelt |
| 147 | g.Settings = func(tree, attempt string) ([]byte, error) { return []byte("{}"), nil } |
| 148 | } |
| 149 | return g |
| 150 | }, |
| 151 | Resolve: func(context.Context, string) bool { return true }, |
| 152 | Exposed: func(string) bool { return false }, |
| 153 | Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }, |
| 154 | Wait: 30 * time.Second, |
| 155 | } |
| 156 | return f |
| 157 | } |
| 158 | |
| 159 | // The whole probe run against a fake Mac whose fixture reports every |
| 160 | // attempt denied: P2 denied, the report valid as a capability report. |
| 161 | func TestRunProbesAllDenied(t *testing.T) { |
| 162 | f := newProbeFixture(t, allLines("denied")) |
| 163 | r := RunProbes(context.Background(), f.h) |
| 164 | if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil { |
| 165 | t.Fatalf("report outside the capability rules: %v %+v", err, r.Probes) |
| 166 | } |
| 167 | var ids []string |
| 168 | for _, p := range r.Probes { |
| 169 | ids = append(ids, p.ID) |
| 170 | } |
| 171 | if !slices.Equal(ids, wire.ProbeIDs) { |
| 172 | t.Fatalf("probes %v", ids) |
| 173 | } |
| 174 | if !r.Sandboxed() || !r.SRTRanXcode || r.Version != "abc1234" || r.Profile != ProfileDigest() { |
| 175 | t.Fatalf("P2 %+v srt=%v", r.Probe("P2"), r.SRTRanXcode) |
| 176 | } |
| 177 | if p := r.Probe("P2"); p.Detail != "unix_only:script.home plugin.home test.home;srt_ran_xcode" { |
| 178 | t.Fatalf("P2 detail %q", p.Detail) |
| 179 | } |
| 180 | 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} { |
| 181 | if p := r.Probe(id); p.Verdict != want { |
| 182 | t.Fatalf("%s %+v", id, p) |
| 183 | } |
| 184 | } |
| 185 | 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") { |
| 186 | t.Fatalf("details %+v", r.Probes) |
| 187 | } |
| 188 | // The sentinel and the Keychain item are gone, the copies too. |
| 189 | if left, _ := filepath.Glob(filepath.Join(f.h.Paths.StateDir, "probe-sentinel-*")); len(left) != 0 { |
| 190 | t.Fatalf("sentinel left %v", left) |
| 191 | } |
| 192 | if left, _ := filepath.Glob(filepath.Join(f.h.Scratch, "*")); len(left) != 0 { |
| 193 | t.Fatalf("scratch left %v", left) |
| 194 | } |
| 195 | added, deleted := false, false |
| 196 | for _, l := range f.execLog { |
| 197 | added = added || strings.HasPrefix(l, "/usr/bin/security add-generic-password -a equipo-probe -s io.amadan.equipo.probe.") && strings.HasSuffix(l, " -A -U") |
| 198 | deleted = deleted || strings.HasPrefix(l, "/usr/bin/security delete-generic-password -a equipo-probe -s io.amadan.equipo.probe.") |
| 199 | } |
| 200 | if !added || !deleted { |
| 201 | t.Fatalf("keychain sentinel not added and removed: %v", f.execLog) |
| 202 | } |
| 203 | raw, _ := json.Marshal(r) |
| 204 | if strings.Contains(string(raw), f.h.Paths.StateDir) || strings.Contains(string(raw), "/Users/") { |
| 205 | t.Fatalf("a path left the machine: %s", raw) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | // Anything short of every attempt denied is not P2's pass: an attempt |
| 210 | // that got through (here the fixture really reads the sentinel, outside |
| 211 | // any sandbox), a lie the loopback listener catches, a missing line, a |
| 212 | // DNS control that failed outside, a fixture that did not build. |
| 213 | func TestP2IsDeniedOnlyWhenEverythingIs(t *testing.T) { |
| 214 | f := newProbeFixture(t, allLines("denied"), "FAKE_READ_STATE=1") |
| 215 | 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") { |
| 216 | t.Fatalf("sentinel read: %+v", p) |
| 217 | } |
| 218 | f = newProbeFixture(t, allLines("denied"), "FAKE_CONNECT=1") |
| 219 | 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") { |
| 220 | t.Fatalf("connection behind a denied line: %+v", p) |
| 221 | } |
| 222 | lines := allLines("denied") |
| 223 | lines["plugin"] = strings.Replace(lines["plugin"], "warning: EQUIPO-PROBE plugin keychain denied\n", "", 1) |
| 224 | f = newProbeFixture(t, lines) |
| 225 | 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") { |
| 226 | t.Fatalf("missing line: %+v", p) |
| 227 | } |
| 228 | f = newProbeFixture(t, allLines("denied")) |
| 229 | f.h.Resolve = func(context.Context, string) bool { return false } |
| 230 | if p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeFailed { |
| 231 | t.Fatalf("DNS control failed outside: %+v", p) |
| 232 | } |
| 233 | f = newProbeFixture(t, allLines("denied"), "FAKE_BUILD_FAIL=1") |
| 234 | 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") { |
| 235 | t.Fatalf("the fixture did not build under srt: %+v ran=%v", p, ran) |
| 236 | } |
| 237 | f = newProbeFixture(t, allLines("denied")) |
| 238 | f.h.Tools.SRT = "" |
| 239 | if p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeUnavailable || ran { |
| 240 | t.Fatalf("no srt: %+v", p) |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | func TestJudgeP2(t *testing.T) { |
| 245 | got := ParseAttempts(allLines("denied")["script"] + allLines("denied")["plugin"] + allLines("denied")["test"] + "EQUIPO-PROBE test dns allowed\n") |
| 246 | if got["test.dns"] != "denied" || len(got) != 33 { |
| 247 | t.Fatalf("the first line for an attempt counts: %v", got) |
| 248 | } |
| 249 | facts := P2Facts{Home: true, DNS: true, Keychain: true, Token: true, Accepted: map[string]bool{}} |
| 250 | if v, g := JudgeP2(got, facts); v != wire.ProbeDenied || len(g) != 0 { |
| 251 | t.Fatalf("%s %v", v, g) |
| 252 | } |
| 253 | facts.Keychain = false |
| 254 | if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 3 { |
| 255 | t.Fatalf("keychain control: %s %v", v, g) |
| 256 | } |
| 257 | facts = P2Facts{Home: false, DNS: true, Keychain: true, Token: true, Accepted: map[string]bool{"plugin": true}} |
| 258 | if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || !slices.Equal(g["allowed"], []string{"plugin.tcp"}) { |
| 259 | t.Fatalf("accepted: %s %v", v, g) |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | func TestACSleepAndNode(t *testing.T) { |
| 264 | if n, ok := ACSleep("Battery Power:\n sleep 1\nAC Power:\n sleep 0\n"); !ok || n != 0 { |
| 265 | t.Fatal("AC sleep 0") |
| 266 | } |
| 267 | if n, ok := ACSleep("AC Power:\n sleep 30\n"); !ok || n != 30 { |
| 268 | t.Fatal("AC sleep 30") |
| 269 | } |
| 270 | if _, ok := ACSleep("Battery Power:\n sleep 1\n"); ok { |
| 271 | t.Fatal("battery taken for AC") |
| 272 | } |
| 273 | if n, ok := ACSleep(" standby 0\n sleep 0 (sleep prevented by powerd)\n"); !ok || n != 0 { |
| 274 | t.Fatal("a desktop Mac's one set of settings") |
| 275 | } |
| 276 | 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} { |
| 277 | if NodeSupported(v) != want { |
| 278 | t.Fatalf("%s", v) |
| 279 | } |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | // What P4 finds: a readable home, the agent not loaded, the Mac that |
| 284 | // sleeps are each a failed P4, said in words without a path. |
| 285 | func TestP4(t *testing.T) { |
| 286 | f := newProbeFixture(t, nil) |
| 287 | f.h.Exposed = func(p string) bool { return p == "/Users/paul" } |
| 288 | p := probeP4(context.Background(), f.h) |
| 289 | if p.Verdict != wire.ProbeFailed || p.Detail != "homes_readable:paul;agent_loaded;sleep_off" { |
| 290 | t.Fatalf("%+v", p) |
| 291 | } |
| 292 | f.h.Paths.HomesUnknown = true |
| 293 | if p := probeP4(context.Background(), f.h); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "homes_unchecked") { |
| 294 | t.Fatalf("unknown homes: %+v", p) |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | // The fixture ships whole: what P2 and P6 run is in the binary. |
| 299 | func TestFixtureShips(t *testing.T) { |
| 300 | root, err := CopyFixture(t.TempDir()) |
| 301 | if err != nil { |
| 302 | t.Fatal(err) |
| 303 | } |
| 304 | 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"} { |
| 305 | raw, err := os.ReadFile(filepath.Join(root, f)) |
| 306 | if err != nil || len(raw) == 0 { |
| 307 | t.Fatalf("%s: %v", f, err) |
| 308 | } |
| 309 | } |
| 310 | pbx, _ := os.ReadFile(filepath.Join(root, "project/Hostile.xcodeproj/project.pbxproj")) |
| 311 | if strings.Count(string(pbx), "ENABLE_USER_SCRIPT_SANDBOXING = NO;") != 2 { |
| 312 | t.Fatal("the script phase must turn Xcode's own script sandbox off, as a hostile repository would") |
| 313 | } |
| 314 | tests, _ := os.ReadFile(filepath.Join(root, "package/Tests/HostileTests/HostileTests.swift")) |
| 315 | wait := string(tests[strings.Index(string(tests), "func testWait"):]) |
| 316 | if strings.Contains(wait, "Thread.sleep") || !strings.Contains(wait, "write(to:") || !strings.Contains(string(tests), "keychain_file") { |
| 317 | t.Fatal("P6's test must work while it is killed, and P2's must try the host keychain file from the simulator") |
| 318 | } |
| 319 | if info, _ := os.Stat(filepath.Join(root, "project/hostile.sh")); info.Mode().Perm() != 0700 { |
| 320 | t.Fatal("hostile.sh not executable") |
| 321 | } |
| 322 | for _, f := range []string{"package/Plugins/HostilePlugin/HostilePlugin.swift", "package/Tests/HostileTests/HostileTests.swift", "project/hostile.sh"} { |
| 323 | raw, _ := os.ReadFile(filepath.Join(root, f)) |
| 324 | for _, what := range []string{"state", "home", "tcp", "dns", "keychain"} { |
| 325 | if !strings.Contains(string(raw), what) { |
| 326 | t.Fatalf("%s does not try %s", f, what) |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | // P2 runs its hostile test on an iOS simulator, as checks do (the fake |
| 333 | // xcodebuild fails it anywhere else), and is denied only for a run whose |
| 334 | // end was proven: a marked process left makes it failed, whatever the |
| 335 | // lines say. Without an iOS simulator P2 cannot say. |
| 336 | func TestP2NeedsTheSimulatorAndAProvenEnd(t *testing.T) { |
| 337 | f := newProbeFixture(t, allLines("denied")) |
| 338 | caps := Capabilities(context.Background(), f.h.Exec, f.h.Tools) |
| 339 | if p, ran, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeDenied || !ran { |
| 340 | t.Fatalf("on the simulator: %+v", p) |
| 341 | } |
| 342 | gate := f.h.Gate |
| 343 | f.h.Gate = func(sandboxed bool) *Gate { |
| 344 | g := gate(sandboxed) |
| 345 | g.Settle = 300 * time.Millisecond |
| 346 | g.procs = withPhantom() |
| 347 | return g |
| 348 | } |
| 349 | if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "end_unproven") { |
| 350 | t.Fatalf("end not proven: %+v", p) |
| 351 | } |
| 352 | f.h.Gate = gate |
| 353 | // Every line says denied, but the hostile build did not complete: |
| 354 | // not a pass. |
| 355 | f = newProbeFixture(t, allLines("denied"), "FAKE_LINES_THEN_FAIL=1") |
| 356 | if p, ran, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeFailed || ran { |
| 357 | t.Fatalf("incomplete run: %+v", p) |
| 358 | } |
| 359 | caps.Simulators = nil |
| 360 | if p, _, _ := probeP2(context.Background(), f.h, caps); p.Verdict != wire.ProbeUnavailable || p.Detail != "no_simulator" { |
| 361 | t.Fatalf("no simulator: %+v", p) |
| 362 | } |
| 363 | } |
| 364 | |
| 365 | // A wait nothing else bounds (a command that ignores its context) ends |
| 366 | // at the run's limit: the report has every probe, the ones not finished |
| 367 | // not proven and listed, and stays a valid capability report. |
| 368 | func TestRunProbesLimit(t *testing.T) { |
| 369 | stuck := make(chan struct{}) |
| 370 | t.Cleanup(func() { close(stuck) }) |
| 371 | h := ProbeHost{Version: "abc1234", UID: 501, Paths: Paths{HomesUnknown: true}, Exposed: func(string) bool { return false }, Limit: 300 * time.Millisecond, |
| 372 | Exec: func(ctx context.Context, name string, args ...string) (string, error) { |
| 373 | if name == "/bin/launchctl" { |
| 374 | <-stuck |
| 375 | } |
| 376 | return "", errors.New("not recorded") |
| 377 | }} |
| 378 | got := make(chan Report, 1) |
| 379 | go func() { got <- RunProbes(context.Background(), h) }() |
| 380 | var r Report |
| 381 | select { |
| 382 | case r = <-got: |
| 383 | case <-time.After(5 * time.Second): |
| 384 | t.Fatal("the probe run outlived its limit") |
| 385 | } |
| 386 | if !slices.Equal(r.Unfinished, []string{"P4", "P5", "P6", "P7"}) { |
| 387 | t.Fatalf("unfinished %v %+v", r.Unfinished, r.Probes) |
| 388 | } |
| 389 | for _, id := range r.Unfinished { |
| 390 | if p := r.Probe(id); p.Verdict != wire.ProbeUnavailable || p.Detail != "probe_limit:300ms" { |
| 391 | t.Fatalf("%s %+v", id, p) |
| 392 | } |
| 393 | } |
| 394 | if p := r.Probe("P1"); p.Verdict != wire.ProbeFailed { |
| 395 | t.Fatalf("P1 finished before the limit: %+v", p) |
| 396 | } |
| 397 | if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil { |
| 398 | t.Fatalf("report outside the capability rules: %v", err) |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | // #1: a probe run that reaches its limit reports at once, but keeps the |
| 403 | // Mac's turn until its gates have stopped (here one that ignores SIGTERM |
| 404 | // for its grace): nothing else takes the turn meanwhile, and it is free |
| 405 | // once they have. |
| 406 | func TestProbeLimitHoldsTheTurnUntilItsGateEnds(t *testing.T) { |
| 407 | f := newProbeFixture(t, allLines("denied"), "FAKE_HANG=1") |
| 408 | turns := NewTurns(filepath.Join(t.TempDir(), "lock")) |
| 409 | inner := f.h.Gate |
| 410 | f.h.Gate = func(sandboxed bool) *Gate { g := inner(sandboxed); g.Grace = 900 * time.Millisecond; return g } |
| 411 | f.h.Turns, f.h.Limit = turns, 400*time.Millisecond |
| 412 | done := make(chan Report, 1) |
| 413 | go func() { done <- RunProbes(context.Background(), f.h) }() |
| 414 | select { |
| 415 | case <-done: |
| 416 | case <-time.After(5 * time.Second): |
| 417 | t.Fatal("no report at the run's limit") |
| 418 | } |
| 419 | time.Sleep(200 * time.Millisecond) |
| 420 | if u, ok := turns.TryTake(OpCheck); ok { |
| 421 | u.Give() |
| 422 | t.Fatal("another operation took the turn while the probe's gate was still stopping") |
| 423 | } |
| 424 | for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(50 * time.Millisecond) { |
| 425 | if u, ok := turns.TryTake(OpCheck); ok { |
| 426 | u.Give() |
| 427 | return |
| 428 | } |
| 429 | if time.Now().After(deadline) { |
| 430 | t.Fatal("the turn was never given back") |
| 431 | } |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | // #11: a probe run that cannot take the Mac's turn says so by a code |
| 436 | // the instance words, not by English of its own. |
| 437 | func TestRunProbesWithoutTheTurn(t *testing.T) { |
| 438 | f := newProbeFixture(t, allLines("denied")) |
| 439 | turns := NewTurns("") |
| 440 | held, err := turns.Take(context.Background(), OpEngineering) |
| 441 | if err != nil { |
| 442 | t.Fatal(err) |
| 443 | } |
| 444 | defer held.Give() |
| 445 | f.h.Turns, f.h.Limit = turns, 200*time.Millisecond |
| 446 | rep := RunProbes(context.Background(), f.h) |
| 447 | for _, p := range rep.Probes { |
| 448 | if p.Verdict != wire.ProbeUnavailable || p.Detail != wire.ProbeDetailTurnBusy { |
| 449 | t.Fatalf("%+v", p) |
| 450 | } |
| 451 | } |
| 452 | } |
| 453 | |