oficina / equipo Public

Mac worker package: srt profile, process-group gate, probes

internal/runner/mac holds the Darwin side, all testable on Linux:
- ChecksSettings: the §4.4 srt 0.0.81 settings over the §4.2 deny
  list (no network, writes only to the tree, the attempt's scratch and
  Xcode's caches, candidate Mach services until P2 records them);
  refuses globs, relative paths and a tree inside a denied place.
- Gate: a session and process group per attempt, EQUIPO_ATTEMPT marker,
  environment from scratch, caffeinate, SIGTERM then SIGKILL, a sweep
  of marked processes (ps -E on a Mac), simctl shutdown of what it
  booted, proof only when the group is gone and nothing marked is
  left. srt exits 0 when its command dies of SIGTERM, so a pass needs
  srt's exit and the recorded status both 0.
- Capabilities from xcodebuild, simctl, swift, node, srt; the
  xcodebuild test gate for a project with no gate of its own.
- Probes P1 to P7 with the hostile fixture (run-script phase, SwiftPM
  plugin, XCTest) shipped as test data; P2 is denied only when every
  attempt is and nothing outside contradicts it.
- The launchd agent and the installer's account refusals.
Wire: Capabilities.probes and StepReport.checks_sandbox (protocol 2,
omitempty, dropped at protocol 1), with fixtures.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 0b4d5333dc11ac30f5fe6b8aefee2dfb00e033b5 parent f1e43c1
28 files changed, +3,043 −1
  • internal/runner/mac/account.go +98 −0
  • internal/runner/mac/account_test.go +153 −0
  • internal/runner/mac/caps.go +176 −0
  • internal/runner/mac/caps_test.go +134 −0
  • internal/runner/mac/fixtures/hostile/README.md +14 −0
  • internal/runner/mac/fixtures/hostile/package/Package.swift +13 −0
  • internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift +83 −0
  • internal/runner/mac/fixtures/hostile/package/Sources/Hostile/Hostile.swift +3 −0
  • internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift +88 −0
  • internal/runner/mac/fixtures/hostile/project/Hostile.xcodeproj/project.pbxproj +132 −0
  • internal/runner/mac/fixtures/hostile/project/hostile.sh +15 −0
  • internal/runner/mac/gate.go +308 −0
  • internal/runner/mac/gate_test.go +243 −0
  • internal/runner/mac/launchd.go +64 −0
  • internal/runner/mac/marked_darwin.go +20 −0
  • internal/runner/mac/marked_linux.go +42 −0
  • internal/runner/mac/probe.go +646 −0
  • internal/runner/mac/probe_test.go +283 −0
  • internal/runner/mac/profile.go +155 −0
  • internal/runner/mac/profile_test.go +90 −0
  • internal/runner/mac/ps.go +33 −0
  • internal/runner/mac/testdata/simctl-devices.json +62 −0
  • internal/runner/mac/xcode.go +133 −0
  • internal/wire/runners.go +35 −1
  • internal/wire/runners_test.go +14 −0
  • internal/wire/tasks.go +4 −0
  • internal/wire/wiretest/testdata/frames/hello-mac-probes.json +1 −0
  • internal/wire/wiretest/testdata/frames/step-mac-checks.json +1 −0
diff --git a/internal/runner/mac/account.go b/internal/runner/mac/account.go
new file mode 100644
index 00000000..ade6d21c
--- /dev/null
+++ b/internal/runner/mac/account.go
@@ -0,0 +1,98 @@
+package mac
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "regexp"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// Account is the macOS user the installer runs as.
+type Account struct {
+ Name string
+ UID int
+ Groups []string
+}
+
+// ReadAccount asks id(1): os/user without cgo cannot see the admin
+// group's members, which Directory Services keeps.
+func ReadAccount(ctx context.Context, x Exec) (Account, error) {
+ name, err1 := x(ctx, "/usr/bin/id", "-un")
+ uid, err2 := x(ctx, "/usr/bin/id", "-u")
+ groups, err3 := x(ctx, "/usr/bin/id", "-Gn")
+ if err := errors.Join(err1, err2, err3); err != nil {
+ return Account{}, err
+ }
+ n, err := strconv.Atoi(strings.TrimSpace(uid))
+ if err != nil {
+ return Account{}, err
+ }
+ return Account{Name: strings.TrimSpace(name), UID: n, Groups: strings.Fields(groups)}, nil
+}
+
+// runnerUser is a dedicated runner user: equipo-<person-handle>, never a
+// shared "equipo" (spec §3.5, Paul's ruling 1).
+var runnerUser = regexp.MustCompile(`^equipo-[a-z0-9][a-z0-9._-]{0,30}$`)
+
+// RefuseAccount is the copy key that refuses this account, or "": not
+// root, not an administrator, and named equipo-<person> (own-Mac mode is
+// not in scope).
+func RefuseAccount(a Account) string {
+ switch {
+ case a.UID == 0 || a.Name == "root":
+ return "runner.mac.root"
+ case slices.Contains(a.Groups, "admin") || slices.Contains(a.Groups, "wheel"):
+ return "runner.mac.admin"
+ case !runnerUser.MatchString(a.Name):
+ return "runner.mac.user"
+ }
+ return ""
+}
+
+// OtherHomes are the homes under users that are not home: every other
+// person's (and /Users/Shared), which every profile denies.
+func OtherHomes(users, home string) []string {
+ entries, err := os.ReadDir(users)
+ if err != nil {
+ return nil
+ }
+ var out []string
+ for _, e := range entries {
+ p := filepath.Join(users, e.Name())
+ if strings.HasPrefix(e.Name(), ".") || p == home || !e.IsDir() {
+ continue
+ }
+ out = append(out, p)
+ }
+ sort.Strings(out)
+ return out
+}
+
+// ReadableHomes are the people's homes this user can list: the installer
+// refuses to enrol while there is one (spec §3.5).
+func ReadableHomes(homes []string, list func(string) bool) []string {
+ var out []string
+ for _, h := range homes {
+ if filepath.Base(h) != "Shared" && list(h) {
+ out = append(out, h)
+ }
+ }
+ return out
+}
+
+// CanList reports whether this user can list dir.
+func CanList(dir string) bool {
+ f, err := os.Open(dir)
+ if err != nil {
+ return false
+ }
+ defer f.Close()
+ _, err = f.Readdirnames(1)
+ return err == nil || errors.Is(err, io.EOF)
+}
diff --git a/internal/runner/mac/account_test.go b/internal/runner/mac/account_test.go
new file mode 100644
index 00000000..7f8e43e1
--- /dev/null
+++ b/internal/runner/mac/account_test.go
@@ -0,0 +1,153 @@
+package mac
+
+import (
+ "context"
+ "encoding/xml"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+)
+
+// The installer runs only as a Standard user named equipo-<person>:
+// never root, never an administrator, never a shared "equipo" or a
+// person's own account (own-Mac mode is not in scope).
+func TestRefuseAccount(t *testing.T) {
+ for _, c := range []struct {
+ a Account
+ want string
+ }{
+ {Account{Name: "equipo-paul", UID: 502, Groups: []string{"staff", "everyone", "_developer"}}, ""},
+ {Account{Name: "root", UID: 0, Groups: []string{"wheel"}}, "runner.mac.root"},
+ {Account{Name: "equipo-paul", UID: 0}, "runner.mac.root"},
+ {Account{Name: "equipo-paul", UID: 502, Groups: []string{"staff", "admin"}}, "runner.mac.admin"},
+ {Account{Name: "paul", UID: 501, Groups: []string{"staff"}}, "runner.mac.user"},
+ {Account{Name: "equipo", UID: 503, Groups: []string{"staff"}}, "runner.mac.user"},
+ {Account{Name: "equipo-", UID: 503, Groups: []string{"staff"}}, "runner.mac.user"},
+ {Account{Name: "equipo-Paul", UID: 503, Groups: []string{"staff"}}, "runner.mac.user"},
+ } {
+ if got := RefuseAccount(c.a); got != c.want {
+ t.Fatalf("%+v: %q, want %q", c.a, got, c.want)
+ }
+ }
+}
+
+func TestReadAccount(t *testing.T) {
+ out := map[string]string{"-un": "equipo-paul\n", "-u": "502\n", "-Gn": "staff everyone localaccounts _appserverusr admin _developer\n"}
+ a, err := ReadAccount(context.Background(), func(_ context.Context, name string, args ...string) (string, error) {
+ if name != "/usr/bin/id" {
+ return "", errors.New(name)
+ }
+ return out[args[0]], nil
+ })
+ if err != nil || a.Name != "equipo-paul" || a.UID != 502 || RefuseAccount(a) != "runner.mac.admin" {
+ t.Fatalf("%+v %v", a, err)
+ }
+}
+
+func TestHomes(t *testing.T) {
+ users := t.TempDir()
+ for _, d := range []string{"equipo-paul", "paul", "Shared", ".localized", "tito"} {
+ if err := os.MkdirAll(filepath.Join(users, d), 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ others := OtherHomes(users, filepath.Join(users, "equipo-paul"))
+ want := []string{filepath.Join(users, "Shared"), filepath.Join(users, "paul"), filepath.Join(users, "tito")}
+ if !slices.Equal(others, want) {
+ t.Fatalf("%v", others)
+ }
+ if err := os.Chmod(filepath.Join(users, "tito"), 0); err != nil {
+ t.Fatal(err)
+ }
+ defer os.Chmod(filepath.Join(users, "tito"), 0700)
+ readable := ReadableHomes(others, CanList)
+ if os.Geteuid() != 0 && !slices.Equal(readable, []string{filepath.Join(users, "paul")}) {
+ t.Fatalf("readable %v", readable)
+ }
+}
+
+// The launchd agent: a well-formed plist, the runner with its env file,
+// kept alive only after a failure (an update exits 75 and restarts; a
+// superseded runner exits 0 and stays down), a Standard process, paths
+// escaped.
+func TestLaunchAgent(t *testing.T) {
+ raw := LaunchAgent("/Users/equipo-paul/.local/lib/equipo-runner/equipo-runner", "/Users/equipo-paul/.config/equipo-runner/runner.env", "/Users/equipo-paul/Library/Logs/equipo-runner & <co>")
+ plist := parsePlist(t, raw)
+ if plist["Label"] != AgentLabel || plist["RunAtLoad"] != "true" || plist["ProcessType"] != "Standard" || plist["KeepAlive.SuccessfulExit"] != "false" {
+ t.Fatalf("%v", plist)
+ }
+ if plist["ProgramArguments"] != "/Users/equipo-paul/.local/lib/equipo-runner/equipo-runner|run|--env-file|/Users/equipo-paul/.config/equipo-runner/runner.env" {
+ t.Fatalf("arguments %q", plist["ProgramArguments"])
+ }
+ if plist["StandardErrorPath"] != "/Users/equipo-paul/Library/Logs/equipo-runner & <co>/runner.log" || plist["Umask"] != "63" {
+ t.Fatalf("%v", plist)
+ }
+ if ExitUpdated == 0 {
+ t.Fatal("an update must exit non-zero to be restarted")
+ }
+}
+
+// parsePlist flattens a plist dict: key to value, arrays joined by |,
+// nested dicts as parent.child.
+func parsePlist(t *testing.T, raw []byte) map[string]string {
+ t.Helper()
+ d := xml.NewDecoder(strings.NewReader(string(raw)))
+ d.Strict = true
+ out := map[string]string{}
+ var stack []string
+ key, inArray := "", ""
+ var arr []string
+ for {
+ tok, err := d.Token()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatalf("not well formed: %v", err)
+ }
+ switch e := tok.(type) {
+ case xml.StartElement:
+ switch e.Name.Local {
+ case "key":
+ var k string
+ if err := d.DecodeElement(&k, &e); err != nil {
+ t.Fatal(err)
+ }
+ key = strings.Join(append(append([]string{}, stack...), k), ".")
+ case "string", "integer":
+ var v string
+ if err := d.DecodeElement(&v, &e); err != nil {
+ t.Fatal(err)
+ }
+ if inArray != "" {
+ arr = append(arr, v)
+ } else {
+ out[key] = v
+ }
+ case "true", "false":
+ out[key] = e.Name.Local
+ case "array":
+ inArray, arr = key, nil
+ case "dict":
+ if key != "" {
+ stack = append(stack, key[strings.LastIndex(key, ".")+1:])
+ }
+ }
+ case xml.EndElement:
+ switch e.Name.Local {
+ case "array":
+ out[inArray] = strings.Join(arr, "|")
+ inArray = ""
+ case "dict":
+ if len(stack) > 0 {
+ stack = stack[:len(stack)-1]
+ }
+ }
+ }
+ }
+ return out
+}
diff --git a/internal/runner/mac/caps.go b/internal/runner/mac/caps.go
new file mode 100644
index 00000000..a73ac20a
--- /dev/null
+++ b/internal/runner/mac/caps.go
@@ -0,0 +1,176 @@
+package mac
+
+import (
+ "context"
+ "encoding/json"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Exec runs a tool and returns its standard output.
+type Exec func(ctx context.Context, name string, args ...string) (string, error)
+
+// Tools are the executables the capability report asks; "" is absent.
+type Tools struct {
+ Xcodebuild, Xcrun, Swift, Node, SRT, RG, Claude, Codex, Git string
+}
+
+// Capabilities is a Mac's capability report (spec §1.3): Xcode, the
+// available simulators, toolchain and harness versions and the tags.
+// Only versions and names leave the machine; ValidCapabilities checks.
+func Capabilities(ctx context.Context, x Exec, t Tools) wire.Capabilities {
+ ask := func(name string, args ...string) string {
+ if name == "" {
+ return ""
+ }
+ c, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ out, err := x(c, name, args...)
+ if err != nil {
+ return ""
+ }
+ return out
+ }
+ c := wire.Capabilities{Simulators: []wire.Simulator{}, Tags: []string{wire.TagMacOS}}
+ c.Xcode = ParseXcode(ask(t.Xcodebuild, "-version"))
+ if c.Xcode.Version != "" {
+ c.Tags = append(c.Tags, wire.TagXcode)
+ c.Simulators = ParseSimulators([]byte(ask(t.Xcrun, "simctl", "list", "-j", "devices", "available")))
+ }
+ for _, s := range c.Simulators {
+ if strings.HasPrefix(s.Runtime, "iOS ") {
+ c.Tags = append(c.Tags, wire.TagIOSSimulator)
+ break
+ }
+ }
+ if m := swiftVersion.FindStringSubmatch(ask(t.Swift, "--version") + " "); m != nil {
+ c.Toolchains.Swift = m[1]
+ }
+ c.Toolchains.Node = word(nodeVersion, ask(t.Node, "--version"))
+ c.Harness.SRT = word(plainVersion, ask(t.SRT, "--version"))
+ c.Harness.Claude = word(plainVersion, ask(t.Claude, "--version"))
+ c.Harness.Codex = word(plainVersion, ask(t.Codex, "--version"))
+ // No claude or codex tag: a Mac worker runs checks only until slice
+ // F, so nothing that needs a harness is placed on it.
+ return c
+}
+
+var (
+ xcodeVersion = regexp.MustCompile(`(?m)^Xcode ([0-9][0-9A-Za-z.]*)\s*$`)
+ xcodeBuild = regexp.MustCompile(`(?m)^Build version ([0-9A-Za-z]+)\s*$`)
+ swiftVersion = regexp.MustCompile(`(?:Swift version ([0-9]+\.[0-9]+(?:\.[0-9]+)?)[ \n(]|$)`)
+ nodeVersion = regexp.MustCompile(`\bv[0-9]+\.[0-9]+\.[0-9]+\b`)
+ plainVersion = regexp.MustCompile(`\b[0-9]+\.[0-9]+\.[0-9]+\b`)
+ runtimeKey = regexp.MustCompile(`^com\.apple\.CoreSimulator\.SimRuntime\.(iOS|watchOS|tvOS|xrOS|visionOS)-([0-9]+(?:-[0-9]+)*)$`)
+ udidPattern = regexp.MustCompile(`^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$`)
+)
+
+func word(re *regexp.Regexp, s string) string { return re.FindString(s) }
+
+// ParseXcode reads `xcodebuild -version`: "Xcode 16.2" and "Build version
+// 16C5032a".
+func ParseXcode(out string) wire.Xcode {
+ v, b := xcodeVersion.FindStringSubmatch(out), xcodeBuild.FindStringSubmatch(out)
+ if v == nil || b == nil {
+ return wire.Xcode{}
+ }
+ return wire.Xcode{Version: v[1], Build: b[1]}
+}
+
+// ParseSimulators reads `xcrun simctl list -j devices available`: the
+// available devices under each runtime, newest runtime first, at most
+// wire.MaxSimulators, each field in the capability string rules.
+func ParseSimulators(raw []byte) []wire.Simulator {
+ var list struct {
+ Devices map[string][]struct {
+ Name string `json:"name"`
+ UDID string `json:"udid"`
+ State string `json:"state"`
+ IsAvailable *bool `json:"isAvailable"`
+ } `json:"devices"`
+ }
+ out := []wire.Simulator{}
+ if json.Unmarshal(raw, &list) != nil {
+ return out
+ }
+ type sim struct {
+ wire.Simulator
+ os string
+ ver []int
+ }
+ var all []sim
+ for key, devices := range list.Devices {
+ m := runtimeKey.FindStringSubmatch(key)
+ if m == nil {
+ continue
+ }
+ var ver []int
+ for _, p := range strings.Split(m[2], "-") {
+ n, _ := strconv.Atoi(p)
+ ver = append(ver, n)
+ }
+ runtime := m[1] + " " + strings.ReplaceAll(m[2], "-", ".")
+ for _, d := range devices {
+ if d.IsAvailable != nil && !*d.IsAvailable {
+ continue
+ }
+ s := wire.Simulator{Name: d.Name, Runtime: runtime, UDID: d.UDID, State: d.State}
+ if !udidPattern.MatchString(s.UDID) || wire.ValidCapabilities(wire.Capabilities{Simulators: []wire.Simulator{s}}) != nil {
+ continue
+ }
+ all = append(all, sim{s, m[1], ver})
+ }
+ }
+ sort.Slice(all, func(i, j int) bool {
+ a, b := all[i], all[j]
+ if (a.os == "iOS") != (b.os == "iOS") {
+ return a.os == "iOS"
+ }
+ if c := compareVersions(a.ver, b.ver); c != 0 {
+ return c > 0
+ }
+ if a.Name != b.Name {
+ return a.Name < b.Name
+ }
+ return a.UDID < b.UDID
+ })
+ for _, s := range all {
+ if len(out) == wire.MaxSimulators {
+ break
+ }
+ out = append(out, s.Simulator)
+ }
+ return out
+}
+
+func compareVersions(a, b []int) int {
+ for i := range max(len(a), len(b)) {
+ x, y := 0, 0
+ if i < len(a) {
+ x = a[i]
+ }
+ if i < len(b) {
+ y = b[i]
+ }
+ if x != y {
+ return x - y
+ }
+ }
+ return 0
+}
+
+// runtimeVersion is "iOS 18.2"'s numbers.
+func runtimeVersion(runtime string) []int {
+ _, v, _ := strings.Cut(runtime, " ")
+ var out []int
+ for _, p := range strings.Split(v, ".") {
+ n, _ := strconv.Atoi(p)
+ out = append(out, n)
+ }
+ return out
+}
diff --git a/internal/runner/mac/caps_test.go b/internal/runner/mac/caps_test.go
new file mode 100644
index 00000000..f1448ac2
--- /dev/null
+++ b/internal/runner/mac/caps_test.go
@@ -0,0 +1,134 @@
+package mac
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// Recorded tool outputs (Xcode 16.2 on macOS 15) stand in for the Mac.
+var recorded = map[string]string{
+ "xcodebuild -version": "Xcode 16.2\nBuild version 16C5032a\n",
+ "swift --version": "swift-driver version: 1.115.1 Apple Swift version 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1)\nTarget: arm64-apple-macosx15.0\n",
+ "node --version": "v22.12.0\n",
+ "srt --version": "0.0.81\n",
+ "claude --version": "2.1.312 (Claude Code)\n",
+ "xcrun simctl list -j devices available": "",
+}
+
+func recordedExec(t *testing.T) Exec {
+ raw, err := os.ReadFile("testdata/simctl-devices.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return func(_ context.Context, name string, args ...string) (string, error) {
+ key := strings.Join(append([]string{name}, args...), " ")
+ if key == "xcrun simctl list -j devices available" {
+ return string(raw), nil
+ }
+ out, ok := recorded[key]
+ if !ok {
+ return "", errors.New("not recorded: " + key)
+ }
+ return out, nil
+ }
+}
+
+func TestCapabilitiesFromRecordedTools(t *testing.T) {
+ c := Capabilities(context.Background(), recordedExec(t), Tools{Xcodebuild: "xcodebuild", Xcrun: "xcrun", Swift: "swift", Node: "node", SRT: "srt", Claude: "claude"})
+ if err := wire.ValidCapabilities(c); err != nil {
+ t.Fatalf("%v: %+v", err, c)
+ }
+ if c.Xcode != (wire.Xcode{Version: "16.2", Build: "16C5032a"}) || c.Toolchains.Swift != "6.0.3" || c.Toolchains.Node != "v22.12.0" || c.Harness.SRT != "0.0.81" || c.Harness.Claude != "2.1.312" {
+ t.Fatalf("versions %+v", c)
+ }
+ if !slices.Equal(c.Tags, []string{wire.TagMacOS, wire.TagXcode, wire.TagIOSSimulator}) {
+ t.Fatalf("tags %v", c.Tags)
+ }
+ var names []string
+ for _, s := range c.Simulators {
+ names = append(names, s.Runtime+" "+s.Name)
+ }
+ want := []string{"iOS 18.2 iPad Pro 13-inch (M4)", "iOS 18.2 iPhone 16", "iOS 18.2 iPhone 16 Pro", "iOS 18.2 iPhone SE (3rd generation)", "iOS 17.5 iPhone 15", "watchOS 11.2 Apple Watch Series 10 (46mm)"}
+ if !slices.Equal(names, want) {
+ t.Fatalf("simulators %v", names)
+ }
+ // Nothing found, nothing claimed: no Xcode, no xcode tag, no simulators.
+ bare := Capabilities(context.Background(), recordedExec(t), Tools{})
+ if !slices.Equal(bare.Tags, []string{wire.TagMacOS}) || len(bare.Simulators) != 0 || bare.Xcode.Version != "" {
+ t.Fatalf("bare %+v", bare)
+ }
+}
+
+func TestParseXcodeNeedsBothLines(t *testing.T) {
+ if (ParseXcode("Xcode 16.2\n")) != (wire.Xcode{}) || ParseXcode("xcode-select: error: tool 'xcodebuild' requires Xcode\n") != (wire.Xcode{}) {
+ t.Fatal("partial output accepted")
+ }
+}
+
+func woodstarTree(t *testing.T, files ...string) string {
+ t.Helper()
+ dir := t.TempDir()
+ for _, f := range files {
+ p := filepath.Join(dir, f)
+ if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
+ t.Fatal(err)
+ }
+ if strings.HasSuffix(f, "/") {
+ continue
+ }
+ if err := os.WriteFile(p, []byte("<Scheme/>\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return dir
+}
+
+// No gate of its own and an Xcode project: xcodebuild test on its one
+// shared scheme, on the newest iPhone simulator, by UDID.
+func TestXcodeGate(t *testing.T) {
+ sims := ParseSimulators(mustRead(t, "testdata/simctl-devices.json"))
+ tree := woodstarTree(t, "Woodstar.xcodeproj/xcshareddata/xcschemes/Woodstar.xcscheme", "Woodstar/Swipe.swift")
+ argv, ok, reason := XcodeGate(tree, sims)
+ want := `exec /usr/bin/xcodebuild test -project 'Woodstar.xcodeproj' -scheme 'Woodstar' -destination 'platform=iOS Simulator,id=8F0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3' -derivedDataPath "$TMPDIR/DerivedData" CODE_SIGNING_ALLOWED=NO`
+ if !ok || reason != "" || !slices.Equal(argv, []string{"/bin/bash", "-c", want}) {
+ t.Fatalf("%v %v %q", argv, ok, reason)
+ }
+ // A workspace wins over its projects; the scheme named like it wins
+ // among several; a quote in a name stays one word.
+ tree = woodstarTree(t, "App's.xcworkspace/contents.xcworkspacedata", "App's.xcworkspace/xcshareddata/xcschemes/App's.xcscheme", "App.xcodeproj/xcshareddata/xcschemes/Widgets.xcscheme", "Pods/Pods.xcodeproj/")
+ argv, ok, reason = XcodeGate(tree, sims)
+ if !ok || reason != "" || !strings.Contains(argv[2], `-workspace 'App'\''s.xcworkspace' -scheme 'App'\''s'`) {
+ t.Fatalf("%v %q", argv, reason)
+ }
+ for name, files := range map[string][]string{
+ "no shared scheme": {"App.xcodeproj/project.pbxproj"},
+ "two schemes": {"App.xcodeproj/xcshareddata/xcschemes/One.xcscheme", "App.xcodeproj/xcshareddata/xcschemes/Two.xcscheme"},
+ "two projects": {"A.xcodeproj/xcshareddata/xcschemes/A.xcscheme", "B.xcodeproj/xcshareddata/xcschemes/B.xcscheme"},
+ "two workspaces": {"A.xcworkspace/xcshareddata/xcschemes/A.xcscheme", "B.xcworkspace/xcshareddata/xcschemes/B.xcscheme"},
+ } {
+ if argv, ok, reason := XcodeGate(woodstarTree(t, files...), sims); !ok || reason != "checks_unavailable" || argv != nil {
+ t.Fatalf("%s: %v %v %q", name, argv, ok, reason)
+ }
+ }
+ if _, ok, reason := XcodeGate(tree, nil); !ok || reason != "checks_unavailable" {
+ t.Fatal("no simulator: gate chosen anyway")
+ }
+ if _, ok, _ := XcodeGate(woodstarTree(t, "Package.swift", "README.md"), sims); ok {
+ t.Fatal("no project: gate synthesised")
+ }
+}
+
+func mustRead(t *testing.T, name string) []byte {
+ raw, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return raw
+}
diff --git a/internal/runner/mac/fixtures/hostile/README.md b/internal/runner/mac/fixtures/hostile/README.md
new file mode 100644
index 00000000..9b9e0414
--- /dev/null
+++ b/internal/runner/mac/fixtures/hostile/README.md
@@ -0,0 +1,14 @@
+# Probe P2's hostile fixture
+
+Test data the Mac runner ships (Mac runners spec §4.3). Probe P2 copies
+it into scratch, writes `equipo-targets.txt` beside it (a sentinel in
+the runner's state dir, another person's home, a loopback port per
+place, a name to resolve and a Keychain item), and runs it under the
+checks profile. A run-script phase (`project/`), a SwiftPM build tool
+plugin and an XCTest (`package/`) each try to read, connect, resolve
+and fetch, and print one `EQUIPO-PROBE <place> <attempt> <result>` line
+per try. Checks run in the sandbox only when every try is denied.
+
+The script phase turns Xcode's own user script sandboxing off, as a
+hostile repository would. Nothing here has been built on a Mac yet:
+the first probe run on tito-studio is its first build.
diff --git a/internal/runner/mac/fixtures/hostile/package/Package.swift b/internal/runner/mac/fixtures/hostile/package/Package.swift
new file mode 100644
index 00000000..c269a738
--- /dev/null
+++ b/internal/runner/mac/fixtures/hostile/package/Package.swift
@@ -0,0 +1,13 @@
+// swift-tools-version:5.9
+import PackageDescription
+
+let package = Package(
+ name: "Hostile",
+ platforms: [.macOS(.v13), .iOS(.v16)],
+ products: [.library(name: "Hostile", targets: ["Hostile"])],
+ targets: [
+ .target(name: "Hostile", plugins: [.plugin(name: "HostilePlugin")]),
+ .plugin(name: "HostilePlugin", capability: .buildTool()),
+ .testTarget(name: "HostileTests", dependencies: ["Hostile"]),
+ ]
+)
diff --git a/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift b/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
new file mode 100644
index 00000000..552bf6c9
--- /dev/null
+++ b/internal/runner/mac/fixtures/hostile/package/Plugins/HostilePlugin/HostilePlugin.swift
@@ -0,0 +1,83 @@
+// What a hostile SwiftPM build tool plugin tries while the build plans.
+// It only reports; it never builds anything.
+import Darwin
+import Foundation
+import PackagePlugin
+import Security
+
+@main
+struct HostilePlugin: BuildToolPlugin {
+ func createBuildCommands(context: PluginContext, target: Target) async throws -> [Command] {
+ let root = URL(fileURLWithPath: context.package.directory.string).deletingLastPathComponent().path
+ for line in Attempts.run(place: "plugin", root: root) {
+ Diagnostics.warning(line)
+ }
+ return []
+ }
+}
+
+enum Attempts {
+ static func targets(_ root: String) -> [String: String] {
+ guard let text = try? String(contentsOfFile: root + "/equipo-targets.txt", encoding: .utf8) else { return [:] }
+ var out: [String: String] = [:]
+ for line in text.split(separator: "\n") {
+ let parts = line.split(separator: "=", maxSplits: 1)
+ if parts.count == 2 { out[String(parts[0])] = String(parts[1]) }
+ }
+ return out
+ }
+
+ static func run(place: String, root: String) -> [String] {
+ let t = targets(root)
+ if t.isEmpty { return ["EQUIPO-PROBE \(place) targets missing"] }
+ var lines: [String] = []
+ func report(_ what: String, _ allowed: Bool) {
+ lines.append("EQUIPO-PROBE \(place) \(what) \(allowed ? "allowed" : "denied")")
+ }
+ report("state", FileManager.default.contents(atPath: t["state"] ?? "") != nil)
+ if let home = t["home"], !home.isEmpty {
+ report("home", (try? FileManager.default.contentsOfDirectory(atPath: home)) != nil)
+ }
+ report("tcp", tcp(port: UInt16(t["port_" + place] ?? "") ?? 0))
+ report("dns", resolve(t["dns"] ?? ""))
+ report("keychain", keychain(t["keychain"] ?? ""))
+ return lines
+ }
+
+ static func tcp(port: UInt16) -> Bool {
+ if port == 0 { return false }
+ let fd = socket(AF_INET, SOCK_STREAM, 0)
+ if fd < 0 { return false }
+ defer { close(fd) }
+ var addr = sockaddr_in()
+ addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
+ addr.sin_family = sa_family_t(AF_INET)
+ addr.sin_port = port.bigEndian
+ addr.sin_addr.s_addr = inet_addr("127.0.0.1")
+ let size = socklen_t(MemoryLayout<sockaddr_in>.size)
+ let rc = withUnsafePointer(to: &addr) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, size) }
+ }
+ return rc == 0
+ }
+
+ static func resolve(_ name: String) -> Bool {
+ if name.isEmpty { return false }
+ var res: UnsafeMutablePointer<addrinfo>?
+ let rc = getaddrinfo(name, nil, nil, &res)
+ if rc == 0 { freeaddrinfo(res) }
+ return rc == 0
+ }
+
+ static func keychain(_ service: String) -> Bool {
+ if service.isEmpty { return false }
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecReturnData as String: true,
+ kSecMatchLimit as String: kSecMatchLimitOne,
+ ]
+ var item: CFTypeRef?
+ return SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess
+ }
+}
diff --git a/internal/runner/mac/fixtures/hostile/package/Sources/Hostile/Hostile.swift b/internal/runner/mac/fixtures/hostile/package/Sources/Hostile/Hostile.swift
new file mode 100644
index 00000000..e502faa7
--- /dev/null
+++ b/internal/runner/mac/fixtures/hostile/package/Sources/Hostile/Hostile.swift
@@ -0,0 +1,3 @@
+public enum Hostile {
+ public static let name = "hostile"
+}
diff --git a/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift b/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
new file mode 100644
index 00000000..6a878fe8
--- /dev/null
+++ b/internal/runner/mac/fixtures/hostile/package/Tests/HostileTests/HostileTests.swift
@@ -0,0 +1,88 @@
+// What a hostile test tries (testHostile, probe P2), and a test that
+// waits to be killed (testWait, probe P6).
+import Darwin
+import Foundation
+import Security
+import XCTest
+
+final class HostileTests: XCTestCase {
+ func testHostile() {
+ // <root>/package/Tests/HostileTests/HostileTests.swift
+ var root = URL(fileURLWithPath: #filePath)
+ for _ in 0..<4 { root = root.deletingLastPathComponent() }
+ for line in Attempts.run(place: "test", root: root.path) {
+ print(line)
+ }
+ }
+
+ func testWait() {
+ print("EQUIPO-PROBE wait started")
+ Thread.sleep(forTimeInterval: 600)
+ }
+}
+
+enum Attempts {
+ static func targets(_ root: String) -> [String: String] {
+ guard let text = try? String(contentsOfFile: root + "/equipo-targets.txt", encoding: .utf8) else { return [:] }
+ var out: [String: String] = [:]
+ for line in text.split(separator: "\n") {
+ let parts = line.split(separator: "=", maxSplits: 1)
+ if parts.count == 2 { out[String(parts[0])] = String(parts[1]) }
+ }
+ return out
+ }
+
+ static func run(place: String, root: String) -> [String] {
+ let t = targets(root)
+ if t.isEmpty { return ["EQUIPO-PROBE \(place) targets missing"] }
+ var lines: [String] = []
+ func report(_ what: String, _ allowed: Bool) {
+ lines.append("EQUIPO-PROBE \(place) \(what) \(allowed ? "allowed" : "denied")")
+ }
+ report("state", FileManager.default.contents(atPath: t["state"] ?? "") != nil)
+ if let home = t["home"], !home.isEmpty {
+ report("home", (try? FileManager.default.contentsOfDirectory(atPath: home)) != nil)
+ }
+ report("tcp", tcp(port: UInt16(t["port_" + place] ?? "") ?? 0))
+ report("dns", resolve(t["dns"] ?? ""))
+ report("keychain", keychain(t["keychain"] ?? ""))
+ return lines
+ }
+
+ static func tcp(port: UInt16) -> Bool {
+ if port == 0 { return false }
+ let fd = socket(AF_INET, SOCK_STREAM, 0)
+ if fd < 0 { return false }
+ defer { close(fd) }
+ var addr = sockaddr_in()
+ addr.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
+ addr.sin_family = sa_family_t(AF_INET)
+ addr.sin_port = port.bigEndian
+ addr.sin_addr.s_addr = inet_addr("127.0.0.1")
+ let size = socklen_t(MemoryLayout<sockaddr_in>.size)
+ let rc = withUnsafePointer(to: &addr) {
+ $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, size) }
+ }
+ return rc == 0
+ }
+
+ static func resolve(_ name: String) -> Bool {
+ if name.isEmpty { return false }
+ var res: UnsafeMutablePointer<addrinfo>?
+ let rc = getaddrinfo(name, nil, nil, &res)
+ if rc == 0 { freeaddrinfo(res) }
+ return rc == 0
+ }
+
+ static func keychain(_ service: String) -> Bool {
+ if service.isEmpty { return false }
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecReturnData as String: true,
+ kSecMatchLimit as String: kSecMatchLimitOne,
+ ]
+ var item: CFTypeRef?
+ return SecItemCopyMatching(query as CFDictionary, &item) == errSecSuccess
+ }
+}
diff --git a/internal/runner/mac/fixtures/hostile/project/Hostile.xcodeproj/project.pbxproj b/internal/runner/mac/fixtures/hostile/project/Hostile.xcodeproj/project.pbxproj
new file mode 100644
index 00000000..feb797c4
--- /dev/null
+++ b/internal/runner/mac/fixtures/hostile/project/Hostile.xcodeproj/project.pbxproj
@@ -0,0 +1,132 @@
+// !$*UTF8*$!
+{
+ archiveVersion = 1;
+ classes = {
+ };
+ objectVersion = 56;
+ objects = {
+
+/* Begin PBXAggregateTarget section */
+ E0E0E0E0E0E0E0E0E0E00001 /* HostileScript */ = {
+ isa = PBXAggregateTarget;
+ buildConfigurationList = E0E0E0E0E0E0E0E0E0E00006 /* Build configuration list for PBXAggregateTarget "HostileScript" */;
+ buildPhases = (
+ E0E0E0E0E0E0E0E0E0E00002 /* ShellScript */,
+ );
+ dependencies = (
+ );
+ name = HostileScript;
+ productName = HostileScript;
+ };
+/* End PBXAggregateTarget section */
+
+/* Begin PBXGroup section */
+ E0E0E0E0E0E0E0E0E0E00003 = {
+ isa = PBXGroup;
+ children = (
+ );
+ sourceTree = "<group>";
+ };
+/* End PBXGroup section */
+
+/* Begin PBXProject section */
+ E0E0E0E0E0E0E0E0E0E00004 /* Project object */ = {
+ isa = PBXProject;
+ attributes = {
+ LastUpgradeCheck = 1600;
+ };
+ buildConfigurationList = E0E0E0E0E0E0E0E0E0E00005 /* Build configuration list for PBXProject "Hostile" */;
+ compatibilityVersion = "Xcode 14.0";
+ developmentRegion = en;
+ hasScannedForEncodings = 0;
+ knownRegions = (
+ en,
+ Base,
+ );
+ mainGroup = E0E0E0E0E0E0E0E0E0E00003;
+ projectDirPath = "";
+ projectRoot = "";
+ targets = (
+ E0E0E0E0E0E0E0E0E0E00001 /* HostileScript */,
+ );
+ };
+/* End PBXProject section */
+
+/* Begin PBXShellScriptBuildPhase section */
+ E0E0E0E0E0E0E0E0E0E00002 /* ShellScript */ = {
+ isa = PBXShellScriptBuildPhase;
+ alwaysOutOfDate = 1;
+ buildActionMask = 2147483647;
+ files = (
+ );
+ inputFileListPaths = (
+ );
+ inputPaths = (
+ );
+ outputFileListPaths = (
+ );
+ outputPaths = (
+ );
+ runOnlyForDeploymentPostprocessing = 0;
+ shellPath = /bin/bash;
+ shellScript = "/bin/bash \"$SRCROOT/hostile.sh\"\n";
+ showEnvVarsInLog = 0;
+ };
+/* End PBXShellScriptBuildPhase section */
+
+/* Begin XCBuildConfiguration section */
+ E0E0E0E0E0E0E0E0E0E00007 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ SDKROOT = macosx;
+ };
+ name = Debug;
+ };
+ E0E0E0E0E0E0E0E0E0E00008 /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ SDKROOT = macosx;
+ };
+ name = Release;
+ };
+ E0E0E0E0E0E0E0E0E0E00009 /* Debug */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ENABLE_USER_SCRIPT_SANDBOXING = NO;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ };
+ name = Debug;
+ };
+ E0E0E0E0E0E0E0E0E0E0000A /* Release */ = {
+ isa = XCBuildConfiguration;
+ buildSettings = {
+ ENABLE_USER_SCRIPT_SANDBOXING = NO;
+ PRODUCT_NAME = "$(TARGET_NAME)";
+ };
+ name = Release;
+ };
+/* End XCBuildConfiguration section */
+
+/* Begin XCConfigurationList section */
+ E0E0E0E0E0E0E0E0E0E00005 /* Build configuration list for PBXProject "Hostile" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ E0E0E0E0E0E0E0E0E0E00007 /* Debug */,
+ E0E0E0E0E0E0E0E0E0E00008 /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+ E0E0E0E0E0E0E0E0E0E00006 /* Build configuration list for PBXAggregateTarget "HostileScript" */ = {
+ isa = XCConfigurationList;
+ buildConfigurations = (
+ E0E0E0E0E0E0E0E0E0E00009 /* Debug */,
+ E0E0E0E0E0E0E0E0E0E0000A /* Release */,
+ );
+ defaultConfigurationIsVisible = 0;
+ defaultConfigurationName = Release;
+ };
+/* End XCConfigurationList section */
+ };
+ rootObject = E0E0E0E0E0E0E0E0E0E00004 /* Project object */;
+}
diff --git a/internal/runner/mac/fixtures/hostile/project/hostile.sh b/internal/runner/mac/fixtures/hostile/project/hostile.sh
new file mode 100644
index 00000000..2d7c63e5
--- /dev/null
+++ b/internal/runner/mac/fixtures/hostile/project/hostile.sh
@@ -0,0 +1,15 @@
+#!/bin/bash
+# What a hostile run-script phase tries (probe P2). It only reports.
+t="$SRCROOT/../equipo-targets.txt"
+get() { sed -n "s/^$1=//p" "$t" | head -n 1; }
+say() { echo "EQUIPO-PROBE script $1 $2"; }
+[ -r "$t" ] || { echo "EQUIPO-PROBE script targets missing"; exit 0; }
+state=$(get state); home=$(get home); port=$(get port_script); dns=$(get dns); svc=$(get keychain)
+if cat "$state" >/dev/null 2>&1; then say state allowed; else say state denied; fi
+if [ -n "$home" ]; then
+ if ls "$home" >/dev/null 2>&1; then say home allowed; else say home denied; fi
+fi
+if /usr/bin/nc -z -G 3 127.0.0.1 "$port" >/dev/null 2>&1; then say tcp allowed; else say tcp denied; fi
+if /usr/bin/dscacheutil -q host -a name "$dns" 2>/dev/null | grep -q address; then say dns allowed; else say dns denied; fi
+if /usr/bin/security find-generic-password -s "$svc" -w >/dev/null 2>&1; then say keychain allowed; else say keychain denied; fi
+exit 0
diff --git a/internal/runner/mac/gate.go b/internal/runner/mac/gate.go
new file mode 100644
index 00000000..e37b2158
--- /dev/null
+++ b/internal/runner/mac/gate.go
@@ -0,0 +1,308 @@
+package mac
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "time"
+)
+
+// Result is one gate run: the output's last lines, the exit code, why it
+// did not finish ("cancelled", "checks_timeout", "checks_unavailable"),
+// whether its end is proven, and how it was confined.
+type Result struct {
+ Output, Reason string
+ Code int
+ Terminated bool
+ // Sandbox is wire.SandboxSeatbelt when srt confined the gate, else
+ // wire.SandboxNone.
+ Sandbox string
+}
+
+// Gate runs a repository's checks in a process group of their own
+// (spec §5): a new session, EQUIPO_ATTEMPT=<key> in the environment, an
+// environment from scratch. With SRT set the gate runs under srt with
+// the attempt's checks profile; without, it runs outside the sandbox
+// (the test build's fake worker, or a Mac whose P2 did not deny).
+type Gate struct {
+ // SRT is the srt executable; "" runs the gate without a sandbox.
+ SRT string
+ // Settings writes the attempt's srt settings for a tree and scratch.
+ Settings func(tree, attempt string) ([]byte, error)
+ // Env is the gate's whole environment but TMPDIR, EQUIPO_ATTEMPT and
+ // EQUIPO_GATE_STATUS, which the run adds.
+ Env []string
+ // Caffeinate keeps the Mac awake while a gate runs
+ // (/usr/bin/caffeinate); "" does not.
+ Caffeinate string
+ // Booted lists the simulators booted now; Shutdown shuts one down.
+ // A run shuts down the simulators it booted.
+ Booted func(context.Context) []string
+ Shutdown func(context.Context, string)
+ // Grace is SIGTERM to SIGKILL (10 s); Settle bounds the proof (30 s).
+ Grace, Settle time.Duration
+ // Lines bounds the output kept (the last 200 lines).
+ Lines int
+ // Sandbox labels the result: srt confines it (seatbelt) or not (none).
+ Sandbox string
+ // Watch sees each line of output as it comes (probe P6 waits for a
+ // test to start before it kills the group).
+ Watch func(string)
+ // find lists marked processes (Marked; tests stand in).
+ find func(string) ([]Proc, error)
+}
+
+// statusScript runs the gate and records its exit status in a file: srt
+// exits 0 when the command it wraps dies of SIGTERM or SIGINT
+// (cli.ts), so the exit code alone could turn a killed gate into a pass.
+const statusScript = `"$@"; s=$?; printf '%s\n' "$s" > "$EQUIPO_GATE_STATUS"; exit "$s"`
+
+// Run runs argv in dir. record gets the attempt's process record before
+// it can do anything, so a restarted runner can prove its end.
+func (g *Gate) Run(ctx context.Context, attempt, dir string, argv []string, limit time.Duration, record func(string)) Result {
+ res := Result{Code: -1, Sandbox: g.Sandbox}
+ unavailable := func() Result { res.Reason, res.Terminated = "checks_unavailable", true; return res }
+ if len(argv) == 0 || strings.ContainsAny(attempt, " \n\x00") {
+ return unavailable()
+ }
+ scratch, err := os.MkdirTemp(filepath.Dir(dir), "attempt-")
+ if err != nil {
+ return unavailable()
+ }
+ defer os.RemoveAll(scratch)
+ status := filepath.Join(scratch, ".equipo-status")
+ cmdline := append([]string{"/bin/sh", "-c", statusScript, "sh"}, argv...)
+ if g.SRT != "" {
+ raw, err := g.Settings(dir, scratch)
+ if err != nil {
+ return unavailable()
+ }
+ // Beside the tree and scratch, not in them: the gate cannot
+ // rewrite its own profile (it is read once, at start, anyway).
+ settings := filepath.Join(filepath.Dir(dir), "srt-settings-"+filepath.Base(scratch)+".json")
+ if err := os.WriteFile(settings, raw, 0600); err != nil {
+ return unavailable()
+ }
+ defer os.Remove(settings)
+ cmdline = append([]string{g.SRT, "--settings", settings, "--"}, cmdline...)
+ }
+ var before []string
+ if g.Booted != nil {
+ before = g.Booted(ctx)
+ }
+ cmd := exec.Command(cmdline[0], cmdline[1:]...)
+ cmd.Dir = dir
+ cmd.Env = append(append([]string{}, g.Env...), "TMPDIR="+scratch, "EQUIPO_ATTEMPT="+attempt, "EQUIPO_GATE_STATUS="+status)
+ out := &tail{max: max(g.Lines, 1), watch: g.Watch}
+ cmd.Stdout, cmd.Stderr = out, out
+ cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ // A child that keeps the output open must not hold the run: once the
+ // leader has gone, the pipes close after a second and the sweep
+ // below kills what is left.
+ cmd.WaitDelay = time.Second
+ if err := cmd.Start(); err != nil {
+ return unavailable()
+ }
+ pgid := cmd.Process.Pid
+ record(RecordID(pgid, attempt))
+ exited := make(chan error, 1)
+ go func() { exited <- cmd.Wait() }()
+ if g.Caffeinate != "" {
+ // Outside the group: it ends by itself when the gate's leader does.
+ awake := exec.Command(g.Caffeinate, "-i", "-w", strconv.Itoa(pgid))
+ if awake.Start() == nil {
+ go func() { _ = awake.Wait() }()
+ }
+ }
+ grace := g.Grace
+ if grace <= 0 {
+ grace = 10 * time.Second
+ }
+ stop := func(reason string) {
+ res.Reason = reason
+ _ = syscall.Kill(-pgid, syscall.SIGTERM)
+ select {
+ case <-exited:
+ case <-time.After(grace):
+ _ = syscall.Kill(-pgid, syscall.SIGKILL)
+ <-exited
+ }
+ }
+ timer := time.NewTimer(limit)
+ defer timer.Stop()
+ select {
+ case err := <-exited:
+ res.Code = exitCode(err)
+ if res.Code == 0 {
+ // Both must say 0: srt's own exit and the status the gate's
+ // shell recorded.
+ raw, rerr := os.ReadFile(status)
+ if n, perr := strconv.Atoi(strings.TrimSpace(string(raw))); rerr != nil || perr != nil || n != 0 {
+ res.Code = 1
+ if perr == nil && n > 0 {
+ res.Code = n
+ }
+ }
+ }
+ case <-ctx.Done():
+ stop("cancelled")
+ case <-timer.C:
+ stop("checks_timeout")
+ }
+ res.Terminated = g.settle(pgid, attempt, true)
+ if g.Booted != nil && g.Shutdown != nil {
+ for _, udid := range g.Booted(context.WithoutCancel(ctx)) {
+ if !contains(before, udid) {
+ g.Shutdown(context.WithoutCancel(ctx), udid)
+ }
+ }
+ }
+ res.Output = out.String()
+ return res
+}
+
+// RecordID is the process record of an attempt: its group and marker.
+func RecordID(pgid int, attempt string) string { return "pg:" + strconv.Itoa(pgid) + ":" + attempt }
+
+// Verify reports whether a recorded attempt has ended for sure, killing
+// what is left of it: after a crash this is what kills every marked
+// process before the runner reports runner_restarted.
+func (g *Gate) Verify(id string) bool {
+ rest, ok := strings.CutPrefix(id, "pg:")
+ if !ok {
+ return false
+ }
+ num, attempt, _ := strings.Cut(rest, ":")
+ pgid, err := strconv.Atoi(num)
+ if err != nil || pgid <= 1 || attempt == "" {
+ return false
+ }
+ return g.settle(pgid, attempt, false)
+}
+
+// settle kills what is left of the group and of the marked processes
+// and reports whether, within Settle, none remains: kill(-pgid, 0) says
+// ESRCH and no process carries the marker. own is true while this
+// process started the group; after a restart the group id may have been
+// reused, so it is killed only while a marked process is in it.
+func (g *Gate) settle(pgid int, attempt string, own bool) bool {
+ limit := g.Settle
+ if limit <= 0 {
+ limit = 30 * time.Second
+ }
+ deadline := time.Now().Add(limit)
+ find := g.find
+ if find == nil {
+ find = Marked
+ }
+ for {
+ marked, err := find(attempt)
+ if err != nil {
+ return false
+ }
+ ours := own
+ for _, p := range marked {
+ ours = ours || p.PGID == pgid
+ _ = syscall.Kill(p.PID, syscall.SIGKILL)
+ }
+ if ours {
+ _ = syscall.Kill(-pgid, syscall.SIGKILL)
+ }
+ gone := syscall.Kill(-pgid, 0) == syscall.ESRCH || !ours
+ if gone && len(marked) == 0 {
+ return true
+ }
+ if time.Now().After(deadline) {
+ return false
+ }
+ time.Sleep(100 * time.Millisecond)
+ }
+}
+
+// Proc is a process carrying an attempt's marker.
+type Proc struct{ PID, PGID int }
+
+// Marked lists this user's processes whose environment carries
+// EQUIPO_ATTEMPT=<attempt> (marked_linux.go reads /proc; on a Mac,
+// ps -E). Never this process.
+func Marked(attempt string) ([]Proc, error) {
+ if attempt == "" {
+ return nil, errors.New("mac: no attempt marker")
+ }
+ return marked(attempt)
+}
+
+func exitCode(err error) int {
+ if err == nil {
+ return 0
+ }
+ var exit *exec.ExitError
+ if errors.As(err, &exit) {
+ if code := exit.ExitCode(); code >= 0 {
+ return code
+ }
+ }
+ return -1
+}
+
+func contains(list []string, s string) bool {
+ for _, x := range list {
+ if x == s {
+ return true
+ }
+ }
+ return false
+}
+
+// tail keeps the last max lines written to it.
+type tail struct {
+ mu sync.Mutex
+ max int
+ watch func(string)
+ lines []string
+ partial []byte
+}
+
+func (t *tail) Write(p []byte) (int, error) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ t.partial = append(t.partial, p...)
+ for {
+ i := strings.IndexByte(string(t.partial), '\n')
+ if i < 0 {
+ break
+ }
+ t.lines = append(t.lines, string(t.partial[:i]))
+ if t.watch != nil {
+ t.watch(string(t.partial[:i]))
+ }
+ t.partial = t.partial[i+1:]
+ if len(t.lines) > t.max {
+ t.lines = t.lines[len(t.lines)-t.max:]
+ }
+ }
+ if len(t.partial) > 64<<10 {
+ t.lines = append(t.lines, string(t.partial))
+ t.partial = nil
+ }
+ return len(p), nil
+}
+
+func (t *tail) String() string {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ lines := t.lines
+ if len(t.partial) > 0 {
+ lines = append(append([]string{}, lines...), string(t.partial))
+ }
+ if len(lines) > t.max {
+ lines = lines[len(lines)-t.max:]
+ }
+ return strings.Join(lines, "\n")
+}
diff --git a/internal/runner/mac/gate_test.go b/internal/runner/mac/gate_test.go
new file mode 100644
index 00000000..8f641249
--- /dev/null
+++ b/internal/runner/mac/gate_test.go
@@ -0,0 +1,243 @@
+package mac
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+)
+
+// fakeSRT stands in for srt on Linux: it needs --settings <file> -- and a
+// readable JSON file, runs the command through a shell as srt does, and
+// exits 0 when the command dies of SIGTERM, as srt's cli does.
+const fakeSRT = `#!/bin/bash
+[ "$1" = --settings ] && [ "$3" = -- ] || exit 97
+python3 -c 'import json,sys; json.load(open(sys.argv[1]))' "$2" || exit 98
+cp "$2" "$FAKE_SRT_SEEN"
+shift 3
+"$@"
+s=$?
+[ "$s" = 143 ] && exit 0
+exit "$s"
+`
+
+func gateFixture(t *testing.T, sandboxed bool) (*Gate, string) {
+ t.Helper()
+ root := t.TempDir()
+ dir := filepath.Join(root, "tree")
+ if err := os.MkdirAll(dir, 0700); err != nil {
+ t.Fatal(err)
+ }
+ g := &Gate{Env: []string{"HOME=" + root, "PATH=/usr/bin:/bin", "CI=1", "FAKE_SRT_SEEN=" + filepath.Join(root, "seen.json")}, Grace: 300 * time.Millisecond, Settle: 5 * time.Second, Lines: 200, Sandbox: "none"}
+ if sandboxed {
+ srt := filepath.Join(root, "srt")
+ if err := os.WriteFile(srt, []byte(fakeSRT), 0700); err != nil {
+ t.Fatal(err)
+ }
+ g.SRT, g.Sandbox = srt, "seatbelt"
+ g.Settings = func(tree, attempt string) ([]byte, error) {
+ return json.Marshal(map[string]string{"tree": tree, "attempt": attempt})
+ }
+ }
+ return g, dir
+}
+
+func run(g *Gate, dir, attempt string, limit time.Duration, script string) (Result, string) {
+ var id string
+ res := g.Run(context.Background(), attempt, dir, []string{"/bin/bash", "-c", script}, limit, func(s string) { id = s })
+ return res, id
+}
+
+// Pass and fail are srt's exit and the recorded status agreeing; the
+// profile is written beside the tree for that attempt and removed.
+func TestGateRunsUnderSRT(t *testing.T) {
+ g, dir := gateFixture(t, true)
+ res, id := run(g, dir, "checks-a-1", time.Minute, "echo hello; exit 0")
+ if res.Code != 0 || !res.Terminated || res.Reason != "" || res.Sandbox != "seatbelt" || res.Output != "hello" {
+ t.Fatalf("pass: %+v", res)
+ }
+ if !strings.HasPrefix(id, "pg:") || !strings.HasSuffix(id, ":checks-a-1") {
+ t.Fatalf("record %q", id)
+ }
+ var seen map[string]string
+ raw, _ := os.ReadFile(filepath.Join(filepath.Dir(dir), "seen.json"))
+ if json.Unmarshal(raw, &seen) != nil || seen["tree"] != dir || !strings.HasPrefix(seen["attempt"], filepath.Dir(dir)+"/attempt-") {
+ t.Fatalf("srt saw %s", raw)
+ }
+ left, _ := filepath.Glob(filepath.Join(filepath.Dir(dir), "srt-settings-*"))
+ scratch, _ := filepath.Glob(filepath.Join(filepath.Dir(dir), "attempt-*"))
+ if len(left) != 0 || len(scratch) != 0 {
+ t.Fatalf("left behind: %v %v", left, scratch)
+ }
+ if res, _ = run(g, dir, "checks-a-2", time.Minute, "echo no; exit 3"); res.Code != 3 || res.Sandbox != "seatbelt" {
+ t.Fatalf("fail: %+v", res)
+ }
+}
+
+// srt exits 0 when its command dies of SIGTERM. A gate that kills the
+// shell recording its status, or exits 143, is never a pass.
+func TestGateSIGTERMIsNotAPass(t *testing.T) {
+ g, dir := gateFixture(t, true)
+ if res, _ := run(g, dir, "checks-b-1", time.Minute, "kill -TERM $PPID; sleep 2"); res.Code == 0 {
+ t.Fatalf("killed status shell passed: %+v", res)
+ }
+ if res, _ := run(g, dir, "checks-b-2", time.Minute, "kill -TERM $$"); res.Code == 0 {
+ t.Fatalf("gate killed by SIGTERM passed: %+v", res)
+ }
+}
+
+// The gate's environment is the gate's alone: nothing of the runner's
+// own reaches it, and TMPDIR is the attempt's scratch.
+func TestGateEnvironmentFromScratch(t *testing.T) {
+ t.Setenv("EQUIPO_SECRET_SENTINEL", "leak")
+ g, dir := gateFixture(t, false)
+ res, _ := run(g, dir, "checks-c-1", time.Minute, "env | sort")
+ if res.Code != 0 || res.Sandbox != "none" {
+ t.Fatalf("%+v", res)
+ }
+ var names []string
+ for _, l := range strings.Split(res.Output, "\n") {
+ k, v, _ := strings.Cut(l, "=")
+ if k == "TMPDIR" && !strings.HasPrefix(v, filepath.Dir(dir)+"/attempt-") {
+ t.Fatalf("TMPDIR %s", v)
+ }
+ names = append(names, k)
+ }
+ for _, k := range names {
+ if !slices.Contains([]string{"HOME", "PATH", "CI", "FAKE_SRT_SEEN", "TMPDIR", "EQUIPO_ATTEMPT", "EQUIPO_GATE_STATUS", "PWD", "SHLVL", "_", "OLDPWD"}, k) {
+ t.Fatalf("unexpected variable %s in %s", k, res.Output)
+ }
+ }
+}
+
+// Cancel and timeout: SIGTERM to the group, SIGKILL after the grace, a
+// sweep of marked processes (a child that ignores SIGTERM and one that
+// left the group but kept its marker), and the proof: the group gone
+// and no marked process, so the attempt is terminated.
+func TestGateCancelAndTimeoutProveTheEnd(t *testing.T) {
+ g, dir := gateFixture(t, true)
+ stubborn := "trap '' TERM; (trap '' TERM; setsid sleep 60 & sleep 60) & sleep 60"
+ ctx, cancel := context.WithCancel(context.Background())
+ var res Result
+ done := make(chan struct{})
+ go func() {
+ res = g.Run(ctx, "checks-d-1", dir, []string{"/bin/bash", "-c", stubborn}, time.Minute, func(string) {})
+ close(done)
+ }()
+ time.Sleep(700 * time.Millisecond)
+ cancel()
+ <-done
+ if res.Reason != "cancelled" || !res.Terminated {
+ t.Fatalf("cancel: %+v", res)
+ }
+ if left, _ := Marked("checks-d-1"); len(left) != 0 {
+ t.Fatalf("marked processes left: %v", left)
+ }
+ res, _ = run(g, dir, "checks-d-2", 500*time.Millisecond, stubborn)
+ if res.Reason != "checks_timeout" || !res.Terminated {
+ t.Fatalf("timeout: %+v", res)
+ }
+ if left, _ := Marked("checks-d-2"); len(left) != 0 {
+ t.Fatalf("marked processes left: %v", left)
+ }
+}
+
+// The simulators an attempt booted are shut down after it; the ones that
+// were already up are left alone.
+func TestGateShutsDownWhatItBooted(t *testing.T) {
+ g, dir := gateFixture(t, false)
+ var mu sync.Mutex
+ booted, down := []string{"A"}, []string{}
+ g.Booted = func(context.Context) []string { mu.Lock(); defer mu.Unlock(); return slices.Clone(booted) }
+ g.Shutdown = func(_ context.Context, u string) { mu.Lock(); down = append(down, u); mu.Unlock() }
+ res := g.Run(context.Background(), "checks-e-1", dir, []string{"/bin/sh", "-c", "true"}, time.Minute, func(string) {
+ mu.Lock()
+ booted = append(booted, "B")
+ mu.Unlock()
+ })
+ if res.Code != 0 || !slices.Equal(down, []string{"B"}) {
+ t.Fatalf("%+v shut down %v", res, down)
+ }
+}
+
+// After a restart a recorded attempt is settled: its marked processes
+// are killed. A group id since reused by an unmarked process is left
+// alone.
+func TestGateVerifyAfterRestart(t *testing.T) {
+ g, _ := gateFixture(t, false)
+ marked := exec.Command("/bin/sleep", "60")
+ marked.Env = []string{"EQUIPO_ATTEMPT=checks-f-1"}
+ marked.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ other := exec.Command("/bin/sleep", "60")
+ other.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
+ for _, c := range []*exec.Cmd{marked, other} {
+ if err := c.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer func(c *exec.Cmd) { _ = c.Process.Kill(); _ = c.Wait() }(c)
+ }
+ waited := make(chan error, 1)
+ go func() { waited <- marked.Wait() }()
+ if !g.Verify(RecordID(marked.Process.Pid, "checks-f-1")) {
+ t.Fatal("marked attempt not settled")
+ }
+ select {
+ case <-waited:
+ case <-time.After(5 * time.Second):
+ t.Fatal("marked process still running")
+ }
+ if !g.Verify(RecordID(other.Process.Pid, "checks-f-2")) {
+ t.Fatal("an attempt with nothing marked is not over")
+ }
+ if syscall.Kill(other.Process.Pid, 0) != nil {
+ t.Fatal("an unmarked group with a reused id was killed")
+ }
+ if g.Verify("pg:1:x") || g.Verify("ns:abc") || g.Verify("pg:"+strconv.Itoa(other.Process.Pid)+":") {
+ t.Fatal("malformed record accepted")
+ }
+}
+
+// ps -E output: the marker must be a whole word of the environment.
+func TestParseMarked(t *testing.T) {
+ out := " 101 101 /bin/bash -c make ci HOME=/Users/e EQUIPO_ATTEMPT=checks/a-1 TMPDIR=/x\n" +
+ " 102 101 xcodebuild test EQUIPO_ATTEMPT=checks/a-10\n" +
+ " 103 103 sleep 9 EQUIPO_ATTEMPT=checks/a-1\n" +
+ " 104 104 grep EQUIPO_ATTEMPT=checks/a-1x\n" +
+ " 555 555 equipo-runner run EQUIPO_ATTEMPT=checks/a-1\n" +
+ "garbage\n"
+ got := ParseMarked(out, "checks/a-1", 555)
+ if !slices.Equal(got, []Proc{{101, 101}, {103, 103}}) {
+ t.Fatalf("%v", got)
+ }
+}
+
+func TestTailKeepsTheLastLines(t *testing.T) {
+ tl := &tail{max: 3}
+ for i := range 10 {
+ _, _ = tl.Write([]byte("line " + strconv.Itoa(i) + "\n"))
+ }
+ _, _ = tl.Write([]byte("partial"))
+ if tl.String() != "line 8\nline 9\npartial" {
+ t.Fatalf("%q", tl.String())
+ }
+}
+
+// The end is proven only when the group is gone AND nothing marked is
+// left: a marked process that cannot be killed keeps the attempt
+// unproven (no Retry), however the group fares.
+func TestGateUnprovenWhileMarkedRemain(t *testing.T) {
+ g, dir := gateFixture(t, false)
+ g.Settle = 500 * time.Millisecond
+ g.find = func(string) ([]Proc, error) { return []Proc{{PID: 1 << 30, PGID: 1 << 30}}, nil }
+ if res, _ := run(g, dir, "checks-g-1", time.Minute, "true"); res.Terminated {
+ t.Fatalf("proven with a marked process left: %+v", res)
+ }
+}
diff --git a/internal/runner/mac/launchd.go b/internal/runner/mac/launchd.go
new file mode 100644
index 00000000..d9a65a72
--- /dev/null
+++ b/internal/runner/mac/launchd.go
@@ -0,0 +1,64 @@
+package mac
+
+import (
+ "bytes"
+ "encoding/xml"
+)
+
+// AgentLabel is the launchd user agent's label.
+const AgentLabel = "io.amadan.equipo-runner"
+
+// Exit statuses under launchd. KeepAlive restarts the runner only after
+// a non-zero exit (SuccessfulExit false): an update exits ExitUpdated so
+// the new binary starts, a runner that lost its lease to a newer process
+// exits 0 so the two never take turns, and a crash restarts.
+const ExitUpdated = 75
+
+// LaunchAgent is ~/Library/LaunchAgents/io.amadan.equipo-runner.plist
+// (spec §3.2): runs at load, kept alive, a Standard process so builds
+// are not throttled, its environment from envFile (launchd has no
+// EnvironmentFile), logs under logDir, private files.
+func LaunchAgent(binary, envFile, logDir string) []byte {
+ var b bytes.Buffer
+ esc := func(s string) string {
+ var e bytes.Buffer
+ _ = xml.EscapeText(&e, []byte(s))
+ return e.String()
+ }
+ b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>Label</key>
+ <string>` + AgentLabel + `</string>
+ <key>ProgramArguments</key>
+ <array>
+ <string>` + esc(binary) + `</string>
+ <string>run</string>
+ <string>--env-file</string>
+ <string>` + esc(envFile) + `</string>
+ </array>
+ <key>RunAtLoad</key>
+ <true/>
+ <key>KeepAlive</key>
+ <dict>
+ <key>SuccessfulExit</key>
+ <false/>
+ </dict>
+ <key>ProcessType</key>
+ <string>Standard</string>
+ <key>ThrottleInterval</key>
+ <integer>10</integer>
+ <key>ExitTimeOut</key>
+ <integer>45</integer>
+ <key>Umask</key>
+ <integer>63</integer>
+ <key>StandardOutPath</key>
+ <string>` + esc(logDir+"/runner.log") + `</string>
+ <key>StandardErrorPath</key>
+ <string>` + esc(logDir+"/runner.log") + `</string>
+</dict>
+</plist>
+`)
+ return b.Bytes()
+}
diff --git a/internal/runner/mac/marked_darwin.go b/internal/runner/mac/marked_darwin.go
new file mode 100644
index 00000000..54db3dbc
--- /dev/null
+++ b/internal/runner/mac/marked_darwin.go
@@ -0,0 +1,20 @@
+package mac
+
+import (
+ "context"
+ "os"
+ "os/exec"
+ "time"
+)
+
+// marked asks ps for this user's processes with their environment
+// (-E shows it for one's own processes only, which is all we may kill).
+func marked(attempt string) ([]Proc, error) {
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ raw, err := exec.CommandContext(ctx, "/bin/ps", "-E", "-ww", "-x", "-o", "pid=,pgid=,command=").Output()
+ if err != nil {
+ return nil, err
+ }
+ return ParseMarked(string(raw), attempt, os.Getpid()), nil
+}
diff --git a/internal/runner/mac/marked_linux.go b/internal/runner/mac/marked_linux.go
new file mode 100644
index 00000000..c431e2b0
--- /dev/null
+++ b/internal/runner/mac/marked_linux.go
@@ -0,0 +1,42 @@
+package mac
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+// marked reads /proc: every process of this user whose environment
+// carries the attempt's marker, with its process group.
+func marked(attempt string) ([]Proc, error) {
+ want := []byte("EQUIPO_ATTEMPT=" + attempt + "\x00")
+ entries, err := os.ReadDir("/proc")
+ if err != nil {
+ return nil, err
+ }
+ var out []Proc
+ for _, e := range entries {
+ pid, err := strconv.Atoi(e.Name())
+ if err != nil || pid == os.Getpid() {
+ continue
+ }
+ env, err := os.ReadFile(filepath.Join("/proc", e.Name(), "environ"))
+ if err != nil || !bytes.Contains(append(env, 0), want) {
+ continue
+ }
+ stat, err := os.ReadFile(filepath.Join("/proc", e.Name(), "stat"))
+ if err != nil {
+ continue
+ }
+ // pid (comm) state ppid pgrp ...; comm may hold spaces.
+ fields := strings.Fields(string(stat[bytes.LastIndexByte(stat, ')')+1:]))
+ pgid := 0
+ if len(fields) > 2 {
+ pgid, _ = strconv.Atoi(fields[2])
+ }
+ out = append(out, Proc{PID: pid, PGID: pgid})
+ }
+ return out, nil
+}
diff --git a/internal/runner/mac/probe.go b/internal/runner/mac/probe.go
new file mode 100644
index 00000000..fbfcb2eb
--- /dev/null
+++ b/internal/runner/mac/probe.go
@@ -0,0 +1,646 @@
+package mac
+
+import (
+ "context"
+ "crypto/rand"
+ "crypto/sha256"
+ "embed"
+ "encoding/hex"
+ "encoding/json"
+ "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: the
+ // checks profile denies it, and the fixture is the tree).
+ Scratch 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
+ // Resolve and ListHome 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
+ ListHome func(path string) bool
+ Listen func() (net.Listener, error)
+ // Wait bounds P6's wait for its test to start (8 minutes).
+ Wait time.Duration
+}
+
+// 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"`
+}
+
+// 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 }
+
+// Current reports whether r was made by this runner version with this
+// checks profile; otherwise the probes run again.
+func (r Report) Current(version string) bool {
+ return r.Version == version && r.Profile == ProfileDigest() && len(r.Probes) == len(wire.ProbeIDs)
+}
+
+// ProfileDigest names the checks profile the probes judged: the
+// settings over fixed paths, the Mach list and the fixture.
+func ProfileDigest() string {
+ raw, _ := ChecksSettings(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"}}, Tree: "/Users/u/t/tree", Attempt: "/Users/u/t/attempt", Mach: CheckMachServices})
+ 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]
+}
+
+// LoadReport reads a saved report; SaveReport replaces it atomically.
+func LoadReport(file string) (Report, error) {
+ var r Report
+ raw, err := os.ReadFile(file)
+ if err == nil {
+ err = json.Unmarshal(raw, &r)
+ }
+ return r, err
+}
+
+func SaveReport(file string, r Report) error {
+ raw, err := json.MarshalIndent(r, "", " ")
+ if err != nil {
+ return err
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(file), ".probes-")
+ if err != nil {
+ return err
+ }
+ defer os.Remove(tmp.Name())
+ if _, err = tmp.Write(raw); err == nil {
+ err = tmp.Sync()
+ }
+ if cerr := tmp.Close(); err == nil {
+ err = cerr
+ }
+ if err != nil {
+ return err
+ }
+ return os.Rename(tmp.Name(), file)
+}
+
+// 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.
+func RunProbes(ctx context.Context, h ProbeHost) Report {
+ r := Report{Version: h.Version, Profile: ProfileDigest(), At: time.Now().UTC()}
+ caps := Capabilities(ctx, h.Exec, h.Tools)
+ r.Probes = append(r.Probes, probeP1(ctx, h, caps))
+ p2, srtRan, keychain := probeP2(ctx, h, caps)
+ r.SRTRanXcode = srtRan
+ r.Probes = append(r.Probes, p2)
+ r.Probes = append(r.Probes, wire.Probe{ID: "P3", Verdict: wire.ProbeSkipped, Detail: clean("sign-in needs a person (slice F); Keychain from the sandbox: " + keychain)})
+ r.Probes = append(r.Probes, probeP4(ctx, h))
+ r.Probes = append(r.Probes, wire.Probe{ID: "P5", Verdict: wire.ProbeSkipped, Detail: "Codex on the Mac is parked (slice G)"})
+ r.Probes = append(r.Probes, probeP6(ctx, h, caps, srtRan))
+ r.Probes = append(r.Probes, probeP7(ctx, h))
+ return r
+}
+
+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++
+ }
+ }
+ if caps.Xcode.Version == "" {
+ return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: clean("no Xcode; " + name)}
+ }
+ detail := fmt.Sprintf("Xcode %s (%s); %d iOS simulators; %s", caps.Xcode.Version, caps.Xcode.Build, ios, name)
+ if ios == 0 {
+ return wire.Probe{ID: "P1", Verdict: wire.ProbeFailed, Detail: clean(detail)}
+ }
+ return wire.Probe{ID: "P1", Verdict: wire.ProbePassed, Detail: clean(detail)}
+}
+
+// ComputerName is the Mac's name as people see it ("Tito Studio").
+func ComputerName(ctx context.Context, x Exec) string {
+ 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"}
+ attemptLine = regexp.MustCompile(`EQUIPO-PROBE (script|plugin|test) (state|home|tcp|dns|keychain) (allowed|denied)\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: the name resolves outside; Keychain: the sentinel item exists.
+ DNS, Keychain 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 DNS or Keychain control that failed outside, 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 = "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
+}
+
+func p2Detail(groups map[string][]string, total int, srtRan bool) string {
+ var parts []string
+ for _, g := range []struct{ key, label string }{{"allowed", "allowed"}, {"unknown", "not shown denied"}, {"unix", "Unix permissions only"}} {
+ if len(groups[g.key]) > 0 {
+ parts = append(parts, g.label+": "+strings.Join(groups[g.key], " "))
+ }
+ }
+ if len(parts) == 0 {
+ parts = append(parts, fmt.Sprintf("all %d attempts denied", total))
+ }
+ if srtRan {
+ parts = append(parts, "xcodebuild ran in srt")
+ } else {
+ parts = append(parts, "xcodebuild did not run in srt")
+ }
+ return clean(strings.Join(parts, "; "))
+}
+
+// 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, "not probed"
+ }
+ if h.Tools.SRT == "" {
+ return fail(wire.ProbeUnavailable, "srt is not installed")
+ }
+ if caps.Xcode.Version == "" {
+ return fail(wire.ProbeUnavailable, "no Xcode")
+ }
+ root, err := copyFixture(h.Scratch)
+ if err != nil {
+ return fail(wire.ProbeUnavailable, "the fixture could not be copied")
+ }
+ 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)
+ targets = append(targets, "state="+sentinel)
+ if home := otherHome(h.Paths.OtherHomes); home != "" {
+ facts.Home, facts.HomeUnix = true, !h.ListHome(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))
+ }
+ facts.DNS = h.Resolve(ctx, "example.com")
+ targets = append(targets, "dns=example.com")
+ service := "io.amadan.equipo.probe." + secret[:12]
+ if _, err := h.Exec(ctx, "/usr/bin/security", "add-generic-password", "-a", "equipo-probe", "-s", service, "-w", secret, "-A", "-U"); err == nil {
+ facts.Keychain = true
+ defer func() {
+ _, _ = h.Exec(context.WithoutCancel(ctx), "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service)
+ }()
+ }
+ targets = append(targets, "keychain="+service)
+ if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0600); err != nil {
+ return fail(wire.ProbeUnavailable, "the fixture could not be prepared")
+ }
+ xb := quote(h.Tools.Xcodebuild)
+ script := `cd project && ` + xb + ` -project Hostile.xcodeproj -target HostileScript -configuration Debug build SYMROOT="$TMPDIR/sym" OBJROOT="$TMPDIR/obj"
+cd ../package && s=Hostile-Package; ` + xb + ` -list 2>/dev/null | grep -q Hostile-Package || s=Hostile
+` + xb + ` test -scheme "$s" -destination 'platform=macOS' -only-testing:HostileTests/HostileTests/testHostile -derivedDataPath "$TMPDIR/dd" -skipPackagePluginValidation`
+ res := h.Gate(true).Run(ctx, "probe-p2-"+secret[:8], root, []string{"/bin/bash", "-c", script}, 20*time.Minute, func(string) {})
+ mu.Lock()
+ defer mu.Unlock()
+ srtRan := res.Code == 0 && strings.Contains(res.Output, "** BUILD SUCCEEDED **") && strings.Contains(res.Output, "** TEST SUCCEEDED **")
+ verdict, groups := JudgeP2(ParseAttempts(res.Output), facts)
+ keychain := "denied"
+ for _, list := range groups {
+ for _, k := range list {
+ if strings.HasSuffix(k, ".keychain") {
+ keychain = "not shown denied"
+ }
+ }
+ }
+ total := len(probePlaces) * len(probeAttempts)
+ if !facts.Home {
+ total -= len(probePlaces)
+ }
+ return wire.Probe{ID: "P2", Verdict: verdict, Detail: p2Detail(groups, total, srtRan)}, 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 h.Paths.OtherHomes {
+ if path.Base(home) != "Shared" && h.ListHome(home) {
+ readable = append(readable, path.Base(home))
+ }
+ }
+ _, err := h.Exec(ctx, "/bin/launchctl", "print", "gui/"+strconv.Itoa(h.UID)+"/"+AgentLabel)
+ loaded := err == nil
+ pm, _ := h.Exec(ctx, "/usr/bin/pmset", "-g", "custom")
+ sleep, known := ACSleep(pm)
+ var parts []string
+ if len(readable) > 0 {
+ parts = append(parts, "readable homes: "+strings.Join(readable, " "))
+ } else {
+ parts = append(parts, "no other home readable")
+ }
+ parts = append(parts, map[bool]string{true: "agent loaded", false: "agent not loaded"}[loaded])
+ switch {
+ case !known:
+ parts = append(parts, "sleep unknown")
+ case sleep == 0:
+ parts = append(parts, "sleep off on power")
+ default:
+ parts = append(parts, fmt.Sprintf("sleeps after %d minutes on power", sleep))
+ }
+ verdict := wire.ProbePassed
+ if len(readable) > 0 || !loaded || !known || sleep != 0 {
+ verdict = wire.ProbeFailed
+ }
+ return wire.Probe{ID: "P4", Verdict: verdict, Detail: clean(strings.Join(parts, "; "))}
+}
+
+// ACSleep reads `pmset -g custom`: the system sleep minutes under "AC
+// Power" (0 is never).
+func ACSleep(out string) (int, bool) {
+ ac := false
+ 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: "no Xcode"}
+ }
+ root, err := copyFixture(h.Scratch)
+ if err != nil {
+ return wire.Probe{ID: "P6", Verdict: wire.ProbeUnavailable, Detail: "the fixture could not be copied"}
+ }
+ 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
+ }
+ xb := quote(h.Tools.Xcodebuild)
+ script := `cd package && s=Hostile-Package; ` + xb + ` -list 2>/dev/null | grep -q Hostile-Package || s=Hostile
+exec ` + xb + ` test -scheme "$s" -destination ` + quote(destination) + ` -only-testing:HostileTests/HostileTests/testWait -derivedDataPath "$TMPDIR/dd" -skipPackagePluginValidation`
+ res := g.Run(run, attempt, root, []string{"/bin/bash", "-c", script}, wait, func(string) {})
+ 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: clean("the waiting test did not start (" + firstNonEmpty(res.Reason, "exit "+strconv.Itoa(res.Code)) + ")")}
+ }
+ var parts []string
+ if res.Terminated {
+ parts = append(parts, fmt.Sprintf("group gone in %s", took))
+ } else {
+ parts = append(parts, "group end not proven")
+ }
+ parts = append(parts, fmt.Sprintf("%d marked left", len(left)))
+ if n := newNames(before, after); len(n) > 0 {
+ parts = append(parts, "still running: "+strings.Join(n, " "))
+ }
+ parts = append(parts, fmt.Sprintf("%d simulators shut down", shut.Load()))
+ parts = append(parts, 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: clean(strings.Join(parts, "; "))}
+}
+
+// processNames are this user's processes by name (basename), counted.
+func processNames(ctx context.Context, x Exec) map[string]int {
+ 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
+}
+
+func newNames(before, after map[string]int) []string {
+ var out []string
+ for n, c := range after {
+ if c > before[n] {
+ out = append(out, n)
+ }
+ }
+ sort.Strings(out)
+ if len(out) > 8 {
+ out = append(out[:8], "and more")
+ }
+ return out
+}
+
+func probeP7(ctx context.Context, h ProbeHost) wire.Probe {
+ ask := func(tool string, args ...string) string {
+ if tool == "" {
+ return ""
+ }
+ out, err := h.Exec(ctx, 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, t.name+" missing"), false
+ } else {
+ parts = append(parts, t.name+" "+t.version)
+ }
+ }
+ if node != "" && !NodeSupported(node) {
+ parts, ok = append(parts, "node older than 22.12"), 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)
+ if _, err := h.Exec(ctx, h.Tools.SRT, "--settings", file, "--", "/usr/bin/true"); err != nil {
+ parts, ok = append(parts, "srt could not run a command"), false
+ }
+ }
+ }
+ verdict := wire.ProbePassed
+ if !ok {
+ verdict = wire.ProbeFailed
+ }
+ return wire.Probe{ID: "P7", Verdict: verdict, Detail: clean(strings.Join(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
+}
+
+// clean keeps a probe detail inside the capability string rules: one
+// line, no path separator, tilde or equals sign, at most 300 bytes.
+func clean(s string) string {
+ s = strings.Map(func(r rune) rune {
+ if strings.ContainsRune("/\\~\n\r\t\x00=", r) {
+ return ' '
+ }
+ return r
+ }, s)
+ for len(s) > wire.MaxCapabilityString {
+ s = s[:len(s)-1]
+ for len(s) > 0 && !utf8Start(s[len(s)-1]) {
+ s = s[:len(s)-1]
+ }
+ }
+ return s
+}
+
+func utf8Start(b byte) bool { return b&0xC0 != 0x80 }
+
+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 ""
+}
diff --git a/internal/runner/mac/probe_test.go b/internal/runner/mac/probe_test.go
new file mode 100644
index 00000000..63e0e2d1
--- /dev/null
+++ b/internal/runner/mac/probe_test.go
@@ -0,0 +1,283 @@
+package mac
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// fakeXcodebuild plays xcodebuild for the fixture: it really reads the
+// targets file the probe wrote, prints the report lines a scenario
+// gives, and with FAKE_CONNECT connects to the test's loopback port
+// while saying "denied" (the probe's listener must catch the lie).
+const fakeXcodebuild = `#!/bin/bash
+case "$*" in
+*-list*) echo " Schemes:"; echo " Hostile-Package"; exit 0 ;;
+*HostileScript*)
+ [ -r ../equipo-targets.txt ] || { echo "no targets"; exit 3; }
+ [ -n "$FAKE_BUILD_FAIL" ] && { echo "Sandbox: deny(1) mach-lookup com.apple.dt.example"; echo "** BUILD FAILED **"; exit 65; }
+ cat "$FAKE_DIR/script.out"; echo "** BUILD SUCCEEDED **"; exit 0 ;;
+*testHostile*)
+ t=../equipo-targets.txt
+ if [ -n "$FAKE_READ_STATE" ] && cat "$(sed -n 's/^state=//p' $t)" >/dev/null 2>&1; then echo "EQUIPO-PROBE test state allowed"; fi
+ if [ -n "$FAKE_CONNECT" ]; then exec 3<>"/dev/tcp/127.0.0.1/$(sed -n 's/^port_test=//p' $t)"; fi
+ cat "$FAKE_DIR/test.out"; echo "** TEST SUCCEEDED **"; exit 0 ;;
+*testWait*) echo "EQUIPO-PROBE wait started"; exec sleep 600 ;;
+esac
+exit 64
+`
+
+func allLines(result string) map[string]string {
+ out := map[string]string{}
+ for _, place := range []string{"script", "plugin", "test"} {
+ var b strings.Builder
+ for _, what := range []string{"state", "home", "tcp", "dns", "keychain"} {
+ b.WriteString("warning: EQUIPO-PROBE " + place + " " + what + " " + result + "\n")
+ }
+ out[place] = b.String()
+ }
+ return out
+}
+
+type probeFixture struct {
+ h ProbeHost
+ dir string
+ execLog []string
+}
+
+func newProbeFixture(t *testing.T, lines map[string]string, env ...string) *probeFixture {
+ t.Helper()
+ root := t.TempDir()
+ f := &probeFixture{dir: root}
+ xb := filepath.Join(root, "xcodebuild")
+ srt := filepath.Join(root, "srt")
+ for p, body := range map[string]string{xb: fakeXcodebuild, srt: fakeSRT} {
+ if err := os.WriteFile(p, []byte(body), 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ // The script and plugin places print through the build log; the
+ // fake prints the plugin's beside the script's.
+ if err := os.WriteFile(filepath.Join(root, "script.out"), []byte(lines["script"]+lines["plugin"]), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(root, "test.out"), []byte(lines["test"]), 0600); err != nil {
+ t.Fatal(err)
+ }
+ state := filepath.Join(root, "state")
+ if err := os.MkdirAll(state, 0700); err != nil {
+ t.Fatal(err)
+ }
+ pm := "Battery Power:\n sleep 1\nAC Power:\n Sleep On Power Button 1\n sleep 0\n displaysleep 10\n"
+ execs := map[string]string{
+ xb + " -version": "Xcode 16.2\nBuild version 16C5032a\n", "/usr/sbin/scutil --get ComputerName": "Tito Studio\n",
+ "node --version": "v22.12.0\n", "rg --version": "ripgrep 14.1.1\n", srt + " --version": "0.0.81\n",
+ "/usr/bin/pmset -g custom": pm, "/bin/ps -x -o comm=": "/bin/zsh\n",
+ "/bin/launchctl print gui/501/io.amadan.equipo-runner": "gui/501/io.amadan.equipo-runner = {\n",
+ }
+ sims, _ := os.ReadFile("testdata/simctl-devices.json")
+ exec := func(ctx context.Context, name string, args ...string) (string, error) {
+ key := strings.Join(append([]string{name}, args...), " ")
+ f.execLog = append(f.execLog, key)
+ switch {
+ case key == "xcrun simctl list -j devices available":
+ return string(sims), nil
+ case strings.HasPrefix(key, "/usr/bin/security "):
+ return "", nil
+ case strings.HasPrefix(key, srt+" --settings "):
+ return "", nil
+ }
+ if out, ok := execs[key]; ok {
+ return out, nil
+ }
+ return "", errors.New("not recorded: " + key)
+ }
+ base := []string{"PATH=/usr/bin:/bin", "HOME=" + root, "FAKE_DIR=" + root, "FAKE_SRT_SEEN=" + filepath.Join(root, "seen.json")}
+ f.h = ProbeHost{Exec: exec, Tools: Tools{Xcodebuild: xb, Xcrun: "xcrun", Node: "node", SRT: srt, RG: "rg"},
+ Paths: Paths{Home: root, StateDir: state, OtherHomes: []string{"/Users/Shared", "/Users/paul"}},
+ Scratch: filepath.Join(root, "scratch"), UID: 501, Version: "abc1234",
+ Gate: func(sandboxed bool) *Gate {
+ g := &Gate{Env: append(append([]string{}, base...), env...), Grace: 300 * time.Millisecond, Settle: 5 * time.Second, Lines: 200, Sandbox: wire.SandboxNone}
+ if sandboxed {
+ g.SRT, g.Sandbox = srt, wire.SandboxSeatbelt
+ g.Settings = func(tree, attempt string) ([]byte, error) { return []byte("{}"), nil }
+ }
+ return g
+ },
+ Resolve: func(context.Context, string) bool { return true },
+ ListHome: func(string) bool { return false },
+ Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") },
+ Wait: 30 * time.Second,
+ }
+ return f
+}
+
+// The whole probe run against a fake Mac whose fixture reports every
+// attempt denied: P2 denied, the report valid as a capability report.
+func TestRunProbesAllDenied(t *testing.T) {
+ f := newProbeFixture(t, allLines("denied"))
+ r := RunProbes(context.Background(), f.h)
+ if err := wire.ValidCapabilities(wire.Capabilities{Probes: r.Probes}); err != nil {
+ t.Fatalf("report outside the capability rules: %v %+v", err, r.Probes)
+ }
+ var ids []string
+ for _, p := range r.Probes {
+ ids = append(ids, p.ID)
+ }
+ if !slices.Equal(ids, wire.ProbeIDs) {
+ t.Fatalf("probes %v", ids)
+ }
+ if !r.Sandboxed() || !r.SRTRanXcode || !r.Current("abc1234") {
+ t.Fatalf("P2 %+v srt=%v", r.Probe("P2"), r.SRTRanXcode)
+ }
+ if p := r.Probe("P2"); p.Detail != "Unix permissions only: script.home plugin.home test.home; xcodebuild ran in srt" {
+ t.Fatalf("P2 detail %q", p.Detail)
+ }
+ for id, want := range map[string]string{"P1": wire.ProbePassed, "P3": wire.ProbeSkipped, "P4": wire.ProbePassed, "P5": wire.ProbeSkipped, "P6": wire.ProbePassed, "P7": wire.ProbePassed} {
+ if p := r.Probe(id); p.Verdict != want {
+ t.Fatalf("%s %+v", id, p)
+ }
+ }
+ if !strings.HasPrefix(r.Probe("P1").Detail, "Xcode 16.2 (16C5032a); 5 iOS simulators; Tito Studio") || !strings.Contains(r.Probe("P6").Detail, "0 marked left") || !strings.Contains(r.Probe("P6").Detail, "tree removed") {
+ t.Fatalf("details %+v", r.Probes)
+ }
+ // The sentinel and the Keychain item are gone, the copies too.
+ if left, _ := filepath.Glob(filepath.Join(f.h.Paths.StateDir, "probe-sentinel-*")); len(left) != 0 {
+ t.Fatalf("sentinel left %v", left)
+ }
+ if left, _ := filepath.Glob(filepath.Join(f.h.Scratch, "*")); len(left) != 0 {
+ t.Fatalf("scratch left %v", left)
+ }
+ added, deleted := false, false
+ for _, l := range f.execLog {
+ added = added || strings.HasPrefix(l, "/usr/bin/security add-generic-password -a equipo-probe -s io.amadan.equipo.probe.") && strings.HasSuffix(l, " -A -U")
+ deleted = deleted || strings.HasPrefix(l, "/usr/bin/security delete-generic-password -a equipo-probe -s io.amadan.equipo.probe.")
+ }
+ if !added || !deleted {
+ t.Fatalf("keychain sentinel not added and removed: %v", f.execLog)
+ }
+ raw, _ := json.Marshal(r)
+ if strings.Contains(string(raw), f.h.Paths.StateDir) || strings.Contains(string(raw), "/Users/") {
+ t.Fatalf("a path left the machine: %s", raw)
+ }
+}
+
+// Anything short of every attempt denied is not P2's pass: an attempt
+// that got through (here the fixture really reads the sentinel, outside
+// any sandbox), a lie the loopback listener catches, a missing line, a
+// DNS control that failed outside, a fixture that did not build.
+func TestP2IsDeniedOnlyWhenEverythingIs(t *testing.T) {
+ f := newProbeFixture(t, allLines("denied"), "FAKE_READ_STATE=1")
+ if p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "allowed: test.state") {
+ t.Fatalf("sentinel read: %+v", p)
+ }
+ f = newProbeFixture(t, allLines("denied"), "FAKE_CONNECT=1")
+ if p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "allowed: test.tcp") {
+ t.Fatalf("connection behind a denied line: %+v", p)
+ }
+ lines := allLines("denied")
+ lines["plugin"] = strings.Replace(lines["plugin"], "warning: EQUIPO-PROBE plugin keychain denied\n", "", 1)
+ f = newProbeFixture(t, lines)
+ if p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "not shown denied: plugin.keychain") {
+ t.Fatalf("missing line: %+v", p)
+ }
+ f = newProbeFixture(t, allLines("denied"))
+ f.h.Resolve = func(context.Context, string) bool { return false }
+ if p, _, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeFailed {
+ t.Fatalf("DNS control failed outside: %+v", p)
+ }
+ f = newProbeFixture(t, allLines("denied"), "FAKE_BUILD_FAIL=1")
+ if p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); ran || p.Verdict != wire.ProbeFailed || !strings.HasSuffix(p.Detail, "xcodebuild did not run in srt") {
+ t.Fatalf("the fixture did not build under srt: %+v ran=%v", p, ran)
+ }
+ f = newProbeFixture(t, allLines("denied"))
+ f.h.Tools.SRT = ""
+ if p, ran, _ := probeP2(context.Background(), f.h, Capabilities(context.Background(), f.h.Exec, f.h.Tools)); p.Verdict != wire.ProbeUnavailable || ran {
+ t.Fatalf("no srt: %+v", p)
+ }
+}
+
+func TestJudgeP2(t *testing.T) {
+ got := ParseAttempts(allLines("denied")["script"] + allLines("denied")["plugin"] + allLines("denied")["test"] + "EQUIPO-PROBE test dns allowed\n")
+ if got["test.dns"] != "denied" || len(got) != 15 {
+ t.Fatalf("the first line for an attempt counts: %v", got)
+ }
+ facts := P2Facts{Home: true, DNS: true, Keychain: true, Accepted: map[string]bool{}}
+ if v, g := JudgeP2(got, facts); v != wire.ProbeDenied || len(g) != 0 {
+ t.Fatalf("%s %v", v, g)
+ }
+ facts.Keychain = false
+ if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || len(g["unknown"]) != 3 {
+ t.Fatalf("keychain control: %s %v", v, g)
+ }
+ facts = P2Facts{Home: false, DNS: true, Keychain: true, Accepted: map[string]bool{"plugin": true}}
+ if v, g := JudgeP2(got, facts); v != wire.ProbeFailed || !slices.Equal(g["allowed"], []string{"plugin.tcp"}) {
+ t.Fatalf("accepted: %s %v", v, g)
+ }
+}
+
+func TestACSleepAndNode(t *testing.T) {
+ if n, ok := ACSleep("Battery Power:\n sleep 1\nAC Power:\n sleep 0\n"); !ok || n != 0 {
+ t.Fatal("AC sleep 0")
+ }
+ if n, ok := ACSleep("AC Power:\n sleep 30\n"); !ok || n != 30 {
+ t.Fatal("AC sleep 30")
+ }
+ if _, ok := ACSleep("Battery Power:\n sleep 1\n"); ok {
+ t.Fatal("battery taken for AC")
+ }
+ for v, want := range map[string]bool{"v22.12.0": true, "v24.1.0": true, "v22.11.9": false, "v20.18.0": false, "22.12.0": false} {
+ if NodeSupported(v) != want {
+ t.Fatalf("%s", v)
+ }
+ }
+}
+
+// What P4 finds: a readable home, the agent not loaded, the Mac that
+// sleeps are each a failed P4, said in words without a path.
+func TestP4(t *testing.T) {
+ f := newProbeFixture(t, nil)
+ f.h.ListHome = func(p string) bool { return p == "/Users/paul" }
+ p := probeP4(context.Background(), f.h)
+ if p.Verdict != wire.ProbeFailed || p.Detail != "readable homes: paul; agent loaded; sleep off on power" {
+ t.Fatalf("%+v", p)
+ }
+}
+
+// The fixture ships whole: what P2 and P6 run is in the binary.
+func TestFixtureShips(t *testing.T) {
+ root, err := copyFixture(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, f := range []string{"package/Package.swift", "package/Plugins/HostilePlugin/HostilePlugin.swift", "package/Tests/HostileTests/HostileTests.swift", "project/Hostile.xcodeproj/project.pbxproj", "project/hostile.sh"} {
+ raw, err := os.ReadFile(filepath.Join(root, f))
+ if err != nil || len(raw) == 0 {
+ t.Fatalf("%s: %v", f, err)
+ }
+ }
+ pbx, _ := os.ReadFile(filepath.Join(root, "project/Hostile.xcodeproj/project.pbxproj"))
+ if strings.Count(string(pbx), "ENABLE_USER_SCRIPT_SANDBOXING = NO;") != 2 {
+ t.Fatal("the script phase must turn Xcode's own script sandbox off, as a hostile repository would")
+ }
+ if info, _ := os.Stat(filepath.Join(root, "project/hostile.sh")); info.Mode().Perm() != 0700 {
+ t.Fatal("hostile.sh not executable")
+ }
+ for _, f := range []string{"package/Plugins/HostilePlugin/HostilePlugin.swift", "package/Tests/HostileTests/HostileTests.swift", "project/hostile.sh"} {
+ raw, _ := os.ReadFile(filepath.Join(root, f))
+ for _, what := range []string{"state", "home", "tcp", "dns", "keychain"} {
+ if !strings.Contains(string(raw), what) {
+ t.Fatalf("%s does not try %s", f, what)
+ }
+ }
+ }
+}
diff --git a/internal/runner/mac/profile.go b/internal/runner/mac/profile.go
new file mode 100644
index 00000000..5ff0ebd0
--- /dev/null
+++ b/internal/runner/mac/profile.go
@@ -0,0 +1,155 @@
+// Package mac is the Mac worker (Mac runners spec §§3 to 5): the srt
+// (Seatbelt) settings for checks, the process-group gate with its
+// termination proof, the capability report, the xcodebuild gate a
+// repository without one gets, the launchd agent, the installer's
+// refusals and the self-probes P1 to P7. Everything here builds and is
+// tested on Linux with recorded outputs; what only a Mac can show is
+// left to the probes.
+package mac
+
+import (
+ "encoding/json"
+ "errors"
+ "path/filepath"
+ "slices"
+ "strings"
+)
+
+// Paths are the places the §4.2 deny list protects on this machine.
+type Paths struct {
+ // Home is the runner user's home (/Users/equipo-paul).
+ Home string
+ // StateDir holds the enrolment key, the steps and the relayed
+ // objects; AccountsRoot and SessionRoot the model sign-ins.
+ StateDir, AccountsRoot, SessionRoot string
+ // InstallDir is where the runner's binaries live (denied writes).
+ InstallDir string
+ // OtherHomes are every home under /Users but the runner user's.
+ OtherHomes []string
+}
+
+// Mach services a checks profile allows by default: what xcodebuild test
+// against a simulator is expected to need. These are candidates until
+// probe P2 on the Mac records the real list (spec §4.4); a service
+// missing here makes xcodebuild fail under srt, which P2 reports, and
+// checks then run outside the sandbox, labelled so.
+var CheckMachServices = []string{
+ "com.apple.CoreSimulator.*",
+ "com.apple.dt.*",
+ "com.apple.testmanagerd*",
+ "com.apple.coresymbolicationd",
+}
+
+// ErrProfile refuses a profile that would not say what it means: a path
+// that is relative, unclean or a glob, or a writable place inside a
+// denied one (srt's denyWrite wins over allowWrite).
+var ErrProfile = errors.New("mac: srt profile refused")
+
+// DenyList is §4.2: what no step may read or write.
+func DenyList(p Paths) []string {
+ out := []string{p.StateDir, p.AccountsRoot, p.SessionRoot}
+ for _, rel := range []string{".ssh", ".aws", ".gnupg", ".config/op", "Library/Keychains"} {
+ out = append(out, filepath.Join(p.Home, rel))
+ }
+ out = append(out, p.OtherHomes...)
+ out = append(out, "/Volumes")
+ return compact(out)
+}
+
+// ChecksInput is one checks attempt: the tree (the exact candidate) and
+// the attempt's scratch (TMPDIR, DerivedData of a synthesised gate).
+type ChecksInput struct {
+ Paths
+ Tree, Attempt string
+ // Mach are the Mach service names allowed (CheckMachServices).
+ Mach []string
+}
+
+// Settings is srt's settings file (sandbox-config.ts in
+// @anthropic-ai/sandbox-runtime 0.0.81): network.allowedDomains and
+// deniedDomains, filesystem.denyRead, allowWrite and denyWrite are
+// required; an empty allowedDomains means no network and an empty
+// allowWrite no writes.
+type Settings struct {
+ Network Network `json:"network"`
+ Filesystem Filesystem `json:"filesystem"`
+ // Explicitly off: no pseudo-terminal, no trustd, no Apple events.
+ AllowPty bool `json:"allowPty"`
+ EnableWeakerNetworkIsolation bool `json:"enableWeakerNetworkIsolation"`
+ AllowAppleEvents bool `json:"allowAppleEvents"`
+}
+
+// Network is srt's network block.
+type Network struct {
+ AllowedDomains []string `json:"allowedDomains"`
+ DeniedDomains []string `json:"deniedDomains"`
+ AllowLocalBinding bool `json:"allowLocalBinding"`
+ AllowMachLookup []string `json:"allowMachLookup"`
+}
+
+// Filesystem is srt's filesystem block.
+type Filesystem struct {
+ DenyRead []string `json:"denyRead"`
+ AllowRead []string `json:"allowRead"`
+ AllowWrite []string `json:"allowWrite"`
+ DenyWrite []string `json:"denyWrite"`
+}
+
+// ChecksSettings is the per-attempt checks profile of §4.4: writes only
+// to the tree, the attempt's scratch and Xcode's and SwiftPM's caches;
+// the §4.2 denies for reads and writes, plus the install dir for
+// writes; no network; the Mach services xcodebuild needs.
+func ChecksSettings(in ChecksInput) ([]byte, error) {
+ deny := DenyList(in.Paths)
+ write := []string{in.Tree, in.Attempt,
+ filepath.Join(in.Home, "Library/Developer/Xcode/DerivedData"),
+ filepath.Join(in.Home, "Library/Caches/org.swift.swiftpm"),
+ filepath.Join(in.Home, "Library/org.swift.swiftpm")}
+ denyWrite := compact(append(slices.Clone(deny), in.InstallDir))
+ for _, p := range append(append(slices.Clone(denyWrite), write...), in.Home) {
+ if !literalPath(p) {
+ return nil, ErrProfile
+ }
+ }
+ // A writable place inside a denied one would not be writable (srt's
+ // denyWrite wins), and a tree inside the state dir would be the
+ // state dir: refuse rather than run a gate that cannot write.
+ for _, w := range write[:2] {
+ for _, d := range denyWrite {
+ if within(d, w) || within(w, d) {
+ return nil, ErrProfile
+ }
+ }
+ }
+ for _, m := range in.Mach {
+ if m == "" || m == "*" || strings.ContainsAny(m, "/ \"") || strings.Contains(strings.TrimSuffix(m, "*"), "*") {
+ return nil, ErrProfile
+ }
+ }
+ s := Settings{
+ Network: Network{AllowedDomains: []string{}, DeniedDomains: []string{}, AllowMachLookup: append([]string{}, in.Mach...)},
+ Filesystem: Filesystem{DenyRead: deny, AllowRead: []string{}, AllowWrite: write, DenyWrite: denyWrite},
+ }
+ return json.MarshalIndent(s, "", " ")
+}
+
+// literalPath is an absolute, clean path srt cannot read as a pattern.
+func literalPath(p string) bool {
+ return p != "" && filepath.IsAbs(p) && filepath.Clean(p) == p && p != "/" && !strings.ContainsAny(p, "*?[]{}\\\n\x00")
+}
+
+// within reports whether path is root or below it.
+func within(root, path string) bool {
+ r, err := filepath.Rel(root, path)
+ return err == nil && (r == "." || r != ".." && !strings.HasPrefix(r, "../"))
+}
+
+func compact(in []string) []string {
+ out := []string{}
+ for _, p := range in {
+ if p != "" && !slices.Contains(out, p) {
+ out = append(out, p)
+ }
+ }
+ return out
+}
diff --git a/internal/runner/mac/profile_test.go b/internal/runner/mac/profile_test.go
new file mode 100644
index 00000000..1e691bca
--- /dev/null
+++ b/internal/runner/mac/profile_test.go
@@ -0,0 +1,90 @@
+package mac
+
+import (
+ "encoding/json"
+ "errors"
+ "slices"
+ "testing"
+)
+
+func testPaths() Paths {
+ return Paths{Home: "/Users/equipo-paul", StateDir: "/Users/equipo-paul/.local/share/equipo-runner/state",
+ AccountsRoot: "/Users/equipo-paul/.local/share/equipo/accounts", SessionRoot: "/Users/equipo-paul/.local/share/equipo-runner/sessions",
+ InstallDir: "/Users/equipo-paul/.local/lib/equipo-runner", OtherHomes: []string{"/Users/paul", "/Users/Shared"}}
+}
+
+// The checks profile is §4.4 over the §4.2 deny list, in srt 0.0.81's
+// settings shape: every required key present, no network, writes only
+// where a build writes, every secret place denied both ways.
+func TestChecksSettings(t *testing.T) {
+ in := ChecksInput{Paths: testPaths(), Tree: "/Users/equipo-paul/.local/share/equipo-runner/scratch/worker-steps/k/tree",
+ Attempt: "/Users/equipo-paul/.local/share/equipo-runner/scratch/worker-steps/k/attempt", Mach: CheckMachServices}
+ raw, err := ChecksSettings(in)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var generic struct{ Network, Filesystem map[string]any }
+ if err := json.Unmarshal(raw, &generic); err != nil {
+ t.Fatal(err)
+ }
+ for block, keys := range map[string][]string{"network": {"allowedDomains", "deniedDomains", "allowMachLookup"}, "filesystem": {"denyRead", "allowWrite", "denyWrite"}} {
+ m := generic.Network
+ if block == "filesystem" {
+ m = generic.Filesystem
+ }
+ for _, k := range keys {
+ if _, ok := m[k]; !ok {
+ t.Fatalf("%s.%s missing: %s", block, k, raw)
+ }
+ }
+ }
+ var s Settings
+ if err := json.Unmarshal(raw, &s); err != nil {
+ t.Fatal(err)
+ }
+ if len(s.Network.AllowedDomains) != 0 || s.Network.AllowLocalBinding || s.AllowPty || s.EnableWeakerNetworkIsolation || s.AllowAppleEvents {
+ t.Fatalf("checks may reach something: %s", raw)
+ }
+ for _, p := range []string{in.StateDir, in.AccountsRoot, in.SessionRoot, "/Users/equipo-paul/.ssh", "/Users/equipo-paul/.aws", "/Users/equipo-paul/.gnupg", "/Users/equipo-paul/.config/op", "/Users/equipo-paul/Library/Keychains", "/Users/paul", "/Users/Shared", "/Volumes"} {
+ if !slices.Contains(s.Filesystem.DenyRead, p) || !slices.Contains(s.Filesystem.DenyWrite, p) {
+ t.Fatalf("%s not denied both ways: %s", p, raw)
+ }
+ }
+ if !slices.Contains(s.Filesystem.DenyWrite, in.InstallDir) || slices.Contains(s.Filesystem.DenyRead, in.InstallDir) {
+ t.Fatalf("install dir: writes denied, reads allowed (srt runs from it): %s", raw)
+ }
+ want := []string{in.Tree, in.Attempt, "/Users/equipo-paul/Library/Developer/Xcode/DerivedData", "/Users/equipo-paul/Library/Caches/org.swift.swiftpm", "/Users/equipo-paul/Library/org.swift.swiftpm"}
+ if !slices.Equal(s.Filesystem.AllowWrite, want) {
+ t.Fatalf("allowWrite %v, want %v", s.Filesystem.AllowWrite, want)
+ }
+ if !slices.Equal(s.Network.AllowMachLookup, CheckMachServices) {
+ t.Fatalf("mach %v", s.Network.AllowMachLookup)
+ }
+}
+
+// A profile that would not mean what it says is refused: a tree inside
+// the state dir (unwritable, srt's denyWrite wins), a glob or relative
+// path, a Mach wildcard that opens everything.
+func TestChecksSettingsRefusals(t *testing.T) {
+ good := ChecksInput{Paths: testPaths(), Tree: "/Users/equipo-paul/scratch/k/tree", Attempt: "/Users/equipo-paul/scratch/k/attempt", Mach: CheckMachServices}
+ if _, err := ChecksSettings(good); err != nil {
+ t.Fatal(err)
+ }
+ for name, bad := range map[string]func(*ChecksInput){
+ "tree in the state dir": func(in *ChecksInput) { in.Tree = in.StateDir + "/worker/steps/k/tree" },
+ "attempt in another home": func(in *ChecksInput) { in.Attempt = "/Users/paul/tmp" },
+ "tree holding the keys": func(in *ChecksInput) { in.Tree = "/Users/equipo-paul" },
+ "glob tree": func(in *ChecksInput) { in.Tree = "/Users/equipo-paul/scratch/*/tree" },
+ "relative attempt": func(in *ChecksInput) { in.Attempt = "scratch/attempt" },
+ "glob home": func(in *ChecksInput) { in.OtherHomes = []string{"/Users/[ab]"} },
+ "every mach service": func(in *ChecksInput) { in.Mach = []string{"*"} },
+ "inner mach wildcard": func(in *ChecksInput) { in.Mach = []string{"com.*.dt"} },
+ } {
+ in := good
+ in.Paths.OtherHomes = slices.Clone(good.OtherHomes)
+ bad(&in)
+ if _, err := ChecksSettings(in); !errors.Is(err, ErrProfile) {
+ t.Fatalf("%s accepted", name)
+ }
+ }
+}
diff --git a/internal/runner/mac/ps.go b/internal/runner/mac/ps.go
new file mode 100644
index 00000000..82508e36
--- /dev/null
+++ b/internal/runner/mac/ps.go
@@ -0,0 +1,33 @@
+package mac
+
+import (
+ "strconv"
+ "strings"
+)
+
+// ParseMarked reads `ps -E -ww -x -o pid=,pgid=,command=` output: each
+// line is the pid, the group, then the command and, separated by spaces,
+// the environment. A process is marked when one of those words is
+// exactly EQUIPO_ATTEMPT=<attempt>. self is never listed.
+func ParseMarked(out, attempt string, self int) []Proc {
+ want := "EQUIPO_ATTEMPT=" + attempt
+ var procs []Proc
+ for _, line := range strings.Split(out, "\n") {
+ f := strings.Fields(line)
+ if len(f) < 3 {
+ continue
+ }
+ pid, err1 := strconv.Atoi(f[0])
+ pgid, err2 := strconv.Atoi(f[1])
+ if err1 != nil || err2 != nil || pid == self {
+ continue
+ }
+ for _, w := range f[2:] {
+ if w == want {
+ procs = append(procs, Proc{PID: pid, PGID: pgid})
+ break
+ }
+ }
+ }
+ return procs
+}
diff --git a/internal/runner/mac/testdata/simctl-devices.json b/internal/runner/mac/testdata/simctl-devices.json
new file mode 100644
index 00000000..39332703
--- /dev/null
+++ b/internal/runner/mac/testdata/simctl-devices.json
@@ -0,0 +1,62 @@
+{
+ "devices" : {
+ "com.apple.CoreSimulator.SimRuntime.iOS-17-5" : [
+ {
+ "lastBootedAt" : "2026-10-02T09:14:11Z",
+ "dataPath" : "\/Users\/equipo-paul\/Library\/Developer\/CoreSimulator\/Devices\/0B0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3\/data",
+ "dataPathSize" : 18446744073709551616,
+ "logPath" : "\/Users\/equipo-paul\/Library\/Logs\/CoreSimulator\/0B0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3",
+ "udid" : "0B0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3",
+ "isAvailable" : true,
+ "deviceTypeIdentifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-15",
+ "state" : "Shutdown",
+ "name" : "iPhone 15"
+ }
+ ],
+ "com.apple.CoreSimulator.SimRuntime.iOS-18-2" : [
+ {
+ "dataPath" : "\/Users\/equipo-paul\/Library\/Developer\/CoreSimulator\/Devices\/5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3\/data",
+ "udid" : "5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3",
+ "isAvailable" : true,
+ "deviceTypeIdentifier" : "com.apple.CoreSimulator.SimDeviceType.iPhone-16-Pro",
+ "state" : "Shutdown",
+ "name" : "iPhone 16 Pro"
+ },
+ {
+ "udid" : "6D0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3",
+ "isAvailable" : true,
+ "state" : "Booted",
+ "name" : "iPhone SE (3rd generation)"
+ },
+ {
+ "udid" : "7E0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3",
+ "isAvailable" : true,
+ "state" : "Shutdown",
+ "name" : "iPad Pro 13-inch (M4)"
+ },
+ {
+ "udid" : "8F0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3",
+ "isAvailable" : true,
+ "state" : "Shutdown",
+ "name" : "iPhone 16"
+ }
+ ],
+ "com.apple.CoreSimulator.SimRuntime.watchOS-11-2" : [
+ {
+ "udid" : "9A0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3",
+ "isAvailable" : true,
+ "state" : "Shutdown",
+ "name" : "Apple Watch Series 10 (46mm)"
+ }
+ ],
+ "com.apple.CoreSimulator.SimRuntime.iOS-16-4" : [
+ {
+ "udid" : "AB0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3",
+ "isAvailable" : false,
+ "availabilityError" : "runtime profile not found",
+ "state" : "Shutdown",
+ "name" : "iPhone 14"
+ }
+ ]
+ }
+}
diff --git a/internal/runner/mac/xcode.go b/internal/runner/mac/xcode.go
new file mode 100644
index 00000000..4ab5e817
--- /dev/null
+++ b/internal/runner/mac/xcode.go
@@ -0,0 +1,133 @@
+package mac
+
+import (
+ "io/fs"
+ "os"
+ "path"
+ "regexp"
+ "strconv"
+ "strings"
+
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// XcodeGate is the gate a repository with an Xcode project and no gate
+// of its own gets on a Mac (spec §4.4): `xcodebuild test` with its one
+// shared scheme (or the one named like the project) on the newest
+// available iPhone simulator, DerivedData in the attempt's scratch,
+// without signing. ok is false when there is no project; reason is
+// checks_unavailable when there are several candidates or none fits.
+func XcodeGate(tree string, sims []wire.Simulator) (argv []string, ok bool, reason string) {
+ root, err := os.OpenRoot(tree)
+ if err != nil {
+ return nil, false, ""
+ }
+ defer root.Close()
+ fsys := root.FS()
+ var workspaces, projects []string
+ for _, dir := range []string{".", "*"} {
+ for _, kind := range []string{"xcworkspace", "xcodeproj"} {
+ found, _ := fs.Glob(fsys, path.Join(dir, "*."+kind))
+ for _, f := range found {
+ if info, err := root.Lstat(f); err != nil || !info.IsDir() {
+ continue
+ }
+ if kind == "xcworkspace" {
+ workspaces = append(workspaces, f)
+ } else {
+ projects = append(projects, f)
+ }
+ }
+ }
+ }
+ if len(workspaces) == 0 && len(projects) == 0 {
+ return nil, false, ""
+ }
+ flag, container := "", ""
+ switch {
+ case len(workspaces) == 1:
+ flag, container = "-workspace", workspaces[0]
+ case len(workspaces) == 0 && len(projects) == 1:
+ flag, container = "-project", projects[0]
+ default:
+ return nil, true, "checks_unavailable"
+ }
+ var schemes []string
+ for _, c := range append(append([]string{}, workspaces...), projects...) {
+ found, _ := fs.Glob(fsys, path.Join(c, "xcshareddata/xcschemes/*.xcscheme"))
+ for _, f := range found {
+ if info, err := root.Lstat(f); err == nil && info.Mode().IsRegular() {
+ schemes = appendNew(schemes, strings.TrimSuffix(path.Base(f), ".xcscheme"))
+ }
+ }
+ }
+ scheme := ""
+ if len(schemes) == 1 {
+ scheme = schemes[0]
+ } else {
+ name := strings.TrimSuffix(path.Base(container), path.Ext(container))
+ for _, s := range schemes {
+ if s == name {
+ scheme = s
+ }
+ }
+ }
+ sim, found := NewestIPhone(sims)
+ if scheme == "" || !found {
+ return nil, true, "checks_unavailable"
+ }
+ cmd := "exec /usr/bin/xcodebuild test " + flag + " " + quote(container) + " -scheme " + quote(scheme) +
+ " -destination " + quote("platform=iOS Simulator,id="+sim.UDID) + ` -derivedDataPath "$TMPDIR/DerivedData" CODE_SIGNING_ALLOWED=NO`
+ return []string{"/bin/bash", "-c", cmd}, true, ""
+}
+
+// XcodeGateName names the synthesised gate on the task page.
+const XcodeGateName = "xcodebuild test"
+
+// NewestIPhone is the available iPhone simulator on the newest iOS
+// runtime, the highest model number there (an SE counts as 0), then the
+// first by name, so the choice is the same every time.
+func NewestIPhone(sims []wire.Simulator) (wire.Simulator, bool) {
+ var best wire.Simulator
+ found := false
+ for _, s := range sims {
+ if !strings.HasPrefix(s.Runtime, "iOS ") || !strings.HasPrefix(s.Name, "iPhone") || !udidPattern.MatchString(s.UDID) {
+ continue
+ }
+ if !found {
+ best, found = s, true
+ continue
+ }
+ c := compareVersions(runtimeVersion(s.Runtime), runtimeVersion(best.Runtime))
+ if c == 0 {
+ c = model(s.Name) - model(best.Name)
+ }
+ if c > 0 || c == 0 && s.Name < best.Name {
+ best = s
+ }
+ }
+ return best, found
+}
+
+// quote is a POSIX shell single-quoted word.
+func quote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
+
+func appendNew(list []string, s string) []string {
+ for _, x := range list {
+ if x == s {
+ return list
+ }
+ }
+ return append(list, s)
+}
+
+var modelNumber = regexp.MustCompile(`iPhone ([0-9]+)`)
+
+func model(name string) int {
+ m := modelNumber.FindStringSubmatch(name)
+ if m == nil {
+ return 0
+ }
+ n, _ := strconv.Atoi(m[1])
+ return n
+}
diff --git a/internal/wire/runners.go b/internal/wire/runners.go
index cfc4ede3..9c42fd49 100644
--- a/internal/wire/runners.go
+++ b/internal/wire/runners.go
@@ -76,8 +76,35 @@ type Capabilities struct {
Toolchains Toolchains `json:"toolchains"`
Harness Harness `json:"harness"`
Tags []string `json:"tags"`
+ // Probes are a Mac worker's self-probes (P1 to P7), run after
+ // enrolment and on demand; absent on Linux.
+ Probes []Probe `json:"probes,omitempty"`
}
+// Probe is one self-probe's result: its ID (P1 to P7), a verdict and a
+// short detail in the capability string rules (no path, one line).
+type Probe struct {
+ ID string `json:"id"`
+ Verdict string `json:"verdict"`
+ Detail string `json:"detail"`
+}
+
+// Probe verdicts. ProbeDenied is P2's pass: every hostile attempt was
+// denied, so checks run in the sandbox; anything else and they run
+// outside it, labelled so (Paul's ruling 2).
+const (
+ ProbePassed = "passed"
+ ProbeDenied = "denied"
+ ProbeFailed = "failed"
+ ProbeSkipped = "skipped"
+ ProbeUnavailable = "unavailable"
+)
+
+// ProbeIDs are the Mac probes of the spec, in order.
+var ProbeIDs = []string{"P1", "P2", "P3", "P4", "P5", "P6", "P7"}
+
+var probeVerdicts = []string{ProbePassed, ProbeDenied, ProbeFailed, ProbeSkipped, ProbeUnavailable}
+
// Xcode is xcodebuild -version's two lines; empty on Linux.
type Xcode struct {
Version string `json:"version"`
@@ -120,6 +147,13 @@ func ValidCapabilities(c Capabilities) error {
return ErrCapabilities
}
}
+ seen := map[string]bool{}
+ for _, p := range c.Probes {
+ if !slices.Contains(ProbeIDs, p.ID) || seen[p.ID] || !slices.Contains(probeVerdicts, p.Verdict) || (p.Verdict == ProbeDenied && p.ID != "P2") {
+ return ErrCapabilities
+ }
+ seen[p.ID] = true
+ }
if err := checkStrings(reflect.ValueOf(c)); err != nil {
return err
}
@@ -339,7 +373,7 @@ func downgrade(body any) bool {
case *LeaseCheck:
v.StepID, v.Attempt, v.Publication = "", 0, ""
case *StepReport:
- v.TerminationKind, v.Have, v.Phase, v.Apple = "", nil, "", false
+ v.TerminationKind, v.Have, v.Phase, v.Apple, v.ChecksSandbox = "", nil, "", false, ""
default:
return false
}
diff --git a/internal/wire/runners_test.go b/internal/wire/runners_test.go
index aee8e90b..b4b97af2 100644
--- a/internal/wire/runners_test.go
+++ b/internal/wire/runners_test.go
@@ -21,6 +21,8 @@ func TestEncodeProtocol1IsTheSlice4Wire(t *testing.T) {
"frames/dispatch-needs.json": "frames/dispatch.json",
"frames/lease-step.json": "frames/lease.json",
"frames/step-process-group.json": "frames/step.json",
+ "frames/hello-mac-probes.json": "frames/hello.json",
+ "frames/step-mac-checks.json": "frames/step.json",
} {
f, _, err := wire.ParseFrame(wiretest.Fixture(v2))
if err != nil {
@@ -100,6 +102,9 @@ func TestCapabilitiesGuard(t *testing.T) {
if err := wire.ValidCapabilities(good); err != nil {
t.Fatalf("fixture refused: %v", err)
}
+ if _, probed, err := wire.ParseFrame(wiretest.Fixture("frames/hello-mac-probes.json")); err != nil || wire.ValidCapabilities(*probed.(*wire.Hello).Capabilities) != nil {
+ t.Fatalf("probe report fixture refused: %v", err)
+ }
if err := wire.ValidCapabilities(wire.Capabilities{}); err != nil {
t.Fatalf("empty report refused: %v", err)
}
@@ -120,6 +125,15 @@ func TestCapabilitiesGuard(t *testing.T) {
"unknown tag": func(c *wire.Capabilities) { c.Tags = append(c.Tags, "gpu") },
"too many simulators": func(c *wire.Capabilities) { c.Simulators = make([]wire.Simulator, wire.MaxSimulators+1) },
"over the total bound": func(c *wire.Capabilities) { c.Simulators = bigSimulators() },
+ "path in a probe": func(c *wire.Capabilities) {
+ c.Probes = []wire.Probe{{ID: "P4", Verdict: wire.ProbeFailed, Detail: "readable: /Users/paul"}}
+ },
+ "unknown probe": func(c *wire.Capabilities) { c.Probes = []wire.Probe{{ID: "P8", Verdict: wire.ProbePassed}} },
+ "probe twice": func(c *wire.Capabilities) {
+ c.Probes = []wire.Probe{{ID: "P1", Verdict: wire.ProbePassed}, {ID: "P1", Verdict: wire.ProbeFailed}}
+ },
+ "unknown verdict": func(c *wire.Capabilities) { c.Probes = []wire.Probe{{ID: "P2", Verdict: "ok"}} },
+ "denied is P2 only": func(c *wire.Capabilities) { c.Probes = []wire.Probe{{ID: "P4", Verdict: wire.ProbeDenied}} },
} {
c := clone()
bad(&c)
diff --git a/internal/wire/tasks.go b/internal/wire/tasks.go
index 87cde4cd..87bf2bb3 100644
--- a/internal/wire/tasks.go
+++ b/internal/wire/tasks.go
@@ -689,6 +689,10 @@ type StepReport struct {
// Apple: Engineering's change touched Swift, Objective-C or Xcode
// files, so its checks need macOS.
Apple bool `json:"apple,omitempty"`
+ // ChecksSandbox is how a worker's checks were confined: seatbelt
+ // (srt, P2 denied every hostile attempt) or none (they ran outside
+ // the sandbox, Paul's ruling 2).
+ ChecksSandbox string `json:"checks_sandbox,omitempty"`
}
// RecheckCommand asks the runner to check now what its agent reaches.
diff --git a/internal/wire/wiretest/testdata/frames/hello-mac-probes.json b/internal/wire/wiretest/testdata/frames/hello-mac-probes.json
new file mode 100644
index 00000000..49ea79a4
--- /dev/null
+++ b/internal/wire/wiretest/testdata/frames/hello-mac-probes.json
@@ -0,0 +1 @@
+{"id":"r-hello-mac-probes","type":"hello","data":{"generation":3,"repos":[],"create_in":[],"home":"","agent":"","catalog":[],"connections":[],"versions":{"claude":"2.1.312","runner":"5eae410"},"protocol":2,"platform":{"os":"darwin","arch":"arm64"},"label":"Tito Studio","sandbox":"none","capabilities":{"xcode":{"version":"16.2","build":"16C5032a"},"simulators":[{"name":"iPhone 16 Pro","runtime":"iOS 18.2","udid":"5C0A1E2B-3D4F-4A5B-9C6D-7E8F90A1B2C3","state":"Shutdown"}],"toolchains":{"go":"go1.26.10","swift":"6.0.3","node":"v22.12.0"},"harness":{"claude":"2.1.312","codex":"","srt":"0.0.81"},"tags":["macos","xcode","ios_simulator"],"probes":[{"id":"P1","verdict":"passed","detail":"Xcode 16.2 (16C5032a); 6 iOS simulators; Tito Studio"},{"id":"P2","verdict":"failed","detail":"allowed: script.keychain plugin.keychain test.keychain; Unix permissions only: script.home plugin.home test.home; xcodebuild ran in srt"},{"id":"P3","verdict":"skipped","detail":"sign-in needs a person (slice F); keychain from the sandbox: allowed"},{"id":"P4","verdict":"passed","detail":"no other home readable; agent loaded; sleep off on power"},{"id":"P5","verdict":"skipped","detail":"Codex on the Mac is parked (slice G)"},{"id":"P6","verdict":"passed","detail":"group gone in 2s; 0 marked left; 1 simulator shut down; tree removed"},{"id":"P7","verdict":"passed","detail":"srt 0.0.81; node v22.12.0; rg 14.1.1"}]}}}
\ No newline at end of file
diff --git a/internal/wire/wiretest/testdata/frames/step-mac-checks.json b/internal/wire/wiretest/testdata/frames/step-mac-checks.json
new file mode 100644
index 00000000..bfa2195d
--- /dev/null
+++ b/internal/wire/wiretest/testdata/frames/step-mac-checks.json
@@ -0,0 +1 @@
+{"id":"r-step-mac-checks","type":"step","data":{"task_id":"tk0001","step_id":"s_0002","attempt":1,"state":"done","reason":"","base_sha":"1111111111111111111111111111111111111111","candidate_sha":"2222222222222222222222222222222222222222","pushed":false,"termination":true,"summary":"","headline":"Fixed swipe-back from the edge.","log_tail":"","family":"","account":"","verdict":"","review_label":"","findings":[],"checks":"failed","gate":"xcodebuild test","exit_code":65,"output":"Testing failed:\n\tWoodstarTests.testEdgeSwipe() failed\n** TEST FAILED **","askable":false,"merge_sha":"","into":"","strategy":"","usage":null,"switched":null,"termination_kind":"process_group","have":["2222222222222222222222222222222222222222"],"checks_sandbox":"none"}}
\ No newline at end of file