package mac import ( "context" "crypto/rand" "crypto/sha256" "embed" "encoding/hex" "encoding/json" "errors" "fmt" "io/fs" "net" "os" "path" "path/filepath" "regexp" "sort" "strconv" "strings" "sync" "sync/atomic" "time" "amadan.net/oficina/equipo/internal/wire" ) // The hostile fixture of probe P2 (and the waiting test of P6) ships // with the runner as test data. // //go:embed all:fixtures/hostile var fixtures embed.FS // ProbeHost is what the probes reach on the Mac. Every effect goes // through it, so the probes run on Linux against recorded outputs. type ProbeHost struct { Exec Exec Tools Tools Paths Paths // Scratch holds the fixture copies (never the state dir, which the // checks profile denies); Runner is the runner's binary (its reader). Scratch, Runner string UID int Version string // Gate is the gate the fixture runs under: sandboxed, srt with the // checks profile; or bare. Gate func(sandboxed bool) *Gate // Turns is the Mac's turns: the whole run is one turn (OpProbe), and // its gates run in it. nil takes none (tests). Turns *Turns // Resolve and Exposed are the same attempts made outside the // sandbox, so a denial can be told from a failure; Listen opens a // loopback port whose accepts are ground truth for "tcp". Resolve func(ctx context.Context, name string) bool Exposed func(path string) bool Listen func() (net.Listener, error) // Wait bounds P6's wait for its test to start (8 minutes). Wait time.Duration // Limit bounds the whole run (ProbeLimit). Limit time.Duration // Warn hears why P2's srt run did not fully succeed, once per run, // redacted (runner.log); nil says nothing. Warn func(msg string, args ...any) // late notes the queries that did not answer in time (RunProbes). late *queries } // QueryLimit bounds each query the probes and the capability report // make (simctl list, xcodebuild -version, launchctl, pmset, a tool's // version): a command that has not answered by then is killed and taken // as unavailable. Only the gates the probes run (a real build and test) // and srt's own start take longer, each with a bound of its own. var QueryLimit = 30 * time.Second // ProbeLimit bounds a whole probe run, whatever hangs inside it. It is // above the bounds of the probes' own gates (P2's 20 minutes, P6's 8), // so it never cuts a slow but healthy first build short: it is the // backstop for a wait nothing else bounds. const ProbeLimit = 30 * time.Minute // Report is what the probes found, kept in the state dir and sent in the // capability report. type Report struct { Version string `json:"version"` Profile string `json:"profile"` At time.Time `json:"at"` Probes []wire.Probe `json:"probes"` // SRTRanXcode: the fixture built and tested under srt with the checks // profile, so srt can confine checks even when P2 is not denied. SRTRanXcode bool `json:"srt_ran_xcode"` // SRT fingerprints the srt, Node and ripgrep the probes ran with // (set by the worker that made the report). SRT string `json:"srt"` // Unfinished are the probes the run's limit cut short: each says // not proven. Unfinished []string `json:"unfinished,omitempty"` } // Probe is the result of one probe ("" verdict when it did not run). func (r Report) Probe(id string) wire.Probe { for _, p := range r.Probes { if p.ID == id { return p } } return wire.Probe{ID: id} } // Sandboxed: P2 denied every attempt, so checks run in the sandbox and // say so (seatbelt). func (r Report) Sandboxed() bool { return r.Probe("P2").Verdict == wire.ProbeDenied } // digestInput is the checks profile over fixed paths that // ProfileDigest names (TestProfileDigest: ChecksSettings accepts it). func digestInput() ChecksInput { return ChecksInput{Paths: Paths{Home: "/Users/u", StateDir: "/Users/u/s", AccountsRoot: "/Users/u/a", SessionRoot: "/Users/u/n", InstallDir: "/Users/u/i", OtherHomes: []string{"/Users/o"}, UserTemp: UserTempPrefix + "/u/T"}, Tree: "/Users/u/t/tree", Attempt: "/Users/u/t/attempt", Mach: CheckMachServices} } // ProfileDigest names the checks profile the probes judged: the // settings over fixed paths, the Mach list and the fixture. A profile // that cannot be made is named so, never as no profile. func ProfileDigest() string { raw, err := ChecksSettings(digestInput()) if err != nil { raw = []byte("unmade: " + err.Error()) } h := sha256.New() h.Write(raw) _ = fs.WalkDir(fixtures, "fixtures", func(p string, d fs.DirEntry, err error) error { if err == nil && !d.IsDir() { b, _ := fixtures.ReadFile(p) fmt.Fprintf(h, "%s %d\n", p, len(b)) h.Write(b) } return nil }) return hex.EncodeToString(h.Sum(nil))[:16] } // RunProbes runs P1 to P7 (spec ยง6) and reports each. None needs a // person: P3 and P5 say what they could not do and why. Every command // is bounded (QueryLimit, or a gate's own limit) and so is the run // (h.Limit): when that passes the run ends with what it has, the // probes it did not finish not proven and listed in Unfinished. func RunProbes(ctx context.Context, h ProbeHost) Report { limit := h.Limit if limit <= 0 { limit = ProbeLimit } run, cancel := context.WithTimeout(ctx, limit) defer cancel() r := Report{Version: h.Version, Profile: ProfileDigest(), At: time.Now().UTC()} // One turn for the run's life: no check, Engineering or token // operation runs between its gates. run, give, err := h.Turns.Hold(run, OpProbe) if err != nil { for _, id := range wire.ProbeIDs { r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: wire.ProbeDetailTurnBusy}) r.Unfinished = append(r.Unfinished, id) } return r } h.late = &queries{run: run, exec: h.Exec, late: map[string]bool{}} h.Exec = h.late.do var mu sync.Mutex got := map[string]wire.Probe{} srtRan := false // A result that comes once the run's limit has passed is left out: // the cancellation, not the Mac, may have decided it. put := func(p wire.Probe, ran ...bool) { mu.Lock() defer mu.Unlock() if run.Err() == nil { got[p.ID] = p if len(ran) > 0 { srtRan = ran[0] } } } done := make(chan struct{}) go func() { defer close(done) caps := Capabilities(run, h.Exec, h.Tools) put(probeP1(run, h, caps)) p2, ran, keychain := probeP2(run, h, caps) put(p2, ran) put(wire.Probe{ID: "P3", Verdict: wire.ProbeSkipped, Detail: wire.ProbeDetail(keychain)}) put(probeP4(run, h)) put(wire.Probe{ID: "P5", Verdict: wire.ProbeSkipped, Detail: wire.ProbeDetail("p5_parked")}) put(probeP6(run, h, caps, ran)) put(probeP7(run, h)) }() // Past the limit the report is made with what there is, but the turn // is held until the run has ended (its context is cancelled, so its // gates stop and prove their end and clean up): nothing else runs // beside a probe still stopping. select { case <-done: give() case <-run.Done(): go func() { <-done; give() }() } mu.Lock() defer mu.Unlock() r.SRTRanXcode = srtRan for _, id := range wire.ProbeIDs { p, ok := got[id] if !ok { p = wire.Probe{ID: id, Verdict: wire.ProbeUnavailable, Detail: wire.ProbeDetail("probe_limit", limit.String())} r.Unfinished = append(r.Unfinished, id) } r.Probes = append(r.Probes, p) } return r } // queries runs the probes' commands and notes each that did not answer // in time: its own deadline passed while the run's had not. type queries struct { run context.Context exec Exec mu sync.Mutex late map[string]bool } func (q *queries) do(ctx context.Context, name string, args ...string) (string, error) { out, err := q.exec(ctx, name, args...) if errors.Is(ctx.Err(), context.DeadlineExceeded) && q.run.Err() == nil { q.mu.Lock() q.late[queryKey(name, args)] = true q.mu.Unlock() } return out, err } // queryKey names a command by its program, or xcrun's by its tool // ("simctl"). func queryKey(name string, args []string) string { if path.Base(name) == "xcrun" && len(args) > 0 { return args[0] } return path.Base(name) } // noXcode and noSimulator are the detail of a probe that needs Xcode or // a simulator and cannot run: a query that did not answer in time // (QueryLimit), or none found ("" for a simulator that answered). func (h ProbeHost) noXcode() string { return h.gone("xcodebuild", "xcode_unavailable", wire.ProbeDetail("no_xcode")) } func (h ProbeHost) noSimulator() string { return h.gone("simctl", "simulator_unavailable", "") } func (h ProbeHost) gone(tool, code, otherwise string) string { if h.late != nil && h.late.was(tool) { return wire.ProbeDetail(code, QueryLimit.String()) } return otherwise } func (q *queries) was(tool string) bool { q.mu.Lock(); defer q.mu.Unlock(); return q.late[tool] } // query runs one probe command bounded by limit. func (h ProbeHost) query(ctx context.Context, limit time.Duration, name string, args ...string) (string, error) { c, cancel := context.WithTimeout(ctx, limit) defer cancel() return h.Exec(c, name, args...) } func probeP1(ctx context.Context, h ProbeHost, caps wire.Capabilities) wire.Probe { name := ComputerName(ctx, h.Exec) ios := 0 for _, s := range caps.Simulators { if strings.HasPrefix(s.Runtime, "iOS ") { ios++ } } computer := map[bool]string{true: wire.ProbeDetail("computer", name)}[name != ""] if caps.Xcode.Version == "" { return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetails(h.noXcode(), computer)} } sims := firstNonEmpty(h.noSimulator(), wire.ProbeDetail("ios_simulators", strconv.Itoa(ios))) detail := wire.ProbeDetails(wire.ProbeDetail("xcode", caps.Xcode.Version, caps.Xcode.Build), sims, computer) if ios == 0 { return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: detail} } return wire.Probe{ID: "P1", Verdict: wire.ProbePassed, Detail: detail} } // ComputerName is the Mac's name as people see it ("Tito Studio"). func ComputerName(ctx context.Context, x Exec) string { ctx, cancel := context.WithTimeout(ctx, QueryLimit) defer cancel() out, err := x(ctx, "/usr/sbin/scutil", "--get", "ComputerName") if err != nil { return "" } return strings.TrimSpace(out) } // The places and attempts of the hostile fixture. var ( probePlaces = []string{"script", "plugin", "test"} probeAttempts = []string{"state", "home", "tcp", "dns", "keychain", "tokenfile", "tokenlink", "tokenenv", "tokenargs", "tokenlaunchd", "tokenfd"} attemptLine = regexp.MustCompile(`EQUIPO-PROBE (script|plugin|test) (state|home|tcp|dns|keychain|token(?:file|link|env|args|launchd|fd)) (allowed|denied|failed)\b`) ) // ParseAttempts reads the fixture's report lines: "place.attempt" to // allowed or denied. The first line for an attempt counts. func ParseAttempts(out string) map[string]string { got := map[string]string{} for _, m := range attemptLine.FindAllStringSubmatch(out, -1) { k := m[1] + "." + m[2] if _, seen := got[k]; !seen { got[k] = m[3] } } return got } // P2Facts are what the probe knows outside the sandbox. type P2Facts struct { // Home: another home was tried; HomeUnix: the runner user cannot // list it even outside the sandbox (Unix permissions deny it). Home, HomeUnix bool // DNS resolves outside; the Keychain item and the sentinel token exist. DNS, Keychain, Token bool // Accepted: places whose loopback port took a connection. Accepted map[string]bool } // JudgeP2 turns the attempts into P2's verdict: denied only when every // attempt of every place says denied and nothing contradicts it. A // missing line, a failed control (DNS outside, the Keychain item, the // token planted) or an accepted connection is not a denial. func JudgeP2(got map[string]string, f P2Facts) (verdict string, groups map[string][]string) { groups = map[string][]string{} verdict = wire.ProbeDenied for _, place := range probePlaces { for _, what := range probeAttempts { if what == "home" && !f.Home { continue } k := place + "." + what r := got[k] switch { case what == "tcp" && f.Accepted[place]: r = "allowed" case r == "": r = "unknown" case r == "denied" && what == "dns" && !f.DNS, r == "denied" && what == "keychain" && !f.Keychain, r == "denied" && strings.HasPrefix(what, "token") && !f.Token: r = "unknown" case r == "denied" && what == "home" && f.HomeUnix: r = "unix" } if r != "denied" { groups[r] = append(groups[r], k) } if r != "denied" && r != "unix" { verdict = wire.ProbeFailed } } } return verdict, groups } // p2Detail says what P2 found (a place all of whose attempts are alike as // place.*) and whether the run's end was proven; why, the steps of a // failed srt run, is last, so the capability string's limit cuts it // first. func p2Detail(groups map[string][]string, total int, srtRan, ended bool, why string) string { var parts []string for _, g := range []struct{ key, code string }{{"allowed", "allowed"}, {"failed", "not_collected"}, {"unknown", "not_shown_denied"}, {"unix", "unix_only"}} { if len(groups[g.key]) > 0 { list := " " + strings.Join(groups[g.key], " ") + " " for _, p := range probePlaces { list = strings.Replace(list, " "+p+"."+strings.Join(probeAttempts, " "+p+".")+" ", " "+p+".* ", 1) } parts = append(parts, wire.ProbeDetail(g.code, strings.TrimSpace(list))) } } if len(parts) == 0 { parts = append(parts, wire.ProbeDetail("all_denied", strconv.Itoa(total))) } if !ended { parts = append(parts, wire.ProbeDetail("end_unproven")) } switch { case srtRan: parts = append(parts, wire.ProbeDetail("srt_ran_xcode")) case why != "": parts = append(parts, wire.ProbeDetail("srt_failed", why)) default: parts = append(parts, wire.ProbeDetail("srt_not_run")) } return wire.ProbeDetails(parts...) } // P2Script is P2's run under srt, one step at a time, each reporting // its exit (EQUIPO-PHASE ) so a failure names its step: the // hostile script phase's build, then the package's resolve, test build, // the simulator's boot and the hostile test on it. Every xcodebuild // writes only into the attempt's scratch (XcodeWrites), as checks do; // the script phase's target is built through its shared scheme because // xcodebuild takes -derivedDataPath only for a scheme, and SYMROOT and // OBJROOT stay in scratch too should a build fall back to them. Each // action has its own result bundle there (XcodeResult). func P2Script(xb, xcrun, udid string) string { dest := quote("platform=iOS Simulator,id=" + udid) pkg := func(step string) string { return ` -scheme "$s" ` + XcodeWrites + ` ` + XcodeResult(step) + ` -skipPackagePluginValidation` } return `phase() { p=$1; shift; "$@"; c=$?; echo "EQUIPO-PHASE $p $c"; return $c; } (cd project && phase script-build ` + xb + ` -project Hostile.xcodeproj -scheme HostileScript -configuration Debug build ` + XcodeWrites + ` ` + XcodeResult("script-build") + ` SYMROOT="$TMPDIR/sym" OBJROOT="$TMPDIR/obj"); a=$? cd package || exit 1 s=Hostile-Package; ` + xb + ` -list ` + XcodeWrites + ` 2>/dev/null | grep -q Hostile-Package || s=Hostile phase package-resolve ` + xb + ` -resolvePackageDependencies` + pkg("package-resolve") + ` && phase test-build ` + xb + ` build-for-testing -destination ` + dest + pkg("test-build") + ` && phase simulator-boot ` + xcrun + ` simctl bootstatus ` + quote(udid) + ` -b && phase test-run ` + xb + ` test-without-building -destination ` + dest + ` -only-testing:HostileTests/HostileTests/testHostile` + pkg("test-run") + ` b=$? [ "$a" = 0 ] && [ "$b" = 0 ]` } // probeP2 runs the hostile fixture under the checks profile. func probeP2(ctx context.Context, h ProbeHost, caps wire.Capabilities) (wire.Probe, bool, string) { fail := func(verdict, why string) (wire.Probe, bool, string) { return wire.Probe{ID: "P2", Verdict: verdict, Detail: why}, false, "p3_keychain_unprobed" } if h.Tools.SRT == "" { return fail(wire.ProbeUnavailable, wire.ProbeDetail("srt_missing")) } // No checks profile without the user's T (ChecksSettings refuses): // say why, and checks wait for the sandbox. if h.Paths.UserTemp == "" { return fail(wire.ProbeUnavailable, wire.ProbeDetail("user_temp_refused")) } if caps.Xcode.Version == "" { return fail(wire.ProbeUnavailable, h.noXcode()) } if why := h.noSimulator(); why != "" { return fail(wire.ProbeUnavailable, why) } // The hostile test runs where production checks run: on an iOS // simulator, through CoreSimulator and the test services. sim, ok := NewestIPhone(caps.Simulators) if !ok { return fail(wire.ProbeUnavailable, wire.ProbeDetail("no_simulator")) } root, err := CopyFixture(h.Scratch) if err != nil { return fail(wire.ProbeUnavailable, wire.ProbeDetail("fixture_uncopied")) } defer os.RemoveAll(filepath.Dir(root)) facts := P2Facts{Accepted: map[string]bool{}} targets := []string{} // A sentinel in the state dir: what a step must never read. secret := token() sentinel := filepath.Join(h.Paths.StateDir, "probe-sentinel-"+secret[:8]) if err := os.WriteFile(sentinel, []byte(secret), 0600); err != nil { return fail(wire.ProbeUnavailable, "no sentinel in the state dir") } defer os.Remove(sentinel) // A sentinel token where connections keep theirs (F3's sources, slice F). tok := filepath.Join(h.Paths.AccountsRoot, "probe-"+secret[:8]) if filepath.IsAbs(tok) { defer os.RemoveAll(tok) facts.Token = os.MkdirAll(tok, 0700) == nil && os.WriteFile(filepath.Join(tok, ".oauth-token"), []byte("sk-ant-oat01-probe-"+secret), 0600) == nil } targets = append(targets, "state="+sentinel, "token=sk-ant-oat01-probe-"+secret, "token_file="+filepath.Join(tok, ".oauth-token"), "helper="+h.Runner) if home := otherHome(h.Paths.OtherHomes); home != "" { facts.Home, facts.HomeUnix = true, !h.Exposed(home) targets = append(targets, "home="+home) } var mu sync.Mutex for _, place := range probePlaces { l, err := h.Listen() if err != nil { return fail(wire.ProbeUnavailable, "no loopback port") } defer l.Close() go func(place string, l net.Listener) { for { c, err := l.Accept() if err != nil { return } c.Close() mu.Lock() facts.Accepted[place] = true mu.Unlock() } }(place, l) targets = append(targets, "port_"+place+"="+strconv.Itoa(l.Addr().(*net.TCPAddr).Port)) } resolve, cancel := context.WithTimeout(ctx, QueryLimit) facts.DNS = h.Resolve(resolve, "example.com") cancel() targets = append(targets, "dns=example.com") service := "io.amadan.equipo.probe." + secret[:12] if _, err := h.query(ctx, QueryLimit, "/usr/bin/security", "add-generic-password", "-a", "equipo-probe", "-s", service, "-w", secret, "-A", "-U"); err == nil { facts.Keychain = true defer func() { _, _ = h.query(context.WithoutCancel(ctx), QueryLimit, "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service) }() } // On a simulator the Keychain API is the simulator's own: the test // there tries the runner user's login keychain file instead. targets = append(targets, "keychain="+service, "keychain_file="+filepath.Join(h.Paths.Home, "Library", "Keychains", "login.keychain-db")) if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0600); err != nil { return fail(wire.ProbeUnavailable, wire.ProbeDetail("fixture_unprepared")) } script := P2Script(quote(h.Tools.Xcodebuild), quote(h.Tools.Xcrun), sim.UDID) g, watch := h.Gate(true), newP2Watch() g.Watch = watch.line res := g.Run(ctx, "probe-p2-"+secret[:8], root, []string{"/bin/bash", "-c", script}, 20*time.Minute, func(string) error { return nil }) mu.Lock() defer mu.Unlock() srtRan := watch.ran(res) verdict, groups := JudgeP2(ParseAttempts(watch.attemptsSeen()), facts) why := "" if !srtRan { // Never the secret, the service, the targets file's contents or a // path under a home. secrets := []string{service, secret, secret[:12], secret[:8]} for _, t := range targets { _, v, _ := strings.Cut(t, "=") secrets = append(secrets, t, v) } red := newRedactor(secrets, append([]string{h.Paths.Home, h.Paths.StateDir, h.Scratch}, h.Paths.OtherHomes...)) f := watch.failure(res, red) why, _, _ = strings.Cut(f.short(), ": ") if h.Warn != nil { h.Warn("p2 srt run failed", "phase", f.Phase, "failed", strings.Join(f.Failed, ", "), "unfinished", f.Unfinished, "exit", f.Exit, "timed_out", f.TimedOut, "gate_reason", res.Reason, "excerpt", f.Excerpt) } } // Denied counts only for a run that did everything and was proven // to end: the hostile build and test completed under srt, and nothing // of them is left. if !srtRan || !res.Terminated { verdict = wire.ProbeFailed } keychain := "p3_keychain_denied" for _, list := range groups { if strings.Contains(" "+strings.Join(list, " ")+" ", ".keychain ") { keychain = "p3_keychain_unshown" } } total := len(probePlaces) * len(probeAttempts) if !facts.Home { total -= len(probePlaces) } detail := p2Detail(groups, total, srtRan, res.Terminated, why) return wire.Probe{ID: "P2", Verdict: verdict, Detail: detail}, srtRan, keychain } // otherHome is the home P2 tries: a person's, not /Users/Shared. func otherHome(homes []string) string { list := append([]string{}, homes...) sort.Strings(list) for _, h := range list { if path.Base(h) != "Shared" { return h } } return "" } func probeP4(ctx context.Context, h ProbeHost) wire.Probe { var readable []string for _, home := range ExposedHomes(h.Paths.OtherHomes, h.Exposed) { readable = append(readable, path.Base(home)) } _, err := h.query(ctx, QueryLimit, "/bin/launchctl", "print", "gui/"+strconv.Itoa(h.UID)+"/"+AgentLabel) loaded := err == nil pm, _ := h.query(ctx, QueryLimit, "/usr/bin/pmset", "-g", "custom") sleep, known := ACSleep(pm) var parts []string switch { case h.Paths.HomesUnknown: parts = append(parts, wire.ProbeDetail("homes_unchecked")) case len(readable) > 0: parts = append(parts, wire.ProbeDetail("homes_readable", strings.Join(readable, " "))) default: parts = append(parts, wire.ProbeDetail("homes_closed")) } parts = append(parts, wire.ProbeDetail(map[bool]string{true: "agent_loaded", false: "agent_not_loaded"}[loaded])) switch { case !known: parts = append(parts, wire.ProbeDetail("sleep_unknown")) case sleep == 0: parts = append(parts, wire.ProbeDetail("sleep_off")) default: parts = append(parts, wire.ProbeDetail("sleep_after", strconv.Itoa(sleep))) } verdict := wire.ProbePassed if h.Paths.HomesUnknown || len(readable) > 0 || !loaded || !known || sleep != 0 { verdict = wire.ProbeFailed } return wire.Probe{ID: "P4", Verdict: verdict, Detail: wire.ProbeDetails(parts...)} } // ACSleep reads `pmset -g custom`: the system sleep minutes under "AC // Power" (0 is never). A desktop Mac may list one unnamed set of // settings; its sleep line counts when there is no section at all. func ACSleep(out string) (int, bool) { ac := true for _, line := range strings.Split(out, "\n") { t := strings.TrimSpace(line) if strings.HasSuffix(t, ":") { ac = strings.HasPrefix(t, "AC Power") continue } f := strings.Fields(t) if ac && len(f) >= 2 && f[0] == "sleep" { n, err := strconv.Atoi(f[1]) return n, err == nil } } return 0, false } // probeP6 starts the fixture's waiting test and kills its group: how long // the end takes to prove, what is left, and whether the tree goes. func probeP6(ctx context.Context, h ProbeHost, caps wire.Capabilities, srtRan bool) wire.Probe { if caps.Xcode.Version == "" { return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: h.noXcode()} } // A simctl that does not answer means CoreSimulator is stuck, and // xcodebuild test asks it for destinations even for macOS: the probe // would only wait out its whole limit. if why := h.noSimulator(); why != "" { return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: why} } root, err := CopyFixture(h.Scratch) if err != nil { return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: wire.ProbeDetail("fixture_uncopied")} } defer os.RemoveAll(filepath.Dir(root)) destination := "platform=macOS" if sim, ok := NewestIPhone(caps.Simulators); ok { destination = "platform=iOS Simulator,id=" + sim.UDID } g := *h.Gate(srtRan && h.Tools.SRT != "") run, cancel := context.WithCancel(ctx) defer cancel() var once sync.Once var mu sync.Mutex var stopped time.Time g.Watch = func(line string) { if strings.Contains(line, "EQUIPO-PROBE wait started") { once.Do(func() { time.AfterFunc(2*time.Second, func() { mu.Lock() stopped = time.Now() mu.Unlock() cancel() }) }) } } var shut atomic.Int32 if inner := g.Shutdown; inner != nil { g.Shutdown = func(c context.Context, u string) { shut.Add(1); inner(c, u) } } before := processNames(ctx, h.Exec) attempt := "probe-p6-" + token()[:8] wait := h.Wait if wait <= 0 { wait = 8 * time.Minute } script := p6Script(quote(h.Tools.Xcodebuild), destination) res := g.Run(run, attempt, root, []string{"/bin/bash", "-c", script}, wait, func(string) error { return nil }) mu.Lock() defer mu.Unlock() took := time.Since(stopped).Round(time.Second) left, _ := Marked(attempt) after := processNames(context.WithoutCancel(ctx), h.Exec) removed := os.RemoveAll(root) == nil if stopped.IsZero() { return wire.Probe{ID: "P6", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("test_not_started", firstNonEmpty(res.Reason, "exit "+strconv.Itoa(res.Code)))} } var parts []string if res.Terminated { parts = append(parts, wire.ProbeDetail("group_gone", took.String())) } else { parts = append(parts, wire.ProbeDetail("group_unproven")) } parts = append(parts, wire.ProbeDetail("marked_left", strconv.Itoa(len(left)))) if n := newNames(before, after); n > 0 { // How many, never their names (a path, or what a process chose). parts = append(parts, wire.ProbeDetail("still_running", strconv.Itoa(n))) } parts = append(parts, wire.ProbeDetail("simulators_shut", strconv.Itoa(int(shut.Load())))) parts = append(parts, wire.ProbeDetail(map[bool]string{true: "tree_removed", false: "tree_not_removable"}[removed])) verdict := wire.ProbePassed if !res.Terminated || len(left) > 0 || !removed { verdict = wire.ProbeFailed } return wire.Probe{ID: "P6", Verdict: verdict, Detail: wire.ProbeDetails(parts...)} } // p6Script starts the fixture's waiting test, its writes in the // attempt's scratch as P2's and the checks' are. func p6Script(xb, destination string) string { return `cd package && s=Hostile-Package; ` + xb + ` -list ` + XcodeWrites + ` 2>/dev/null | grep -q Hostile-Package || s=Hostile exec ` + xb + ` test -scheme "$s" -destination ` + quote(destination) + ` -only-testing:HostileTests/HostileTests/testWait ` + XcodeWrites + ` ` + XcodeResult("wait") + ` -skipPackagePluginValidation` } // processNames are this user's processes by name (basename), counted. func processNames(ctx context.Context, x Exec) map[string]int { ctx, cancel := context.WithTimeout(ctx, QueryLimit) defer cancel() out, err := x(ctx, "/bin/ps", "-x", "-o", "comm=") names := map[string]int{} if err != nil { return names } for _, l := range strings.Split(out, "\n") { if l = strings.TrimSpace(l); l != "" { names[path.Base(l)]++ } } return names } // newNames is how many process names are new or more numerous after. func newNames(before, after map[string]int) (n int) { for name, c := range after { if c > before[name] { n++ } } return n } func probeP7(ctx context.Context, h ProbeHost) wire.Probe { ask := func(tool string, args ...string) string { if tool == "" { return "" } out, err := h.query(ctx, QueryLimit, tool, args...) if err != nil { return "" } return out } srt := word(plainVersion, ask(h.Tools.SRT, "--version")) node := word(nodeVersion, ask(h.Tools.Node, "--version")) rg := word(plainVersion, ask(h.Tools.RG, "--version")) var parts []string ok := true for _, t := range []struct{ name, version string }{{"srt", srt}, {"node", node}, {"rg", rg}} { if t.version == "" { parts, ok = append(parts, wire.ProbeDetail("tool_missing", t.name)), false } else { parts = append(parts, wire.ProbeDetail("tool_version", t.name, t.version)) } } if node != "" && !NodeSupported(node) { parts, ok = append(parts, wire.ProbeDetail("node_old")), false } if ok { // srt itself: the smallest profile around /usr/bin/true. file := filepath.Join(h.Scratch, "probe-p7-"+token()[:8]+".json") raw, _ := json.Marshal(Settings{Network: Network{AllowedDomains: []string{}, DeniedDomains: []string{}, AllowMachLookup: []string{}}, Filesystem: Filesystem{DenyRead: []string{}, AllowRead: []string{}, AllowWrite: []string{}, DenyWrite: []string{}}}) if os.WriteFile(file, raw, 0600) != nil { ok = false } else { defer os.Remove(file) // srt starts its own runtime before the command: a minute, not a query's 30 s. if _, err := h.query(ctx, time.Minute, h.Tools.SRT, "--settings", file, "--", "/usr/bin/true"); err != nil { parts, ok = append(parts, wire.ProbeDetail("srt_cannot_run")), false } } } verdict := wire.ProbePassed if !ok { verdict = wire.ProbeFailed } return wire.Probe{ID: "P7", Verdict: verdict, Detail: wire.ProbeDetails(parts...)} } // NodeSupported: srt needs Node 22.12 or later. func NodeSupported(v string) bool { var n [3]int if _, err := fmt.Sscanf(v, "v%d.%d.%d", &n[0], &n[1], &n[2]); err != nil { return false } return compareVersions(n[:], []int{22, 12, 0}) >= 0 } // CopyFixture writes the hostile fixture into a fresh directory under // scratch and returns its root. func CopyFixture(scratch string) (string, error) { if err := os.MkdirAll(scratch, 0700); err != nil { return "", err } dir, err := os.MkdirTemp(scratch, "probe-") if err != nil { return "", err } root := filepath.Join(dir, "hostile") err = fs.WalkDir(fixtures, "fixtures/hostile", func(p string, d fs.DirEntry, err error) error { if err != nil { return err } dst := filepath.Join(root, strings.TrimPrefix(p, "fixtures/hostile")) if d.IsDir() { return os.MkdirAll(dst, 0700) } raw, err := fixtures.ReadFile(p) if err != nil { return err } mode := os.FileMode(0600) if strings.HasSuffix(p, ".sh") { mode = 0700 } return os.WriteFile(dst, raw, mode) }) if err != nil { os.RemoveAll(dir) return "", err } return root, nil } func token() string { b := make([]byte, 16) _, _ = rand.Read(b) return hex.EncodeToString(b) } func firstNonEmpty(s ...string) string { for _, x := range s { if x != "" { return x } } return "" }