oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "context"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "errors"
9 "io"
10 "log/slog"
11 "net"
12 "net/http"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "runtime"
17 "slices"
18 "strconv"
19 "strings"
20 "sync"
21 "sync/atomic"
22 "time"
23
24 "amadan.net/oficina/equipo/internal/release"
25 "amadan.net/oficina/equipo/internal/runner"
26 "amadan.net/oficina/equipo/internal/runner/mac"
27 "amadan.net/oficina/equipo/internal/wire"
28)
29
30// A Mac worker (Mac runners spec §§3 to 5): checks only, under srt when
31// probe P2 denied every hostile attempt, otherwise outside the sandbox
32// and labelled so (Paul's ruling 2). The pieces are in internal/runner/
33// mac; this file wires them to the worker.
34
35// macGate adapts a Mac gate to the worker's GateRunner.
36type macGate struct{ g *mac.Gate }
37
38// A Mac launch of the pinned CLI goes through the same starter as a
39// Linux one (recordedStart).
40var _ starter = (*mac.Starter)(nil)
41
42func (m macGate) Sandbox() string { return m.g.Sandbox }
43
44func (m macGate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) gateResult {
45 r := m.g.Run(ctx, attempt, dir, argv, limit, record)
46 return gateResult{output: r.Output, reason: r.Reason, code: r.Code, terminated: r.Terminated, sandbox: r.Sandbox}
47}
48
49func (m macGate) Verify(id string) bool { return m.g.Verify(id) }
50
51// Acknowledge: the step's recovery committed what Verify proved of id.
52func (m macGate) Acknowledge(id string) { m.g.Acknowledge(id, mac.ConsumerStep) }
53
54// acknowledge tells a gate that keeps evidence for its proofs (a Mac's)
55// that the step's recovery committed what it proved of id.
56func acknowledge(g GateRunner, id string) {
57 if a, ok := g.(interface{ Acknowledge(string) }); ok {
58 a.Acknowledge(id)
59 }
60}
61
62// macChecks chooses each attempt's gate from the probe report this
63// process made and still trusts (macProbes.trusted): srt and seatbelt
64// when P2 denied; srt still, labelled none, when the fixture at least
65// built under srt (the boundary is unproven, not absent); otherwise no
66// sandbox, labelled none. Once any check has run labelled none the
67// runner is tainted for good (macTaint): it never labels a check
68// sandboxed again.
69type macChecks struct {
70 probes *macProbes
71 taint *macTaint
72 // creds is the Mac's credential operations: its hold decides whether
73 // a check may run outside the sandbox at all (unsandboxedAllowed).
74 creds *macCreds
75 srt string
76 sandboxed, unproven, bare *mac.Gate
77}
78
79func (m *macChecks) pick() *mac.Gate {
80 r, ok := m.probes.trusted()
81 switch {
82 case !ok || m.srt == "":
83 return m.bare
84 case r.Sandboxed() && !m.taint.Tainted():
85 return m.sandboxed
86 case r.Sandboxed() || r.SRTRanXcode:
87 return m.unproven
88 }
89 return m.bare
90}
91
92func (m *macChecks) Sandbox() string { return m.pick().Sandbox }
93
94// Run runs a check outside the sandbox (bare, or srt unproven) only when
95// the person chose that for this attempt (unsandboxedChosen) and the Mac
96// holds no model credential (unsandboxedAllowed); otherwise it runs
97// nothing, taints nothing and says sandbox_unproven, which the instance
98// turns back into waiting for the Mac's sandbox. It taints the runner
99// before a check runs outside the sandbox: what it runs could change
100// anything this user may.
101func (m *macChecks) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string) error) gateResult {
102 g := m.pick()
103 if g.Sandbox != wire.SandboxSeatbelt {
104 refused := gateResult{reason: wire.ReasonSandboxUnproven, terminated: true, sandbox: g.Sandbox}
105 if !unsandboxedChosen(ctx) || !m.unsandboxedAllowed(ctx) {
106 return refused
107 }
108 m.taint.Set()
109 // Read again now the taint is set: a token store checks the taint
110 // in its own turn, so one that got past that check before it was
111 // set is on record here (its attempt holds from its start), and
112 // the check never shares the Mac with it. The Mac stays tainted.
113 if !m.unsandboxedAllowed(ctx) {
114 return refused
115 }
116 }
117 return macGate{g}.Run(ctx, attempt, dir, argv, limit, record)
118}
119
120// unsandboxedAllowed is D1 on the worker (Paul, 2026-11-28): no check
121// runs outside the sandbox here while this Mac holds, or may hold, a
122// model credential (its durable hold: an attempt connecting, a sign-out
123// owed, a binding, anything in the accounts root, a Keychain record).
124// Before its connections open nothing says it holds none, so it refuses.
125// If Paul rules otherwise, this and the instance's unsandboxedAllowed
126// are the change (with the warning naming the Claude connection).
127func (m *macChecks) unsandboxedAllowed(ctx context.Context) bool {
128 return m.creds != nil && m.creds.held != nil && !m.creds.held(ctx)
129}
130
131// unsandboxedKey carries an attempt's recorded choice to run outside the
132// sandbox from its dispatch (DispatchCommand.Unsandboxed, protocol 7) to
133// the gate that runs it.
134type unsandboxedKey struct{}
135
136// withUnsandboxed is ctx for an attempt whose dispatch carried the
137// person's choice to run outside the sandbox (chosen).
138func withUnsandboxed(ctx context.Context, chosen bool) context.Context {
139 if !chosen {
140 return ctx
141 }
142 return context.WithValue(ctx, unsandboxedKey{}, true)
143}
144
145// unsandboxedChosen reports whether the person chose to run this attempt
146// outside the sandbox.
147func unsandboxedChosen(ctx context.Context) bool {
148 chosen, _ := ctx.Value(unsandboxedKey{}).(bool)
149 return chosen
150}
151
152// Verify settles a recorded attempt the same way whatever confined it,
153// with the user temp, so the attempt's own unfinished cleanup is
154// finished once its end is proven.
155func (m *macChecks) Verify(id string) bool { return m.sandboxed.Verify(id) }
156
157// Acknowledge is macGate's, on the gate that verifies.
158func (m *macChecks) Acknowledge(id string) { m.sandboxed.Acknowledge(id, mac.ConsumerStep) }
159
160// macTaint is sticky: set once a check ran outside the sandbox, kept in
161// the state dir and by the instance (which says so in every welcome), so
162// deleting the file does not clear it. Only installing again as a new
163// Mac user starts clean.
164type macTaint struct {
165 file string
166 on atomic.Bool
167 changed func()
168}
169
170func loadTaint(file string) *macTaint {
171 t := &macTaint{file: file}
172 if _, err := os.Lstat(file); err == nil {
173 t.on.Store(true)
174 }
175 return t
176}
177
178func (t *macTaint) Tainted() bool { return t.on.Load() }
179
180// Set taints the runner (again is harmless).
181func (t *macTaint) Set() {
182 if t.on.Swap(true) {
183 return
184 }
185 _ = os.WriteFile(t.file, []byte(time.Now().UTC().Format(time.RFC3339)+"\n"), 0600)
186 if t.changed != nil {
187 t.changed()
188 }
189}
190
191// probeTrust is how long a probe report is trusted.
192const probeTrust = 24 * time.Hour
193
194// macProbes holds the probe report in this process's memory only.
195// Nothing on disk is ever read back as a verdict: a gate that ran
196// outside the sandbox runs as this user and could write any file this
197// process could. A report is trusted while it is this runner version's,
198// for this checks profile, made with the srt, Node and ripgrep that are
199// on disk now matching the pins compiled into this binary (verified),
200// and less than a day old; otherwise checks
201// run as not verified. The probes run again only when that can change
202// the answer (see untrusted), not on every look. `equipo-runner probe`
203// asks for a run at once (request): a forged request costs a probe run
204// and never upgrades trust.
205type macProbes struct {
206 version string
207 run func(context.Context) mac.Report
208 verified func() bool
209 // fingerprint names the tools on disk a report depends on (cheaply:
210 // paths, link targets, sizes and times); nil is "".
211 fingerprint func() string
212 request string
213 now func() time.Time
214 // log hears each run start and finish, with the verdicts, and why a
215 // report is not trusted.
216 log *slog.Logger
217
218 mu sync.Mutex
219 last mac.Report
220 ready chan struct{}
221 again chan struct{}
222 // What the last run was made with and when it started; whether a
223 // run asked for by untrusted has yet to report; the wait before the
224 // next run of an unchanged untrusted report; the last reason warned.
225 ranWith string
226 ranAt time.Time
227 pending bool
228 backoff time.Duration
229 warned string
230}
231
232// probeRetry is the first wait before an untrusted report whose inputs
233// have not changed is probed again; it doubles up to probeTrust.
234const probeRetry = time.Hour
235
236func newMacProbes(version, request string, run func(context.Context) mac.Report, verified func() bool) *macProbes {
237 return &macProbes{version: version, request: request, run: run, verified: verified, now: time.Now, ready: make(chan struct{}), again: make(chan struct{}, 1), backoff: probeRetry}
238}
239
240// inputs is what a report depends on: this binary's version, the tools'
241// fingerprint and whether they match their pins.
242func (p *macProbes) inputs(verified bool) string {
243 fp := ""
244 if p.fingerprint != nil {
245 fp = p.fingerprint()
246 }
247 return p.version + "|" + strconv.FormatBool(verified) + "|" + fp
248}
249
250// report is the newest report, for the instance to show.
251func (p *macProbes) report() mac.Report {
252 p.mu.Lock()
253 defer p.mu.Unlock()
254 return p.last
255}
256
257// trusted is the newest report and whether it may decide a gate now.
258func (p *macProbes) trusted() (mac.Report, bool) {
259 r := p.report()
260 verified, now := p.verified(), p.now()
261 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
262 if !ok && !r.At.IsZero() {
263 p.untrusted(r, verified, now)
264 }
265 return r, ok
266}
267
268// untrusted decides whether an untrusted report is probed again. Every
269// hello and every check looks, so asking each time would run the whole
270// suite on every heartbeat. A run is asked for when the report expired,
271// or what it was made with changed (the version, the tools' fingerprint,
272// whether they match their pins), or else once probeRetry has passed
273// since the last run, the wait doubling each time up to a day. One run
274// at a time: none is asked for while one asked for has yet to report.
275// Each reason, and each run it asks for, is warned once.
276func (p *macProbes) untrusted(r mac.Report, verified bool, now time.Time) {
277 reason := ""
278 switch {
279 case r.Version != p.version || r.Profile != mac.ProfileDigest():
280 reason = "the report is another runner version's or checks profile's"
281 case !verified:
282 reason = "srt or its tools on disk do not match their pins"
283 case r.SRT != srtPinned:
284 reason = "the report was made with tools that did not match their pins"
285 case now.Sub(r.At) < -time.Minute:
286 reason = "the report is dated in the future"
287 default:
288 reason = "the report is more than a day old"
289 }
290 expired := now.Sub(r.At) >= probeTrust || now.Sub(r.At) < -time.Minute
291 inputs := p.inputs(verified)
292 p.mu.Lock()
293 again, why := false, ""
294 switch {
295 case p.pending:
296 case expired:
297 again, why = true, "expired"
298 case inputs != p.ranWith:
299 again, why, p.backoff = true, "its inputs changed", probeRetry
300 case now.Sub(p.ranAt) >= p.backoff:
301 again, why = true, "retry after "+p.backoff.String()
302 p.backoff = min(2*p.backoff, probeTrust)
303 }
304 if again {
305 p.pending = true
306 }
307 warn := again || reason != p.warned
308 p.warned = reason
309 p.mu.Unlock()
310 if warn && p.log != nil {
311 attrs := []any{"reason", reason, "probe_again", again}
312 if again {
313 attrs = append(attrs, "because", why)
314 }
315 p.log.Warn("probe report not trusted", attrs...)
316 }
317 if again {
318 p.probeSoon()
319 }
320}
321
322func (p *macProbes) probeSoon() {
323 select {
324 case p.again <- struct{}{}:
325 default:
326 }
327}
328
329// start probes now and again whenever asked (a stale report, a
330// request), or a day after the last run. ready closes after the first
331// run; refresh tells the instance.
332func (p *macProbes) start(ctx context.Context, refresh func()) {
333 go func() {
334 first := true
335 said := ""
336 for {
337 // The tools must match their pins before the probes and still
338 // after them: a report made with anything else is never
339 // trusted.
340 before := p.verified()
341 inputs := p.inputs(before)
342 p.mu.Lock()
343 p.ranWith, p.ranAt = inputs, p.now()
344 p.mu.Unlock()
345 // The first run at info; later ones (a day on, asked for, or
346 // an untrusted report's retry) at debug unless their verdicts
347 // changed.
348 start, level := time.Now(), slog.LevelDebug
349 if first {
350 level = slog.LevelInfo
351 }
352 if p.log != nil {
353 p.log.Log(ctx, level, "probes started")
354 }
355 r := p.run(ctx)
356 if ctx.Err() != nil {
357 return
358 }
359 if v := verdicts(r.Probes); p.log != nil {
360 if v != said {
361 level = slog.LevelInfo
362 }
363 p.log.Log(ctx, level, "probes finished", "took", took(start), "verdicts", v)
364 said = v
365 }
366 if len(r.Unfinished) > 0 && p.log != nil {
367 p.log.Warn("probe run reached its limit; unfinished probes are not proven", "unfinished", strings.Join(r.Unfinished, " "))
368 }
369 if before && p.verified() {
370 r.SRT = srtPinned
371 }
372 p.mu.Lock()
373 p.last, p.pending = r, false
374 p.mu.Unlock()
375 if first {
376 close(p.ready)
377 first = false
378 }
379 refresh()
380 select {
381 case <-ctx.Done():
382 return
383 case <-p.again:
384 case <-time.After(probeTrust - time.Hour):
385 }
386 }
387 }()
388}
389
390// watch turns `equipo-runner probe` (it touches the request file) into a
391// new probe run.
392func (p *macProbes) watch(ctx context.Context) {
393 var seen time.Time
394 if info, err := os.Stat(p.request); err == nil {
395 seen = info.ModTime()
396 }
397 for {
398 select {
399 case <-ctx.Done():
400 return
401 case <-time.After(30 * time.Second):
402 }
403 if info, err := os.Stat(p.request); err == nil && !info.ModTime().Equal(seen) {
404 seen = info.ModTime()
405 p.probeSoon()
406 }
407 }
408}
409
410// verdicts is each probe's name and verdict ("P1=passed P2=denied"),
411// never its detail.
412func verdicts(probes []wire.Probe) string {
413 out := make([]string, 0, len(probes))
414 for _, p := range probes {
415 out = append(out, p.ID+"="+p.Verdict)
416 }
417 return strings.Join(out, " ")
418}
419
420func (p *macProbes) wait(ctx context.Context) error {
421 select {
422 case <-p.ready:
423 return nil
424 case <-ctx.Done():
425 return ctx.Err()
426 }
427}
428
429// toolFingerprint names the tools a probe report depends on without
430// reading them (verified hashes them): each one's path, link target,
431// size, mode and modification time, and the srt package tree's.
432func toolFingerprint(installDir string, t mac.Tools) string {
433 var b strings.Builder
434 for _, path := range []string{t.SRT, t.Node, t.RG, filepath.Join(installDir, "srt", "node_modules")} {
435 b.WriteString(path)
436 if target, err := os.Readlink(path); err == nil {
437 b.WriteString(" -> " + target)
438 }
439 if info, err := os.Stat(path); err == nil {
440 b.WriteString(" " + strconv.FormatInt(info.Size(), 10) + " " + info.Mode().String() + " " + strconv.FormatInt(info.ModTime().UnixNano(), 10))
441 }
442 b.WriteByte('\n')
443 }
444 return b.String()
445}
446
447// srtPinned marks a report made with srt, Node and ripgrep matching the
448// pins compiled into this binary.
449const srtPinned = "pinned"
450
451// macUsers is where a Mac keeps its people's homes.
452var macUsers = "/Users"
453
454// macUserTemp resolves the runner user's DARWIN_USER_TEMP_DIR (tests
455// stand in: a Linux host has none).
456var macUserTemp = func(ctx context.Context, x mac.Exec) (string, error) {
457 return mac.UserTemp(ctx, x, os.Getuid(), mac.UserTempPrefix)
458}
459
460// macHost is the Mac worker's setup: its tools, paths and gates.
461type macHost struct {
462 // scratch is the runner's scratch root: the probes' fixture copies
463 // live there, outside every denied place.
464 scratch string
465 paths mac.Paths
466 tools mac.Tools
467 env []string
468 probes *macProbes
469 checks *macChecks
470 taint *macTaint
471 caps func(context.Context) wire.Capabilities
472 // log hears slow commands, and each command of the first capability
473 // gathering (capsLogged) and of xcode-select at start.
474 log *slog.Logger
475 capsLogged atomic.Bool
476 // turns lets one gate at a time run (mac.Turns).
477 turns *mac.Turns
478 // creds is the Claude credential's guards and operations
479 // (maccreds.go).
480 creds *macCreds
481 // fetchClaude fetches the pinned Claude Code (mac.OfficialClaude).
482 fetchClaude mac.ClaudeFetch
483 // version is this runner's; eng its F probes and Engineering status
484 // (mac_fprobe.go).
485 version string
486 eng *macEngineering
487 // runner is this runner's own binary: P2's direct kernel reader.
488 runner string
489 // warmMu guards warmed, the Xcode (version and build) whose plugin
490 // cache was last warmed.
491 warmMu sync.Mutex
492 warmed string
493}
494
495// warm builds Xcode's plugin cache (DARWIN_USER_CACHE_DIR/
496// com.apple.DeveloperTools/<version>/Xcode/PlugInCache-xcodebuild.
497// xcplugincache) outside the sandbox, once per Xcode version and build:
498// a checks profile does not let a gate write it, so a sandboxed
499// xcodebuild must find it current. Bounded by QueryLimit.
500func (h *macHost) warm(ctx context.Context, x wire.Xcode) {
501 key := x.Version + " " + x.Build
502 if x.Version == "" || h.tools.Xcodebuild == "" {
503 return
504 }
505 h.warmMu.Lock()
506 defer h.warmMu.Unlock()
507 // Not while a gate runs (its T cleanup could take what the warm
508 // writes there): the next gathering tries again, as after a failure.
509 if h.warmed == key {
510 return
511 }
512 if h.turns != nil {
513 turn, ok := h.turns.TryTake(mac.OpWarm)
514 if !ok {
515 return
516 }
517 defer turn.Give()
518 // Nor while an earlier attempt's end is unproven (its cleanup
519 // pending): the next gate settles that first.
520 if h.turns.Pending() {
521 return
522 }
523 }
524 c, cancel := context.WithTimeout(ctx, mac.QueryLimit)
525 defer cancel()
526 if _, err := h.run(c, h.tools.Xcodebuild, "-showsdks"); err != nil {
527 if h.log != nil {
528 h.log.Info("xcode plugin cache not warmed", "xcode", key, "err", err)
529 }
530 return
531 }
532 h.warmed = key
533}
534
535// claudeHere: only a darwin/arm64 worker provisions the pinned Claude
536// Code (the only darwin pin). Tests on Linux never fetch it.
537var claudeHere = runtime.GOOS == "darwin" && runtime.GOARCH == "arm64"
538
539// slowCommand is how long a command the Mac worker runs may take before
540// it is logged as slow: while it still runs, so a hung child shows.
541var slowCommand = 10 * time.Second
542
543// commandWaitDelay bounds how long run waits for a command's output once
544// it has exited or been killed: a grandchild still holding the pipe
545// cannot hold the runner.
546var commandWaitDelay = 5 * time.Second
547
548// Mac tool discovery (spec §3.3): EQUIPO_SRT_PATH and the installer's
549// private srt first, then the usual places. Claude Code is not
550// discovered: no EQUIPO_CLAUDE_PATH, no claude on a path (spec §8.2).
551func macTools(installDir, home string, getenv func(string) string) mac.Tools {
552 dirs := []string{filepath.Join(installDir, "srt", "node_modules", ".bin"), filepath.Join(home, ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin"}
553 pinned := mac.PinnedTools(installDir)
554 at := map[string]string{"srt": pinned.SRT, "node": pinned.Node, "rg": pinned.RG}
555 find := func(env, name string) string {
556 if p := getenv(env); filepath.IsAbs(p) && executable(p) {
557 return p
558 }
559 if p := at[name]; p != "" && executable(p) {
560 return p
561 }
562 for _, d := range dirs {
563 if p := filepath.Join(d, name); executable(p) {
564 return p
565 }
566 }
567 return ""
568 }
569 return mac.Tools{Xcodebuild: "/usr/bin/xcodebuild", Xcrun: "/usr/bin/xcrun", Swift: "/usr/bin/swift", Git: getenv("EQUIPO_GIT_PATH"),
570 SRT: find("EQUIPO_SRT_PATH", "srt"), Node: find("EQUIPO_NODE_PATH", "node"), RG: find("EQUIPO_RG_PATH", "rg"), Codex: find("EQUIPO_CODEX_PATH", "codex"),
571 // Never looked up: the pinned CLI the worker provisions itself.
572 Claude: mac.NewClaudeCLI(home, installDir)}
573}
574
575func executable(p string) bool {
576 info, err := os.Stat(p)
577 return err == nil && info.Mode().IsRegular() && info.Mode().Perm()&0111 != 0
578}
579
580// run runs a tool with the runner's own environment but its PATH: the
581// runner's Node and ripgrep first (srt starts through `env node` and
582// looks for rg there), then the system's. launchd gives an agent only
583// the system PATH.
584func (h *macHost) run(ctx context.Context, name string, args ...string) (string, error) {
585 cmd := exec.CommandContext(ctx, name, args...)
586 cmd.Env = withPath(os.Environ(), gatePath(h.tools))
587 // Its own process group, killed whole at the timeout, and a bounded
588 // wait for its output: a grandchild holding the pipe (xcrun, swift
589 // or claude starting a helper) cannot block run past its timeout.
590 ownGroup(cmd)
591 cmd.WaitDelay = commandWaitDelay
592 done := h.watchSlow(name, args)
593 // The runner's own helper (mac.StartOwn): a turn's sweep spares it.
594 var buf strings.Builder
595 cmd.Stdout = &buf
596 err := mac.StartOwn(cmd)
597 if err == nil {
598 err = cmd.Wait()
599 }
600 out := buf.String()
601 if errors.Is(err, exec.ErrWaitDelay) {
602 // The command itself exited successfully; only something it left
603 // behind in its group still held the pipe. That goes, and what
604 // the command printed is its answer.
605 _ = killGroup(cmd)
606 err = nil
607 if h.log != nil {
608 h.log.Debug("command left a helper holding its output; helper killed", "cmd", name, "args", logArgs(args))
609 }
610 }
611 done(err)
612 return out, err
613}
614
615// watchSlow warns when a command is still running after slowCommand,
616// and again with its time and error when such a command ends.
617func (h *macHost) watchSlow(name string, args []string) func(error) {
618 if h.log == nil {
619 return func(error) {}
620 }
621 start, limit := time.Now(), slowCommand
622 t := time.AfterFunc(limit, func() {
623 h.log.Warn("command still running", "cmd", name, "args", logArgs(args), "after", limit)
624 })
625 return func(err error) {
626 if t.Stop() {
627 return
628 }
629 attrs := []any{"cmd", name, "args", logArgs(args), "took", took(start)}
630 if err != nil {
631 attrs = append(attrs, "err", err.Error())
632 }
633 h.log.Warn("slow command finished", attrs...)
634 }
635}
636
637// logged runs a command through run and logs it at level with its time
638// and, when it failed, its exit status.
639func (h *macHost) logged(level slog.Level) mac.Exec {
640 return func(ctx context.Context, name string, args ...string) (string, error) {
641 start := time.Now()
642 out, err := h.run(ctx, name, args...)
643 if h.log != nil {
644 attrs := []any{"cmd", name, "args", logArgs(args), "took", took(start)}
645 if err != nil {
646 attrs = append(attrs, "err", err.Error())
647 }
648 h.log.Log(ctx, level, "command", attrs...)
649 }
650 return out, err
651 }
652}
653
654// logArgs is a command's arguments for a log line, a password argument's
655// value (security -w) withheld.
656func logArgs(args []string) string {
657 out := make([]string, len(args))
658 for i, a := range args {
659 if i > 0 && args[i-1] == "-w" {
660 a = "[withheld]"
661 }
662 out[i] = a
663 }
664 return strings.Join(out, " ")
665}
666
667func withPath(env []string, path string) []string {
668 out := []string{"PATH=" + path}
669 for _, kv := range env {
670 if !strings.HasPrefix(kv, "PATH=") {
671 out = append(out, kv)
672 }
673 }
674 return out
675}
676
677// gatePath is a gate's fixed PATH: the system's, Homebrew's, and Node's
678// directory (srt runs on Node).
679func gatePath(t mac.Tools) string {
680 dirs := []string{"/usr/bin", "/bin", "/usr/sbin", "/sbin", "/opt/homebrew/bin", "/usr/local/bin"}
681 for _, tool := range []string{t.Node, t.RG} {
682 if tool != "" {
683 if d := filepath.Dir(tool); !contains(dirs, d) {
684 dirs = append([]string{d}, dirs...)
685 }
686 }
687 }
688 return strings.Join(dirs, ":")
689}
690
691func contains(list []string, s string) bool {
692 for _, x := range list {
693 if x == s {
694 return true
695 }
696 }
697 return false
698}
699
700func newMacHost(c runner.Config, o Options) (h *macHost, err error) {
701 done := startPhase(o.Logger, "mac_host")
702 defer func() { done(err) }()
703 getenv := o.Getenv
704 if getenv == nil {
705 getenv = os.Getenv
706 }
707 home, err := os.UserHomeDir()
708 if err != nil {
709 return nil, err
710 }
711 accounts := o.AccountsRoot
712 if accounts == "" {
713 accounts = DefaultAccountsRoot()
714 }
715 h = &macHost{scratch: c.ScratchRoot, log: o.Logger, version: o.Version, runner: c.Executable}
716 h.eng = newMacEngineering(h)
717 others, err := mac.OtherHomes(macUsers, home)
718 h.paths = mac.Paths{Home: home, StateDir: c.StateDir, AccountsRoot: accounts, SessionRoot: SessionRoot(c), InstallDir: filepath.Dir(c.Executable), OtherHomes: others, HomesUnknown: err != nil}
719 h.tools = macTools(h.paths.InstallDir, home, getenv)
720 h.fetchClaude = mac.OfficialClaude(getenv)
721 h.env = []string{"HOME=" + home, "PATH=" + gatePath(h.tools), "CI=1", "LANG=en_US.UTF-8"}
722 // One turn for every operation (a gate, a probe run, the warm, and
723 // Engineering, asks and token operations), across this user's runner
724 // processes. On a Mac each turn's end also sweeps the runner user
725 // (spec §8.8); off a Mac there is no such table and nothing sweeps.
726 h.turns = mac.NewTurns(filepath.Join(c.StateDir, "mac-gate.lock"))
727 if p := mac.MachineProcs(); p != nil {
728 h.turns.Sweep(p)
729 }
730 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
731 if out, err := h.logged(slog.LevelInfo)(ctx, "/usr/bin/xcode-select", "-p"); err == nil && filepath.IsAbs(strings.TrimSpace(out)) {
732 h.env = append(h.env, "DEVELOPER_DIR="+strings.TrimSpace(out))
733 }
734 // The user's T, which checks may write: refused, no checks profile
735 // can be made, P2 says why and checks wait for the sandbox.
736 if t, err := macUserTemp(ctx, h.logged(slog.LevelInfo)); err == nil {
737 h.paths.UserTemp = t
738 } else {
739 h.paths.UserTempWhy = "not resolved"
740 var why *mac.UserTempError
741 if errors.As(err, &why) {
742 h.paths.UserTempWhy = why.Why
743 }
744 if h.log != nil {
745 h.log.Warn("user temp folder refused", "why", h.paths.UserTempWhy)
746 }
747 }
748 cancel()
749 settings := func(tree, attempt string) ([]byte, error) {
750 return mac.ChecksSettings(mac.ChecksInput{Paths: h.paths, Tree: tree, Attempt: attempt, Mach: mac.CheckMachServices})
751 }
752 // Both bounded: a simctl that never answers (CoreSimulator stuck)
753 // must not hold a gate or a probe run.
754 booted := func(ctx context.Context) []string {
755 c, cancel := context.WithTimeout(ctx, mac.QueryLimit)
756 defer cancel()
757 out, err := h.run(c, h.tools.Xcrun, "simctl", "list", "-j", "devices", "booted")
758 var udids []string
759 if err == nil {
760 for _, s := range mac.ParseSimulators([]byte(out)) {
761 if s.State == "Booted" {
762 udids = append(udids, s.UDID)
763 }
764 }
765 }
766 return udids
767 }
768 shutdown := func(ctx context.Context, udid string) {
769 c, cancel := context.WithTimeout(ctx, time.Minute)
770 defer cancel()
771 _, _ = h.run(c, h.tools.Xcrun, "simctl", "shutdown", udid)
772 }
773 gate := func(srt, label string) *mac.Gate {
774 g := &mac.Gate{SRT: srt, Env: h.env, Caffeinate: "/usr/bin/caffeinate", Booted: booted, Shutdown: shutdown, Lines: wire.MaxChecksLines, Sandbox: label, Turns: h.turns}
775 if srt != "" {
776 g.Settings, g.UserTemp, g.QuietSimulators = settings, h.paths.UserTemp, h.quietSimulators
777 }
778 return g
779 }
780 h.probes = newMacProbes(o.Version, ProbeRequest(c), func(ctx context.Context) mac.Report {
781 h.warmNow(ctx)
782 return mac.RunProbes(ctx, h.probeHost(o.Version, gate))
783 }, func() bool { return mac.VerifyTools(h.paths.InstallDir, h.tools) == nil })
784 h.probes.log = o.Logger
785 h.probes.fingerprint = func() string { return toolFingerprint(h.paths.InstallDir, h.tools) }
786 h.taint = loadTaint(filepath.Join(c.StateDir, "tainted"))
787 h.creds = h.newCreds(c)
788 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)}
789 h.caps = func(ctx context.Context) wire.Capabilities {
790 // The first gathering is the one the first hello waits on: each
791 // command at info. Later ones (hourly, each check's gate) at debug.
792 level := slog.LevelDebug
793 if h.capsLogged.CompareAndSwap(false, true) {
794 level = slog.LevelInfo
795 }
796 // Outside the turn (the coordinator's ruling): a T cleanup may take
797 // these queries' temp files, which costs availability only.
798 caps := mac.Capabilities(ctx, h.logged(level), h.tools)
799 h.warm(ctx, caps.Xcode)
800 if probes := h.probes.report().Probes; len(probes) > 0 {
801 caps.Probes = probes
802 }
803 caps.Tainted = h.taint.Tainted()
804 h.credentialCaps(ctx, &caps)
805 h.eng.compose(&caps)
806 if code, n := h.turns.Unproven(); code != "" && caps.Unproven == "" {
807 caps.Unproven, caps.UnprovenCount = code, n
808 }
809 return caps
810 }
811 return h, nil
812}
813
814// credentialCaps says why the Mac can take no Claude connection, if its
815// guards say so (maccreds.go), and as which user, and looks again for a
816// Keychain item it found.
817func (h *macHost) credentialCaps(ctx context.Context, caps *wire.Capabilities) {
818 caps.Engineering = h.creds.status()
819 if wire.ValidRunnerUser(h.creds.user) {
820 // As whom the Machines page says to close a folder.
821 caps.RunnerUser = h.creds.user
822 }
823 if h.creds.Held() {
824 h.creds.settle(ctx, false)
825 }
826 if left, err := h.creds.keychain.Unproven(); err != nil || len(left) > 0 {
827 // Said before an incomplete attempt record: it closes the Mac's
828 // connections, and a restart of the Mac clears it.
829 caps.Unproven = wire.UnprovenCredential
830 }
831}
832
833// engineering is the Mac's Engineering pieces: an executor for an attempt
834// with sandboxed Xcode access (the user's T cleaned after it, the
835// simulators quieted first), xcode-select's developer dir, and whether
836// this process's own trusted probe report allows that access now: P2 and
837// F5 denied, the user's T resolved, the runner not tainted.
838func (h *macHost) engineering() *WorkerEngineering {
839 dev := ""
840 for _, kv := range h.env {
841 if v, ok := strings.CutPrefix(kv, "DEVELOPER_DIR="); ok {
842 dev = v
843 }
844 }
845 return &WorkerEngineering{XcodeExec: &mac.Executor{Turns: h.turns, UserTemp: h.paths.UserTemp, QuietSimulators: h.quietSimulators}, DeveloperDir: dev, Leaks: h.leaks,
846 Xcode: func() bool {
847 r, ok := h.probes.trusted()
848 if !ok || !r.Sandboxed() || h.paths.UserTemp == "" || h.taint.Tainted() {
849 return false
850 }
851 ctx, cancel := context.WithTimeout(context.Background(), 2*mac.QueryLimit)
852 defer cancel()
853 return h.eng.xcodeNow(ctx)
854 }}
855}
856
857// simShutdownLimit bounds `simctl shutdown all` before a T cleanup.
858// It shuts every booted simulator down one after another, each taking
859// seconds to tens of seconds, so QueryLimit (30 s) would cut a Mac with
860// a few booted short; two minutes is the most an attempt's end waits.
861var simShutdownLimit = 2 * time.Minute
862
863// macPS lists this user's processes by name (tests stand in).
864var macPS = "/bin/ps"
865
866// quietSimulators shuts down every simulator of the runner user (a
867// dedicated user, so all are the runner's) before a sandboxed
868// attempt's T is cleaned: CoreSimulator's processes are outside the
869// attempt's group and outside srt, and may still write T. Bounded; it
870// never fails the attempt. What simulator processes are left is
871// logged at info, names only.
872func (h *macHost) quietSimulators(ctx context.Context) {
873 c, cancel := context.WithTimeout(ctx, simShutdownLimit)
874 _, err := h.run(c, h.tools.Xcrun, "simctl", "shutdown", "all")
875 cancel()
876 if h.log == nil {
877 return
878 }
879 if err != nil {
880 h.log.Info("simulators not all shut down", "err", err)
881 }
882 c, cancel = context.WithTimeout(ctx, mac.QueryLimit)
883 out, _ := h.run(c, macPS, "-x", "-o", "comm=")
884 cancel()
885 var left []string
886 for _, l := range strings.Split(out, "\n") {
887 if n := filepath.Base(strings.TrimSpace(l)); strings.Contains(strings.ToLower(n), "sim") && !slices.Contains(left, n) {
888 left = append(left, n)
889 }
890 }
891 if len(left) > 0 {
892 slices.Sort(left)
893 h.log.Info("simulator processes still running", "names", strings.Join(left, " "))
894 }
895}
896
897// warmNow warms the plugin cache for the Xcode installed now (the
898// probes run before any capability gathering may have).
899func (h *macHost) warmNow(ctx context.Context) {
900 c, cancel := context.WithTimeout(ctx, mac.QueryLimit)
901 out, _ := h.run(c, h.tools.Xcodebuild, "-version")
902 cancel()
903 h.warm(ctx, mac.ParseXcode(out))
904}
905
906func (h *macHost) probeHost(version string, gate func(string, string) *mac.Gate) mac.ProbeHost {
907 // P2's reader is this runner's own binary, when it is one.
908 reader := ""
909 if executable(h.runner) {
910 reader = h.runner
911 }
912 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,
913 Gate: func(sandboxed bool) *mac.Gate {
914 if sandboxed {
915 return gate(h.tools.SRT, wire.SandboxSeatbelt)
916 }
917 return gate("", wire.SandboxNone)
918 },
919 Resolve: func(ctx context.Context, name string) bool {
920 addrs, err := net.DefaultResolver.LookupHost(ctx, name)
921 return err == nil && len(addrs) > 0
922 },
923 Exposed: mac.Exposed,
924 Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") },
925 Warn: h.warn,
926 }
927}
928
929// warn is runner.log at WARN, nil when there is no log.
930func (h *macHost) warn(msg string, args ...any) {
931 if h.log != nil {
932 h.log.Warn(msg, args...)
933 }
934}
935
936// find chooses a Mac's gate: the repository's own (with macOS's bash),
937// else xcodebuild test for an Xcode project.
938func (h *macHost) find(dir string) (gate, string, bool) {
939 if g, ok := findGate(dir); ok {
940 if len(g.argv) > 0 && g.argv[0] == "/usr/bin/bash" {
941 g.argv = append([]string{"/bin/bash"}, g.argv[1:]...)
942 }
943 return g, "", true
944 }
945 ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
946 defer cancel()
947 argv, ok, reason := mac.XcodeGate(dir, h.caps(ctx).Simulators)
948 if !ok {
949 return gate{}, "", false
950 }
951 return gate{name: mac.XcodeGateName, argv: argv}, reason, true
952}
953
954// runMac serves the instance as a Mac worker.
955func runMac(ctx context.Context, c runner.Config, o Options) error {
956 h, err := newMacHost(c, o)
957 if err != nil {
958 return err
959 }
960 return serveMac(ctx, c, o, h)
961}
962
963// serveMac serves the instance as the Mac worker h sets up.
964func serveMac(ctx context.Context, c runner.Config, o Options, h *macHost) error {
965 if o.Logger != nil && h.tools.SRT == "" {
966 o.Logger.Warn("srt is not installed: checks run outside the sandbox and say so")
967 }
968 up := &macUpdater{origin: c.Origin, version: o.Version, binary: c.Executable, fetch: fetchLimited}
969 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,
970 started: func(ctx context.Context, refresh func()) {
971 h.taint.changed = refresh
972 h.probes.start(ctx, func() { refresh(); h.eng.soon() })
973 h.eng.start(ctx, refresh)
974 go h.probes.watch(ctx)
975 if claudeHere {
976 go mac.KeepClaude(ctx, h.tools.Claude, h.fetchClaude, refresh, h.warn)
977 }
978 },
979 welcomed: func(w wire.Welcome, worker *Worker, stop context.CancelCauseFunc) {
980 if w.Tainted {
981 h.taint.Set()
982 }
983 up.offer(w, worker.hold, func() { stop(ErrUpdated) }, o.Logger)
984 }})
985}
986
987// ProbeRequest is the file `equipo-runner probe` touches to ask the
988// running worker to probe again.
989func ProbeRequest(c runner.Config) string { return filepath.Join(c.StateDir, "probe-request") }
990
991// RunProbes runs the Mac probes now in this process, for the person
992// asking, and asks the running worker to run its own: only a worker's
993// own run decides how it confines checks.
994func RunProbes(ctx context.Context, c runner.Config, o Options) (mac.Report, error) {
995 h, err := newMacHost(c, o)
996 if err != nil {
997 return mac.Report{}, err
998 }
999 r := h.probes.run(ctx)
1000 if err := ctx.Err(); err != nil {
1001 return r, err
1002 }
1003 now := time.Now()
1004 if f, err := os.OpenFile(ProbeRequest(c), os.O_CREATE|os.O_WRONLY, 0600); err == nil {
1005 f.Close()
1006 }
1007 return r, os.Chtimes(ProbeRequest(c), now, now)
1008}
1009
1010// macUpdater replaces the worker's binary with the release its instance
1011// serves (spec §3.3): the darwin/arm64 runner of that release's install
1012// manifest, verified against its digest, swapped between steps; then the
1013// worker exits mac.ExitUpdated and launchd starts the new one.
1014type macUpdater struct {
1015 origin, version, binary string
1016 fetch func(ctx context.Context, url string, limit int64) ([]byte, error)
1017 once sync.Once
1018 done chan error
1019}
1020
1021func (u *macUpdater) offer(w wire.Welcome, hold func() func(), stop func(), log interface{ Warn(string, ...any) }) {
1022 if w.Release == "" || w.Release == u.version || !release.ValidInstallVersion(w.Release) {
1023 return
1024 }
1025 u.once.Do(func() {
1026 u.done = make(chan error, 1)
1027 go func() {
1028 err := u.apply(context.Background(), w.Release, hold, stop)
1029 if err != nil && log != nil {
1030 log.Warn("update to the instance's release failed", "release", w.Release, "err", err)
1031 }
1032 u.done <- err
1033 }()
1034 })
1035}
1036
1037func (u *macUpdater) apply(ctx context.Context, version string, hold func() func(), stop func()) error {
1038 base := u.origin + "/releases/" + version + "/"
1039 raw, err := u.fetch(ctx, base+"install-manifest.json", 1<<20)
1040 if err != nil {
1041 return err
1042 }
1043 var m release.InstallManifest
1044 if err := json.Unmarshal(raw, &m); err != nil {
1045 return err
1046 }
1047 t, err := m.DarwinTarget(version)
1048 if err != nil {
1049 return err
1050 }
1051 bin, err := u.fetch(ctx, base+release.DarwinDir+"/equipo-runner", 128<<20)
1052 if err != nil {
1053 return err
1054 }
1055 if sum := sha256.Sum256(bin); hex.EncodeToString(sum[:]) != t.RunnerSHA256 {
1056 return errors.New("the release's runner does not match its digest")
1057 }
1058 tmp, err := os.CreateTemp(filepath.Dir(u.binary), ".equipo-runner-update-")
1059 if err != nil {
1060 return err
1061 }
1062 defer os.Remove(tmp.Name())
1063 if _, err = tmp.Write(bin); err == nil {
1064 err = tmp.Chmod(0700)
1065 }
1066 if err == nil {
1067 err = tmp.Sync()
1068 }
1069 if cerr := tmp.Close(); err == nil {
1070 err = cerr
1071 }
1072 if err != nil {
1073 return err
1074 }
1075 // Between steps: no attempt runs while the binary changes.
1076 release := hold()
1077 defer release()
1078 if err := os.Rename(tmp.Name(), u.binary); err != nil {
1079 return err
1080 }
1081 stop()
1082 return nil
1083}
1084
1085// fetchLimited GETs url (no redirects) and refuses more than limit bytes.
1086func fetchLimited(ctx context.Context, url string, limit int64) ([]byte, error) {
1087 c := http.Client{Timeout: 5 * time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
1088 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
1089 if err != nil {
1090 return nil, err
1091 }
1092 resp, err := c.Do(req)
1093 if err != nil {
1094 return nil, err
1095 }
1096 defer resp.Body.Close()
1097 if resp.StatusCode != http.StatusOK {
1098 return nil, errors.New("release download: " + resp.Status)
1099 }
1100 b, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
1101 if err != nil || int64(len(b)) > limit {
1102 return nil, errors.New("release download too large")
1103 }
1104 return b, nil
1105}
1106
1107// leaks scans stage with the pinned gitleaks beside the runner, in the
1108// Mac's checks gate, and only in the sandboxed one: the gate that P2's
1109// trusted verdict picks for checks, on a runner never tainted. Anything
1110// else cannot confine it, so it cannot scan and nothing leaves.
1111func (h *macHost) leaks(ctx context.Context, stage, marker string, record func(string) error) (bool, error) {
1112 if g := h.checks.pick(); g != h.checks.sandboxed {
1113 return false, errScanner
1114 }
1115 binary, pin := previewScannerTool(runner.Config{Executable: filepath.Join(h.paths.InstallDir, "equipo-runner")})
1116 return gateLeaks(ctx, h.checks.sandboxed, binary, pin, stage, marker, record)
1117}
1118