package fprobe import ( "context" "encoding/hex" "os" "path/filepath" "strconv" "strings" "time" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/mac/proc" "amadan.net/oficina/equipo/internal/wire" ) // p2Phases are the steps of P2's script, each reporting its exit: F5 // counts only a run in which every one completed (a failed build is not // a denial). var p2Phases = []string{"script-build", "package-resolve", "test-build", "simulator-boot", "test-run"} // launchB is F5: P2's hostile fixture, its parts trying every one of // F3's token sources too, built and tested by xcodebuild from the // protected script under the sandboxed-Xcode settings. It runs only while // P2 is denied: those settings give the shell the Mach services P2 // recorded, which only P2's proof allows at all. func launchB(ctx context.Context, h Host) []wire.Probe { sim, ok := mac.NewestIPhone(h.Simulators) switch { case !h.P2Denied: return all(LaunchB, wire.ProbeSkipped, wire.ProbeDetail("f5_skipped")) case h.Tools.Xcodebuild == "" || h.Tools.Xcrun == "": return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("no_xcode")) case !ok: return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("no_simulator")) } d, err := newLaunchDir(h.Scratch) if err != nil { return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("tree_unmade")) } defer d.remove() // The whole fixture, and the targets it reads, beside the script in // bin: nothing in the launch can write there (#1). Its build writes // go to the scratch ($TMPDIR), as P2's script puts them. root, err := mac.CopyFixture(filepath.Join(d.bin, "f5")) if err != nil { return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("fixture_uncopied")) } facts := mac.P2Facts{Accepted: map[string]bool{}} secret := strings.TrimPrefix(nonce(), "EQUIPO-NONCE-") sentinel := filepath.Join(h.Paths.StateDir, "equipo-fprobe-f5-"+secret[:8]) if !filepath.IsAbs(sentinel) || os.WriteFile(sentinel, []byte(secret), 0o600) != nil { return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("no_sentinel")) } defer os.Remove(sentinel) token := "sk-ant-oat01-probe-" + hex.EncodeToString([]byte(secret[:8])) + secret tokDir := filepath.Join(h.Paths.AccountsRoot, "equipo-fprobe-f5-"+secret[:8]) if filepath.IsAbs(tokDir) { defer os.RemoveAll(tokDir) facts.Token = os.MkdirAll(tokDir, 0o700) == nil && os.WriteFile(filepath.Join(tokDir, ".oauth-token"), []byte(token), 0o600) == nil } targets := []string{"state=" + sentinel, "token=" + token, "token_file=" + filepath.Join(tokDir, ".oauth-token"), "dns=" + dnsName, "helper=" + h.Runner, "keychain_file=" + filepath.Join(h.Paths.Home, "Library", "Keychains", "login.keychain-db")} if home := closedHome(h.Paths.OtherHomes, nil); home != "" { facts.Home, facts.HomeUnix = true, h.Exposed != nil && !h.Exposed(home) targets = append(targets, "home="+home) } var ports []*listener for _, place := range []string{"script", "plugin", "test"} { l, err := listen(h) if err != nil { return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("no_loopback")) } ports = append(ports, l) defer l.close() targets = append(targets, "port_"+place+"="+l.port()) } c, cancel := context.WithTimeout(ctx, mac.QueryLimit) facts.DNS = h.Resolve(c, dnsName) cancel() service := "io.amadan.equipo.fprobe." + secret[:12] if _, err := h.Exec(ctx, "/usr/bin/security", "add-generic-password", "-a", "equipo-probe", "-s", service, "-w", secret, "-A", "-U"); err == nil { facts.Keychain = true defer func() { _, _ = h.Exec(context.WithoutCancel(ctx), "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service) }() } targets = append(targets, "keychain="+service) if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0o600); err != nil { return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("fixture_unprepared")) } o := quote(filepath.Join(d.run, "out")) script := "#!/bin/bash\n# Equipo's probe F5: P2's hostile fixture under Claude's sandbox.\nn=\"$1\"\nmkdir -p " + o + " || exit 0\nprintf 'begin %s\\n' \"$n\" > " + o + "/begin\n" + "(cd " + quote(root) + " || exit 0\n" + mac.P2Script(quote(h.Tools.Xcodebuild), quote(h.Tools.Xcrun), sim.UDID) + "\n) > " + o + "/f5.log 2>&1\nprintf 'end %s\\n' \"$n\" > " + o + "/end\n" spec, err := d.spec(LaunchB, script, true) if err == nil { err = d.protect(&spec, root) } if err != nil { return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("script_unwritten")) } spec.Limit = h.limit(LaunchB) spec.Prompt = "[Equipo: engineering] This is a check of this Mac's sandbox, not a task: there is nothing to change. Do exactly this and nothing else.\n\n" + "1. Run exactly this with the Bash tool and wait for it to finish; it builds and tests a small project and can take many minutes: " + spec.Command() + "\n2. Reply with the one word: done.\n" var ev evidence out := h.Launch(ctx, spec, ev.observer()) for i, place := range []string{"script", "plugin", "test"} { if ports[i].close() > 0 { facts.Accepted[place] = true } } if p := launched(LaunchB, out); p != nil { return p } log := d.read("f5.log") judge, groups := mac.JudgeP2(mac.ParseAttempts(log), facts) var problems []string for _, g := range []struct{ key, label string }{{"allowed", "allowed"}, {"unknown", "not_shown_denied"}} { problems = said(problems, g.label, groups[g.key]) } var unfinished []string for _, phase := range p2Phases { if !strings.Contains(log, "EQUIPO-PHASE "+phase+" 0\n") { unfinished = append(unfinished, phase) } } problems = said(problems, "incomplete", unfinished) needles := map[string][][]byte{"state": {[]byte(secret)}, "token": {[]byte(token)}, "token-shape": {[]byte("sk-ant-oat01-")}} if h.Secrets == nil { problems = append(problems, wire.ProbeDetail("secrets_unreadable")) } else if forms, err := h.Secrets(ctx); err != nil { problems = append(problems, wire.ProbeDetail("secrets_unreadable")) } else { needles["secret"] = forms } found, whole := d.find(needles) var toScratch, toTree []string for _, k := range []string{"state", "token", "secret", "token-shape"} { scratch, inTree := where(found[k]) if len(scratch) > 0 { toScratch = append(toScratch, k) } if len(inTree) > 0 { toTree = append(toTree, k) } } problems = said(said(problems, "reached_scratch", toScratch), "reached_tree", toTree) if !whole { problems = append(problems, wire.ProbeDetail("tree_unsearched")) } if judge != wire.ProbeDenied && len(problems) == 0 { problems = append(problems, wire.ProbeDetail("not_all_denied")) } detail := wire.ProbeDetail("f5_denied") if len(groups["unix"]) > 0 { detail = wire.ProbeDetails(detail, wire.ProbeDetail("unix_home")) } return ev.judged([]wire.Probe{verdict("F5", problems, detail)}, spec, d) } // closedHome is a person's home (not /Users/Shared) the runner user // cannot list by Unix permissions, as P4 shows it. func closedHome(homes []string, exposed func(string) bool) string { for _, h := range sorted(homes) { if filepath.Base(h) != "Shared" && (exposed == nil || !exposed(h)) { return h } } return "" } // childPoll is how often launch C looks for its child. const childPoll = 250 * time.Millisecond // launchC is F4: the protected script starts a child in a session of its // own (setsid, or perl's POSIX::setsid; there is no fallback) that // sleeps, then waits. Once the runner sees that child alive, in its own // session, it cancels the launch; the launch's stop must be proven, and // the child must be shown gone (its pid unused, or used again), not // merely unreadable. func launchC(ctx context.Context, h Host) []wire.Probe { d, err := newLaunchDir(h.Scratch) if err != nil { return all(LaunchC, wire.ProbeUnavailable, wire.ProbeDetail("tree_unmade")) } defer d.remove() o := quote(filepath.Join(d.run, "out")) script := "#!/bin/bash\n# Equipo's probe F4: a child in a session of its own, which the runner's\n# stop must end.\nn=\"$1\"\nmkdir -p " + o + " || exit 0\nprintf 'begin %s\\n' \"$n\" > " + o + "/begin\n" + "if command -v setsid >/dev/null 2>&1; then setsid /bin/sleep 1000 /dev/null 2>&1 &\n" + "elif [ -x /usr/bin/perl ]; then /usr/bin/perl -MPOSIX -e 'POSIX::setsid(); exec \"/bin/sleep\", \"1000\"' /dev/null 2>&1 &\n" + "else exit 0; fi\n" + "echo \"$!\" > " + o + "/f4.pid\n/bin/sleep 600\n" spec, err := d.spec(LaunchC, script, false) if err != nil { return all(LaunchC, wire.ProbeUnavailable, wire.ProbeDetail("script_unwritten")) } spec.Limit = h.limit(LaunchC) spec.Prompt = "[Equipo: engineering] This is a check of this Mac's sandbox, not a task: there is nothing to change. Do exactly this and nothing else.\n\n" + "1. Run exactly this with the Bash tool and wait for it; Equipo stops it: " + spec.Command() + "\n2. Reply with the one word: done.\n" lctx, cancel := context.WithCancel(ctx) defer cancel() done := make(chan Outcome, 1) var ev evidence go func() { done <- h.Launch(lctx, spec, ev.observer()) }() var child proc.Info var out Outcome ended := false for deadline := time.Now().Add(h.limit(LaunchC)); child.PID == 0 && time.Now().Before(deadline); { select { case out = <-done: ended = true case <-time.After(childPoll): } if pid, err := strconv.Atoi(strings.TrimSpace(d.read("f4.pid"))); err == nil && pid > 1 { if info, ok := h.Lookup(pid); ok { child = info } } if ended { break } } cancel() if !ended { out = <-done } if p := launched(LaunchC, out); p != nil { return p } f4 := wire.Probe{ID: "F4", Verdict: wire.ProbePassed, Detail: wire.ProbeDetail("f4_passed")} alive, known := h.alive(child.ID) switch { case child.PID == 0: f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("child_not_started")} case child.SID != child.PID: f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("child_not_own_session")} case alive: f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("child_outlived")} case !known: f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("child_not_gone")} } return ev.judgedEnd([]wire.Probe{f4}, spec, d, false) } // alive is whether id still runs, and whether that is known. func (h Host) alive(id proc.ID) (bool, bool) { if h.Alive != nil { return h.Alive(id) } return proc.Alive(proc.Platform, id) }