//go:build testbuild package thin import ( "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "net" "os" "os/exec" "path/filepath" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/mac/fprobe" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" ) // The shipped probes through the real Engineering launch on Linux (slice // F task 14): the darwin launch of the pinned stand-in, the fake CLI, // the runner's own permission tool, no sandbox (so nothing here shows a // sandbox holding: that is the Mac's, task 18). // probeHost is the probes' host over the Engineering rig. func probeHost(x *engRig) fprobe.Host { d := x.darwinRig var tokens []string for _, home := range x.homes { tokens = append(tokens, filepath.Join(home, provider.TokenFile)) } return fprobe.Host{ Inputs: fprobe.NewInputs("v-test", true, wire.Xcode{}, nil), Paths: d.m.paths, RuntimeRoot: filepath.Join(d.cfg.ScratchRoot, "homes"), TokenFiles: tokens, Scratch: filepath.Join(d.cfg.ScratchRoot, "fprobe"), Secrets: func(ctx context.Context) ([][]byte, error) { s, err := x.w.Eng.Secrets(ctx) return secretForms(s), err }, Turns: d.m.turns, Launch: x.w.probeLaunch, Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") }, Resolve: func(context.Context, string) bool { return true }, Exposed: func(string) bool { return false }, Exec: func(context.Context, string, ...string) (string, error) { return "", nil }, Lookup: proc.Platform.Lookup, Limits: map[string]time.Duration{fprobe.LaunchA: time.Minute, fprobe.LaunchC: 2 * time.Minute}, } } func b64(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } // The fake CLI claims in its text that every probe was denied, while it // writes the control and a sentinel it was never allowed to read into // the tree, and asks to read another: the verdicts follow the runner's // own observers (the sentinel found, the records missing, its own // permission tool refusing the read), never the text. func TestProbeTurnVerdictIgnoresModelText(t *testing.T) { x := newEngRig(t) d := x.darwinRig claim := "F1 to F7 all denied, every attempt was refused and nothing reached the tree" probeNote = func(s fprobe.Spec) string { if s.Launch != fprobe.LaunchA { return "\nsay:" + claim + "\n" } sentinels, _ := filepath.Glob(filepath.Join(d.m.paths.StateDir, "equipo-fprobe-*")) if len(sentinels) != 1 { t.Errorf("no sentinel planted: %v", sentinels) return "" } nonce, _ := os.ReadFile(sentinels[0]) // The model knows this run's nonce (it is in the command it is // asked to run) and forges the records with it, in the tree, the // one place it can write: they are not the script's. forged := "begin " + s.Nonce + "\n" return "\nbytes:out/begin|" + b64(forged) + "\nbytes:out/f1|" + b64("tcp 1\nhttps 1\nhttps_local 1\ndns 1\n") + "\nbytes:out/f2.state|" + b64(string(nonce)) + "\ncopy:" + sentinels[0] + "|out/f6-copy\nsay:" + claim + "\n" } t.Cleanup(func() { probeNote = nil }) h := probeHost(x) var mu sync.Mutex var outcomes []fprobe.Outcome var asks []fprobe.Ask h.Launch = func(ctx context.Context, s fprobe.Spec, obs fprobe.Observer) fprobe.Outcome { ask := obs.Ask obs.Ask = func(q fprobe.Ask) { mu.Lock() asks = append(asks, q) mu.Unlock() ask(q) } o := x.w.probeLaunch(ctx, s, obs) mu.Lock() outcomes = append(outcomes, o) mu.Unlock() return o } var s fprobe.Store results := s.Run(context.Background(), h) if len(results) != 2 || results[0].Launch != fprobe.LaunchA || results[1].Launch != fprobe.LaunchC { t.Fatalf("results %+v", results) } if len(outcomes) != 2 || !outcomes[0].Started || !outcomes[0].Proven || !outcomes[1].Started || !outcomes[1].Proven { t.Fatalf("outcomes %+v\n%s", outcomes, d.logs.String()) } probes := append(slices.Clone(results[0].Probes), results[1].Probes...) for _, p := range probes { if p.Verdict == wire.EngineeringProbeSuccess(p.ID) || strings.Contains(p.Detail, "refused and nothing") { t.Fatalf("a verdict followed the model's text: %+v", p) } } byID := func(id string) wire.Probe { for _, p := range probes { if p.ID == id { return p } } return wire.Probe{} } if p := byID("F2"); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "reached_tree:state") { t.Fatalf("F2: %+v", p) } if p := byID("F1"); p.Verdict != wire.ProbeFailed || !strings.HasPrefix(p.Detail, "script_not_run;") || !strings.Contains(p.Detail, "not_shown_denied:tcp https https_local dns") { t.Fatalf("F1 (the forged records in the tree are not the script's): %+v", p) } // The fake CLI runs no Bash: the runner's tool never saw a script run. if p := byID("F4"); p.Verdict != wire.ProbeFailed || p.Detail != "script_not_run;child_not_started" { t.Fatalf("F4: %+v", p) } if p := byID("F7"); p.Verdict != wire.ProbeUnavailable { t.Fatalf("F7 without Xcode: %+v", p) } // The runner's own permission tool refused the read the fake asked // for, and said so to the observer. refused := false for _, q := range asks { var in struct { FilePath string `json:"file_path"` } _ = json.Unmarshal(q.Input, &in) if q.Tool == "Read" && strings.HasPrefix(in.FilePath, d.m.paths.StateDir) { refused = !q.Allowed } } if !refused { t.Fatalf("the read of the state dir was not refused by the runner's tool: %+v", asks) } // Nothing of the probes is left: no tree, no sentinel, no step log, // no kept session, no Keychain watch. if left, _ := filepath.Glob(filepath.Join(h.Scratch, "*")); len(left) != 0 { t.Fatalf("tree left: %v", left) } if left, _ := filepath.Glob(filepath.Join(d.m.paths.StateDir, "equipo-f*")); len(left) != 0 { t.Fatalf("sentinel left: %v", left) } if left, _ := filepath.Glob(filepath.Join(x.w.Engine.root(), "*fprobe*")); len(left) != 0 { t.Fatalf("a step log: %v", left) } if x.keptRows(t) != 0 || d.m.keychain.Held() { t.Fatal("a kept session or a Keychain watch was left") } // The launches ran on the small model, through the Engineering // launch (its darwin policy for the tree). small := 0 for _, l := range d.launches() { if strings.Contains(l.argv, provider.ClaudeGlanceModel) { small++ } } if small != 2 { t.Fatalf("launches on the small model: %d", small) } } // The capability report carries F1 to F7 beside P1 to P7 and the // Engineering status they make with the guards and the connections; the // claude tag goes with ready, and Xcode access follows F5. func TestMacEngineeringStatusInCaps(t *testing.T) { x := newEngRig(t) h := &macHost{version: "v-test", probes: newMacProbes("v-test", "", nil, func() bool { return true })} h.eng = newMacEngineering(h) sims := []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789", State: "Shutdown"}} xcode := wire.Xcode{Version: "27.2", Build: "27B52"} in := fprobe.NewInputs("v-test", true, xcode, sims) for _, l := range fprobe.Launches { r := fprobe.Result{Launch: l, Inputs: in, At: time.Now()} for _, id := range wire.EngineeringProbeIDs { if fprobe.LaunchOf(id) == l { r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.EngineeringProbeSuccess(id), Detail: wire.ProbeDetail("f1_denied")}) } } h.eng.store.Put(r) } report := func(mut func(*wire.Capabilities)) wire.Capabilities { c := wire.Capabilities{Tags: []string{wire.TagMacOS, wire.TagXcode}, Simulators: sims, Xcode: xcode, Harness: wire.Harness{Claude: provider.ClaudeVersion}, Probes: []wire.Probe{{ID: "P1", Verdict: wire.ProbePassed}}} if mut != nil { mut(&c) } h.eng.compose(&c) if err := wire.ValidCapabilities(c); err != nil { t.Fatalf("invalid report: %v", err) } return c } c := report(nil) if c.Engineering == nil || c.Engineering.State != wire.EngineeringNoConnection || slices.Contains(c.Tags, wire.TagClaude) { t.Fatalf("no connection bound: %+v %v", c.Engineering, c.Tags) } if len(c.Probes) != 8 || c.Probes[0].ID != "P1" || c.Probes[1].ID != "F1" || c.Probes[7].ID != "F7" { t.Fatalf("probes %+v", c.Probes) } h.eng.bind(x.w, x.conns, nil) if c = report(nil); *c.Engineering != (wire.EngineeringStatus{State: wire.EngineeringProbesPending, Reason: "P2"}) { t.Fatalf("no trusted P2: %+v", c.Engineering) } if h.eng.xcode() { t.Fatal("Xcode access without P2 denied: F5 is skipped") } h.probes.last = mac.Report{Version: "v-test", Profile: mac.ProfileDigest(), At: time.Now(), SRT: srtPinned, Probes: []wire.Probe{{ID: "P2", Verdict: wire.ProbeDenied}}} c = report(nil) if *c.Engineering != (wire.EngineeringStatus{State: wire.EngineeringReady}) || !slices.Contains(c.Tags, wire.TagClaude) { t.Fatalf("ready: %+v %v", c.Engineering, c.Tags) } for _, cs := range []struct { name string mut func(*wire.Capabilities) want wire.EngineeringStatus }{ {"tainted", func(c *wire.Capabilities) { c.Engineering = &wire.EngineeringStatus{State: wire.EngineeringTainted} }, wire.EngineeringStatus{State: wire.EngineeringTainted}}, {"credential unproven", func(c *wire.Capabilities) { c.Unproven = wire.UnprovenCredential }, wire.EngineeringStatus{State: wire.EngineeringNoConnection, Reason: wire.UnprovenCredential}}, {"cli", func(c *wire.Capabilities) { c.Harness.Claude = "" }, wire.EngineeringStatus{State: wire.EngineeringCLIUnpinned}}, {"xcode changed", func(c *wire.Capabilities) { c.Xcode.Build = "27B53" }, wire.EngineeringStatus{State: wire.EngineeringProbesPending, Reason: "F1 F2 F3 F4 F6 F7"}}, } { if c := report(cs.mut); *c.Engineering != cs.want || slices.Contains(c.Tags, wire.TagClaude) { t.Fatalf("%s: %+v %v", cs.name, c.Engineering, c.Tags) } } // Below protocol 37 the F probes and the status are dropped. c = report(nil) hello := wire.Hello{Capabilities: &c} if !wire.WithoutMacEngineering(&hello) || hello.Capabilities.Engineering != nil || len(hello.Capabilities.Probes) != 1 { t.Fatalf("below 37: %+v", hello.Capabilities) } } // The probe launch's permission tool (fix round 1, #1): beyond the // Engineering rules, Bash is the probe script exactly (its bytes as the // runner wrote them, this run's nonce), and no native write lands // outside the tree; every answer is heard by the probe. func TestProbePermission(t *testing.T) { dir := t.TempDir() script := filepath.Join(dir, "bin", "probe.sh") if err := os.MkdirAll(filepath.Dir(script), 0o700); err != nil { t.Fatal(err) } if err := os.WriteFile(script, []byte("echo probe\n"), 0o600); err != nil { t.Fatal(err) } sum := sha256.Sum256([]byte("echo probe\n")) s := fprobe.Spec{Tree: filepath.Join(dir, "tree"), Scratch: filepath.Join(dir, "run"), Script: script, ScriptSHA256: hex.EncodeToString(sum[:]), Nonce: "EQUIPO-NONCE-1"} var heard []fprobe.Ask allowAll := func(json.RawMessage, provider.Policy) json.RawMessage { return json.RawMessage(`{"behavior":"allow","updatedInput":{}}`) } perm := probePermission(allowAll, s, func(q fprobe.Ask) { heard = append(heard, q) }) ask := func(tool string, input map[string]string) bool { raw, _ := json.Marshal(map[string]any{"tool_name": tool, "tool_use_id": "u1", "input": input}) return !denied(perm(raw, provider.Policy{})) } if !ask("Bash", map[string]string{"command": s.Command()}) || !ask("Write", map[string]string{"file_path": filepath.Join(s.Tree, "x")}) { t.Fatal("the script and a write in the tree are refused") } for _, c := range []struct { tool string input map[string]string }{ {"Bash", map[string]string{"command": "echo dns 1 >> " + filepath.Join(s.Scratch, "out", "f1")}}, {"Bash", map[string]string{"command": s.Command() + " && true"}}, {"Write", map[string]string{"file_path": filepath.Join(s.Scratch, "out", "f1")}}, {"Edit", map[string]string{"file_path": script}}, } { if ask(c.tool, c.input) { t.Fatalf("allowed %+v", c) } } if len(heard) != 6 || heard[0].ToolUseID != "u1" || !heard[0].Allowed || heard[2].Allowed { t.Fatalf("heard %+v", heard) } // The Engineering rules still decide first. refuseAll := func(json.RawMessage, provider.Policy) json.RawMessage { return json.RawMessage(`{"behavior":"deny","message":"no"}`) } if raw, _ := json.Marshal(map[string]any{"tool_name": "Bash", "input": map[string]string{"command": s.Command()}}); !denied(probePermission(refuseAll, s, func(fprobe.Ask) {})(raw, provider.Policy{})) { t.Fatal("the probe allowed what the Engineering rules refused") } } // Readiness and Xcode access are decided afresh at each use (fix round // 1, #9): the inputs read now (not the hour-old report) and the time now. func TestMacEngineeringRevalidates(t *testing.T) { x := newEngRig(t) h := &macHost{version: "v-test", probes: newMacProbes("v-test", "", nil, func() bool { return true }), creds: x.m, taint: x.m.taint, turns: x.m.turns} h.eng = newMacEngineering(h) sims := []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789", State: "Shutdown"}} live := wire.Capabilities{Tags: []string{wire.TagMacOS}, Simulators: sims, Xcode: wire.Xcode{Version: "27.2", Build: "27B52"}, Harness: wire.Harness{Claude: provider.ClaudeVersion}} h.eng.live = func(context.Context) wire.Capabilities { return live } now := time.Now() h.eng.now = func() time.Time { return now } in := fprobe.NewInputs("v-test", true, live.Xcode, sims) for _, l := range fprobe.Launches { r := fprobe.Result{Launch: l, Inputs: in, At: now} for _, id := range wire.EngineeringProbeIDs { if fprobe.LaunchOf(id) == l { r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.EngineeringProbeSuccess(id)}) } } h.eng.store.Put(r) } h.eng.bind(x.w, x.conns, nil) ctx := context.Background() h.probes.last = mac.Report{Version: "v-test", Profile: mac.ProfileDigest(), At: now, SRT: srtPinned, Probes: []wire.Probe{{ID: "P2", Verdict: wire.ProbeDenied}}} if st := h.eng.statusNow(ctx); st == nil || st.State != wire.EngineeringReady { t.Fatalf("ready now: %+v", st) } // P2 trusted denied, so F5 counts; the report composed now says it. h.probes.last = mac.Report{Version: "v-test", Profile: mac.ProfileDigest(), At: now, SRT: srtPinned, Probes: []wire.Probe{{ID: "P2", Verdict: wire.ProbeDenied}}} report := live h.eng.compose(&report) if !h.eng.xcode() || !h.eng.xcodeNow(ctx) { t.Fatal("Xcode access with P2 and F5 denied") } live.Xcode.Build = "27B53" if st := h.eng.statusNow(ctx); st == nil || st.State != wire.EngineeringProbesPending { t.Fatalf("Xcode changed since the report: %+v", st) } live.Xcode.Build = "27B52" now = now.Add(25 * time.Hour) if st := h.eng.statusNow(ctx); st == nil || st.State != wire.EngineeringProbesPending { t.Fatalf("a day later: %+v", st) } if h.eng.xcodeNow(ctx) { t.Fatal("Xcode access a day later") } x.m.taint.Set() if st := h.eng.statusNow(ctx); st == nil || st.State != wire.EngineeringTainted { t.Fatalf("tainted now: %+v", st) } } // Below protocol 37 a Mac's hello says no claude tag (fix round 1, #10): // an older instance would place Engineering on it. func TestMacClaudeTagBelow37(t *testing.T) { caps := wire.Capabilities{Tags: []string{wire.TagMacOS, wire.TagXcode, wire.TagClaude}, Simulators: []wire.Simulator{}, Engineering: &wire.EngineeringStatus{State: wire.EngineeringReady}} hello := wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Connections: []wire.HeldConnection{}, Platform: &wire.Platform{OS: "darwin", Arch: "arm64"}, Capabilities: &caps} f, err := wire.NewFrame("h1", wire.FrameHello, hello) if err != nil { t.Fatal(err) } tags := func(p int) []string { enc, err := wire.Encode(f, p) if err != nil { t.Fatal(err) } raw, _ := json.Marshal(enc) _, body, err := wire.ParseFrame(raw) if err != nil { t.Fatal(err) } return body.(*wire.Hello).Capabilities.Tags } if got := tags(36); slices.Contains(got, wire.TagClaude) || !slices.Contains(got, wire.TagMacOS) { t.Fatalf("at 36: %v", got) } if got := tags(37); !slices.Contains(got, wire.TagClaude) { t.Fatalf("at 37: %v", got) } // A Linux runner's claude tag is not the Mac's to strip. hello.Platform, hello.Capabilities = &wire.Platform{OS: "linux", Arch: "amd64"}, &wire.Capabilities{Tags: []string{wire.TagLinux, wire.TagClaude}, Simulators: []wire.Simulator{}} if f, err = wire.NewFrame("h2", wire.FrameHello, hello); err != nil { t.Fatal(err) } if got := tags(36); !slices.Contains(got, wire.TagClaude) { t.Fatalf("linux at 36: %v", got) } } // #5 (fix round 2): the production host names the runner's own binary // as P2's reader. Built by newMacHost and probeHost, it runs the shipped // script phase with a stand-in at that path: P2's targets give it, and // the script then says tokenargs and tokenfd. func TestMacProbeHostNamesTheReader(t *testing.T) { root := t.TempDir() exe := filepath.Join(root, "lib", "equipo-runner") c := runner.Config{StateDir: filepath.Join(root, "state"), ScratchRoot: filepath.Join(root, "scratch"), WorkspaceRoot: filepath.Join(root, "work"), Executable: exe} if err := os.MkdirAll(filepath.Dir(exe), 0o700); err != nil { t.Fatal(err) } // The stand-in reads only its caller's parent, the hostile shell. stand := "#!/bin/bash\nmode=$2; shift 2\npp=$(ps -o ppid= -p $PPID | tr -d ' ')\ncase \"$mode\" in pids) echo $PPID; echo $pp ;; procargs) for p in \"$@\"; do echo \"procargs-start $p\"; if [ \"$p\" = \"$PPID\" ] || [ \"$p\" = \"$pp\" ]; then echo \"procargs-end $p ok\"; else echo \"procargs-end $p refused\"; fi; done ;; fds) echo fds-done ;; esac\n" if err := os.WriteFile(exe, []byte(stand), 0o700); err != nil { t.Fatal(err) } was, wasTemp := macUsers, macUserTemp macUsers = filepath.Join(root, "Users") macUserTemp = func(context.Context, mac.Exec) (string, error) { return "/private/var/folders/4m/abc123_def/T", nil } defer func() { macUsers, macUserTemp = was, wasTemp }() h, err := newMacHost(c, OptionsFromEnv(func(string) string { return "" })) if err != nil { t.Fatal(err) } ph := h.probeHost("v1", nil) if ph.Runner != exe { t.Fatalf("P2's reader %q, want the runner %q", ph.Runner, exe) } fixture, err := mac.CopyFixture(t.TempDir()) if err != nil { t.Fatal(err) } token := filepath.Join(root, "accounts", ".oauth-token") if err := os.MkdirAll(filepath.Dir(token), 0o700); err != nil || os.WriteFile(token, []byte("sk-ant-oat01-probe-0123456789abcdef"), 0o600) != nil { t.Fatal(err) } targets := "state=/nonexistent\ndns=example.invalid\nkeychain=io.amadan.equipo.probe.x\nport_script=1\ntoken=sk-ant-oat01-probe-0123456789abcdef\ntoken_file=" + token + "\nhelper=" + ph.Runner + "\n" if err := os.WriteFile(filepath.Join(fixture, "equipo-targets.txt"), []byte(targets), 0o600); err != nil { t.Fatal(err) } cmd := exec.Command("bash", filepath.Join(fixture, "project", "hostile.sh")) cmd.Env = []string{"PATH=/usr/bin:/bin", "SRCROOT=" + filepath.Join(fixture, "project"), "TMPDIR=" + t.TempDir()} out, _ := cmd.CombinedOutput() got := mac.ParseAttempts(string(out)) if got["script.tokenargs"] != "denied" || got["script.tokenfd"] != "denied" { t.Fatalf("the script did not use the runner's reader: %v\n%s", got, out) } } // #7 (fix round 2): the simulators a launch runs on are read afresh with // its inputs, never the cached report's. func TestMacProbeSimulatorsFresh(t *testing.T) { x := newEngRig(t) h := &macHost{version: "v-test", probes: newMacProbes("v-test", "", nil, func() bool { return true }), creds: x.m, taint: x.m.taint, turns: x.m.turns, scratch: x.cfg.ScratchRoot} h.eng = newMacEngineering(h) stale := []wire.Simulator{{Name: "iPhone 16", Runtime: "iOS 27.0", UDID: "00000000-0000-0000-0000-000000000000"}} fresh := []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}} h.eng.live = func(context.Context) wire.Capabilities { return wire.Capabilities{Simulators: fresh, Xcode: wire.Xcode{Version: "27.2", Build: "27B52"}, Harness: wire.Harness{Claude: provider.ClaudeVersion}} } h.eng.bind(x.w, x.conns, func(context.Context) wire.Capabilities { return wire.Capabilities{Simulators: stale, Xcode: wire.Xcode{Version: "27.0", Build: "27A1"}, Harness: wire.Harness{Claude: provider.ClaudeVersion}} }) host, ok := h.eng.host(context.Background()) if !ok { t.Fatal("no host with a usable connection") } in, sims := host.Live(context.Background()) if !slices.Equal(sims, fresh) || in.Runtimes != "iOS 27.2" || in.Xcode != "27.2 (27B52)" { t.Fatalf("live %+v %+v", in, sims) } }