package thin import ( "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "io" "log/slog" "net" "net/http" "os" "os/exec" "path/filepath" "runtime" "slices" "strconv" "strings" "sync" "sync/atomic" "time" "amadan.net/oficina/equipo/internal/release" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/wire" ) // A Mac worker (Mac runners spec §§3 to 5): checks only, under srt when // probe P2 denied every hostile attempt, otherwise outside the sandbox // and labelled so (Paul's ruling 2). The pieces are in internal/runner/ // mac; this file wires them to the worker. // macGate adapts a Mac gate to the worker's GateRunner. type macGate struct{ g *mac.Gate } // A Mac launch of the pinned CLI goes through the same starter as a // Linux one (recordedStart). var _ starter = (*mac.Starter)(nil) func (m macGate) Sandbox() string { return m.g.Sandbox } func (m macGate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) gateResult { r := m.g.Run(ctx, attempt, dir, argv, limit, record) return gateResult{output: r.Output, reason: r.Reason, code: r.Code, terminated: r.Terminated, sandbox: r.Sandbox} } func (m macGate) Verify(id string) bool { return m.g.Verify(id) } // Acknowledge: the step's recovery committed what Verify proved of id. func (m macGate) Acknowledge(id string) { m.g.Acknowledge(id, mac.ConsumerStep) } // acknowledge tells a gate that keeps evidence for its proofs (a Mac's) // that the step's recovery committed what it proved of id. func acknowledge(g GateRunner, id string) { if a, ok := g.(interface{ Acknowledge(string) }); ok { a.Acknowledge(id) } } // macChecks chooses each attempt's gate from the probe report this // process made and still trusts (macProbes.trusted): srt and seatbelt // when P2 denied; srt still, labelled none, when the fixture at least // built under srt (the boundary is unproven, not absent); otherwise no // sandbox, labelled none. Once any check has run labelled none the // runner is tainted for good (macTaint): it never labels a check // sandboxed again. type macChecks struct { probes *macProbes taint *macTaint // creds is the Mac's credential operations: its hold decides whether // a check may run outside the sandbox at all (unsandboxedAllowed). creds *macCreds srt string sandboxed, unproven, bare *mac.Gate } func (m *macChecks) pick() *mac.Gate { r, ok := m.probes.trusted() switch { case !ok || m.srt == "": return m.bare case r.Sandboxed() && !m.taint.Tainted(): return m.sandboxed case r.Sandboxed() || r.SRTRanXcode: return m.unproven } return m.bare } func (m *macChecks) Sandbox() string { return m.pick().Sandbox } // Run runs a check outside the sandbox (bare, or srt unproven) only when // the person chose that for this attempt (unsandboxedChosen) and the Mac // holds no model credential (unsandboxedAllowed); otherwise it runs // nothing, taints nothing and says sandbox_unproven, which the instance // turns back into waiting for the Mac's sandbox. It taints the runner // before a check runs outside the sandbox: what it runs could change // anything this user may. func (m *macChecks) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) gateResult { g := m.pick() if g.Sandbox != wire.SandboxSeatbelt { refused := gateResult{reason: wire.ReasonSandboxUnproven, terminated: true, sandbox: g.Sandbox} if !unsandboxedChosen(ctx) || !m.unsandboxedAllowed(ctx) { return refused } m.taint.Set() // Read again now the taint is set: a token store checks the taint // in its own turn, so one that got past that check before it was // set is on record here (its attempt holds from its start), and // the check never shares the Mac with it. The Mac stays tainted. if !m.unsandboxedAllowed(ctx) { return refused } } return macGate{g}.Run(ctx, attempt, dir, argv, limit, record) } // unsandboxedAllowed is D1 on the worker (Paul, 2026-11-28): no check // runs outside the sandbox here while this Mac holds, or may hold, a // model credential (its durable hold: an attempt connecting, a sign-out // owed, a binding, anything in the accounts root, a Keychain record). // Before its connections open nothing says it holds none, so it refuses. // If Paul rules otherwise, this and the instance's unsandboxedAllowed // are the change (with the warning naming the Claude connection). func (m *macChecks) unsandboxedAllowed(ctx context.Context) bool { return m.creds != nil && m.creds.held != nil && !m.creds.held(ctx) } // unsandboxedKey carries an attempt's recorded choice to run outside the // sandbox from its dispatch (DispatchCommand.Unsandboxed, protocol 7) to // the gate that runs it. type unsandboxedKey struct{} // withUnsandboxed is ctx for an attempt whose dispatch carried the // person's choice to run outside the sandbox (chosen). func withUnsandboxed(ctx context.Context, chosen bool) context.Context { if !chosen { return ctx } return context.WithValue(ctx, unsandboxedKey{}, true) } // unsandboxedChosen reports whether the person chose to run this attempt // outside the sandbox. func unsandboxedChosen(ctx context.Context) bool { chosen, _ := ctx.Value(unsandboxedKey{}).(bool) return chosen } // Verify settles a recorded attempt the same way whatever confined it, // with the user temp, so the attempt's own unfinished cleanup is // finished once its end is proven. func (m *macChecks) Verify(id string) bool { return m.sandboxed.Verify(id) } // Acknowledge is macGate's, on the gate that verifies. func (m *macChecks) Acknowledge(id string) { m.sandboxed.Acknowledge(id, mac.ConsumerStep) } // macTaint is sticky: set once a check ran outside the sandbox, kept in // the state dir and by the instance (which says so in every welcome), so // deleting the file does not clear it. Only installing again as a new // Mac user starts clean. type macTaint struct { file string on atomic.Bool changed func() } func loadTaint(file string) *macTaint { t := &macTaint{file: file} if _, err := os.Lstat(file); err == nil { t.on.Store(true) } return t } func (t *macTaint) Tainted() bool { return t.on.Load() } // Set taints the runner (again is harmless). func (t *macTaint) Set() { if t.on.Swap(true) { return } _ = os.WriteFile(t.file, []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), 0600) if t.changed != nil { t.changed() } } // probeTrust is how long a probe report is trusted. const probeTrust = 24 * time.Hour // macProbes holds the probe report in this process's memory only. // Nothing on disk is ever read back as a verdict: a gate that ran // outside the sandbox runs as this user and could write any file this // process could. A report is trusted while it is this runner version's, // for this checks profile, made with the srt, Node and ripgrep that are // on disk now matching the pins compiled into this binary (verified), // and less than a day old; otherwise checks // run as not verified. The probes run again only when that can change // the answer (see untrusted), not on every look. `equipo-runner probe` // asks for a run at once (request): a forged request costs a probe run // and never upgrades trust. type macProbes struct { version string run func(context.Context) mac.Report verified func() bool // fingerprint names the tools on disk a report depends on (cheaply: // paths, link targets, sizes and times); nil is "". fingerprint func() string request string now func() time.Time // log hears each run start and finish, with the verdicts, and why a // report is not trusted. log *slog.Logger mu sync.Mutex last mac.Report ready chan struct{} again chan struct{} // What the last run was made with and when it started; whether a // run asked for by untrusted has yet to report; the wait before the // next run of an unchanged untrusted report; the last reason warned. ranWith string ranAt time.Time pending bool backoff time.Duration warned string } // probeRetry is the first wait before an untrusted report whose inputs // have not changed is probed again; it doubles up to probeTrust. const probeRetry = time.Hour func newMacProbes(version, request string, run func(context.Context) mac.Report, verified func() bool) *macProbes { return &macProbes{version: version, request: request, run: run, verified: verified, now: time.Now, ready: make(chan struct{}), again: make(chan struct{}, 1), backoff: probeRetry} } // inputs is what a report depends on: this binary's version, the tools' // fingerprint and whether they match their pins. func (p *macProbes) inputs(verified bool) string { fp := "" if p.fingerprint != nil { fp = p.fingerprint() } return p.version + "|" + strconv.FormatBool(verified) + "|" + fp } // report is the newest report, for the instance to show. func (p *macProbes) report() mac.Report { p.mu.Lock() defer p.mu.Unlock() return p.last } // trusted is the newest report and whether it may decide a gate now. func (p *macProbes) trusted() (mac.Report, bool) { r := p.report() verified, now := p.verified(), p.now() ok := r.Version == p.version && r.Profile == mac.ProfileDigest() && r.SRT == srtPinned && verified && !r.At.IsZero() && now.Sub(r.At) < probeTrust && now.Sub(r.At) >= -time.Minute if !ok && !r.At.IsZero() { p.untrusted(r, verified, now) } return r, ok } // untrusted decides whether an untrusted report is probed again. Every // hello and every check looks, so asking each time would run the whole // suite on every heartbeat. A run is asked for when the report expired, // or what it was made with changed (the version, the tools' fingerprint, // whether they match their pins), or else once probeRetry has passed // since the last run, the wait doubling each time up to a day. One run // at a time: none is asked for while one asked for has yet to report. // Each reason, and each run it asks for, is warned once. func (p *macProbes) untrusted(r mac.Report, verified bool, now time.Time) { reason := "" switch { case r.Version != p.version || r.Profile != mac.ProfileDigest(): reason = "the report is another runner version's or checks profile's" case !verified: reason = "srt or its tools on disk do not match their pins" case r.SRT != srtPinned: reason = "the report was made with tools that did not match their pins" case now.Sub(r.At) < -time.Minute: reason = "the report is dated in the future" default: reason = "the report is more than a day old" } expired := now.Sub(r.At) >= probeTrust || now.Sub(r.At) < -time.Minute inputs := p.inputs(verified) p.mu.Lock() again, why := false, "" switch { case p.pending: case expired: again, why = true, "expired" case inputs != p.ranWith: again, why, p.backoff = true, "its inputs changed", probeRetry case now.Sub(p.ranAt) >= p.backoff: again, why = true, "retry after "+p.backoff.String() p.backoff = min(2*p.backoff, probeTrust) } if again { p.pending = true } warn := again || reason != p.warned p.warned = reason p.mu.Unlock() if warn && p.log != nil { attrs := []any{"reason", reason, "probe_again", again} if again { attrs = append(attrs, "because", why) } p.log.Warn("probe report not trusted", attrs...) } if again { p.probeSoon() } } func (p *macProbes) probeSoon() { select { case p.again <- struct{}{}: default: } } // start probes now and again whenever asked (a stale report, a // request), or a day after the last run. ready closes after the first // run; refresh tells the instance. func (p *macProbes) start(ctx context.Context, refresh func()) { go func() { first := true said := "" for { // The tools must match their pins before the probes and still // after them: a report made with anything else is never // trusted. before := p.verified() inputs := p.inputs(before) p.mu.Lock() p.ranWith, p.ranAt = inputs, p.now() p.mu.Unlock() // The first run at info; later ones (a day on, asked for, or // an untrusted report's retry) at debug unless their verdicts // changed. start, level := time.Now(), slog.LevelDebug if first { level = slog.LevelInfo } if p.log != nil { p.log.Log(ctx, level, "probes started") } r := p.run(ctx) if ctx.Err() != nil { return } if v := verdicts(r.Probes); p.log != nil { if v != said { level = slog.LevelInfo } p.log.Log(ctx, level, "probes finished", "took", took(start), "verdicts", v) said = v } if len(r.Unfinished) > 0 && p.log != nil { p.log.Warn("probe run reached its limit; unfinished probes are not proven", "unfinished", strings.Join(r.Unfinished, " ")) } if before && p.verified() { r.SRT = srtPinned } p.mu.Lock() p.last, p.pending = r, false p.mu.Unlock() if first { close(p.ready) first = false } refresh() select { case <-ctx.Done(): return case <-p.again: case <-time.After(probeTrust - time.Hour): } } }() } // watch turns `equipo-runner probe` (it touches the request file) into a // new probe run. func (p *macProbes) watch(ctx context.Context) { var seen time.Time if info, err := os.Stat(p.request); err == nil { seen = info.ModTime() } for { select { case <-ctx.Done(): return case <-time.After(30 * time.Second): } if info, err := os.Stat(p.request); err == nil && !info.ModTime().Equal(seen) { seen = info.ModTime() p.probeSoon() } } } // verdicts is each probe's name and verdict ("P1=passed P2=denied"), // never its detail. func verdicts(probes []wire.Probe) string { out := make([]string, 0, len(probes)) for _, p := range probes { out = append(out, p.ID+"="+p.Verdict) } return strings.Join(out, " ") } func (p *macProbes) wait(ctx context.Context) error { select { case <-p.ready: return nil case <-ctx.Done(): return ctx.Err() } } // toolFingerprint names the tools a probe report depends on without // reading them (verified hashes them): each one's path, link target, // size, mode and modification time, and the srt package tree's. func toolFingerprint(installDir string, t mac.Tools) string { var b strings.Builder for _, path := range []string{t.SRT, t.Node, t.RG, filepath.Join(installDir, "srt", "node_modules")} { b.WriteString(path) if target, err := os.Readlink(path); err == nil { b.WriteString(" -> " + target) } if info, err := os.Stat(path); err == nil { b.WriteString(" " + strconv.FormatInt(info.Size(), 10) + " " + info.Mode().String() + " " + strconv.FormatInt(info.ModTime().UnixNano(), 10)) } b.WriteByte('\n') } return b.String() } // srtPinned marks a report made with srt, Node and ripgrep matching the // pins compiled into this binary. const srtPinned = "pinned" // macUsers is where a Mac keeps its people's homes. var macUsers = "/Users" // macUserTemp resolves the runner user's DARWIN_USER_TEMP_DIR (tests // stand in: a Linux host has none). var macUserTemp = func(ctx context.Context, x mac.Exec) (string, error) { return mac.UserTemp(ctx, x, os.Getuid(), mac.UserTempPrefix) } // macHost is the Mac worker's setup: its tools, paths and gates. type macHost struct { // scratch is the runner's scratch root: the probes' fixture copies // live there, outside every denied place. scratch string paths mac.Paths tools mac.Tools env []string probes *macProbes checks *macChecks taint *macTaint caps func(context.Context) wire.Capabilities // log hears slow commands, and each command of the first capability // gathering (capsLogged) and of xcode-select at start. log *slog.Logger capsLogged atomic.Bool // turns lets one gate at a time run (mac.Turns). turns *mac.Turns // creds is the Claude credential's guards and operations // (maccreds.go). creds *macCreds // fetchClaude fetches the pinned Claude Code (mac.OfficialClaude). fetchClaude mac.ClaudeFetch // version is this runner's; eng its F probes and Engineering status // (mac_fprobe.go). version string eng *macEngineering // runner is this runner's own binary: P2's direct kernel reader. runner string // warmMu guards warmed, the Xcode (version and build) whose plugin // cache was last warmed. warmMu sync.Mutex warmed string } // warm builds Xcode's plugin cache (DARWIN_USER_CACHE_DIR/ // com.apple.DeveloperTools//Xcode/PlugInCache-xcodebuild. // xcplugincache) outside the sandbox, once per Xcode version and build: // a checks profile does not let a gate write it, so a sandboxed // xcodebuild must find it current. Bounded by QueryLimit. func (h *macHost) warm(ctx context.Context, x wire.Xcode) { key := x.Version + " " + x.Build if x.Version == "" || h.tools.Xcodebuild == "" { return } h.warmMu.Lock() defer h.warmMu.Unlock() // Not while a gate runs (its T cleanup could take what the warm // writes there): the next gathering tries again, as after a failure. if h.warmed == key { return } if h.turns != nil { turn, ok := h.turns.TryTake(mac.OpWarm) if !ok { return } defer turn.Give() // Nor while an earlier attempt's end is unproven (its cleanup // pending): the next gate settles that first. if h.turns.Pending() { return } } c, cancel := context.WithTimeout(ctx, mac.QueryLimit) defer cancel() if _, err := h.run(c, h.tools.Xcodebuild, "-showsdks"); err != nil { if h.log != nil { h.log.Info("xcode plugin cache not warmed", "xcode", key, "err", err) } return } h.warmed = key } // claudeHere: only a darwin/arm64 worker provisions the pinned Claude // Code (the only darwin pin). Tests on Linux never fetch it. var claudeHere = runtime.GOOS == "darwin" && runtime.GOARCH == "arm64" // slowCommand is how long a command the Mac worker runs may take before // it is logged as slow: while it still runs, so a hung child shows. var slowCommand = 10 * time.Second // commandWaitDelay bounds how long run waits for a command's output once // it has exited or been killed: a grandchild still holding the pipe // cannot hold the runner. var commandWaitDelay = 5 * time.Second // Mac tool discovery (spec §3.3): EQUIPO_SRT_PATH and the installer's // private srt first, then the usual places. Claude Code is not // discovered: no EQUIPO_CLAUDE_PATH, no claude on a path (spec §8.2). func macTools(installDir, home string, getenv func(string) string) mac.Tools { dirs := []string{filepath.Join(installDir, "srt", "node_modules", ".bin"), filepath.Join(home, ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"} pinned := mac.PinnedTools(installDir) at := map[string]string{"srt": pinned.SRT, "node": pinned.Node, "rg": pinned.RG} find := func(env, name string) string { if p := getenv(env); filepath.IsAbs(p) && executable(p) { return p } if p := at[name]; p != "" && executable(p) { return p } for _, d := range dirs { if p := filepath.Join(d, name); executable(p) { return p } } return "" } return mac.Tools{Xcodebuild: "/usr/bin/xcodebuild", Xcrun: "/usr/bin/xcrun", Swift: "/usr/bin/swift", Git: getenv("EQUIPO_GIT_PATH"), SRT: find("EQUIPO_SRT_PATH", "srt"), Node: find("EQUIPO_NODE_PATH", "node"), RG: find("EQUIPO_RG_PATH", "rg"), Codex: find("EQUIPO_CODEX_PATH", "codex"), // Never looked up: the pinned CLI the worker provisions itself. Claude: mac.NewClaudeCLI(home, installDir)} } func executable(p string) bool { info, err := os.Stat(p) return err == nil && info.Mode().IsRegular() && info.Mode().Perm()&0111 != 0 } // run runs a tool with the runner's own environment but its PATH: the // runner's Node and ripgrep first (srt starts through `env node` and // looks for rg there), then the system's. launchd gives an agent only // the system PATH. func (h *macHost) run(ctx context.Context, name string, args ...string) (string, error) { cmd := exec.CommandContext(ctx, name, args...) cmd.Env = withPath(os.Environ(), gatePath(h.tools)) // Its own process group, killed whole at the timeout, and a bounded // wait for its output: a grandchild holding the pipe (xcrun, swift // or claude starting a helper) cannot block run past its timeout. ownGroup(cmd) cmd.WaitDelay = commandWaitDelay done := h.watchSlow(name, args) // The runner's own helper (mac.StartOwn): a turn's sweep spares it. var buf strings.Builder cmd.Stdout = &buf err := mac.StartOwn(cmd) if err == nil { err = cmd.Wait() } out := buf.String() if errors.Is(err, exec.ErrWaitDelay) { // The command itself exited successfully; only something it left // behind in its group still held the pipe. That goes, and what // the command printed is its answer. _ = killGroup(cmd) err = nil if h.log != nil { h.log.Debug("command left a helper holding its output; helper killed", "cmd", name, "args", logArgs(args)) } } done(err) return out, err } // watchSlow warns when a command is still running after slowCommand, // and again with its time and error when such a command ends. func (h *macHost) watchSlow(name string, args []string) func(error) { if h.log == nil { return func(error) {} } start, limit := time.Now(), slowCommand t := time.AfterFunc(limit, func() { h.log.Warn("command still running", "cmd", name, "args", logArgs(args), "after", limit) }) return func(err error) { if t.Stop() { return } attrs := []any{"cmd", name, "args", logArgs(args), "took", took(start)} if err != nil { attrs = append(attrs, "err", err.Error()) } h.log.Warn("slow command finished", attrs...) } } // logged runs a command through run and logs it at level with its time // and, when it failed, its exit status. func (h *macHost) logged(level slog.Level) mac.Exec { return func(ctx context.Context, name string, args ...string) (string, error) { start := time.Now() out, err := h.run(ctx, name, args...) if h.log != nil { attrs := []any{"cmd", name, "args", logArgs(args), "took", took(start)} if err != nil { attrs = append(attrs, "err", err.Error()) } h.log.Log(ctx, level, "command", attrs...) } return out, err } } // logArgs is a command's arguments for a log line, a password argument's // value (security -w) withheld. func logArgs(args []string) string { out := make([]string, len(args)) for i, a := range args { if i > 0 && args[i-1] == "-w" { a = "[withheld]" } out[i] = a } return strings.Join(out, " ") } func withPath(env []string, path string) []string { out := []string{"PATH=" + path} for _, kv := range env { if !strings.HasPrefix(kv, "PATH=") { out = append(out, kv) } } return out } // gatePath is a gate's fixed PATH: the system's, Homebrew's, and Node's // directory (srt runs on Node). func gatePath(t mac.Tools) string { dirs := []string{"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/opt/homebrew/bin", "/usr/local/bin"} for _, tool := range []string{t.Node, t.RG} { if tool != "" { if d := filepath.Dir(tool); !contains(dirs, d) { dirs = append([]string{d}, dirs...) } } } return strings.Join(dirs, ":") } func contains(list []string, s string) bool { for _, x := range list { if x == s { return true } } return false } func newMacHost(c runner.Config, o Options) (h *macHost, err error) { done := startPhase(o.Logger, "mac_host") defer func() { done(err) }() getenv := o.Getenv if getenv == nil { getenv = os.Getenv } home, err := os.UserHomeDir() if err != nil { return nil, err } accounts := o.AccountsRoot if accounts == "" { accounts = DefaultAccountsRoot() } h = &macHost{scratch: c.ScratchRoot, log: o.Logger, version: o.Version, runner: c.Executable} h.eng = newMacEngineering(h) others, err := mac.OtherHomes(macUsers, home) h.paths = mac.Paths{Home: home, StateDir: c.StateDir, AccountsRoot: accounts, SessionRoot: SessionRoot(c), InstallDir: filepath.Dir(c.Executable), OtherHomes: others, HomesUnknown: err != nil} h.tools = macTools(h.paths.InstallDir, home, getenv) h.fetchClaude = mac.OfficialClaude(getenv) h.env = []string{"HOME=" + home, "PATH=" + gatePath(h.tools), "CI=1", "LANG=en_US.UTF-8"} // One turn for every operation (a gate, a probe run, the warm, and // Engineering, asks and token operations), across this user's runner // processes. On a Mac each turn's end also sweeps the runner user // (spec §8.8); off a Mac there is no such table and nothing sweeps. h.turns = mac.NewTurns(filepath.Join(c.StateDir, "mac-gate.lock")) if p := mac.MachineProcs(); p != nil { h.turns.Sweep(p) } ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) if out, err := h.logged(slog.LevelInfo)(ctx, "/usr/bin/xcode-select", "-p"); err == nil && filepath.IsAbs(strings.TrimSpace(out)) { h.env = append(h.env, "DEVELOPER_DIR="+strings.TrimSpace(out)) } // The user's T, which checks may write: refused, no checks profile // can be made, P2 says why and checks wait for the sandbox. if t, err := macUserTemp(ctx, h.logged(slog.LevelInfo)); err == nil { h.paths.UserTemp = t } else { h.paths.UserTempWhy = "not resolved" var why *mac.UserTempError if errors.As(err, &why) { h.paths.UserTempWhy = why.Why } if h.log != nil { h.log.Warn("user temp folder refused", "why", h.paths.UserTempWhy) } } cancel() settings := func(tree, attempt string) ([]byte, error) { return mac.ChecksSettings(mac.ChecksInput{Paths: h.paths, Tree: tree, Attempt: attempt, Mach: mac.CheckMachServices}) } // Both bounded: a simctl that never answers (CoreSimulator stuck) // must not hold a gate or a probe run. booted := func(ctx context.Context) []string { c, cancel := context.WithTimeout(ctx, mac.QueryLimit) defer cancel() out, err := h.run(c, h.tools.Xcrun, "simctl", "list", "-j", "devices", "booted") var udids []string if err == nil { for _, s := range mac.ParseSimulators([]byte(out)) { if s.State == "Booted" { udids = append(udids, s.UDID) } } } return udids } shutdown := func(ctx context.Context, udid string) { c, cancel := context.WithTimeout(ctx, time.Minute) defer cancel() _, _ = h.run(c, h.tools.Xcrun, "simctl", "shutdown", udid) } gate := func(srt, label string) *mac.Gate { g := &mac.Gate{SRT: srt, Env: h.env, Caffeinate: "/usr/bin/caffeinate", Booted: booted, Shutdown: shutdown, Lines: wire.MaxChecksLines, Sandbox: label, Turns: h.turns} if srt != "" { g.Settings, g.UserTemp, g.QuietSimulators = settings, h.paths.UserTemp, h.quietSimulators } return g } h.probes = newMacProbes(o.Version, ProbeRequest(c), func(ctx context.Context) mac.Report { h.warmNow(ctx) return mac.RunProbes(ctx, h.probeHost(o.Version, gate)) }, func() bool { return mac.VerifyTools(h.paths.InstallDir, h.tools) == nil }) h.probes.log = o.Logger h.probes.fingerprint = func() string { return toolFingerprint(h.paths.InstallDir, h.tools) } h.taint = loadTaint(filepath.Join(c.StateDir, "tainted")) h.creds = h.newCreds(c) h.checks = &macChecks{probes: h.probes, taint: h.taint, creds: h.creds, srt: h.tools.SRT, sandboxed: gate(h.tools.SRT, wire.SandboxSeatbelt), unproven: gate(h.tools.SRT, wire.SandboxNone), bare: gate("", wire.SandboxNone)} h.caps = func(ctx context.Context) wire.Capabilities { // The first gathering is the one the first hello waits on: each // command at info. Later ones (hourly, each check's gate) at debug. level := slog.LevelDebug if h.capsLogged.CompareAndSwap(false, true) { level = slog.LevelInfo } // Outside the turn (the coordinator's ruling): a T cleanup may take // these queries' temp files, which costs availability only. caps := mac.Capabilities(ctx, h.logged(level), h.tools) h.warm(ctx, caps.Xcode) if probes := h.probes.report().Probes; len(probes) > 0 { caps.Probes = probes } caps.Tainted = h.taint.Tainted() h.credentialCaps(ctx, &caps) h.eng.compose(&caps) if code, n := h.turns.Unproven(); code != "" && caps.Unproven == "" { caps.Unproven, caps.UnprovenCount = code, n } return caps } return h, nil } // credentialCaps says why the Mac can take no Claude connection, if its // guards say so (maccreds.go), and as which user, and looks again for a // Keychain item it found. func (h *macHost) credentialCaps(ctx context.Context, caps *wire.Capabilities) { caps.Engineering = h.creds.status() if wire.ValidRunnerUser(h.creds.user) { // As whom the Machines page says to close a folder. caps.RunnerUser = h.creds.user } if h.creds.Held() { h.creds.settle(ctx, false) } if left, err := h.creds.keychain.Unproven(); err != nil || len(left) > 0 { // Said before an incomplete attempt record: it closes the Mac's // connections, and a restart of the Mac clears it. caps.Unproven = wire.UnprovenCredential } } // engineering is the Mac's Engineering pieces: an executor for an attempt // with sandboxed Xcode access (the user's T cleaned after it, the // simulators quieted first), xcode-select's developer dir, and whether // this process's own trusted probe report allows that access now: P2 and // F5 denied, the user's T resolved, the runner not tainted. func (h *macHost) engineering() *WorkerEngineering { dev := "" for _, kv := range h.env { if v, ok := strings.CutPrefix(kv, "DEVELOPER_DIR="); ok { dev = v } } return &WorkerEngineering{XcodeExec: &mac.Executor{Turns: h.turns, UserTemp: h.paths.UserTemp, QuietSimulators: h.quietSimulators}, DeveloperDir: dev, Leaks: h.leaks, Xcode: func() bool { r, ok := h.probes.trusted() if !ok || !r.Sandboxed() || h.paths.UserTemp == "" || h.taint.Tainted() { return false } ctx, cancel := context.WithTimeout(context.Background(), 2*mac.QueryLimit) defer cancel() return h.eng.xcodeNow(ctx) }} } // simShutdownLimit bounds `simctl shutdown all` before a T cleanup. // It shuts every booted simulator down one after another, each taking // seconds to tens of seconds, so QueryLimit (30 s) would cut a Mac with // a few booted short; two minutes is the most an attempt's end waits. var simShutdownLimit = 2 * time.Minute // macPS lists this user's processes by name (tests stand in). var macPS = "/bin/ps" // quietSimulators shuts down every simulator of the runner user (a // dedicated user, so all are the runner's) before a sandboxed // attempt's T is cleaned: CoreSimulator's processes are outside the // attempt's group and outside srt, and may still write T. Bounded; it // never fails the attempt. What simulator processes are left is // logged at info, names only. func (h *macHost) quietSimulators(ctx context.Context) { c, cancel := context.WithTimeout(ctx, simShutdownLimit) _, err := h.run(c, h.tools.Xcrun, "simctl", "shutdown", "all") cancel() if h.log == nil { return } if err != nil { h.log.Info("simulators not all shut down", "err", err) } c, cancel = context.WithTimeout(ctx, mac.QueryLimit) out, _ := h.run(c, macPS, "-x", "-o", "comm=") cancel() var left []string for _, l := range strings.Split(out, "\n") { if n := filepath.Base(strings.TrimSpace(l)); strings.Contains(strings.ToLower(n), "sim") && !slices.Contains(left, n) { left = append(left, n) } } if len(left) > 0 { slices.Sort(left) h.log.Info("simulator processes still running", "names", strings.Join(left, " ")) } } // warmNow warms the plugin cache for the Xcode installed now (the // probes run before any capability gathering may have). func (h *macHost) warmNow(ctx context.Context) { c, cancel := context.WithTimeout(ctx, mac.QueryLimit) out, _ := h.run(c, h.tools.Xcodebuild, "-version") cancel() h.warm(ctx, mac.ParseXcode(out)) } func (h *macHost) probeHost(version string, gate func(string, string) *mac.Gate) mac.ProbeHost { // P2's reader is this runner's own binary, when it is one. reader := "" if executable(h.runner) { reader = h.runner } return mac.ProbeHost{Exec: h.run, Tools: h.tools, Paths: h.paths, Scratch: filepath.Join(h.scratch, "probes"), Runner: reader, UID: os.Getuid(), Version: version, Turns: h.turns, Gate: func(sandboxed bool) *mac.Gate { if sandboxed { return gate(h.tools.SRT, wire.SandboxSeatbelt) } return gate("", wire.SandboxNone) }, Resolve: func(ctx context.Context, name string) bool { addrs, err := net.DefaultResolver.LookupHost(ctx, name) return err == nil && len(addrs) > 0 }, Exposed: mac.Exposed, Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }, Warn: h.warn, } } // warn is runner.log at WARN, nil when there is no log. func (h *macHost) warn(msg string, args ...any) { if h.log != nil { h.log.Warn(msg, args...) } } // find chooses a Mac's gate: the repository's own (with macOS's bash), // else xcodebuild test for an Xcode project. func (h *macHost) find(dir string) (gate, string, bool) { if g, ok := findGate(dir); ok { if len(g.argv) > 0 && g.argv[0] == "/usr/bin/bash" { g.argv = append([]string{"/bin/bash"}, g.argv[1:]...) } return g, "", true } ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() argv, ok, reason := mac.XcodeGate(dir, h.caps(ctx).Simulators) if !ok { return gate{}, "", false } return gate{name: mac.XcodeGateName, argv: argv}, reason, true } // runMac serves the instance as a Mac worker. func runMac(ctx context.Context, c runner.Config, o Options) error { h, err := newMacHost(c, o) if err != nil { return err } return serveMac(ctx, c, o, h) } // serveMac serves the instance as the Mac worker h sets up. func serveMac(ctx context.Context, c runner.Config, o Options, h *macHost) error { if o.Logger != nil && h.tools.SRT == "" { o.Logger.Warn("srt is not installed: checks run outside the sandbox and say so") } up := &macUpdater{origin: c.Origin, version: o.Version, binary: c.Executable, fetch: fetchLimited} return runWorker(ctx, c, o, hostPlatform(), workerSetup{probe: h.caps, gate: h.checks, find: h.find, ready: h.probes.wait, creds: h.creds, engineering: h.engineering(), fprobes: h.eng, started: func(ctx context.Context, refresh func()) { h.taint.changed = refresh h.probes.start(ctx, func() { refresh(); h.eng.soon() }) h.eng.start(ctx, refresh) go h.probes.watch(ctx) if claudeHere { go mac.KeepClaude(ctx, h.tools.Claude, h.fetchClaude, refresh, h.warn) } }, welcomed: func(w wire.Welcome, worker *Worker, stop context.CancelCauseFunc) { if w.Tainted { h.taint.Set() } up.offer(w, worker.hold, func() { stop(ErrUpdated) }, o.Logger) }}) } // ProbeRequest is the file `equipo-runner probe` touches to ask the // running worker to probe again. func ProbeRequest(c runner.Config) string { return filepath.Join(c.StateDir, "probe-request") } // RunProbes runs the Mac probes now in this process, for the person // asking, and asks the running worker to run its own: only a worker's // own run decides how it confines checks. func RunProbes(ctx context.Context, c runner.Config, o Options) (mac.Report, error) { h, err := newMacHost(c, o) if err != nil { return mac.Report{}, err } r := h.probes.run(ctx) if err := ctx.Err(); err != nil { return r, err } now := time.Now() if f, err := os.OpenFile(ProbeRequest(c), os.O_CREATE|os.O_WRONLY, 0600); err == nil { f.Close() } return r, os.Chtimes(ProbeRequest(c), now, now) } // macUpdater replaces the worker's binary with the release its instance // serves (spec §3.3): the darwin/arm64 runner of that release's install // manifest, verified against its digest, swapped between steps; then the // worker exits mac.ExitUpdated and launchd starts the new one. type macUpdater struct { origin, version, binary string fetch func(ctx context.Context, url string, limit int64) ([]byte, error) once sync.Once done chan error } func (u *macUpdater) offer(w wire.Welcome, hold func() func(), stop func(), log interface{ Warn(string, ...any) }) { if w.Release == "" || w.Release == u.version || !release.ValidInstallVersion(w.Release) { return } u.once.Do(func() { u.done = make(chan error, 1) go func() { err := u.apply(context.Background(), w.Release, hold, stop) if err != nil && log != nil { log.Warn("update to the instance's release failed", "release", w.Release, "err", err) } u.done <- err }() }) } func (u *macUpdater) apply(ctx context.Context, version string, hold func() func(), stop func()) error { base := u.origin + "/releases/" + version + "/" raw, err := u.fetch(ctx, base+"install-manifest.json", 1<<20) if err != nil { return err } var m release.InstallManifest if err := json.Unmarshal(raw, &m); err != nil { return err } t, err := m.DarwinTarget(version) if err != nil { return err } bin, err := u.fetch(ctx, base+release.DarwinDir+"/equipo-runner", 128<<20) if err != nil { return err } if sum := sha256.Sum256(bin); hex.EncodeToString(sum[:]) != t.RunnerSHA256 { return errors.New("the release's runner does not match its digest") } tmp, err := os.CreateTemp(filepath.Dir(u.binary), ".equipo-runner-update-") if err != nil { return err } defer os.Remove(tmp.Name()) if _, err = tmp.Write(bin); err == nil { err = tmp.Chmod(0700) } if err == nil { err = tmp.Sync() } if cerr := tmp.Close(); err == nil { err = cerr } if err != nil { return err } // Between steps: no attempt runs while the binary changes. release := hold() defer release() if err := os.Rename(tmp.Name(), u.binary); err != nil { return err } stop() return nil } // fetchLimited GETs url (no redirects) and refuses more than limit bytes. func fetchLimited(ctx context.Context, url string, limit int64) ([]byte, error) { c := http.Client{Timeout: 5 * time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } resp, err := c.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return nil, errors.New("release download: " + resp.Status) } b, err := io.ReadAll(io.LimitReader(resp.Body, limit+1)) if err != nil || int64(len(b)) > limit { return nil, errors.New("release download too large") } return b, nil } // leaks scans stage with the pinned gitleaks beside the runner, in the // Mac's checks gate, and only in the sandboxed one: the gate that P2's // trusted verdict picks for checks, on a runner never tainted. Anything // else cannot confine it, so it cannot scan and nothing leaves. func (h *macHost) leaks(ctx context.Context, stage, marker string, record func(string) error) (bool, error) { if g := h.checks.pick(); g != h.checks.sandboxed { return false, errScanner } binary, pin := previewScannerTool(runner.Config{Executable: filepath.Join(h.paths.InstallDir, "equipo-runner")}) return gateLeaks(ctx, h.checks.sandboxed, binary, pin, stage, marker, record) }