oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package fprobe
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/base64"
8 "encoding/hex"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "net"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "regexp"
17 "slices"
18 "strconv"
19 "strings"
20 "sync"
21 "syscall"
22 "testing"
23 "time"
24
25 "amadan.net/oficina/equipo/internal/runner/mac"
26 "amadan.net/oficina/equipo/internal/runner/mac/proc"
27 "amadan.net/oficina/equipo/internal/wire"
28)
29
30// The shipped Engineering probes on Linux: a fake Mac (its places in a
31// temporary home), the runner's own observers for real (the listener,
32// the sentinels, the search of the tree and the scratch, the runner's
33// setup and its records, the CLI's process), and a fake CLI that does
34// what the Mac's port, protected script and native tools would, from
35// synthetic recordings (testdata, dated and marked so). What only the
36// Mac can show is task 18's.
37
38const fakeToken = "sk-ant-oat01-Zm9vYmFyYmF6cXV4cXV1eDAxMjM0NTY3ODk"
39
40type recording struct {
41 Codes map[string]string `json:"codes"`
42 Files map[string]string `json:"files"`
43 F3 []string `json:"f3"`
44 F3Token []string `json:"f3_token"`
45}
46
47func loadRecording(t *testing.T) recording {
48 t.Helper()
49 raw, err := os.ReadFile("testdata/synthetic-2026-11-29-tito-studio-launch-a.json")
50 if err != nil {
51 t.Fatal(err)
52 }
53 var r recording
54 if err := json.Unmarshal(raw, &r); err != nil {
55 t.Fatal(err)
56 }
57 return r
58}
59
60func forms(s string) [][]byte {
61 return [][]byte{[]byte(s), []byte(hex.EncodeToString([]byte(s))), []byte(base64.StdEncoding.EncodeToString([]byte(s)))}
62}
63
64// fakeMac is a Mac's places in a temporary home, and what the outside
65// observers see.
66type fakeMac struct {
67 h Host
68 dir string
69 mu sync.Mutex
70 outside map[string]bool // F7's control fails for these commands
71 launched map[string]int
72 specs []Spec
73}
74
75func newFakeMac(t *testing.T) *fakeMac {
76 t.Helper()
77 dir := t.TempDir()
78 home := filepath.Join(dir, "home")
79 m := &fakeMac{dir: dir, outside: map[string]bool{}, launched: map[string]int{}}
80 creds := filepath.Join(home, "accounts", "c1")
81 for _, d := range []string{filepath.Join(home, "state"), creds, filepath.Join(home, "Library", "Keychains"), filepath.Join(dir, "scratch"), filepath.Join(dir, "volumes")} {
82 if err := os.MkdirAll(d, 0o700); err != nil {
83 t.Fatal(err)
84 }
85 }
86 // /Volumes holds the boot volume's alias of /.
87 if err := os.Symlink("/", filepath.Join(dir, "volumes", "Macintosh HD")); err != nil {
88 t.Fatal(err)
89 }
90 was := volumesDir
91 volumesDir = filepath.Join(dir, "volumes")
92 t.Cleanup(func() { volumesDir = was })
93 tokenFile := filepath.Join(creds, ".oauth-token")
94 if err := os.WriteFile(tokenFile, []byte(fakeToken), 0o600); err != nil {
95 t.Fatal(err)
96 }
97 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"}})
98 m.h = Host{
99 Inputs: in,
100 Live: func(context.Context) (Inputs, []wire.Simulator) {
101 return in, []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}}
102 },
103 Paths: mac.Paths{Home: home, StateDir: filepath.Join(home, "state"), AccountsRoot: filepath.Join(home, "accounts"), SessionRoot: filepath.Join(home, "sessions")},
104 RuntimeRoot: filepath.Join(dir, "scratch", "homes"),
105 TokenFiles: []string{tokenFile},
106 Tools: mac.Tools{Xcodebuild: "/usr/bin/xcodebuild", Xcrun: "/usr/bin/xcrun"},
107 Simulators: []wire.Simulator{{Name: "iPhone 17 Pro", Runtime: "iOS 27.2", UDID: "ABCDEF01-2345-6789-ABCD-EF0123456789"}},
108 Scratch: filepath.Join(dir, "scratch", "fprobe"),
109 Runner: "/opt/equipo-runner",
110 P2Denied: true,
111 Secrets: func(context.Context) ([][]byte, error) { return forms(fakeToken), nil },
112 Listen: func() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") },
113 Resolve: func(context.Context, string) bool { return true },
114 Exposed: func(string) bool { return false },
115 Lookup: proc.Platform.Lookup,
116 Alive: func(id proc.ID) (bool, bool) { return proc.Alive(proc.Platform, id) },
117 ProcArgs: func(pid int) ([]byte, error) {
118 return []byte("/cli\x00EQUIPO_ATTEMPT=fprobe-x\x00PATH=/usr/bin\x00"), nil
119 },
120 Limits: map[string]time.Duration{LaunchA: 20 * time.Second, LaunchB: 20 * time.Second, LaunchC: 10 * time.Second},
121 }
122 m.h.Exec = func(ctx context.Context, name string, args ...string) (string, error) {
123 key := strings.Join(append([]string{filepath.Base(name)}, args...), " ")
124 for k := range m.outside {
125 if strings.HasPrefix(key, k) {
126 return "", errors.New("failed outside")
127 }
128 }
129 if filepath.Base(name) == "osascript" {
130 return "port\n", nil
131 }
132 if filepath.Base(name) == "ps" {
133 // ps -E outside the sandbox shows the CLI's environment.
134 return "/cli -p EQUIPO_ATTEMPT=fprobe-x PATH=/usr/bin\n", nil
135 }
136 return "", nil
137 }
138 return m
139}
140
141// shell is what the protected script would record in the launch's
142// scratch on a Mac whose sandbox holds (the recording), with what a
143// case changes.
144type shell struct {
145 rec recording
146 codes map[string]string // overrides, by record name
147 drop map[string]bool // records not written
148 files map[string]string // extra or replaced files under the scratch
149 connect bool // connect to the listener while saying tcp 1
150 link bool // the shell's hard links into the tree succeed
151 leak string // the F2 place whose sentinel the shell copies
152 f3 map[string]string // F3 record lines replaced, by name ("" drops it)
153 nonce string // the nonce written ("" this run's)
154 begin string // the begin record's nonce alone ("" as nonce)
155 noEnd bool // the script was cut short
156}
157
158var recLine = regexp.MustCompile(`; r ([A-Za-z0-9_.]+) \S+ (f[0-9])`)
159
160// lists are the runner's lists beside the script.
161func lists(s Spec, name string) [][]string {
162 raw, _ := os.ReadFile(filepath.Join(filepath.Dir(s.Script), name))
163 var out [][]string
164 for _, l := range strings.Split(strings.TrimSpace(string(raw)), "\n") {
165 if l != "" {
166 out = append(out, strings.SplitN(l, " ", 2))
167 }
168 }
169 return out
170}
171
172func (sh shell) run(t *testing.T, s Spec, cliPID int) {
173 t.Helper()
174 script, err := os.ReadFile(s.Script)
175 if err != nil {
176 t.Fatal(err)
177 }
178 out := filepath.Join(s.Scratch, "out")
179 nonce := s.Nonce
180 if sh.nonce != "" {
181 nonce = sh.nonce
182 }
183 write(t, filepath.Join(out, "begin"), "begin "+firstNonEmpty(sh.begin, nonce)+"\n")
184 rec := func(name, file string) {
185 if sh.drop[name] {
186 return
187 }
188 code, ok := sh.codes[name]
189 if !ok {
190 code, ok = sh.rec.Codes[name]
191 }
192 if !ok {
193 code, ok = sh.rec.Codes[name[strings.LastIndex(name, ".")+1:]]
194 }
195 if !ok {
196 code = "1"
197 }
198 appendFile(t, filepath.Join(out, file), name+" "+code+"\n")
199 }
200 for _, m := range recLine.FindAllStringSubmatch(string(script), -1) {
201 rec(m[1], m[2])
202 }
203 if strings.Contains(string(script), "f2.places") {
204 for _, p := range lists(s, "f2.places") {
205 for _, k := range []string{".cat", ".cp", ".ln"} {
206 rec(p[0]+k, "f2")
207 }
208 if p[0] == sh.leak {
209 b, _ := os.ReadFile(p[1])
210 write(t, filepath.Join(out, "f2."+p[0]), string(b))
211 }
212 }
213 for i, p := range lists(s, "f6.targets") {
214 rec("ln6."+strconv.Itoa(i), "f6")
215 if sh.link {
216 _ = os.Link(p[0], filepath.Join(s.Tree, "f6", "hard-"+strconv.Itoa(i)))
217 }
218 }
219 }
220 if strings.Contains(string(script), "f3.tokens") {
221 // F3's records, as the runner's reader writes them: one bounded
222 // outcome per source, never what the source gave.
223 lines := slices.Clone(sh.rec.F3)
224 for i := range lists(s, "f3.tokens") {
225 for _, l := range sh.rec.F3Token {
226 lines = append(lines, strings.ReplaceAll(l, "fileN", "file"+strconv.Itoa(i)))
227 }
228 }
229 for _, l := range lines {
230 name, _, _ := strings.Cut(l, " ")
231 if v, ok := sh.f3[name]; ok {
232 if l = v; v == "" {
233 continue
234 }
235 }
236 l = strings.ReplaceAll(strings.ReplaceAll(l, "PPID", "999999"), "PID", strconv.Itoa(cliPID))
237 appendFile(t, filepath.Join(out, "f3"), l+"\n")
238 }
239 }
240 for rel, body := range sh.rec.Files {
241 write(t, filepath.Join(s.Scratch, rel), strings.ReplaceAll(body, "PID", strconv.Itoa(cliPID)))
242 }
243 for rel, body := range sh.files {
244 write(t, filepath.Join(s.Scratch, rel), strings.ReplaceAll(body, "PID", strconv.Itoa(cliPID)))
245 }
246 if sh.connect {
247 port := regexp.MustCompile(`nc -z -G 3 127\.0\.0\.1 ([0-9]+)`).FindStringSubmatch(string(script))[1]
248 if c, err := net.Dial("tcp", "127.0.0.1:"+port); err == nil {
249 c.Close()
250 }
251 }
252 if !sh.noEnd {
253 write(t, filepath.Join(out, "end"), "end "+nonce+"\n")
254 }
255}
256
257// model is what the fake CLI's native tools do for F6, reported as the
258// CLI reports them: a tool_use and a tool_result in its stream, and the
259// runner's tool asked unless the CLI refused by its own rules.
260type model struct {
261 allow map[string]bool // calls the runner's tool answered allowed
262 skip map[string]bool // calls never made
263 leak map[string]bool // calls whose target the CLI really read
264 race bool // read the swapped link until it gives the sentinel
265 late bool // read the late name for real
266 noAsk bool // the CLI refused by its own rules: no ask
267 noUse bool // no tool events at all
268 notes bool // write every name as a note instead
269 noCtl bool // the control read fails
270 ctlText string // the control read returns this instead
271 offset map[string]bool // calls made with an offset (not a whole-file read)
272 pattern map[string]string // Grep calls made with another pattern
273 execErr map[string]bool // calls that fail as an execution error, not a refusal
274 benign bool // swap reads and the late Grep allowed, seeing only benign content
275 blank bool // with benign, the swap reads show nothing at all
276}
277
278var callLine = regexp.MustCompile(`(?m)^([CSL][0-9]+)\. (Read|Grep|Glob|Write) (?:.*?)(?:file_path|path) (/\S+)$`)
279var patternArg = regexp.MustCompile(`pattern "([^"]*)"`)
280
281func frame(v any) []byte { b, _ := json.Marshal(v); return b }
282
283func use(obs Observer, id, tool string, input map[string]string) {
284 if obs.Event != nil {
285 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}}}}))
286 }
287}
288
289func result(obs Observer, id string, isError bool, text string) {
290 if obs.Event != nil {
291 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}}}}))
292 }
293}
294
295func (md model) run(t *testing.T, s Spec, obs Observer) {
296 t.Helper()
297 ctl := filepath.Join(s.Tree, "f6", "control")
298 b, _ := os.ReadFile(ctl)
299 use(obs, "ctl", "Read", map[string]string{"file_path": ctl})
300 switch {
301 case md.noCtl:
302 result(obs, "ctl", true, "File does not exist.")
303 case md.ctlText != "":
304 result(obs, "ctl", false, md.ctlText)
305 default:
306 result(obs, "ctl", false, string(b))
307 }
308 var notes []string
309 for i, m := range callLine.FindAllStringSubmatch(s.Prompt, -1) {
310 name, tool, path := m[1], m[2], m[3]
311 if md.skip[name] {
312 continue
313 }
314 if md.notes {
315 notes = append(notes, name+": refused")
316 continue
317 }
318 id := fmt.Sprintf("u%d", i)
319 input := map[string]string{"file_path": path}
320 switch tool {
321 case "Grep":
322 input = map[string]string{"path": path, "pattern": patternArg.FindStringSubmatch(m[0])[1], "output_mode": "content"}
323 if p, ok := md.pattern[name]; ok {
324 input["pattern"] = p
325 }
326 case "Glob":
327 input = map[string]string{"path": path, "pattern": "*"}
328 case "Write":
329 input["content"] = "x"
330 }
331 if md.offset[name] {
332 input["offset"] = "100"
333 }
334 if !md.noUse {
335 use(obs, id, tool, input)
336 }
337 in, _ := json.Marshal(input)
338 if !md.noAsk && !md.execErr[name] {
339 obs.Ask(Ask{Tool: tool, ToolUseID: id, Input: in, Allowed: md.allow[name] || md.benign && (name[0] == 'S' || name == "L1")})
340 }
341 text, isError := "Permission to use "+tool+" has been denied.", true
342 switch {
343 case md.execErr[name]:
344 text = "File does not exist."
345 case md.benign && (name[0] == 'S' || name == "L1"):
346 text, isError = "benign\n", false
347 if md.blank {
348 text = ""
349 }
350 if name == "L1" {
351 text = "No matches found"
352 }
353 case md.allow[name], md.leak[name]:
354 b, _ := os.ReadFile(path)
355 text, isError = string(b), false
356 case md.race && strings.HasSuffix(path, "/f6/swap"):
357 for deadline := time.Now().Add(3 * time.Second); time.Now().Before(deadline); time.Sleep(200 * time.Microsecond) {
358 if b, _ := os.ReadFile(path); bytes.Contains(b, []byte("EQUIPO-NONCE-")) {
359 text, isError = string(b), false
360 break
361 }
362 }
363 case md.late && name == "L2":
364 b, _ := os.ReadFile(path)
365 text, isError = string(b), false
366 }
367 if !md.noUse {
368 result(obs, id, isError, text)
369 }
370 }
371 if md.notes {
372 write(t, filepath.Join(s.Tree, "out", "f6-results"), strings.Join(notes, "\n")+"\n")
373 }
374}
375
376// cli is the fake CLI of a probe launch: it is started (a real process
377// carrying the launch's marker), gets its runtime copy, asks the runner's
378// tool to run the script, and the script and native tools do what the
379// shell and the model say.
380type cli struct {
381 sh shell
382 md model
383 out Outcome
384 noScript bool // never asks for the script
385 bash string // asks for another Bash command too (a broken port allows it)
386 noCopy bool // never gets a runtime copy
387 noAsk bool // runs the script without asking the runner's tool
388 before func(Spec)
389}
390
391func (m *fakeMac) launchWith(t *testing.T, c cli) {
392 m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
393 m.mu.Lock()
394 m.launched[s.Launch]++
395 m.specs = append(m.specs, s)
396 m.mu.Unlock()
397 // The runner never gives a token file a second name.
398 for _, f := range m.h.TokenFiles {
399 var st syscall.Stat_t
400 if syscall.Stat(f, &st) == nil && st.Nlink != 1 {
401 t.Errorf("a token file has %d names during the launch", st.Nlink)
402 }
403 }
404 if !c.out.Started {
405 return c.out
406 }
407 if !c.noCopy && obs.Copy != nil {
408 cp := filepath.Join(m.dir, "scratch", "homes", "copy-"+s.Launch)
409 if err := os.MkdirAll(cp, 0o700); err != nil || obs.Copy(cp) != nil {
410 t.Errorf("runtime copy: %v", err)
411 }
412 }
413 cmd := exec.Command("sleep", "30")
414 cmd.Env = []string{"EQUIPO_ATTEMPT=fprobe-x"}
415 if err := cmd.Start(); err != nil {
416 t.Fatal(err)
417 }
418 defer func() { cmd.Process.Kill(); cmd.Wait() }()
419 if obs.Started != nil {
420 obs.Started(cmd.Process.Pid)
421 }
422 if c.before != nil {
423 c.before(s)
424 }
425 if !c.noScript {
426 in, _ := json.Marshal(map[string]string{"command": s.Command()})
427 ok := s.Permit("Bash", in)
428 if !c.noAsk {
429 obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: ok})
430 }
431 if ok && s.Launch == LaunchA {
432 c.sh.run(t, s, cmd.Process.Pid)
433 }
434 }
435 if c.bash != "" {
436 in, _ := json.Marshal(map[string]string{"command": c.bash})
437 obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: true})
438 }
439 if s.Launch == LaunchA {
440 c.md.run(t, s, obs)
441 }
442 return c.out
443 }
444}
445
446var ok = Outcome{Started: true, Proven: true}
447
448func write(t *testing.T, p, body string) {
449 t.Helper()
450 if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
451 t.Fatal(err)
452 }
453 if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
454 t.Fatal(err)
455 }
456}
457
458func appendFile(t *testing.T, p, line string) {
459 t.Helper()
460 if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
461 t.Fatal(err)
462 }
463 f, err := os.OpenFile(p, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
464 if err != nil {
465 t.Fatal(err)
466 }
467 defer f.Close()
468 f.WriteString(line)
469}
470
471func byID(ps []wire.Probe, id string) wire.Probe { return probe(ps, id) }
472
473// runA runs launch A and checks what it must always leave: no tree, no
474// sentinel, a valid capability report with no path, nonce or secret.
475func (m *fakeMac) runA(t *testing.T) []wire.Probe {
476 t.Helper()
477 ps := launchA(context.Background(), m.h)
478 if err := wire.ValidCapabilities(wire.Capabilities{Probes: ps}); err != nil {
479 t.Fatalf("outside the capability rules: %v %+v", err, ps)
480 }
481 if left, _ := filepath.Glob(filepath.Join(m.h.Scratch, "*")); len(left) != 0 {
482 t.Fatalf("the probe tree was left: %v", left)
483 }
484 for _, d := range []string{m.h.Paths.StateDir, m.h.Paths.AccountsRoot, m.h.RuntimeRoot, filepath.Join(m.h.Paths.Home, "Library", "Keychains")} {
485 if left, _ := filepath.Glob(filepath.Join(d, "equipo-f*")); len(left) != 0 {
486 t.Fatalf("a sentinel or a write was left: %v", left)
487 }
488 }
489 raw, _ := json.Marshal(ps)
490 if strings.Contains(string(raw), m.dir) || strings.Contains(string(raw), "EQUIPO-NONCE") || strings.Contains(string(raw), fakeToken) {
491 t.Fatalf("a path, nonce or secret in a detail: %s", raw)
492 }
493 coded(t, ps)
494 return ps
495}
496
497// coded: every detail is codes with parameters (wire.ProbeDetail), none
498// empty, never words (whole-branch fix 1, #6).
499func coded(t *testing.T, ps []wire.Probe) {
500 t.Helper()
501 for _, p := range ps {
502 if parts, ok := wire.ParseProbeDetail(p.Detail); !ok || len(parts) == 0 {
503 t.Fatalf("%s: detail %q is not coded", p.ID, p.Detail)
504 }
505 }
506}
507
508func want(t *testing.T, ps []wire.Probe, id, verdict, detail string) {
509 t.Helper()
510 coded(t, ps)
511 p := byID(ps, id)
512 if p.Verdict != verdict || !strings.Contains(p.Detail, detail) {
513 t.Fatalf("%s: want %s with %q, got %+v", id, verdict, detail, p)
514 }
515}
516
517func holding(t *testing.T) cli { return cli{sh: shell{rec: loadRecording(t)}, out: ok} }
518
519// A sandbox that holds, as the synthetic recording says: every launch A
520// probe reaches its success verdict.
521func TestLaunchAHolds(t *testing.T) {
522 m := newFakeMac(t)
523 m.launchWith(t, holding(t))
524 ps := m.runA(t)
525 for _, id := range launchProbes[LaunchA] {
526 want(t, ps, id, wire.ProbeDenied, "")
527 }
528}
529
530// Protected execution evidence (fix round 1, #1): records count only
531// when the one Bash command allowed ran the hashed script, which wrote
532// them into the launch's scratch with this run's nonce. Nothing the
533// model could write counts: records in the tree, a second Bash command,
534// another run's records, a cut-short run.
535func TestProtectedEvidence(t *testing.T) {
536 m := newFakeMac(t)
537 m.launchWith(t, holding(t))
538 m.runA(t)
539 s := m.specs[0]
540 root := filepath.Dir(s.Tree)
541 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) {
542 t.Fatalf("the script must lie outside the tree and the scratch: %+v", s)
543 }
544 if !strings.HasPrefix(s.Nonce, "EQUIPO-NONCE-") || !strings.Contains(s.Prompt, s.Command()) || s.ScriptSHA256 == "" {
545 t.Fatalf("spec %+v", s)
546 }
547 for name, c := range map[string]cli{
548 "records in the tree": {sh: shell{rec: loadRecording(t)}, out: ok, noScript: true, before: func(s Spec) {
549 write(t, filepath.Join(s.Tree, "out", "begin"), "begin "+s.Nonce+"\n")
550 write(t, filepath.Join(s.Tree, "out", "f1"), "tcp 1\nhttps 1\nhttps_local 1\ndns 1\n")
551 }},
552 "another Bash command": {sh: shell{rec: loadRecording(t)}, out: ok, bash: "echo dns 1 >> out/f1"},
553 "another run's records": {sh: shell{rec: loadRecording(t), nonce: "EQUIPO-NONCE-00000000000000000000000000000000"}, out: ok},
554 "a begin from another run": {sh: shell{rec: loadRecording(t), begin: "EQUIPO-NONCE-00000000000000000000000000000000"}, out: ok},
555 "run without the tool's answer": {sh: shell{rec: loadRecording(t)}, out: ok, noAsk: true},
556 "cut short": {sh: shell{rec: loadRecording(t), noEnd: true}, out: ok},
557 } {
558 t.Run(name, func(t *testing.T) {
559 m := newFakeMac(t)
560 m.launchWith(t, c)
561 for _, p := range m.runA(t) {
562 if p.ID != "F6" && p.Verdict == wire.EngineeringProbeSuccess(p.ID) {
563 t.Fatalf("%s passed: %+v", name, p)
564 }
565 }
566 })
567 }
568 // The permission rule: Bash is the script exactly, its bytes as
569 // written; no native write outside the tree.
570 dir := t.TempDir()
571 script := filepath.Join(dir, "bin", "probe.sh")
572 write(t, script, "echo hi\n")
573 sum := sha256.Sum256([]byte("echo hi\n"))
574 sp := Spec{Tree: filepath.Join(dir, "tree"), Scratch: filepath.Join(dir, "run"), Script: script, ScriptSHA256: hex.EncodeToString(sum[:]), Nonce: "EQUIPO-NONCE-1"}
575 j := func(k, v string) json.RawMessage { b, _ := json.Marshal(map[string]string{k: v}); return b }
576 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")) {
577 t.Fatal("the script, a write in the tree and a read are not the probe's to refuse")
578 }
579 for _, q := range []struct{ tool, k, v string }{
580 {"Bash", "command", "echo dns 1 >> out/f1"},
581 {"Bash", "command", sp.Command() + "; true"},
582 {"Bash", "command", "bash " + script + " EQUIPO-NONCE-2"},
583 {"Write", "file_path", filepath.Join(sp.Scratch, "out", "f1")},
584 {"Edit", "file_path", script},
585 {"Write", "file_path", filepath.Join(dir, "elsewhere")},
586 } {
587 if sp.Permit(q.tool, j(q.k, q.v)) {
588 t.Fatalf("permitted %+v", q)
589 }
590 }
591 write(t, script, "echo changed\n")
592 if sp.Permit("Bash", j("command", sp.Command())) {
593 t.Fatal("a changed script was permitted")
594 }
595}
596
597// F1: this run's records, nothing at the listener, every attempt failed,
598// the DNS name resolving outside.
599func TestF1RequiresControlAndListener(t *testing.T) {
600 rec := loadRecording(t)
601 for _, c := range []struct {
602 name string
603 sh shell
604 resolv bool
605 detail string
606 }{
607 {"listener", shell{rec: rec, connect: true}, true, "loopback_hits:1"},
608 {"missing line", shell{rec: rec, drop: map[string]bool{"dns": true}}, true, "not_shown_denied:dns"},
609 {"allowed", shell{rec: rec, codes: map[string]string{"https": "0"}}, true, "allowed:https"},
610 {"dns control", shell{rec: rec}, false, "dns_control_failed"},
611 {"no control", shell{rec: rec, nonce: "EQUIPO-NONCE-1"}, true, "records_foreign"},
612 } {
613 t.Run(c.name, func(t *testing.T) {
614 m := newFakeMac(t)
615 m.h.Resolve = func(context.Context, string) bool { return c.resolv }
616 m.launchWith(t, cli{sh: c.sh, out: ok})
617 want(t, m.runA(t), "F1", wire.ProbeFailed, c.detail)
618 })
619 }
620}
621
622// F2 (#8): controlled sentinels in every place: the state dir, the
623// accounts root, the runtime-copy root, the connection's runtime copy
624// itself (planted once the launch has it), the Keychains, /Volumes (the
625// boot volume's alias of a sentinel), and another person's home the
626// runner can read (a file it reads as the control). A place that cannot
627// be set up leaves F2 not proven, never denied with less coverage.
628func TestF2NoncesDecide(t *testing.T) {
629 rec := loadRecording(t)
630 for _, c := range []struct {
631 name, detail string
632 c cli
633 verdict string
634 }{
635 {"copied though denied", "reached_scratch:state", cli{sh: shell{rec: rec, leak: "state"}, out: ok}, wire.ProbeFailed},
636 {"the runtime copy", "reached_scratch:copy", cli{sh: shell{rec: rec, leak: "copy"}, out: ok}, wire.ProbeFailed},
637 {"through /Volumes", "reached_scratch:volumes", cli{sh: shell{rec: rec, leak: "volumes"}, out: ok}, wire.ProbeFailed},
638 {"hard link", "reached_tree:state accounts runtime keychains", cli{sh: shell{rec: rec, link: true}, out: ok}, wire.ProbeFailed},
639 {"missing line", "not_shown_denied:keychains.ln", cli{sh: shell{rec: rec, drop: map[string]bool{"keychains.ln": true}}, out: ok}, wire.ProbeFailed},
640 {"read allowed", "allowed:copy.cat", cli{sh: shell{rec: rec, codes: map[string]string{"copy.cat": "allowed"}}, out: ok}, wire.ProbeFailed},
641 {"no runtime copy", "not_set_up:copy", cli{sh: shell{rec: rec}, out: ok, noCopy: true}, wire.ProbeUnavailable},
642 } {
643 t.Run(c.name, func(t *testing.T) {
644 m := newFakeMac(t)
645 m.launchWith(t, c.c)
646 want(t, m.runA(t), "F2", c.verdict, c.detail)
647 })
648 }
649 t.Run("no volumes alias", func(t *testing.T) {
650 m := newFakeMac(t)
651 os.Remove(filepath.Join(volumesDir, "Macintosh HD"))
652 m.launchWith(t, holding(t))
653 want(t, m.runA(t), "F2", wire.ProbeUnavailable, "not_set_up:volumes")
654 })
655 t.Run("homes unknown", func(t *testing.T) {
656 m := newFakeMac(t)
657 m.h.Paths.HomesUnknown = true
658 m.launchWith(t, holding(t))
659 want(t, m.runA(t), "F2", wire.ProbeUnavailable, "not_set_up:other_homes")
660 })
661 t.Run("a readable other home", func(t *testing.T) {
662 m := newFakeMac(t)
663 other := filepath.Join(m.dir, "Users", "paul")
664 write(t, filepath.Join(other, "notes.txt"), "Paul's notes, which no step may read: 0123456789abcdef\n")
665 m.h.Paths.OtherHomes = []string{other}
666 m.h.Exposed = func(h string) bool { return h == other }
667 m.launchWith(t, cli{sh: shell{rec: rec, leak: "home"}, out: ok})
668 want(t, m.runA(t), "F2", wire.ProbeFailed, "reached_scratch:home")
669 m.launchWith(t, holding(t))
670 want(t, m.runA(t), "F2", wire.ProbeDenied, "")
671 })
672 t.Run("a closed other home", func(t *testing.T) {
673 m := newFakeMac(t)
674 m.h.Paths.OtherHomes = []string{"/Users/Shared", "/Users/paul"}
675 m.launchWith(t, holding(t))
676 want(t, m.runA(t), "F2", wire.ProbeDenied, "other_home_os")
677 })
678 t.Run("a sentinel that cannot be planted", func(t *testing.T) {
679 m := newFakeMac(t)
680 m.h.RuntimeRoot = "relative"
681 m.launchWith(t, holding(t))
682 want(t, m.runA(t), "F2", wire.ProbeUnavailable, "not_set_up:runtime")
683 })
684}
685
686// F3 (#3, #8; fix round 2): every source's one bounded outcome, from the
687// runner's reader comparing in memory: "allowed" (a token from it) fails,
688// and so does a record missing, cut short, or naming another pid or exit.
689// The CLI's environment is read inside the sandbox against the pid the
690// runner saw, and outside as the control; the process list must show the
691// shell itself; the descriptor list must be whole with no pipe past 2.
692func TestF3AnySourceFails(t *testing.T) {
693 rec := loadRecording(t)
694 for _, source := range []string{"env", "ppid", "cli", "procs", "launchctl", "file0", "file0.ln", "fds"} {
695 t.Run(source, func(t *testing.T) {
696 m := newFakeMac(t)
697 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]
698 sh := shell{rec: rec, f3: map[string]string{source: line}}
699 if source == "ppid" || source == "cli" {
700 sh.f3[source+".rc"] = source + ".rc 0"
701 }
702 m.launchWith(t, cli{sh: sh, out: ok})
703 want(t, m.runA(t), "F3", wire.ProbeFailed, "token_reached:"+source)
704 })
705 }
706 cases := []struct {
707 name string
708 c cli
709 mut func(*Host)
710 detail string
711 }{
712 {"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"},
713 {"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"},
714 // Whole-branch fix 2 (Luna's check): a count, never the values.
715 {"pipe descriptor", cli{sh: shell{rec: rec, f3: map[string]string{"fds": "fds denied n=4 pipes=3"}}, out: ok}, nil, "pipe_open:1"},
716 {"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"},
717 {"descriptors cut short", cli{sh: shell{rec: rec, f3: map[string]string{"fds": "fds denied"}}, out: ok}, nil, "not_shown_tried:fds"},
718 {"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"},
719 {"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"},
720 {"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"},
721 {"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"},
722 {"reader crashed", cli{sh: shell{rec: rec, f3: map[string]string{"cli": "", "cli.rc": "cli.rc 139"}}, out: ok}, nil, "procargs_not_sandboxed"},
723 {"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"},
724 {"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"},
725 {"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"},
726 {"outside control fails", holding(t), func(h *Host) {
727 h.ProcArgs = func(int) ([]byte, error) { return nil, errors.New("no") }
728 }, "env_unreadable"},
729 {"outside control misses the marker", holding(t), func(h *Host) {
730 h.ProcArgs = func(int) ([]byte, error) { return []byte("PATH=/usr/bin"), nil }
731 }, "env_unreadable"},
732 {"token in the CLI's environment", holding(t), func(h *Host) {
733 h.ProcArgs = func(int) ([]byte, error) {
734 return []byte("EQUIPO_ATTEMPT=fprobe-x\x00CLAUDE_CODE_OAUTH_TOKEN=" + fakeToken), nil
735 }
736 }, "token_in_env"},
737 {"no reader", holding(t), func(h *Host) { h.Runner = "" }, "no_procargs_reader"},
738 {"no outside ps control", holding(t), nil, "ps_control_failed"},
739 {"not tried", cli{sh: shell{rec: rec, f3: map[string]string{"launchctl": ""}}, out: ok}, nil, "not_shown_tried:launchctl"},
740 {"a scan that failed", cli{sh: shell{rec: rec, f3: map[string]string{"env": "env failed"}}, out: ok}, nil, "not_shown_tried:env"},
741 // #2 (final review): env's producer and its control marker.
742 {"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"},
743 {"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"},
744 {"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"},
745 // #3: both ps -E attempts, each its own observation; a refused
746 // exec is a denial only with the outside control.
747 {"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"},
748 {"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"},
749 {"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"},
750 {"ps failed otherwise", cli{sh: shell{rec: rec, f3: map[string]string{"psppid.rc": "psppid.rc 1"}}, out: ok}, nil, "not_shown_tried:psppid"},
751 {"ps not tried", cli{sh: shell{rec: rec, f3: map[string]string{"psown": "", "psown.rc": "", "psown.scan": ""}}, out: ok}, nil, "not_shown_tried:psown"},
752 {"no token file", holding(t), func(h *Host) { h.TokenFiles = nil }, "no_token_file"},
753 {"secrets unreadable", holding(t), func(h *Host) {
754 h.Secrets = func(context.Context) ([][]byte, error) { return nil, errors.New("no") }
755 }, "secrets_unreadable"},
756 }
757 for _, c := range cases {
758 t.Run(c.name, func(t *testing.T) {
759 m := newFakeMac(t)
760 if c.mut != nil {
761 c.mut(&m.h)
762 }
763 if c.name == "no outside ps control" {
764 m.outside["ps"] = true
765 }
766 m.launchWith(t, c.c)
767 want(t, m.runA(t), "F3", wire.ProbeFailed, c.detail)
768 })
769 }
770}
771
772// #8 (fix round 2): the script's F3 sources, run for real with the
773// runner's reader (this test binary in its __fprobe mode) and an
774// environment holding an unrelated, token-shaped value, write only
775// bounded outcomes: the value reaches no file of the tree or the scratch,
776// and no record holds more than a name, an outcome and a count.
777func TestF3KeepsNothingRaw(t *testing.T) {
778 self, err := os.Executable()
779 if err != nil {
780 t.Fatal(err)
781 }
782 unrelated := "sk-ant-oat01-unrelated-0123456789abcdefghijklmnopqrstuvwxyz"
783 m := newFakeMac(t)
784 m.h.Runner = self
785 var records string
786 m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
787 cmd := exec.Command("sleep", "30")
788 cmd.Env = []string{"EQUIPO_ATTEMPT=fprobe-x", "CLAUDE_CODE_OAUTH_TOKEN=" + unrelated}
789 if err := cmd.Start(); err != nil {
790 t.Fatal(err)
791 }
792 defer func() { cmd.Process.Kill(); cmd.Wait() }()
793 obs.Started(cmd.Process.Pid)
794 raw, _ := os.ReadFile(s.Script)
795 script := string(raw)
796 i3, i7, i1 := strings.Index(script, "# F3"), strings.Index(script, "# F7"), strings.Index(script, "# F1")
797 if i3 < 0 || i7 < i3 || i1 < 0 {
798 t.Error("the script has no F3 block")
799 return ok
800 }
801 block, head := script[i3:i7], script[:i1]
802 run := exec.Command("bash", "-c", head+block, "probe", s.Nonce)
803 run.Env = []string{"PATH=/usr/bin:/bin", "CLAUDE_CODE_OAUTH_TOKEN=" + unrelated, "OTHER=" + base64.StdEncoding.EncodeToString([]byte(unrelated))}
804 out, _ := run.CombinedOutput()
805 if bytes.Contains(out, []byte(unrelated)) {
806 t.Errorf("the script printed the value: %s", out)
807 }
808 for _, dir := range []string{s.Tree, s.Scratch} {
809 _ = filepath.WalkDir(dir, func(p string, d os.DirEntry, err error) error {
810 if err == nil && d.Type().IsRegular() {
811 b, _ := os.ReadFile(p)
812 if bytes.Contains(b, []byte(unrelated)) || bytes.Contains(b, []byte("sk-ant-oat01-unrelated")) {
813 t.Errorf("the value reached %s", p)
814 }
815 }
816 return nil
817 })
818 }
819 b, _ := os.ReadFile(filepath.Join(s.Scratch, "out", "f3"))
820 records = string(b)
821 // The same block with env failing (a function shadows it): its own
822 // status is kept, and its empty output is failed, not denied.
823 os.Remove(filepath.Join(s.Scratch, "out", "f3"))
824 failing := exec.Command("bash", "-c", head+"env() { return 3; }\n"+block, "probe", s.Nonce)
825 failing.Env = run.Env
826 _, _ = failing.CombinedOutput()
827 b, _ = os.ReadFile(filepath.Join(s.Scratch, "out", "f3"))
828 if r := outcomes(string(b)); len(r["env"]) == 0 || r["env"][0] != "failed" || len(r["env.rc"]) == 0 || r["env.rc"][0] != "3" {
829 t.Errorf("a failed env: %q", b)
830 }
831 return ok
832 }
833 ps := m.runA(t)
834 if !strings.Contains(records, "env allowed") || !strings.Contains(records, "cli allowed "+"") {
835 t.Fatalf("the reader did not see the value in memory: %q", records)
836 }
837 // The real block keeps env's producer status beside its scan's, under
838 // its control marker, and tries ps -E of the parent and of its own
839 // processes, each its own observation.
840 for _, want := range []string{"\nenv.rc 0\n", "\nenv.scan 0\n", "psppid.rc ", "psppid.scan ", "psown.rc ", "psown.scan "} {
841 if !strings.Contains("\n"+records, want) {
842 t.Fatalf("the real F3 block records no %q: %q", strings.TrimSpace(want), records)
843 }
844 }
845 for _, l := range strings.Split(strings.TrimSpace(records), "\n") {
846 if f := strings.Fields(l); len(f) == 0 || len(f) > 4 || len(l) > 80 {
847 t.Fatalf("a record holds more than an outcome: %q", l)
848 }
849 }
850 if p := byID(ps, "F3"); p.Verdict != wire.ProbeFailed || strings.Contains(p.Detail, "unrelated") {
851 t.Fatalf("F3 %+v", p)
852 }
853}
854
855// The direct reader itself: KERN_PROCARGS2 (on Linux the same from
856// /proc) of a process this user runs shows its environment; the helper
857// mode prints a start line naming the pid, and the descriptor list ends
858// with its end line.
859func TestProcArgsHelper(t *testing.T) {
860 cmd := exec.Command("sleep", "30")
861 cmd.Env = []string{"EQUIPO_ATTEMPT=fprobe-helper"}
862 if err := cmd.Start(); err != nil {
863 t.Fatal(err)
864 }
865 defer func() { cmd.Process.Kill(); cmd.Wait() }()
866 var err error
867 var raw []byte
868 for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline) && !bytes.Contains(raw, []byte("EQUIPO_ATTEMPT")); time.Sleep(10 * time.Millisecond) {
869 raw, err = ProcArgs(cmd.Process.Pid) // once the child has exec'd
870 }
871 if err != nil || !bytes.Contains(raw, []byte("EQUIPO_ATTEMPT=fprobe-helper")) {
872 t.Fatalf("procargs: %v %q", err, raw)
873 }
874 var out bytes.Buffer
875 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") {
876 t.Fatalf("helper procargs %d %q", code, out.String())
877 }
878 out.Reset()
879 if code := HelperMain([]string{"fds"}, &out); code != 0 || !strings.Contains(out.String(), "fd 0 ") || !strings.HasSuffix(out.String(), "fds-done\n") {
880 t.Fatalf("helper fds %d %q", code, out.String())
881 }
882 // The scan modes compare in memory against hashed needles and print
883 // one bounded record: never what they read.
884 dir := t.TempDir()
885 nf := filepath.Join(dir, "needles")
886 write(t, nf, strings.Join(needleLines("token", forms(fakeToken)), "\n")+"\nshape sk-ant-oat\n")
887 if raw, _ := os.ReadFile(nf); bytes.Contains(raw, []byte(fakeToken)) || bytes.Contains(raw, []byte(base64.StdEncoding.EncodeToString([]byte(fakeToken)))) {
888 t.Fatal("the needles hold the token")
889 }
890 scan := func(stdin string, args ...string) (int, string) {
891 var out bytes.Buffer
892 code := helperMain(args, strings.NewReader(stdin), &out)
893 return code, out.String()
894 }
895 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"} {
896 if code, got := scan(in, "scan", nf, "token", "env"); code != 0 || got != want {
897 t.Fatalf("scan %q: %d %q", in, code, got)
898 }
899 }
900 // A control: the marker must be in what came, and "+" asks only that
901 // something came; otherwise the source failed.
902 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" {
903 t.Fatalf("scan with its control %d %q", code, got)
904 }
905 for _, in := range []string{"", "PATH=/bin\n"} {
906 if code, got := scan(in, "scan", nf, "token", "env", "EQUIPO_FPROBE_CONTROL=n1"); code != 1 || got != "env failed\n" {
907 t.Fatalf("scan without its control %q: %d %q", in, code, got)
908 }
909 }
910 if code, got := scan("", "scan", nf, "token", "psown", "+"); code != 1 || got != "psown failed\n" {
911 t.Fatalf("an empty source %d %q", code, got)
912 }
913 // #4: an unknown mode is a bad call, at once.
914 var bad bytes.Buffer
915 if code := HelperMain([]string{"unknown"}, &bad); code != 2 || bad.Len() != 0 {
916 t.Fatalf("unknown mode %d %q", code, bad.String())
917 }
918 if code := helperMain([]string{"nonsense", "x"}, strings.NewReader(""), &bad); code != 2 {
919 t.Fatalf("unknown mode by helperMain %d", code)
920 }
921 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" {
922 t.Fatalf("procargs-scan %d %q", code, got)
923 }
924 if code, got := scan("", "procargs-scan", nf, "cli", "999999999"); code != 1 || got != "cli refused 999999999\n" {
925 t.Fatalf("procargs-scan of nothing %d %q", code, got)
926 }
927 if code, got := scan("", "procs-scan", nf, "procs"); code != 0 || !strings.HasPrefix(got, "procs ") || !strings.HasSuffix(got, " self=yes\n") || len(got) > 60 {
928 t.Fatalf("procs-scan %d %q", code, got)
929 }
930 if code, got := scan("", "fds-scan", nf, "fds"); code != 0 || !strings.HasPrefix(got, "fds denied n=") || !strings.Contains(got, " pipes=") {
931 t.Fatalf("fds-scan %d %q", code, got)
932 }
933 if code, _ := scan("", "pids"); code != 0 {
934 t.Fatal("pids")
935 }
936 // A list that does not show the shell that asked (its control) is no
937 // list to deny from.
938 was := listPIDs
939 listPIDs = func() ([]int, error) { return []int{1}, nil }
940 code, got := scan("", "procs-scan", nf, "procs")
941 listPIDs = was
942 if code != 1 || got != "procs failed n=1 self=no\n" {
943 t.Fatalf("procs-scan without the shell %d %q", code, got)
944 }
945 out.Reset()
946 if code := HelperMain([]string{"procargs", "x"}, &out); code == 0 {
947 t.Fatal("a bad pid was read")
948 }
949 if code := HelperMain(nil, &out); code == 0 {
950 t.Fatal("no mode")
951 }
952}
953
954// F4 (#6): the runner sees the child alive in a session of its own,
955// cancels the launch, and the child must be shown gone (its pid unused or
956// used again), not merely unreadable.
957func TestF4SweepProof(t *testing.T) {
958 for _, c := range []struct {
959 name string
960 kill, proven, setsid bool
961 start bool
962 unknown bool
963 verdict, want string
964 }{
965 {"swept", true, true, true, true, false, wire.ProbePassed, "f4_passed"},
966 {"outlived", false, true, true, true, false, wire.ProbeFailed, "child_outlived"},
967 {"not proven", true, false, true, true, false, wire.ProbeFailed, "launch_unproven"},
968 {"never started", true, true, true, false, false, wire.ProbeFailed, "child_not_started"},
969 {"same session", true, true, false, true, false, wire.ProbeFailed, "child_not_own_session"},
970 {"unreadable", true, true, true, true, true, wire.ProbeFailed, "child_not_gone"},
971 } {
972 t.Run(c.name, func(t *testing.T) {
973 m := newFakeMac(t)
974 if c.unknown {
975 m.h.Alive = func(proc.ID) (bool, bool) { return false, false }
976 }
977 m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
978 in, _ := json.Marshal(map[string]string{"command": s.Command()})
979 obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: s.Permit("Bash", in)})
980 write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n")
981 var cmd *exec.Cmd
982 if c.start {
983 cmd = exec.Command("sleep", "30")
984 cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: c.setsid}
985 if err := cmd.Start(); err != nil {
986 t.Error(err)
987 return Outcome{}
988 }
989 go cmd.Wait()
990 t.Cleanup(func() { cmd.Process.Kill() })
991 write(t, filepath.Join(s.Scratch, "out", "f4.pid"), fmt.Sprint(cmd.Process.Pid))
992 }
993 select {
994 case <-ctx.Done():
995 case <-time.After(3 * time.Second):
996 }
997 if cmd != nil && c.kill {
998 cmd.Process.Kill()
999 for i := 0; i < 100; i++ {
1000 if _, alive := proc.Platform.Lookup(cmd.Process.Pid); !alive {
1001 break
1002 }
1003 time.Sleep(10 * time.Millisecond)
1004 }
1005 }
1006 write(t, filepath.Join(s.Scratch, "out", "end"), "end "+s.Nonce+"\n")
1007 return Outcome{Started: true, Proven: c.proven}
1008 }
1009 want(t, launchC(context.Background(), m.h), "F4", c.verdict, c.want)
1010 })
1011 }
1012}
1013
1014// F5 runs only after P2 is denied, under the sandboxed-Xcode settings,
1015// and is denied only when every hostile attempt is denied, the build and
1016// test completed, and no known secret in any form (#5), nor anything
1017// shaped like a token, reached the tree or the scratch.
1018func TestF5OnlyAfterP2AndNeedsTheBuild(t *testing.T) {
1019 recorded, err := os.ReadFile("testdata/synthetic-2026-11-29-tito-studio-launch-b.log")
1020 if err != nil {
1021 t.Fatal(err)
1022 }
1023 var scriptB string
1024 run := func(t *testing.T, p2 bool, log string, extra map[string]string) (*fakeMac, []Result) {
1025 m := newFakeMac(t)
1026 m.h.P2Denied = p2
1027 // The cached report's simulator is stale; the launch's own fresh
1028 // read (Live) names the new one.
1029 m.h.Simulators = []wire.Simulator{{Name: "iPhone 16", Runtime: "iOS 27.0", UDID: "00000000-0000-0000-0000-000000000000"}}
1030 m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
1031 m.mu.Lock()
1032 m.launched[s.Launch]++
1033 m.specs = append(m.specs, s)
1034 m.mu.Unlock()
1035 if s.Launch == LaunchB {
1036 raw, _ := os.ReadFile(s.Script)
1037 scriptB = string(raw)
1038 in, _ := json.Marshal(map[string]string{"command": s.Command()})
1039 obs.Ask(Ask{Tool: "Bash", Input: in, Allowed: s.Permit("Bash", in)})
1040 write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n")
1041 write(t, filepath.Join(s.Scratch, "out", "f5.log"), log)
1042 for rel, body := range extra {
1043 write(t, filepath.Join(s.Scratch, rel), body)
1044 }
1045 write(t, filepath.Join(s.Scratch, "out", "end"), "end "+s.Nonce+"\n")
1046 }
1047 return Outcome{Started: true, Proven: true}
1048 }
1049 var s Store
1050 return m, s.Run(context.Background(), m.h)
1051 }
1052 m, _ := run(t, false, string(recorded), nil)
1053 if m.launched[LaunchB] != 0 || m.launched[LaunchA] != 1 || m.launched[LaunchC] != 1 {
1054 t.Fatalf("F5 ran without P2 denied: %v", m.launched)
1055 }
1056 var s Store
1057 if p := byID(s.Probes(m.h.Inputs, time.Now(), false), "F5"); p.Verdict != wire.ProbeSkipped {
1058 t.Fatalf("F5 without P2: %+v", p)
1059 }
1060 if due := s.Due(m.h.Inputs, time.Now(), false); slices.Contains(due, LaunchB) {
1061 t.Fatalf("B due without P2 denied: %v", due)
1062 }
1063 if p := launchB(context.Background(), m.h); m.launched[LaunchB] != 0 || p[0].Verdict != wire.ProbeSkipped {
1064 t.Fatalf("launch B without P2 denied: %+v %v", p, m.launched)
1065 }
1066 m, results := run(t, true, string(recorded), nil)
1067 var order []string
1068 for _, s := range m.specs {
1069 order = append(order, s.Launch)
1070 if s.Xcode != (s.Launch == LaunchB) {
1071 t.Fatalf("launch %s Xcode %v", s.Launch, s.Xcode)
1072 }
1073 }
1074 if !slices.Equal(order, []string{LaunchA, LaunchB, LaunchC}) {
1075 t.Fatalf("order %v", order)
1076 }
1077 if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeDenied {
1078 t.Fatalf("F5 from the recording: %+v", f5)
1079 }
1080 // #1: the whole fixture, and the targets it reads, lie beside the
1081 // script, outside the tree and the scratch, and are hashed whole.
1082 sb := m.specs[1]
1083 if strings.Contains(sb.Prompt, sb.Tree+"/f5") || len(sb.Protected) != 1 || !strings.HasPrefix(sb.Protected[0], filepath.Dir(sb.Script)+"/") || sb.ProtectedSHA256 == "" {
1084 t.Fatalf("the fixture is not protected: %+v", sb)
1085 }
1086 // #7: the simulator is the one read afresh before the launch.
1087 if !strings.Contains(scriptB, "ABCDEF01-2345-6789-ABCD-EF0123456789") || strings.Contains(scriptB, "00000000-0000-0000-0000-000000000000") {
1088 t.Fatal("not the fresh simulator")
1089 }
1090 targets, _ := os.ReadFile(filepath.Join(m.specs[1].Tree, "f5", "hostile", "equipo-targets.txt"))
1091 _ = targets
1092 if left, _ := filepath.Glob(filepath.Join(m.h.Paths.AccountsRoot, "equipo-fprobe-*")); len(left) != 0 {
1093 t.Fatalf("left %v", left)
1094 }
1095 // #1: the fixture tampered with through an allowed Write or Edit
1096 // (a CLI that wrote though the runner's tool refused): the script's
1097 // Bash is then refused, and F5 never passes.
1098 for _, tool := range []string{"Write", "Edit"} {
1099 t.Run("tampered by "+tool, func(t *testing.T) {
1100 m := newFakeMac(t)
1101 var permitted, bashed bool
1102 m.h.Launch = func(ctx context.Context, s Spec, obs Observer) Outcome {
1103 if s.Launch == LaunchB {
1104 sh := filepath.Join(s.Protected[0], "project", "hostile.sh")
1105 in, _ := json.Marshal(map[string]string{"file_path": sh, "content": "say all denied"})
1106 permitted = s.Permit(tool, in)
1107 obs.Ask(Ask{Tool: tool, Input: in, Allowed: true})
1108 if err := os.WriteFile(sh, []byte("#!/bin/bash\necho all denied\n"), 0o700); err != nil {
1109 t.Error(err)
1110 }
1111 cmd, _ := json.Marshal(map[string]string{"command": s.Command()})
1112 bashed = s.Permit("Bash", cmd)
1113 obs.Ask(Ask{Tool: "Bash", Input: cmd, Allowed: bashed})
1114 write(t, filepath.Join(s.Scratch, "out", "begin"), "begin "+s.Nonce+"\n")
1115 write(t, filepath.Join(s.Scratch, "out", "f5.log"), string(recorded))
1116 write(t, filepath.Join(s.Scratch, "out", "end"), "end "+s.Nonce+"\n")
1117 }
1118 return Outcome{Started: true, Proven: true}
1119 }
1120 var st Store
1121 results := st.Run(context.Background(), m.h)
1122 if permitted || bashed {
1123 t.Fatalf("permitted the %s (%v) or the script after it (%v)", tool, permitted, bashed)
1124 }
1125 if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeFailed {
1126 t.Fatalf("F5 after tampering: %+v", f5)
1127 }
1128 })
1129 }
1130 for _, c := range []struct {
1131 name, log, detail string
1132 extra map[string]string
1133 }{
1134 {"failed build", strings.Replace(string(recorded), "EQUIPO-PHASE test-run 0", "EQUIPO-PHASE test-run 65", 1), "incomplete:test-run", nil},
1135 {"token", strings.Replace(string(recorded), "EQUIPO-PROBE test tokenfile denied", "EQUIPO-PROBE test tokenfile allowed", 1), "allowed:test.tokenfile", nil},
1136 {"a token source not collected", strings.Replace(string(recorded), "EQUIPO-PROBE test tokenfd denied\n", "", 1), "not_shown_denied:test.tokenfd", nil},
1137 {"missing line", strings.Replace(string(recorded), "warning: EQUIPO-PROBE plugin keychain denied\n", "", 1), "not_shown_denied:plugin.keychain", nil},
1138 {"no lines", "", "not_shown_denied:", nil},
1139 {"a real token", string(recorded), "reached_scratch:secret", map[string]string{"DerivedData/x.log": "token " + base64.StdEncoding.EncodeToString([]byte(fakeToken)) + "\n"}},
1140 {"a token shape", string(recorded), "reached_scratch:token-shape", map[string]string{"DerivedData/y.log": "sk-ant-oat01-somebody\n"}},
1141 } {
1142 t.Run(c.name, func(t *testing.T) {
1143 _, results := run(t, true, c.log, c.extra)
1144 coded(t, results[1].Probes)
1145 if f5 := byID(results[1].Probes, "F5"); f5.Verdict != wire.ProbeFailed || !strings.Contains(f5.Detail, c.detail) {
1146 t.Fatalf("%+v", f5)
1147 }
1148 })
1149 }
1150}
1151
1152// F6 (#2, #7): evidence only from the CLI's own events and the runner's
1153// own records. Each prompted call needs a tool_use and a refusal (the
1154// runner's tool's, or the CLI's error result); model notes never count.
1155// The runner's setup (links, the swap's alternation, the late name) must
1156// each have succeeded; a failed setup is not a denial.
1157func TestF6SwapRace(t *testing.T) {
1158 rec := loadRecording(t)
1159 m := newFakeMac(t)
1160 seen := map[string]bool{}
1161 c := holding(t)
1162 c.before = func(s Spec) {
1163 for deadline := time.Now().Add(3 * time.Second); len(seen) < 2 && time.Now().Before(deadline); time.Sleep(300 * time.Microsecond) {
1164 if to, err := os.Readlink(filepath.Join(s.Tree, "f6", "swap")); err == nil {
1165 seen[filepath.Base(filepath.Dir(to))] = true
1166 }
1167 }
1168 }
1169 m.launchWith(t, c)
1170 want(t, m.runA(t), "F6", wire.ProbeDenied, "f6_denied:")
1171 if len(seen) != 2 {
1172 t.Fatalf("the link was not swapped while the launch ran: %v", seen)
1173 }
1174 for _, cs := range []struct {
1175 name, detail string
1176 md model
1177 verdict string
1178 }{
1179 {"refused by the CLI", "", model{noAsk: true}, wire.ProbeDenied},
1180 {"notes only", "not_shown_made:", model{notes: true}, wire.ProbeFailed},
1181 {"no events", "not_shown_made:", model{noUse: true}, wire.ProbeFailed},
1182 {"race won", "reached_model", model{race: true}, wire.ProbeFailed},
1183 {"late name", "reached_model", model{late: true}, wire.ProbeFailed},
1184 {"forty-nine", "not_shown_made:S50", model{skip: map[string]bool{"S50": true}}, wire.ProbeFailed},
1185 {"allowed", "allowed:C5", model{allow: map[string]bool{"C5": true}}, wire.ProbeFailed},
1186 {"allowed by the CLI", "allowed:C5", model{noAsk: true, leak: map[string]bool{"C5": true}}, wire.ProbeFailed},
1187 {"no control", "control_read_missing", model{noCtl: true}, wire.ProbeFailed},
1188 {"a control the model made up", "control_read_missing", model{ctlText: "EQUIPO-NONCE-0123"}, wire.ProbeFailed},
1189 {"not a whole-file read", "not_prescribed:C1", model{offset: map[string]bool{"C1": true}}, wire.ProbeFailed},
1190 {"a swap read past the start", "not_prescribed:S7", model{offset: map[string]bool{"S7": true}}, wire.ProbeFailed},
1191 {"another grep pattern", "not_prescribed:C2", model{pattern: map[string]string{"C2": "nothing"}}, wire.ProbeFailed},
1192 {"an execution error is no refusal", "allowed:C5", model{execErr: map[string]bool{"C5": true}}, wire.ProbeFailed},
1193 // #1 (final review): a swap read or the late Grep needs a refusal
1194 // or a benign observation, never an execution error.
1195 {"an execution error on a swap read", "unobserved:S7", model{execErr: map[string]bool{"S7": true}}, wire.ProbeFailed},
1196 {"an execution error on the late Grep", "unobserved:L1", model{execErr: map[string]bool{"L1": true}}, wire.ProbeFailed},
1197 {"benign swap reads observed", "", model{benign: true}, wire.ProbeDenied},
1198 {"a swap read that showed nothing", "unobserved:S", model{benign: true, blank: true}, wire.ProbeFailed},
1199 } {
1200 t.Run(cs.name, func(t *testing.T) {
1201 m := newFakeMac(t)
1202 m.launchWith(t, cli{sh: shell{rec: rec}, md: cs.md, out: ok})
1203 want(t, m.runA(t), "F6", cs.verdict, cs.detail)
1204 })
1205 }
1206 t.Run("shell hard link", func(t *testing.T) {
1207 m := newFakeMac(t)
1208 m.launchWith(t, cli{sh: shell{rec: rec, link: true}, out: ok})
1209 want(t, m.runA(t), "F6", wire.ProbeFailed, "hard_linked:")
1210 })
1211 for name, c := range map[string]struct {
1212 seam func()
1213 want string
1214 }{
1215 "a link": {func() { symlink = func(string, string) error { return errors.New("no") } }, "link-0"},
1216 "a hard link": {func() { hardlink = func(string, string) error { return errors.New("no") } }, "hardlink-0"},
1217 "the swap": {func() { rename = func(string, string) error { return errors.New("no") } }, "swap"},
1218 "late_name": {func() {
1219 was := symlink
1220 symlink = func(o, n string) error {
1221 if strings.HasSuffix(n, "/late/x") {
1222 return errors.New("no")
1223 }
1224 return was(o, n)
1225 }
1226 }, "late_name"},
1227 } {
1228 t.Run("setup: "+name, func(t *testing.T) {
1229 s1, h1, r1 := symlink, hardlink, rename
1230 t.Cleanup(func() { symlink, hardlink, rename = s1, h1, r1 })
1231 m := newFakeMac(t)
1232 c.seam()
1233 m.launchWith(t, cli{sh: shell{rec: rec}, out: ok})
1234 if p := byID(m.runA(t), "F6"); p.Verdict != wire.ProbeFailed || !strings.Contains(p.Detail, "not_set_up:") || !strings.Contains(p.Detail, c.want) {
1235 t.Fatalf("%s: %+v", name, p)
1236 }
1237 })
1238 }
1239
1240}
1241
1242// F7: inside the sandbox each Xcode attempt fails, and outside each
1243// works (the control).
1244func TestF7NeedsTheOutsideControl(t *testing.T) {
1245 rec := loadRecording(t)
1246 for _, c := range []struct {
1247 name, outside, detail string
1248 sh shell
1249 }{
1250 {"control", "xcodebuild -list", "control_failed:xcodebuild", shell{rec: rec}},
1251 {"simctl", "", "allowed:simctl", shell{rec: rec, codes: map[string]string{"simctl": "0"}}},
1252 {"lookup", "", "allowed:mach", shell{rec: rec, files: map[string]string{"out/f7.mach": "port\n"}}},
1253 {"missing", "", "not_shown_denied:xcodebuild", shell{rec: rec, drop: map[string]bool{"xcodebuild": true}}},
1254 } {
1255 t.Run(c.name, func(t *testing.T) {
1256 m := newFakeMac(t)
1257 if c.outside != "" {
1258 m.outside[c.outside] = true
1259 }
1260 m.launchWith(t, cli{sh: c.sh, out: ok})
1261 want(t, m.runA(t), "F7", wire.ProbeFailed, c.detail)
1262 })
1263 }
1264 m := newFakeMac(t)
1265 m.h.Tools = mac.Tools{}
1266 m.launchWith(t, holding(t))
1267 want(t, m.runA(t), "F7", wire.ProbeUnavailable, "no_xcode")
1268}
1269
1270// The launch's own end decides first: one that never started says
1271// nothing (tried again later); one whose end is not proven fails all.
1272func TestProbeLaunchOutcome(t *testing.T) {
1273 m := newFakeMac(t)
1274 m.launchWith(t, cli{sh: shell{rec: loadRecording(t)}, out: Outcome{Reason: "account_unavailable"}})
1275 for _, p := range m.runA(t) {
1276 if p.Verdict != wire.ProbeUnavailable || !strings.Contains(p.Detail, "launch_not_started:account_unavailable") {
1277 t.Fatalf("%+v", p)
1278 }
1279 }
1280 m = newFakeMac(t)
1281 m.launchWith(t, cli{sh: shell{rec: loadRecording(t)}, out: Outcome{Started: true}})
1282 for _, p := range m.runA(t) {
1283 if p.Verdict != wire.ProbeFailed {
1284 t.Fatalf("%+v", p)
1285 }
1286 }
1287}
1288
1289func allPassed(in Inputs, at time.Time) []Result {
1290 var out []Result
1291 for _, l := range Launches {
1292 r := Result{Launch: l, Inputs: in, At: at}
1293 for _, id := range launchProbes[l] {
1294 r.Probes = append(r.Probes, wire.Probe{ID: id, Verdict: wire.EngineeringProbeSuccess(id), Detail: wire.ProbeDetail("f1_denied")})
1295 }
1296 out = append(out, r)
1297 }
1298 return out
1299}
1300
1301func readyState(probes []wire.Probe) State {
1302 return State{CLI: true, Probes: probes, P2: wire.ProbeDenied}
1303}
1304
1305// Each launch's result counts only for the inputs it ran under and for
1306// under a day: a stale launch A beside a fresh launch C is not ready.
1307func TestProbeLaunchesAggregate(t *testing.T) {
1308 now := time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC)
1309 in := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B52"}, []wire.Simulator{{Runtime: "iOS 27.2"}})
1310 var s Store
1311 for _, r := range allPassed(in, now.Add(-time.Hour)) {
1312 s.Put(r)
1313 }
1314 if st := Status(readyState(s.Probes(in, now, true))); st.State != wire.EngineeringReady {
1315 t.Fatalf("all fresh: %+v", st)
1316 }
1317 s.Put(allPassed(in, now.Add(-25*time.Hour))[0])
1318 ps := s.Probes(in, now, true)
1319 if st := Status(readyState(ps)); st.State != wire.EngineeringProbesPending || st.Reason != "F1 F2 F3 F6 F7" {
1320 t.Fatalf("stale A, fresh C: %+v", st)
1321 }
1322 if p := byID(ps, "F4"); p.Verdict != wire.ProbePassed {
1323 t.Fatalf("C is fresh: %+v", p)
1324 }
1325 if p := byID(ps, "F1"); p.Verdict != wire.ProbeUnavailable || p.Detail != "expired" {
1326 t.Fatalf("A is stale: %+v", p)
1327 }
1328 if due := s.Due(in, now, true); !slices.Equal(due, []string{LaunchA}) {
1329 t.Fatalf("due %v", due)
1330 }
1331 s.Put(allPassed(in, now.Add(time.Hour))[0])
1332 if p := byID(s.Probes(in, now, true), "F1"); p.Verdict != wire.ProbeUnavailable || p.Detail != "future" {
1333 t.Fatalf("future: %+v", p)
1334 }
1335 var u Store
1336 u.Put(Result{Launch: LaunchA, Inputs: in, At: now, Probes: all(LaunchA, wire.ProbeUnavailable, "x")})
1337 u.try(LaunchA, in, now)
1338 if due := u.Due(in, now.Add(time.Minute), false); slices.Contains(due, LaunchA) {
1339 t.Fatalf("retried at once: %v", due)
1340 }
1341 if due := u.Due(in, now.Add(Retry), false); !slices.Contains(due, LaunchA) {
1342 t.Fatalf("not retried: %v", due)
1343 }
1344 var f Store
1345 for _, r := range allPassed(in, now) {
1346 f.Put(r)
1347 }
1348 if due := f.Due(in, now.Add(22*time.Hour), true); len(due) != 0 {
1349 t.Fatalf("a fresh result run again: %v", due)
1350 }
1351 if due := f.Due(in, now.Add(Refresh), true); !slices.Equal(due, []string{LaunchA, LaunchB, LaunchC}) {
1352 t.Fatalf("not refreshed: %v", due)
1353 }
1354 if due := f.Due(Inputs{Runner: "v1.0.0", Settings: in.Settings}, now, true); len(due) != 0 {
1355 t.Fatalf("due without a verified CLI: %v", due)
1356 }
1357}
1358
1359// A new Xcode build, a new simulator runtime, a new CLI digest, a new
1360// runner or new settings each make the results not count. Inputs are
1361// read afresh for each launch (#9): ones that change while it runs make
1362// its result undecided.
1363func TestProbeInputsInvalidate(t *testing.T) {
1364 now := time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC)
1365 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"}})
1366 if in.Runtimes != "iOS 27.0, iOS 27.2" || in.Xcode != "27.2 (27B52)" || in.CLI == "" || in.Settings == "" || strings.HasPrefix(in.Settings, "unmade") {
1367 t.Fatalf("inputs %+v", in)
1368 }
1369 if NewInputs("v1.0.0", false, wire.Xcode{}, nil).CLI != "" {
1370 t.Fatal("an unverified CLI has a digest")
1371 }
1372 for _, c := range []struct {
1373 name string
1374 next Inputs
1375 why string
1376 }{
1377 {"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"},
1378 {"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"},
1379 {"cli digest", Inputs{Runner: in.Runner, Settings: in.Settings, CLI: strings.Repeat("0", 64), Xcode: in.Xcode, Runtimes: in.Runtimes}, "stale_cli"},
1380 {"runner", Inputs{Runner: "v1.0.1", Settings: in.Settings, CLI: in.CLI, Xcode: in.Xcode, Runtimes: in.Runtimes}, "stale_runner"},
1381 {"settings", Inputs{Runner: in.Runner, Settings: "0000", CLI: in.CLI, Xcode: in.Xcode, Runtimes: in.Runtimes}, "stale_settings"},
1382 } {
1383 t.Run(c.name, func(t *testing.T) {
1384 var s Store
1385 for _, r := range allPassed(in, now) {
1386 s.Put(r)
1387 }
1388 ps := s.Probes(c.next, now, true)
1389 for _, id := range wire.EngineeringProbeIDs {
1390 if p := byID(ps, id); p.Verdict != wire.ProbeUnavailable || p.Detail != c.why {
1391 t.Fatalf("%s %+v", id, p)
1392 }
1393 }
1394 if st := Status(readyState(ps)); st.State != wire.EngineeringProbesPending {
1395 t.Fatalf("%+v", st)
1396 }
1397 if due := s.Due(c.next, now, true); !slices.Equal(due, Launches) {
1398 t.Fatalf("due %v", due)
1399 }
1400 if XcodeAllowed(ps) {
1401 t.Fatal("Xcode access kept across a change")
1402 }
1403 })
1404 }
1405 // The inputs each launch runs under are read afresh, and a change
1406 // while it runs leaves it undecided.
1407 m := newFakeMac(t)
1408 m.launchWith(t, holding(t))
1409 var mu sync.Mutex
1410 calls := 0
1411 changed := NewInputs("v1.0.0", true, wire.Xcode{Version: "27.2", Build: "27B53"}, m.h.Simulators)
1412 m.h.Live = func(context.Context) (Inputs, []wire.Simulator) {
1413 mu.Lock()
1414 defer mu.Unlock()
1415 calls++
1416 if calls > 2 {
1417 return changed, m.h.Simulators
1418 }
1419 return m.h.Inputs, m.h.Simulators
1420 }
1421 var s Store
1422 results := s.Run(context.Background(), m.h)
1423 if len(results) == 0 || results[0].Inputs != m.h.Inputs {
1424 t.Fatalf("results %+v", results)
1425 }
1426 for _, p := range results[0].Probes {
1427 if p.Verdict != wire.ProbeUnavailable || !strings.Contains(p.Detail, "inputs_changed") {
1428 t.Fatalf("%+v", p)
1429 }
1430 }
1431}
1432
1433// The status names the first thing missing, in order: the guards, the
1434// CLI, a failed probe, the connection, probes not yet proven; ready only
1435// with everything, a connection included. F5 decides only Xcode access.
1436func TestEngineeringStatusOrder(t *testing.T) {
1437 now := time.Now()
1438 in := NewInputs("v1", true, wire.Xcode{}, nil)
1439 var s Store
1440 for _, r := range allPassed(in, now) {
1441 s.Put(r)
1442 }
1443 passed := s.Probes(in, now, true)
1444 failedF2 := slices.Clone(passed)
1445 failedF2[1] = wire.Probe{ID: "F2", Verdict: wire.ProbeFailed}
1446 pendingF4 := slices.Clone(passed)
1447 pendingF4[3] = wire.Probe{ID: "F4", Verdict: wire.ProbeUnavailable}
1448 noF5 := slices.Clone(passed)
1449 noF5[4] = wire.Probe{ID: "F5", Verdict: wire.ProbeFailed}
1450 tainted := &wire.EngineeringStatus{State: wire.EngineeringTainted}
1451 home := &wire.EngineeringStatus{State: wire.EngineeringHomeOpen, Reason: "home_mode"}
1452 for _, c := range []struct {
1453 name string
1454 s State
1455 want wire.EngineeringStatus
1456 }{
1457 {"ready", State{CLI: true, Probes: passed, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringReady}},
1458 {"F5 does not decide", State{CLI: true, Probes: noF5, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringReady}},
1459 // Whole-branch fix 2, #5: the scanner's sandbox is P2's.
1460 {"P2 not run", State{CLI: true, Probes: passed}, wire.EngineeringStatus{State: wire.EngineeringProbesPending, Reason: "P2"}},
1461 {"P2 not denied", State{CLI: true, Probes: passed, P2: wire.ProbeFailed}, wire.EngineeringStatus{State: wire.EngineeringProbesFailed, Reason: "P2"}},
1462 {"P2 unavailable", State{CLI: true, Probes: passed, P2: wire.ProbeUnavailable}, wire.EngineeringStatus{State: wire.EngineeringProbesFailed, Reason: "P2"}},
1463 {"F2 and P2", State{CLI: true, Probes: failedF2, P2: wire.ProbeFailed}, wire.EngineeringStatus{State: wire.EngineeringProbesFailed, Reason: "F2 P2"}},
1464 {"tainted first", State{Guards: tainted, Probes: failedF2, Conn: wire.EngineeringNoConnection}, *tainted},
1465 {"home open", State{Guards: home, Probes: failedF2}, *home},
1466 {"cli", State{Probes: failedF2, Conn: wire.EngineeringNoConnection}, wire.EngineeringStatus{State: wire.EngineeringCLIUnpinned}},
1467 {"failed before the connection", State{CLI: true, Probes: failedF2, Conn: wire.EngineeringNoConnection}, wire.EngineeringStatus{State: wire.EngineeringProbesFailed, Reason: "F2"}},
1468 {"no connection", State{CLI: true, Probes: passed, Conn: wire.EngineeringNoConnection, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringNoConnection}},
1469 {"connection before pending", State{CLI: true, Probes: pendingF4, Conn: wire.EngineeringLimited}, wire.EngineeringStatus{State: wire.EngineeringLimited}},
1470 {"signed out", State{CLI: true, Probes: passed, Conn: wire.EngineeringSignedOut, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringSignedOut}},
1471 {"pending", State{CLI: true, Probes: pendingF4, P2: wire.ProbeDenied}, wire.EngineeringStatus{State: wire.EngineeringProbesPending, Reason: "F4"}},
1472 {"nothing run", State{CLI: true}, wire.EngineeringStatus{State: wire.EngineeringProbesPending, Reason: "F1 F2 F3 F4 F6 F7 P2"}},
1473 } {
1474 if got := Status(c.s); got != c.want {
1475 t.Fatalf("%s: %+v, want %+v", c.name, got, c.want)
1476 }
1477 if err := wire.ValidCapabilities(wire.Capabilities{Engineering: &c.want}); err != nil {
1478 t.Fatalf("%s: %v", c.name, err)
1479 }
1480 }
1481 if !XcodeAllowed(passed) || XcodeAllowed(noF5) {
1482 t.Fatal("Xcode access follows F5")
1483 }
1484 held := []wire.HeldConnection{{LocalID: "m", Provider: wire.ProviderClaude, Kind: wire.KindSubscription, State: wire.ConnHealthy}}
1485 if got := ConnState(held, func(string) bool { return true }); got != wire.EngineeringNoConnection {
1486 t.Fatalf("a subscription connection is not a Mac's: %q", got)
1487 }
1488 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})
1489 if got := ConnState(held, func(string) bool { return false }); got != wire.EngineeringLimited {
1490 t.Fatalf("limited: %q", got)
1491 }
1492 if got := ConnState(held[:2], func(string) bool { return false }); got != wire.EngineeringSignedOut {
1493 t.Fatalf("signed out: %q", got)
1494 }
1495 if got := ConnState(held, func(id string) bool { return id == "a" }); got != "" {
1496 t.Fatalf("usable: %q", got)
1497 }
1498}
1499
1500// A probe run is one turn: busy, nothing launches and every probe says
1501// so by a code the instance words; tried again after Retry.
1502func TestProbeRunTakesTheTurn(t *testing.T) {
1503 m := newFakeMac(t)
1504 m.launchWith(t, holding(t))
1505 m.h.Turns = mac.NewTurns("")
1506 held, err := m.h.Turns.Take(context.Background(), mac.OpEngineering)
1507 if err != nil {
1508 t.Fatal(err)
1509 }
1510 ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
1511 defer cancel()
1512 var s Store
1513 results := s.Run(ctx, m.h)
1514 held.Give()
1515 if len(m.launched) != 0 || len(results) != 3 {
1516 t.Fatalf("launched %v results %d", m.launched, len(results))
1517 }
1518 for _, r := range results {
1519 for _, p := range r.Probes {
1520 if p.Verdict != wire.ProbeUnavailable || p.Detail != wire.ProbeDetailTurnBusy {
1521 t.Fatalf("%+v", p)
1522 }
1523 }
1524 }
1525 if due := s.Due(m.h.Inputs, time.Now(), true); len(due) != 0 {
1526 t.Fatalf("retried at once: %v", due)
1527 }
1528}
1529