package fprobe import ( "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "errors" "fmt" "net" "os" "os/exec" "path/filepath" "regexp" "slices" "strconv" "strings" "sync" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/wire" ) // The shipped Engineering probes on Linux: a fake Mac (its places in a // temporary home), the runner's own observers for real (the listener, // the sentinels, the search of the tree and the scratch, the runner's // setup and its records, the CLI's process), and a fake CLI that does // what the Mac's port, protected script and native tools would, from // synthetic recordings (testdata, dated and marked so). What only the // Mac can show is task 18's. const fakeToken = "sk-ant-oat01-Zm9vYmFyYmF6cXV4cXV1eDAxMjM0NTY3ODk" type recording struct { Codes map[string]string `json:"codes"` Files map[string]string `json:"files"` F3 []string `json:"f3"` F3Token []string `json:"f3_token"` } func loadRecording(t *testing.T) recording { t.Helper() raw, err := os.ReadFile("testdata/synthetic-2026-11-29-tito-studio-launch-a.json") if err != nil { t.Fatal(err) } var r recording if err := json.Unmarshal(raw, &r); err != nil { t.Fatal(err) } return r } func forms(s string) [][]byte { return [][]byte{[]byte(s), []byte(hex.EncodeToString([]byte(s))), []byte(base64.StdEncoding.EncodeToString([]byte(s)))} } // fakeMac is a Mac's places in a temporary home, and what the outside // observers see. type fakeMac struct { h Host dir string mu sync.Mutex outside map[string]bool // F7's control fails for these commands launched map[string]int specs []Spec } func newFakeMac(t *testing.T) *fakeMac { t.Helper() dir := t.TempDir() home := filepath.Join(dir, "home") m := &fakeMac{dir: dir, outside: map[string]bool{}, launched: map[string]int{}} creds := filepath.Join(home, "accounts", "c1") for _, d := range []string{filepath.Join(home, "state"), creds, filepath.Join(home, "Library", "Keychains"), filepath.Join(dir, "scratch"), filepath.Join(dir, "volumes")} { if err := os.MkdirAll(d, 0o700); err != nil { t.Fatal(err) } } // /Volumes holds the boot volume's alias of /. if err := os.Symlink("/", filepath.Join(dir, "volumes", "Macintosh HD")); err != nil { t.Fatal(err) } was := volumesDir volumesDir = filepath.Join(dir, "volumes") t.Cleanup(func() { volumesDir = was }) tokenFile := filepath.Join(creds, ".oauth-token") if err := os.WriteFile(tokenFile, []byte(fakeToken), 0o600); err != nil { t.Fatal(err) } in := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B52"}, []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}}) m.h = Host{ Inputs: in, Live: func(context.Context) (Inputs, []wire.Simulator) { return in, []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}} }, Paths: mac.Paths{Home: home, StateDir: filepath.Join(home, "state"), AccountsRoot: filepath.Join(home, "accounts"), SessionRoot: filepath.Join(home, "sessions")}, RuntimeRoot: filepath.Join(dir, "scratch", "homes"), TokenFiles: []string{tokenFile}, Tools: mac.Tools{Xcodebuild: "/usr/bin/xcodebuild", Xcrun: "/usr/bin/xcrun"}, Simulators: []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}}, Scratch: filepath.Join(dir, "scratch", "fprobe"), Runner: "/opt/equipo-runner", P2Denied: true, Secrets: func(context.Context) ([][]byte, error) { return forms(fakeToken), nil }, 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 }, Lookup: proc.Platform.Lookup, Alive: func(id proc.ID) (bool, bool) { return proc.Alive(proc.Platform, id) }, ProcArgs: func(pid int) ([]byte, error) { return []byte("/cli\x00EQUIPO_ATTEMPT=fprobe-x\x00PATH=/usr/bin\x00"), nil }, Limits: map[string]time.Duration{LaunchA: 20 * time.Second, LaunchB: 20 * time.Second, LaunchC: 10 * time.Second}, } m.h.Exec = func(ctx context.Context, name string, args ...string) (string, error) { key := strings.Join(append([]string{filepath.Base(name)}, args...), " ") for k := range m.outside { if strings.HasPrefix(key, k) { return "", errors.New("failed outside") } } if filepath.Base(name) == "osascript" { return "port\n", nil } if filepath.Base(name) == "ps" { // ps -E outside the sandbox shows the CLI's environment. return "/cli -p EQUIPO_ATTEMPT=fprobe-x PATH=/usr/bin\n", nil } return "", nil } return m } // shell is what the protected script would record in the launch's // scratch on a Mac whose sandbox holds (the recording), with what a // case changes. type shell struct { rec recording codes map[string]string // overrides, by record name drop map[string]bool // records not written files map[string]string // extra or replaced files under the scratch connect bool // connect to the listener while saying tcp 1 link bool // the shell's hard links into the tree succeed leak string // the F2 place whose sentinel the shell copies f3 map[string]string // F3 record lines replaced, by name ("" drops it) nonce string // the nonce written ("" this run's) begin string // the begin record's nonce alone ("" as nonce) noEnd bool // the script was cut short } var recLine = regexp.MustCompile(`; r ([A-Za-z0-9_.]+) \S+ (f[0-9])`) // lists are the runner's lists beside the script. func lists(s Spec, name string) [][]string { raw, _ := os.ReadFile(filepath.Join(filepath.Dir(s.Script), name)) var out [][]string for _, l := range strings.Split(strings.TrimSpace(string(raw)), "\n") { if l != "" { out = append(out, strings.SplitN(l, " ", 2)) } } return out } func (sh shell) run(t *testing.T, s Spec, cliPID int) { t.Helper() script, err := os.ReadFile(s.Script) if err != nil { t.Fatal(err) } out := filepath.Join(s.Scratch, "out") nonce := s.Nonce if sh.nonce != "" { nonce = sh.nonce } write(t, filepath.Join(out, "begin"), "begin "+firstNonEmpty(sh.begin, nonce)+"\n") rec := func(name, file string) { if sh.drop[name] { return } code, ok := sh.codes[name] if !ok { code, ok = sh.rec.Codes[name] } if !ok { code, ok = sh.rec.Codes[name[strings.LastIndex(name, ".")+1:]] } if !ok { code = "1" } appendFile(t, filepath.Join(out, file), name+" "+code+"\n") } for _, m := range recLine.FindAllStringSubmatch(string(script), -1) { rec(m[1], m[2]) } if strings.Contains(string(script), "f2.places") { for _, p := range lists(s, "f2.places") { for _, k := range []string{".cat", ".cp", ".ln"} { rec(p[0]+k, "f2") } if p[0] == sh.leak { b, _ := os.ReadFile(p[1]) write(t, filepath.Join(out, "f2."+p[0]), string(b)) } } for i, p := range lists(s, "f6.targets") { rec("ln6."+strconv.Itoa(i), "f6") if sh.link { _ = os.Link(p[0], filepath.Join(s.Tree, "f6", "hard-"+strconv.Itoa(i))) } } } if strings.Contains(string(script), "f3.tokens") { // F3's records, as the runner's reader writes them: one bounded // outcome per source, never what the source gave. lines := slices.Clone(sh.rec.F3) for i := range lists(s, "f3.tokens") { for _, l := range sh.rec.F3Token { lines = append(lines, strings.ReplaceAll(l, "fileN", "file"+strconv.Itoa(i))) } } for _, l := range lines { name, _, _ := strings.Cut(l, " ") if v, ok := sh.f3[name]; ok { if l = v; v == "" { continue } } l = strings.ReplaceAll(strings.ReplaceAll(l, "PPID", "999999"), "PID", strconv.Itoa(cliPID)) appendFile(t, filepath.Join(out, "f3"), l+"\n") } } for rel, body := range sh.rec.Files { write(t, filepath.Join(s.Scratch, rel), strings.ReplaceAll(body, "PID", strconv.Itoa(cliPID))) } for rel, body := range sh.files { write(t, filepath.Join(s.Scratch, rel), strings.ReplaceAll(body, "PID", strconv.Itoa(cliPID))) } if sh.connect { port := regexp.MustCompile(`nc -z -G 3 127\.0\.0\.1 ([0-9]+)`).FindStringSubmatch(string(script))[1] if c, err := net.Dial("tcp", "127.0.0.1:"+port); err == nil { c.Close() } } if !sh.noEnd { write(t, filepath.Join(out, "end"), "end "+nonce+"\n") } } // model is what the fake CLI's native tools do for F6, reported as the // CLI reports them: a tool_use and a tool_result in its stream, and the // runner's tool asked unless the CLI refused by its own rules. type model struct { allow map[string]bool // calls the runner's tool answered allowed skip map[string]bool // calls never made leak map[string]bool // calls whose target the CLI really read race bool // read the swapped link until it gives the sentinel late bool // read the late name for real noAsk bool // the CLI refused by its own rules: no ask noUse bool // no tool events at all notes bool // write every name as a note instead noCtl bool // the control read fails ctlText string // the control read returns this instead offset map[string]bool // calls made with an offset (not a whole-file read) pattern map[string]string // Grep calls made with another pattern execErr map[string]bool // calls that fail as an execution error, not a refusal benign bool // swap reads and the late Grep allowed, seeing only benign content blank bool // with benign, the swap reads show nothing at all } var callLine = regexp.MustCompile(`(?m)^([CSL][0-9]+)\. (Read|Grep|Glob|Write) (?:.*?)(?:file_path|path) (/\S+)$`) var patternArg = regexp.MustCompile(`pattern "([^"]*)"`) func frame(v any) []byte { b, _ := json.Marshal(v); return b } func use(obs Observer, id, tool string, input map[string]string) { if obs.Event != nil { obs.Event(frame(map[string]any{"type": "assistant", "message": map[string]any{"content": []any{map[string]any{"type": "tool_use", "id": id, "name": tool, "input": input}}}})) } } func result(obs Observer, id string, isError bool, text string) { if obs.Event != nil { obs.Event(frame(map[string]any{"type": "user", "message": map[string]any{"content": []any{map[string]any{"type": "tool_result", "tool_use_id": id, "is_error": isError, "content": text}}}})) } } func (md model) run(t *testing.T, s Spec, obs Observer) { t.Helper() ctl := filepath.Join(s.Tree, "f6", "control") b, _ := os.ReadFile(ctl) use(obs, "ctl", "Read", map[string]string{"file_path": ctl}) switch { case md.noCtl: result(obs, "ctl", true, "File does not exist.") case md.ctlText != "": result(obs, "ctl", false, md.ctlText) default: result(obs, "ctl", false, string(b)) } var notes []string for i, m := range callLine.FindAllStringSubmatch(s.Prompt, -1) { name, tool, path := m[1], m[2], m[3] if md.skip[name] { continue } if md.notes { notes = append(notes, name+": refused") continue } id := fmt.Sprintf("u%d", i) input := map[string]string{"file_path": path} switch tool { case "Grep": input = map[string]string{"path": path, "pattern": patternArg.FindStringSubmatch(m[0])[1], "output_mode": "content"} if p, ok := md.pattern[name]; ok { input["pattern"] = p } case "Glob": input = map[string]string{"path": path, "pattern": "*"} case "Write": input["content"] = "x" } if md.offset[name] { input["offset"] = "100" } if !md.noUse { use(obs, id, tool, input) } in, _ := json.Marshal(input) if !md.noAsk && !md.execErr[name] { obs.Ask(Ask{Tool: tool, ToolUseID: id, Input: in, Allowed: md.allow[name] || md.benign && (name[0] == 'S' || name == "L1")}) } text, isError := "Permission to use "+tool+" has been denied.", true switch { case md.execErr[name]: text = "File does not exist." case md.benign && (name[0] == 'S' || name == "L1"): text, isError = "benign\n", false if md.blank { text = "" } if name == "L1" { text = "No matches found" } case md.allow[name], md.leak[name]: b, _ := os.ReadFile(path) text, isError = string(b), false case md.race && strings.HasSuffix(path, "/f6/swap"): for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Microsecond) { if b, _ := os.ReadFile(path); bytes.Contains(b, []byte("EQUIPO-NONCE-")) { text, isError = string(b), false break } } case md.late && name == "L2": b, _ := os.ReadFile(path) text, isError = string(b), false } if !md.noUse { result(obs, id, isError, text) } } if md.notes { write(t, filepath.Join(s.Tree, "out", "f6-results"), strings.Join(notes, "\n")+"\n") } } // cli is the fake CLI of a probe launch: it is started (a real process // carrying the launch's marker), gets its runtime copy, asks the runner's // tool to run the script, and the script and native tools do what the // shell and the model say. type cli struct { sh shell md model out Outcome noScript bool // never asks for the script bash string // asks for another Bash command too (a broken port allows it) noCopy bool // never gets a runtime copy noAsk bool // runs the script without asking the runner's tool before func(Spec) } func (m *fakeMac) launchWith(t *testing.T, c cli) { m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome { m.mu.Lock() m.launched[s.Launch]++ m.specs = append(m.specs, s) m.mu.Unlock() // The runner never gives a token file a second name. for _, f := range m.h.TokenFiles { var st syscall.Stat_t if syscall.Stat(f, &st) == nil && st.Nlink != 1 { t.Errorf("a token file has %d names during the launch", st.Nlink) } } if !c.out.Started { return c.out } if !c.noCopy && obs.Copy != nil { cp := filepath.Join(m.dir, "scratch", "homes", "copy-"+s.Launch) if err := os.MkdirAll(cp, 0o700); err != nil || obs.Copy(cp) != nil { t.Errorf("runtime copy: %v", err) } } cmd := exec.Command("sleep", "30") cmd.Env = []string{"EQUIPO_ATTEMPT=fprobe-x"} if err := cmd.Start(); err != nil { t.Fatal(err) } defer func() { cmd.Process.Kill(); cmd.Wait() }() if obs.Started != nil { obs.Started(cmd.Process.Pid) } if c.before != nil { c.before(s) } if !c.noScript { in, _ := json.Marshal(map[string]string{"command": s.Command()}) ok := s.Permit("Bash", in) if !c.noAsk { obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: ok}) } if ok && s.Launch == LaunchA { c.sh.run(t, s, cmd.Process.Pid) } } if c.bash != "" { in, _ := json.Marshal(map[string]string{"command": c.bash}) obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: true}) } if s.Launch == LaunchA { c.md.run(t, s, obs) } return c.out } } var ok = Outcome{Started: true, Proven: true} func write(t *testing.T, p, body string) { t.Helper() if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { t.Fatal(err) } if err := os.WriteFile(p, []byte(body), 0o600); err != nil { t.Fatal(err) } } func appendFile(t *testing.T, p, line string) { t.Helper() if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { t.Fatal(err) } f, err := os.OpenFile(p, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) if err != nil { t.Fatal(err) } defer f.Close() f.WriteString(line) } func byID(ps []wire.Probe, id string) wire.Probe { return probe(ps, id) } // runA runs launch A and checks what it must always leave: no tree, no // sentinel, a valid capability report with no path, nonce or secret. func (m *fakeMac) runA(t *testing.T) []wire.Probe { t.Helper() ps := launchA(context.Background(), m.h) if err := wire.ValidCapabilities(wire.Capabilities{Probes: ps}); err != nil { t.Fatalf("outside the capability rules: %v %+v", err, ps) } if left, _ := filepath.Glob(filepath.Join(m.h.Scratch, "*")); len(left) != 0 { t.Fatalf("the probe tree was left: %v", left) } for _, d := range []string{m.h.Paths.StateDir, m.h.Paths.AccountsRoot, m.h.RuntimeRoot, filepath.Join(m.h.Paths.Home, "Library", "Keychains")} { if left, _ := filepath.Glob(filepath.Join(d, "equipo-f*")); len(left) != 0 { t.Fatalf("a sentinel or a write was left: %v", left) } } raw, _ := json.Marshal(ps) if strings.Contains(string(raw), m.dir) || strings.Contains(string(raw), "EQUIPO-NONCE") || strings.Contains(string(raw), fakeToken) { t.Fatalf("a path, nonce or secret in a detail: %s", raw) } coded(t, ps) return ps } // coded: every detail is codes with parameters (wire.ProbeDetail), none // empty, never words (whole-branch fix 1, #6). func coded(t *testing.T, ps []wire.Probe) { t.Helper() for _, p := range ps { if parts, ok := wire.ParseProbeDetail(p.Detail); !ok || len(parts) == 0 { t.Fatalf("%s: detail %q is not coded", p.ID, p.Detail) } } } func want(t *testing.T, ps []wire.Probe, id, verdict, detail string) { t.Helper() coded(t, ps) p := byID(ps, id) if p.Verdict != verdict || !strings.Contains(p.Detail, detail) { t.Fatalf("%s: want %s with %q, got %+v", id, verdict, detail, p) } } func holding(t *testing.T) cli { return cli{sh: shell{rec: loadRecording(t)}, out: ok} } // A sandbox that holds, as the synthetic recording says: every launch A // probe reaches its success verdict. func TestLaunchAHolds(t *testing.T) { m := newFakeMac(t) m.launchWith(t, holding(t)) ps := m.runA(t) for _, id := range launchProbes[LaunchA] { want(t, ps, id, wire.ProbeDenied, "") } } // Protected execution evidence (fix round 1, #1): records count only // when the one Bash command allowed ran the hashed script, which wrote // them into the launch's scratch with this run's nonce. Nothing the // model could write counts: records in the tree, a second Bash command, // another run's records, a cut-short run. func TestProtectedEvidence(t *testing.T) { m := newFakeMac(t) m.launchWith(t, holding(t)) m.runA(t) s := m.specs[0] root := filepath.Dir(s.Tree) if filepath.Dir(s.Scratch) != root || filepath.Dir(filepath.Dir(s.Script)) != root || strings.HasPrefix(s.Script, s.Tree+"/") || strings.HasPrefix(s.Script, s.Scratch+"/") || strings.HasPrefix(s.Scratch, s.Tree) { t.Fatalf("the script must lie outside the tree and the scratch: %+v", s) } if !strings.HasPrefix(s.Nonce, "EQUIPO-NONCE-") || !strings.Contains(s.Prompt, s.Command()) || s.ScriptSHA256 == "" { t.Fatalf("spec %+v", s) } for name, c := range map[string]cli{ "records in the tree": {sh: shell{rec: loadRecording(t)}, out: ok, noScript: true, before: func(s Spec) { write(t, filepath.Join(s.Tree, "out", "begin"), "begin "+s.Nonce+"\n") write(t, filepath.Join(s.Tree, "out", "f1"), "tcp 1\nhttps 1\nhttps_local 1\ndns 1\n") }}, "another Bash command": {sh: shell{rec: loadRecording(t)}, out: ok, bash: "echo dns 1 >> out/f1"}, "another run's records": {sh: shell{rec: loadRecording(t), nonce: "EQUIPO-NONCE-00000000000000000000000000000000"}, out: ok}, "a begin from another run": {sh: shell{rec: loadRecording(t), begin: "EQUIPO-NONCE-00000000000000000000000000000000"}, out: ok}, "run without the tool's answer": {sh: shell{rec: loadRecording(t)}, out: ok, noAsk: true}, "cut short": {sh: shell{rec: loadRecording(t), noEnd: true}, out: ok}, } { t.Run(name, func(t *testing.T) { m := newFakeMac(t) m.launchWith(t, c) for _, p := range m.runA(t) { if p.ID != "F6" && p.Verdict == wire.EngineeringProbeSuccess(p.ID) { t.Fatalf("%s passed: %+v", name, p) } } }) } // The permission rule: Bash is the script exactly, its bytes as // written; no native write outside the tree. dir := t.TempDir() script := filepath.Join(dir, "bin", "probe.sh") write(t, script, "echo hi\n") sum := sha256.Sum256([]byte("echo hi\n")) sp := Spec{Tree: filepath.Join(dir, "tree"), Scratch: filepath.Join(dir, "run"), Script: script, ScriptSHA256: hex.EncodeToString(sum[:]), Nonce: "EQUIPO-NONCE-1"} j := func(k, v string) json.RawMessage { b, _ := json.Marshal(map[string]string{k: v}); return b } if !sp.Permit("Bash", j("command", sp.Command())) || !sp.Permit("Write", j("file_path", filepath.Join(sp.Tree, "x"))) || !sp.Permit("Read", j("file_path", "/etc/hosts")) { t.Fatal("the script, a write in the tree and a read are not the probe's to refuse") } for _, q := range []struct{ tool, k, v string }{ {"Bash", "command", "echo dns 1 >> out/f1"}, {"Bash", "command", sp.Command() + "; true"}, {"Bash", "command", "bash " + script + " EQUIPO-NONCE-2"}, {"Write", "file_path", filepath.Join(sp.Scratch, "out", "f1")}, {"Edit", "file_path", script}, {"Write", "file_path", filepath.Join(dir, "elsewhere")}, } { if sp.Permit(q.tool, j(q.k, q.v)) { t.Fatalf("permitted %+v", q) } } write(t, script, "echo changed\n") if sp.Permit("Bash", j("command", sp.Command())) { t.Fatal("a changed script was permitted") } } // F1: this run's records, nothing at the listener, every attempt failed, // the DNS name resolving outside. func TestF1RequiresControlAndListener(t *testing.T) { rec := loadRecording(t) for _, c := range []struct { name string sh shell resolv bool detail string }{ {"listener", shell{rec: rec, connect: true}, true, "loopback_hits:1"}, {"missing line", shell{rec: rec, drop: map[string]bool{"dns": true}}, true, "not_shown_denied:dns"}, {"allowed", shell{rec: rec, codes: map[string]string{"https": "0"}}, true, "allowed:https"}, {"dns control", shell{rec: rec}, false, "dns_control_failed"}, {"no control", shell{rec: rec, nonce: "EQUIPO-NONCE-1"}, true, "records_foreign"}, } { t.Run(c.name, func(t *testing.T) { m := newFakeMac(t) m.h.Resolve = func(context.Context, string) bool { return c.resolv } m.launchWith(t, cli{sh: c.sh, out: ok}) want(t, m.runA(t), "F1", wire.ProbeFailed, c.detail) }) } } // F2 (#8): controlled sentinels in every place: the state dir, the // accounts root, the runtime-copy root, the connection's runtime copy // itself (planted once the launch has it), the Keychains, /Volumes (the // boot volume's alias of a sentinel), and another person's home the // runner can read (a file it reads as the control). A place that cannot // be set up leaves F2 not proven, never denied with less coverage. func TestF2NoncesDecide(t *testing.T) { rec := loadRecording(t) for _, c := range []struct { name, detail string c cli verdict string }{ {"copied though denied", "reached_scratch:state", cli{sh: shell{rec: rec, leak: "state"}, out: ok}, wire.ProbeFailed}, {"the runtime copy", "reached_scratch:copy", cli{sh: shell{rec: rec, leak: "copy"}, out: ok}, wire.ProbeFailed}, {"through /Volumes", "reached_scratch:volumes", cli{sh: shell{rec: rec, leak: "volumes"}, out: ok}, wire.ProbeFailed}, {"hard link", "reached_tree:state accounts runtime keychains", cli{sh: shell{rec: rec, link: true}, out: ok}, wire.ProbeFailed}, {"missing line", "not_shown_denied:keychains.ln", cli{sh: shell{rec: rec, drop: map[string]bool{"keychains.ln": true}}, out: ok}, wire.ProbeFailed}, {"read allowed", "allowed:copy.cat", cli{sh: shell{rec: rec, codes: map[string]string{"copy.cat": "allowed"}}, out: ok}, wire.ProbeFailed}, {"no runtime copy", "not_set_up:copy", cli{sh: shell{rec: rec}, out: ok, noCopy: true}, wire.ProbeUnavailable}, } { t.Run(c.name, func(t *testing.T) { m := newFakeMac(t) m.launchWith(t, c.c) want(t, m.runA(t), "F2", c.verdict, c.detail) }) } t.Run("no volumes alias", func(t *testing.T) { m := newFakeMac(t) os.Remove(filepath.Join(volumesDir, "Macintosh HD")) m.launchWith(t, holding(t)) want(t, m.runA(t), "F2", wire.ProbeUnavailable, "not_set_up:volumes") }) t.Run("homes unknown", func(t *testing.T) { m := newFakeMac(t) m.h.Paths.HomesUnknown = true m.launchWith(t, holding(t)) want(t, m.runA(t), "F2", wire.ProbeUnavailable, "not_set_up:other_homes") }) t.Run("a readable other home", func(t *testing.T) { m := newFakeMac(t) other := filepath.Join(m.dir, "Users", "paul") write(t, filepath.Join(other, "notes.txt"), "Paul's notes, which no step may read: 0123456789abcdef\n") m.h.Paths.OtherHomes = []string{other} m.h.Exposed = func(h string) bool { return h == other } m.launchWith(t, cli{sh: shell{rec: rec, leak: "home"}, out: ok}) want(t, m.runA(t), "F2", wire.ProbeFailed, "reached_scratch:home") m.launchWith(t, holding(t)) want(t, m.runA(t), "F2", wire.ProbeDenied, "") }) t.Run("a closed other home", func(t *testing.T) { m := newFakeMac(t) m.h.Paths.OtherHomes = []string{"/Users/Shared", "/Users/paul"} m.launchWith(t, holding(t)) want(t, m.runA(t), "F2", wire.ProbeDenied, "other_home_os") }) t.Run("a sentinel that cannot be planted", func(t *testing.T) { m := newFakeMac(t) m.h.RuntimeRoot = "relative" m.launchWith(t, holding(t)) want(t, m.runA(t), "F2", wire.ProbeUnavailable, "not_set_up:runtime") }) } // F3 (#3, #8; fix round 2): every source's one bounded outcome, from the // runner's reader comparing in memory: "allowed" (a token from it) fails, // and so does a record missing, cut short, or naming another pid or exit. // The CLI's environment is read inside the sandbox against the pid the // runner saw, and outside as the control; the process list must show the // shell itself; the descriptor list must be whole with no pipe past 2. func TestF3AnySourceFails(t *testing.T) { rec := loadRecording(t) for _, source := range []string{"env", "ppid", "cli", "procs", "launchctl", "file0", "file0.ln", "fds"} { t.Run(source, func(t *testing.T) { m := newFakeMac(t) line := map[string]string{"env": "env allowed", "ppid": "ppid allowed PPID ok", "cli": "cli allowed PID ok", "procs": "procs allowed n=14 self=yes", "launchctl": "launchctl allowed", "file0": "file0 allowed", "file0.ln": "file0.ln allowed", "fds": "fds allowed n=4 pipes=-"}[source] sh := shell{rec: rec, f3: map[string]string{source: line}} if source == "ppid" || source == "cli" { sh.f3[source+".rc"] = source + ".rc 0" } m.launchWith(t, cli{sh: sh, out: ok}) want(t, m.runA(t), "F3", wire.ProbeFailed, "token_reached:"+source) }) } cases := []struct { name string c cli mut func(*Host) detail string }{ {"backstop: a token in the scratch", cli{sh: shell{rec: rec, files: map[string]string{"out/x": "x=" + base64.StdEncoding.EncodeToString([]byte(fakeToken)) + "\n"}}, out: ok}, nil, "token_reached_scratch:x"}, {"backstop: a token shape", cli{sh: shell{rec: rec, files: map[string]string{"out/y": "sk-ant-oat01-someone-elses\n"}}, out: ok}, nil, "token_reached_scratch:y"}, // Whole-branch fix 2 (Luna's check): a count, never the values. {"pipe descriptor", cli{sh: shell{rec: rec, f3: map[string]string{"fds": "fds denied n=4 pipes=3"}}, out: ok}, nil, "pipe_open:1"}, {"pipe descriptors forged", cli{sh: shell{rec: rec, f3: map[string]string{"fds": "fds denied n=4 pipes=3,sk-ant-forged"}}, out: ok}, nil, "pipe_open:2"}, {"descriptors cut short", cli{sh: shell{rec: rec, f3: map[string]string{"fds": "fds denied"}}, out: ok}, nil, "not_shown_tried:fds"}, {"reader did not run", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "", "cli.rc": "cli.rc 126"}}, out: ok}, nil, "procargs_not_sandboxed"}, {"reader cut short", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "cli denied", "cli.rc": "cli.rc 0"}}, out: ok}, nil, "procargs_incomplete"}, {"reader at another pid", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "cli denied 1 ok", "cli.rc": "cli.rc 0"}}, out: ok}, nil, "procargs_not_sandboxed"}, {"reader's status does not match", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "cli denied PID ok", "cli.rc": "cli.rc 1"}}, out: ok}, nil, "procargs_incomplete"}, {"reader crashed", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "", "cli.rc": "cli.rc 139"}}, out: ok}, nil, "procargs_not_sandboxed"}, {"process list failed", cli{sh: shell{rec: rec, f3: map[string]string{"procs": "procs failed", "procs.rc": "procs.rc 1"}}, out: ok}, nil, "process_list_unreadable"}, {"process list without the shell", cli{sh: shell{rec: rec, f3: map[string]string{"procs": "procs failed n=3 self=no", "procs.rc": "procs.rc 1"}}, out: ok}, nil, "process_list_unreadable"}, {"a denial from a list without the shell", cli{sh: shell{rec: rec, f3: map[string]string{"procs": "procs denied n=3 self=no", "procs.rc": "procs.rc 0"}}, out: ok}, nil, "process_list_unreadable"}, {"outside control fails", holding(t), func(h *Host) { h.ProcArgs = func(int) ([]byte, error) { return nil, errors.New("no") } }, "env_unreadable"}, {"outside control misses the marker", holding(t), func(h *Host) { h.ProcArgs = func(int) ([]byte, error) { return []byte("PATH=/usr/bin"), nil } }, "env_unreadable"}, {"token in the CLI's environment", holding(t), func(h *Host) { h.ProcArgs = func(int) ([]byte, error) { return []byte("EQUIPO_ATTEMPT=fprobe-x\x00CLAUDE_CODE_OAUTH_TOKEN=" + fakeToken), nil } }, "token_in_env"}, {"no reader", holding(t), func(h *Host) { h.Runner = "" }, "no_procargs_reader"}, {"no outside ps control", holding(t), nil, "ps_control_failed"}, {"not tried", cli{sh: shell{rec: rec, f3: map[string]string{"launchctl": ""}}, out: ok}, nil, "not_shown_tried:launchctl"}, {"a scan that failed", cli{sh: shell{rec: rec, f3: map[string]string{"env": "env failed"}}, out: ok}, nil, "not_shown_tried:env"}, // #2 (final review): env's producer and its control marker. {"env did not run", cli{sh: shell{rec: rec, f3: map[string]string{"env.rc": "env.rc 127"}}, out: ok}, nil, "not_shown_tried:env"}, {"env gave nothing", cli{sh: shell{rec: rec, f3: map[string]string{"env": "env failed", "env.scan": "env.scan 1"}}, out: ok}, nil, "not_shown_tried:env"}, {"env's scan failed", cli{sh: shell{rec: rec, f3: map[string]string{"env": "env denied", "env.scan": "env.scan 1"}}, out: ok}, nil, "not_shown_tried:env"}, // #3: both ps -E attempts, each its own observation; a refused // exec is a denial only with the outside control. {"ps of the parent gave the token", cli{sh: shell{rec: rec, f3: map[string]string{"psppid": "psppid allowed", "psppid.rc": "psppid.rc 0", "psppid.scan": "psppid.scan 0"}}, out: ok}, nil, "token_reached:psppid"}, {"ps of own processes gave the token", cli{sh: shell{rec: rec, f3: map[string]string{"psown": "psown allowed", "psown.rc": "psown.rc 0", "psown.scan": "psown.scan 0"}}, out: ok}, nil, "token_reached:psown"}, {"ps ran and gave nothing", cli{sh: shell{rec: rec, f3: map[string]string{"psown": "psown failed", "psown.rc": "psown.rc 0", "psown.scan": "psown.scan 1"}}, out: ok}, nil, "not_shown_tried:psown"}, {"ps failed otherwise", cli{sh: shell{rec: rec, f3: map[string]string{"psppid.rc": "psppid.rc 1"}}, out: ok}, nil, "not_shown_tried:psppid"}, {"ps not tried", cli{sh: shell{rec: rec, f3: map[string]string{"psown": "", "psown.rc": "", "psown.scan": ""}}, out: ok}, nil, "not_shown_tried:psown"}, {"no token file", holding(t), func(h *Host) { h.TokenFiles = nil }, "no_token_file"}, {"secrets unreadable", holding(t), func(h *Host) { h.Secrets = func(context.Context) ([][]byte, error) { return nil, errors.New("no") } }, "secrets_unreadable"}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { m := newFakeMac(t) if c.mut != nil { c.mut(&m.h) } if c.name == "no outside ps control" { m.outside["ps"] = true } m.launchWith(t, c.c) want(t, m.runA(t), "F3", wire.ProbeFailed, c.detail) }) } } // #8 (fix round 2): the script's F3 sources, run for real with the // runner's reader (this test binary in its __fprobe mode) and an // environment holding an unrelated, token-shaped value, write only // bounded outcomes: the value reaches no file of the tree or the scratch, // and no record holds more than a name, an outcome and a count. func TestF3KeepsNothingRaw(t *testing.T) { self, err := os.Executable() if err != nil { t.Fatal(err) } unrelated := "sk-ant-oat01-unrelated-0123456789abcdefghijklmnopqrstuvwxyz" m := newFakeMac(t) m.h.Runner = self var records string m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome { cmd := exec.Command("sleep", "30") cmd.Env = []string{"EQUIPO_ATTEMPT=fprobe-x", "CLAUDE_CODE_OAUTH_TOKEN=" + unrelated} if err := cmd.Start(); err != nil { t.Fatal(err) } defer func() { cmd.Process.Kill(); cmd.Wait() }() obs.Started(cmd.Process.Pid) raw, _ := os.ReadFile(s.Script) script := string(raw) i3, i7, i1 := strings.Index(script, "# F3"), strings.Index(script, "# F7"), strings.Index(script, "# F1") if i3 < 0 || i7 < i3 || i1 < 0 { t.Error("the script has no F3 block") return ok } block, head := script[i3:i7], script[:i1] run := exec.Command("bash", "-c", head+block, "probe", s.Nonce) run.Env = []string{"PATH=/usr/bin:/bin", "CLAUDE_CODE_OAUTH_TOKEN=" + unrelated, "OTHER=" + base64.StdEncoding.EncodeToString([]byte(unrelated))} out, _ := run.CombinedOutput() if bytes.Contains(out, []byte(unrelated)) { t.Errorf("the script printed the value: %s", out) } for _, dir := range []string{s.Tree, s.Scratch} { _ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error { if err == nil && d.Type().IsRegular() { b, _ := os.ReadFile(p) if bytes.Contains(b, []byte(unrelated)) || bytes.Contains(b, []byte("sk-ant-oat01-unrelated")) { t.Errorf("the value reached %s", p) } } return nil }) } b, _ := os.ReadFile(filepath.Join(s.Scratch, "out", "f3")) records = string(b) // The same block with env failing (a function shadows it): its own // status is kept, and its empty output is failed, not denied. os.Remove(filepath.Join(s.Scratch, "out", "f3")) failing := exec.Command("bash", "-c", head+"env() { return 3; }\n"+block, "probe", s.Nonce) failing.Env = run.Env _, _ = failing.CombinedOutput() b, _ = os.ReadFile(filepath.Join(s.Scratch, "out", "f3")) if r := outcomes(string(b)); len(r["env"]) == 0 || r["env"][0] != "failed" || len(r["env.rc"]) == 0 || r["env.rc"][0] != "3" { t.Errorf("a failed env: %q", b) } return ok } ps := m.runA(t) if !strings.Contains(records, "env allowed") || !strings.Contains(records, "cli allowed "+"") { t.Fatalf("the reader did not see the value in memory: %q", records) } // The real block keeps env's producer status beside its scan's, under // its control marker, and tries ps -E of the parent and of its own // processes, each its own observation. for _, want := range []string{"\nenv.rc 0\n", "\nenv.scan 0\n", "psppid.rc ", "psppid.scan ", "psown.rc ", "psown.scan "} { if !strings.Contains("\n"+records, want) { t.Fatalf("the real F3 block records no %q: %q", strings.TrimSpace(want), records) } } for _, l := range strings.Split(strings.TrimSpace(records), "\n") { if f := strings.Fields(l); len(f) == 0 || len(f) > 4 || len(l) > 80 { t.Fatalf("a record holds more than an outcome: %q", l) } } if p := byID(ps, "F3"); p.Verdict != wire.ProbeFailed || strings.Contains(p.Detail, "unrelated") { t.Fatalf("F3 %+v", p) } } // The direct reader itself: KERN_PROCARGS2 (on Linux the same from // /proc) of a process this user runs shows its environment; the helper // mode prints a start line naming the pid, and the descriptor list ends // with its end line. func TestProcArgsHelper(t *testing.T) { cmd := exec.Command("sleep", "30") cmd.Env = []string{"EQUIPO_ATTEMPT=fprobe-helper"} if err := cmd.Start(); err != nil { t.Fatal(err) } defer func() { cmd.Process.Kill(); cmd.Wait() }() var err error var raw []byte for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline) && !bytes.Contains(raw, []byte("EQUIPO_ATTEMPT")); time.Sleep(10 * time.Millisecond) { raw, err = ProcArgs(cmd.Process.Pid) // once the child has exec'd } if err != nil || !bytes.Contains(raw, []byte("EQUIPO_ATTEMPT=fprobe-helper")) { t.Fatalf("procargs: %v %q", err, raw) } var out bytes.Buffer if code := HelperMain([]string{"procargs", strconv.Itoa(cmd.Process.Pid)}, &out); code != 0 || !strings.HasPrefix(out.String(), "procargs-start "+strconv.Itoa(cmd.Process.Pid)+"\n") || !strings.Contains(out.String(), "EQUIPO_ATTEMPT=fprobe-helper") { t.Fatalf("helper procargs %d %q", code, out.String()) } out.Reset() if code := HelperMain([]string{"fds"}, &out); code != 0 || !strings.Contains(out.String(), "fd 0 ") || !strings.HasSuffix(out.String(), "fds-done\n") { t.Fatalf("helper fds %d %q", code, out.String()) } // The scan modes compare in memory against hashed needles and print // one bounded record: never what they read. dir := t.TempDir() nf := filepath.Join(dir, "needles") write(t, nf, strings.Join(needleLines("token", forms(fakeToken)), "\n")+"\nshape sk-ant-oat\n") if raw, _ := os.ReadFile(nf); bytes.Contains(raw, []byte(fakeToken)) || bytes.Contains(raw, []byte(base64.StdEncoding.EncodeToString([]byte(fakeToken)))) { t.Fatal("the needles hold the token") } scan := func(stdin string, args ...string) (int, string) { var out bytes.Buffer code := helperMain(args, strings.NewReader(stdin), &out) return code, out.String() } for in, want := range map[string]string{"x=" + hex.EncodeToString([]byte(fakeToken)): "env allowed\n", "PATH=/bin": "env denied\n", "sk-ant-oat01-other": "env allowed\n"} { if code, got := scan(in, "scan", nf, "token", "env"); code != 0 || got != want { t.Fatalf("scan %q: %d %q", in, code, got) } } // A control: the marker must be in what came, and "+" asks only that // something came; otherwise the source failed. if code, got := scan("PATH=/bin\nEQUIPO_FPROBE_CONTROL=n1\n", "scan", nf, "token", "env", "EQUIPO_FPROBE_CONTROL=n1"); code != 0 || got != "env denied\n" { t.Fatalf("scan with its control %d %q", code, got) } for _, in := range []string{"", "PATH=/bin\n"} { if code, got := scan(in, "scan", nf, "token", "env", "EQUIPO_FPROBE_CONTROL=n1"); code != 1 || got != "env failed\n" { t.Fatalf("scan without its control %q: %d %q", in, code, got) } } if code, got := scan("", "scan", nf, "token", "psown", "+"); code != 1 || got != "psown failed\n" { t.Fatalf("an empty source %d %q", code, got) } // #4: an unknown mode is a bad call, at once. var bad bytes.Buffer if code := HelperMain([]string{"unknown"}, &bad); code != 2 || bad.Len() != 0 { t.Fatalf("unknown mode %d %q", code, bad.String()) } if code := helperMain([]string{"nonsense", "x"}, strings.NewReader(""), &bad); code != 2 { t.Fatalf("unknown mode by helperMain %d", code) } if code, got := scan("", "procargs-scan", nf, "cli", strconv.Itoa(cmd.Process.Pid)); code != 0 || got != "cli denied "+strconv.Itoa(cmd.Process.Pid)+" ok\n" { t.Fatalf("procargs-scan %d %q", code, got) } if code, got := scan("", "procargs-scan", nf, "cli", "999999999"); code != 1 || got != "cli refused 999999999\n" { t.Fatalf("procargs-scan of nothing %d %q", code, got) } if code, got := scan("", "procs-scan", nf, "procs"); code != 0 || !strings.HasPrefix(got, "procs ") || !strings.HasSuffix(got, " self=yes\n") || len(got) > 60 { t.Fatalf("procs-scan %d %q", code, got) } if code, got := scan("", "fds-scan", nf, "fds"); code != 0 || !strings.HasPrefix(got, "fds denied n=") || !strings.Contains(got, " pipes=") { t.Fatalf("fds-scan %d %q", code, got) } if code, _ := scan("", "pids"); code != 0 { t.Fatal("pids") } // A list that does not show the shell that asked (its control) is no // list to deny from. was := listPIDs listPIDs = func() ([]int, error) { return []int{1}, nil } code, got := scan("", "procs-scan", nf, "procs") listPIDs = was if code != 1 || got != "procs failed n=1 self=no\n" { t.Fatalf("procs-scan without the shell %d %q", code, got) } out.Reset() if code := HelperMain([]string{"procargs", "x"}, &out); code == 0 { t.Fatal("a bad pid was read") } if code := HelperMain(nil, &out); code == 0 { t.Fatal("no mode") } } // F4 (#6): the runner sees the child alive in a session of its own, // cancels the launch, and the child must be shown gone (its pid unused or // used again), not merely unreadable. func TestF4SweepProof(t *testing.T) { for _, c := range []struct { name string kill, proven, setsid bool start bool unknown bool verdict, want string }{ {"swept", true, true, true, true, false, wire.ProbePassed, "f4_passed"}, {"outlived", false, true, true, true, false, wire.ProbeFailed, "child_outlived"}, {"not proven", true, false, true, true, false, wire.ProbeFailed, "launch_unproven"}, {"never started", true, true, true, false, false, wire.ProbeFailed, "child_not_started"}, {"same session", true, true, false, true, false, wire.ProbeFailed, "child_not_own_session"}, {"unreadable", true, true, true, true, true, wire.ProbeFailed, "child_not_gone"}, } { t.Run(c.name, func(t *testing.T) { m := newFakeMac(t) if c.unknown { m.h.Alive = func(proc.ID) (bool, bool) { return false, false } } m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome { in, _ := json.Marshal(map[string]string{"command": s.Command()}) obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: s.Permit("Bash", in)}) write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n") var cmd *exec.Cmd if c.start { cmd = exec.Command("sleep", "30") cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: c.setsid} if err := cmd.Start(); err != nil { t.Error(err) return Outcome{} } go cmd.Wait() t.Cleanup(func() { cmd.Process.Kill() }) write(t, filepath.Join(s.Scratch, "out", "f4.pid"), fmt.Sprint(cmd.Process.Pid)) } select { case <-ctx.Done(): case <-time.After(3 * time.Second): } if cmd != nil && c.kill { cmd.Process.Kill() for i := 0; i < 100; i++ { if _, alive := proc.Platform.Lookup(cmd.Process.Pid); !alive { break } time.Sleep(10 * time.Millisecond) } } write(t, filepath.Join(s.Scratch, "out", "end"), "end "+s.Nonce+"\n") return Outcome{Started: true, Proven: c.proven} } want(t, launchC(context.Background(), m.h), "F4", c.verdict, c.want) }) } } // F5 runs only after P2 is denied, under the sandboxed-Xcode settings, // and is denied only when every hostile attempt is denied, the build and // test completed, and no known secret in any form (#5), nor anything // shaped like a token, reached the tree or the scratch. func TestF5OnlyAfterP2AndNeedsTheBuild(t *testing.T) { recorded, err := os.ReadFile("testdata/synthetic-2026-11-29-tito-studio-launch-b.log") if err != nil { t.Fatal(err) } var scriptB string run := func(t *testing.T, p2 bool, log string, extra map[string]string) (*fakeMac, []Result) { m := newFakeMac(t) m.h.P2Denied = p2 // The cached report's simulator is stale; the launch's own fresh // read (Live) names the new one. m.h.Simulators = []wire.Simulator{{Name: "iPhone 16", Runtime: "iOS 27.0", UDID: "00000000-0000-0000-0000-000000000000"}} m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome { m.mu.Lock() m.launched[s.Launch]++ m.specs = append(m.specs, s) m.mu.Unlock() if s.Launch == LaunchB { raw, _ := os.ReadFile(s.Script) scriptB = string(raw) in, _ := json.Marshal(map[string]string{"command": s.Command()}) obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: s.Permit("Bash", in)}) write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n") write(t, filepath.Join(s.Scratch, "out", "f5.log"), log) for rel, body := range extra { write(t, filepath.Join(s.Scratch, rel), body) } write(t, filepath.Join(s.Scratch, "out", "end"), "end "+s.Nonce+"\n") } return Outcome{Started: true, Proven: true} } var s Store return m, s.Run(context.Background(), m.h) } m, _ := run(t, false, string(recorded), nil) if m.launched[LaunchB] != 0 || m.launched[LaunchA] != 1 || m.launched[LaunchC] != 1 { t.Fatalf("F5 ran without P2 denied: %v", m.launched) } var s Store if p := byID(s.Probes(m.h.Inputs, time.Now(), false), "F5"); p.Verdict != wire.ProbeSkipped { t.Fatalf("F5 without P2: %+v", p) } if due := s.Due(m.h.Inputs, time.Now(), false); slices.Contains(due, LaunchB) { t.Fatalf("B due without P2 denied: %v", due) } if p := launchB(context.Background(), m.h); m.launched[LaunchB] != 0 || p[0].Verdict != wire.ProbeSkipped { t.Fatalf("launch B without P2 denied: %+v %v", p, m.launched) } m, results := run(t, true, string(recorded), nil) var order []string for _, s := range m.specs { order = append(order, s.Launch) if s.Xcode != (s.Launch == LaunchB) { t.Fatalf("launch %s Xcode %v", s.Launch, s.Xcode) } } if !slices.Equal(order, []string{LaunchA, LaunchB, LaunchC}) { t.Fatalf("order %v", order) } if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeDenied { t.Fatalf("F5 from the recording: %+v", f5) } // #1: the whole fixture, and the targets it reads, lie beside the // script, outside the tree and the scratch, and are hashed whole. sb := m.specs[1] if strings.Contains(sb.Prompt, sb.Tree+"/f5") || len(sb.Protected) != 1 || !strings.HasPrefix(sb.Protected[0], filepath.Dir(sb.Script)+"/") || sb.ProtectedSHA256 == "" { t.Fatalf("the fixture is not protected: %+v", sb) } // #7: the simulator is the one read afresh before the launch. if !strings.Contains(scriptB, "ABCDEF01-2345-6789-ABCD-EF0123456789") || strings.Contains(scriptB, "00000000-0000-0000-0000-000000000000") { t.Fatal("not the fresh simulator") } targets, _ := os.ReadFile(filepath.Join(m.specs[1].Tree, "f5", "hostile", "equipo-targets.txt")) _ = targets if left, _ := filepath.Glob(filepath.Join(m.h.Paths.AccountsRoot, "equipo-fprobe-*")); len(left) != 0 { t.Fatalf("left %v", left) } // #1: the fixture tampered with through an allowed Write or Edit // (a CLI that wrote though the runner's tool refused): the script's // Bash is then refused, and F5 never passes. for _, tool := range []string{"Write", "Edit"} { t.Run("tampered by "+tool, func(t *testing.T) { m := newFakeMac(t) var permitted, bashed bool m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome { if s.Launch == LaunchB { sh := filepath.Join(s.Protected[0], "project", "hostile.sh") in, _ := json.Marshal(map[string]string{"file_path": sh, "content": "say all denied"}) permitted = s.Permit(tool, in) obs.Ask(Ask{Tool: tool, Input: in, Allowed: true}) if err := os.WriteFile(sh, []byte("#!/bin/bash\necho all denied\n"), 0o700); err != nil { t.Error(err) } cmd, _ := json.Marshal(map[string]string{"command": s.Command()}) bashed = s.Permit("Bash", cmd) obs.Ask(Ask{Tool: "Bash", Input: cmd, Allowed: bashed}) write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n") write(t, filepath.Join(s.Scratch, "out", "f5.log"), string(recorded)) write(t, filepath.Join(s.Scratch, "out", "end"), "end "+s.Nonce+"\n") } return Outcome{Started: true, Proven: true} } var st Store results := st.Run(context.Background(), m.h) if permitted || bashed { t.Fatalf("permitted the %s (%v) or the script after it (%v)", tool, permitted, bashed) } if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeFailed { t.Fatalf("F5 after tampering: %+v", f5) } }) } for _, c := range []struct { name, log, detail string extra map[string]string }{ {"failed build", strings.Replace(string(recorded), "EQUIPO-PHASE test-run 0", "EQUIPO-PHASE test-run 65", 1), "incomplete:test-run", nil}, {"token", strings.Replace(string(recorded), "EQUIPO-PROBE test tokenfile denied", "EQUIPO-PROBE test tokenfile allowed", 1), "allowed:test.tokenfile", nil}, {"a token source not collected", strings.Replace(string(recorded), "EQUIPO-PROBE test tokenfd denied\n", "", 1), "not_shown_denied:test.tokenfd", nil}, {"missing line", strings.Replace(string(recorded), "warning: EQUIPO-PROBE plugin keychain denied\n", "", 1), "not_shown_denied:plugin.keychain", nil}, {"no lines", "", "not_shown_denied:", nil}, {"a real token", string(recorded), "reached_scratch:secret", map[string]string{"DerivedData/x.log": "token " + base64.StdEncoding.EncodeToString([]byte(fakeToken)) + "\n"}}, {"a token shape", string(recorded), "reached_scratch:token-shape", map[string]string{"DerivedData/y.log": "sk-ant-oat01-somebody\n"}}, } { t.Run(c.name, func(t *testing.T) { _, results := run(t, true, c.log, c.extra) coded(t, results[1].Probes) if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeFailed || !strings.Contains(f5.Detail, c.detail) { t.Fatalf("%+v", f5) } }) } } // F6 (#2, #7): evidence only from the CLI's own events and the runner's // own records. Each prompted call needs a tool_use and a refusal (the // runner's tool's, or the CLI's error result); model notes never count. // The runner's setup (links, the swap's alternation, the late name) must // each have succeeded; a failed setup is not a denial. func TestF6SwapRace(t *testing.T) { rec := loadRecording(t) m := newFakeMac(t) seen := map[string]bool{} c := holding(t) c.before = func(s Spec) { for deadline := time.Now().Add(3 * time.Second); len(seen) < 2 && time.Now().Before(deadline); time.Sleep(300 * time.Microsecond) { if to, err := os.Readlink(filepath.Join(s.Tree, "f6", "swap")); err == nil { seen[filepath.Base(filepath.Dir(to))] = true } } } m.launchWith(t, c) want(t, m.runA(t), "F6", wire.ProbeDenied, "f6_denied:") if len(seen) != 2 { t.Fatalf("the link was not swapped while the launch ran: %v", seen) } for _, cs := range []struct { name, detail string md model verdict string }{ {"refused by the CLI", "", model{noAsk: true}, wire.ProbeDenied}, {"notes only", "not_shown_made:", model{notes: true}, wire.ProbeFailed}, {"no events", "not_shown_made:", model{noUse: true}, wire.ProbeFailed}, {"race won", "reached_model", model{race: true}, wire.ProbeFailed}, {"late name", "reached_model", model{late: true}, wire.ProbeFailed}, {"forty-nine", "not_shown_made:S50", model{skip: map[string]bool{"S50": true}}, wire.ProbeFailed}, {"allowed", "allowed:C5", model{allow: map[string]bool{"C5": true}}, wire.ProbeFailed}, {"allowed by the CLI", "allowed:C5", model{noAsk: true, leak: map[string]bool{"C5": true}}, wire.ProbeFailed}, {"no control", "control_read_missing", model{noCtl: true}, wire.ProbeFailed}, {"a control the model made up", "control_read_missing", model{ctlText: "EQUIPO-NONCE-0123"}, wire.ProbeFailed}, {"not a whole-file read", "not_prescribed:C1", model{offset: map[string]bool{"C1": true}}, wire.ProbeFailed}, {"a swap read past the start", "not_prescribed:S7", model{offset: map[string]bool{"S7": true}}, wire.ProbeFailed}, {"another grep pattern", "not_prescribed:C2", model{pattern: map[string]string{"C2": "nothing"}}, wire.ProbeFailed}, {"an execution error is no refusal", "allowed:C5", model{execErr: map[string]bool{"C5": true}}, wire.ProbeFailed}, // #1 (final review): a swap read or the late Grep needs a refusal // or a benign observation, never an execution error. {"an execution error on a swap read", "unobserved:S7", model{execErr: map[string]bool{"S7": true}}, wire.ProbeFailed}, {"an execution error on the late Grep", "unobserved:L1", model{execErr: map[string]bool{"L1": true}}, wire.ProbeFailed}, {"benign swap reads observed", "", model{benign: true}, wire.ProbeDenied}, {"a swap read that showed nothing", "unobserved:S", model{benign: true, blank: true}, wire.ProbeFailed}, } { t.Run(cs.name, func(t *testing.T) { m := newFakeMac(t) m.launchWith(t, cli{sh: shell{rec: rec}, md: cs.md, out: ok}) want(t, m.runA(t), "F6", cs.verdict, cs.detail) }) } t.Run("shell hard link", func(t *testing.T) { m := newFakeMac(t) m.launchWith(t, cli{sh: shell{rec: rec, link: true}, out: ok}) want(t, m.runA(t), "F6", wire.ProbeFailed, "hard_linked:") }) for name, c := range map[string]struct { seam func() want string }{ "a link": {func() { symlink = func(string, string) error { return errors.New("no") } }, "link-0"}, "a hard link": {func() { hardlink = func(string, string) error { return errors.New("no") } }, "hardlink-0"}, "the swap": {func() { rename = func(string, string) error { return errors.New("no") } }, "swap"}, "late_name": {func() { was := symlink symlink = func(o, n string) error { if strings.HasSuffix(n, "/late/x") { return errors.New("no") } return was(o, n) } }, "late_name"}, } { t.Run("setup: "+name, func(t *testing.T) { s1, h1, r1 := symlink, hardlink, rename t.Cleanup(func() { symlink, hardlink, rename = s1, h1, r1 }) m := newFakeMac(t) c.seam() m.launchWith(t, cli{sh: shell{rec: rec}, out: ok}) if p := byID(m.runA(t), "F6"); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "not_set_up:") || !strings.Contains(p.Detail, c.want) { t.Fatalf("%s: %+v", name, p) } }) } } // F7: inside the sandbox each Xcode attempt fails, and outside each // works (the control). func TestF7NeedsTheOutsideControl(t *testing.T) { rec := loadRecording(t) for _, c := range []struct { name, outside, detail string sh shell }{ {"control", "xcodebuild -list", "control_failed:xcodebuild", shell{rec: rec}}, {"simctl", "", "allowed:simctl", shell{rec: rec, codes: map[string]string{"simctl": "0"}}}, {"lookup", "", "allowed:mach", shell{rec: rec, files: map[string]string{"out/f7.mach": "port\n"}}}, {"missing", "", "not_shown_denied:xcodebuild", shell{rec: rec, drop: map[string]bool{"xcodebuild": true}}}, } { t.Run(c.name, func(t *testing.T) { m := newFakeMac(t) if c.outside != "" { m.outside[c.outside] = true } m.launchWith(t, cli{sh: c.sh, out: ok}) want(t, m.runA(t), "F7", wire.ProbeFailed, c.detail) }) } m := newFakeMac(t) m.h.Tools = mac.Tools{} m.launchWith(t, holding(t)) want(t, m.runA(t), "F7", wire.ProbeUnavailable, "no_xcode") } // The launch's own end decides first: one that never started says // nothing (tried again later); one whose end is not proven fails all. func TestProbeLaunchOutcome(t *testing.T) { m := newFakeMac(t) m.launchWith(t, cli{sh: shell{rec: loadRecording(t)}, out: Outcome{Reason: "account_unavailable"}}) for _, p := range m.runA(t) { if p.Verdict != wire.ProbeUnavailable || !strings.Contains(p.Detail, "launch_not_started:account_unavailable") { t.Fatalf("%+v", p) } } m = newFakeMac(t) m.launchWith(t, cli{sh: shell{rec: loadRecording(t)}, out: Outcome{Started: true}}) for _, p := range m.runA(t) { if p.Verdict != wire.ProbeFailed { t.Fatalf("%+v", p) } } } func allPassed(in Inputs, at time.Time) []Result { var out []Result for _, l := range Launches { r := Result{Launch: l, Inputs: in, At: at} for _, id := range launchProbes[l] { r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.EngineeringProbeSuccess(id), Detail: wire.ProbeDetail("f1_denied")}) } out = append(out, r) } return out } func readyState(probes []wire.Probe) State { return State{CLI: true, Probes: probes, P2: wire.ProbeDenied} } // Each launch's result counts only for the inputs it ran under and for // under a day: a stale launch A beside a fresh launch C is not ready. func TestProbeLaunchesAggregate(t *testing.T) { now := time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC) in := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B52"}, []wire.Simulator{{Runtime: "iOS 27.2"}}) var s Store for _, r := range allPassed(in, now.Add(-time.Hour)) { s.Put(r) } if st := Status(readyState(s.Probes(in, now, true))); st.State != wire.EngineeringReady { t.Fatalf("all fresh: %+v", st) } s.Put(allPassed(in, now.Add(-25*time.Hour))[0]) ps := s.Probes(in, now, true) if st := Status(readyState(ps)); st.State != wire.EngineeringProbesPending || st.Reason != "F1 F2 F3 F6 F7" { t.Fatalf("stale A, fresh C: %+v", st) } if p := byID(ps, "F4"); p.Verdict != wire.ProbePassed { t.Fatalf("C is fresh: %+v", p) } if p := byID(ps, "F1"); p.Verdict != wire.ProbeUnavailable || p.Detail != "expired" { t.Fatalf("A is stale: %+v", p) } if due := s.Due(in, now, true); !slices.Equal(due, []string{LaunchA}) { t.Fatalf("due %v", due) } s.Put(allPassed(in, now.Add(time.Hour))[0]) if p := byID(s.Probes(in, now, true), "F1"); p.Verdict != wire.ProbeUnavailable || p.Detail != "future" { t.Fatalf("future: %+v", p) } var u Store u.Put(Result{Launch: LaunchA, Inputs: in, At: now, Probes: all(LaunchA, wire.ProbeUnavailable, "x")}) u.try(LaunchA, in, now) if due := u.Due(in, now.Add(time.Minute), false); slices.Contains(due, LaunchA) { t.Fatalf("retried at once: %v", due) } if due := u.Due(in, now.Add(Retry), false); !slices.Contains(due, LaunchA) { t.Fatalf("not retried: %v", due) } var f Store for _, r := range allPassed(in, now) { f.Put(r) } if due := f.Due(in, now.Add(22*time.Hour), true); len(due) != 0 { t.Fatalf("a fresh result run again: %v", due) } if due := f.Due(in, now.Add(Refresh), true); !slices.Equal(due, []string{LaunchA, LaunchB, LaunchC}) { t.Fatalf("not refreshed: %v", due) } if due := f.Due(Inputs{Runner: "v1.0.0", Settings: in.Settings}, now, true); len(due) != 0 { t.Fatalf("due without a verified CLI: %v", due) } } // A new Xcode build, a new simulator runtime, a new CLI digest, a new // runner or new settings each make the results not count. Inputs are // read afresh for each launch (#9): ones that change while it runs make // its result undecided. func TestProbeInputsInvalidate(t *testing.T) { now := time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC) in := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B52"}, []wire.Simulator{{Runtime: "iOS 27.2"}, {Runtime: "iOS 27.0"}, {Runtime: "iOS 27.2"}}) if in.Runtimes != "iOS 27.0, iOS 27.2" || in.Xcode != "27.2 (27B52)" || in.CLI == "" || in.Settings == "" || strings.HasPrefix(in.Settings, "unmade") { t.Fatalf("inputs %+v", in) } if NewInputs("v1.0.0", false, wire.Xcode{}, nil).CLI != "" { t.Fatal("an unverified CLI has a digest") } for _, c := range []struct { name string next Inputs why string }{ {"xcode build", NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B53"}, []wire.Simulator{{Runtime: "iOS 27.2"}, {Runtime: "iOS 27.0"}}), "stale_xcode"}, {"runtime", NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B52"}, []wire.Simulator{{Runtime: "iOS 27.2"}, {Runtime: "iOS 27.0"}, {Runtime: "iOS 27.3"}}), "stale_runtimes"}, {"cli digest", Inputs{Runner: in.Runner, Settings: in.Settings, CLI: strings.Repeat("0", 64), Xcode: in.Xcode, Runtimes: in.Runtimes}, "stale_cli"}, {"runner", Inputs{Runner: "v1.0.1", Settings: in.Settings, CLI: in.CLI, Xcode: in.Xcode, Runtimes: in.Runtimes}, "stale_runner"}, {"settings", Inputs{Runner: in.Runner, Settings: "0000", CLI: in.CLI, Xcode: in.Xcode, Runtimes: in.Runtimes}, "stale_settings"}, } { t.Run(c.name, func(t *testing.T) { var s Store for _, r := range allPassed(in, now) { s.Put(r) } ps := s.Probes(c.next, now, true) for _, id := range wire.EngineeringProbeIDs { if p := byID(ps, id); p.Verdict != wire.ProbeUnavailable || p.Detail != c.why { t.Fatalf("%s %+v", id, p) } } if st := Status(readyState(ps)); st.State != wire.EngineeringProbesPending { t.Fatalf("%+v", st) } if due := s.Due(c.next, now, true); !slices.Equal(due, Launches) { t.Fatalf("due %v", due) } if XcodeAllowed(ps) { t.Fatal("Xcode access kept across a change") } }) } // The inputs each launch runs under are read afresh, and a change // while it runs leaves it undecided. m := newFakeMac(t) m.launchWith(t, holding(t)) var mu sync.Mutex calls := 0 changed := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B53"}, m.h.Simulators) m.h.Live = func(context.Context) (Inputs, []wire.Simulator) { mu.Lock() defer mu.Unlock() calls++ if calls > 2 { return changed, m.h.Simulators } return m.h.Inputs, m.h.Simulators } var s Store results := s.Run(context.Background(), m.h) if len(results) == 0 || results[0].Inputs != m.h.Inputs { t.Fatalf("results %+v", results) } for _, p := range results[0].Probes { if p.Verdict != wire.ProbeUnavailable || !strings.Contains(p.Detail, "inputs_changed") { t.Fatalf("%+v", p) } } } // The status names the first thing missing, in order: the guards, the // CLI, a failed probe, the connection, probes not yet proven; ready only // with everything, a connection included. F5 decides only Xcode access. func TestEngineeringStatusOrder(t *testing.T) { now := time.Now() in := NewInputs("v1", true, wire.Xcode{}, nil) var s Store for _, r := range allPassed(in, now) { s.Put(r) } passed := s.Probes(in, now, true) failedF2 := slices.Clone(passed) failedF2[1] = wire.Probe{ID: "F2", Verdict: wire.ProbeFailed} pendingF4 := slices.Clone(passed) pendingF4[3] = wire.Probe{ID: "F4", Verdict: wire.ProbeUnavailable} noF5 := slices.Clone(passed) noF5[4] = wire.Probe{ID: "F5", Verdict: wire.ProbeFailed} tainted := &wire.EngineeringStatus{State: wire.EngineeringTainted} home := &wire.EngineeringStatus{State: wire.EngineeringHomeOpen, Reason: "home_mode"} for _, c := range []struct { name string s State want wire.EngineeringStatus }{ {"ready", State{CLI: true, Probes: passed, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringReady}}, {"F5 does not decide", State{CLI: true, Probes: noF5, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringReady}}, // Whole-branch fix 2, #5: the scanner's sandbox is P2's. {"P2 not run", State{CLI: true, Probes: passed}, wire.EngineeringStatus{State: wire.EngineeringProbesPending, Reason: "P2"}}, {"P2 not denied", State{CLI: true, Probes: passed, P2: wire.ProbeFailed}, wire.EngineeringStatus{State: wire.EngineeringProbesFailed, Reason: "P2"}}, {"P2 unavailable", State{CLI: true, Probes: passed, P2: wire.ProbeUnavailable}, wire.EngineeringStatus{State: wire.EngineeringProbesFailed, Reason: "P2"}}, {"F2 and P2", State{CLI: true, Probes: failedF2, P2: wire.ProbeFailed}, wire.EngineeringStatus{State: wire.EngineeringProbesFailed, Reason: "F2 P2"}}, {"tainted first", State{Guards: tainted, Probes: failedF2, Conn: wire.EngineeringNoConnection}, *tainted}, {"home open", State{Guards: home, Probes: failedF2}, *home}, {"cli", State{Probes: failedF2, Conn: wire.EngineeringNoConnection}, wire.EngineeringStatus{State: wire.EngineeringCLIUnpinned}}, {"failed before the connection", State{CLI: true, Probes: failedF2, Conn: wire.EngineeringNoConnection}, wire.EngineeringStatus{State: wire.EngineeringProbesFailed, Reason: "F2"}}, {"no connection", State{CLI: true, Probes: passed, Conn: wire.EngineeringNoConnection, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringNoConnection}}, {"connection before pending", State{CLI: true, Probes: pendingF4, Conn: wire.EngineeringLimited}, wire.EngineeringStatus{State: wire.EngineeringLimited}}, {"signed out", State{CLI: true, Probes: passed, Conn: wire.EngineeringSignedOut, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringSignedOut}}, {"pending", State{CLI: true, Probes: pendingF4, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringProbesPending, Reason: "F4"}}, {"nothing run", State{CLI: true}, wire.EngineeringStatus{State: wire.EngineeringProbesPending, Reason: "F1 F2 F3 F4 F6 F7 P2"}}, } { if got := Status(c.s); got != c.want { t.Fatalf("%s: %+v, want %+v", c.name, got, c.want) } if err := wire.ValidCapabilities(wire.Capabilities{Engineering: &c.want}); err != nil { t.Fatalf("%s: %v", c.name, err) } } if !XcodeAllowed(passed) || XcodeAllowed(noF5) { t.Fatal("Xcode access follows F5") } held := []wire.HeldConnection{{LocalID: "m", Provider: wire.ProviderClaude, Kind: wire.KindSubscription, State: wire.ConnHealthy}} if got := ConnState(held, func(string) bool { return true }); got != wire.EngineeringNoConnection { t.Fatalf("a subscription connection is not a Mac's: %q", got) } held = append(held, wire.HeldConnection{LocalID: "a", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnSignInAgain}, wire.HeldConnection{LocalID: "b", Provider: wire.ProviderClaude, Kind: wire.KindToken, State: wire.ConnLimited}) if got := ConnState(held, func(string) bool { return false }); got != wire.EngineeringLimited { t.Fatalf("limited: %q", got) } if got := ConnState(held[:2], func(string) bool { return false }); got != wire.EngineeringSignedOut { t.Fatalf("signed out: %q", got) } if got := ConnState(held, func(id string) bool { return id == "a" }); got != "" { t.Fatalf("usable: %q", got) } } // A probe run is one turn: busy, nothing launches and every probe says // so by a code the instance words; tried again after Retry. func TestProbeRunTakesTheTurn(t *testing.T) { m := newFakeMac(t) m.launchWith(t, holding(t)) m.h.Turns = mac.NewTurns("") held, err := m.h.Turns.Take(context.Background(), mac.OpEngineering) if err != nil { t.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() var s Store results := s.Run(ctx, m.h) held.Give() if len(m.launched) != 0 || len(results) != 3 { t.Fatalf("launched %v results %d", m.launched, len(results)) } for _, r := range results { for _, p := range r.Probes { if p.Verdict != wire.ProbeUnavailable || p.Detail != wire.ProbeDetailTurnBusy { t.Fatalf("%+v", p) } } } if due := s.Due(m.h.Inputs, time.Now(), true); len(due) != 0 { t.Fatalf("retried at once: %v", due) } }