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 "context"
5 "encoding/hex"
6 "os"
7 "path/filepath"
8 "strconv"
9 "strings"
10 "time"
11
12 "amadan.net/oficina/equipo/internal/runner/mac"
13 "amadan.net/oficina/equipo/internal/runner/mac/proc"
14 "amadan.net/oficina/equipo/internal/wire"
15)
16
17// p2Phases are the steps of P2's script, each reporting its exit: F5
18// counts only a run in which every one completed (a failed build is not
19// a denial).
20var p2Phases = []string{"script-build", "package-resolve", "test-build", "simulator-boot", "test-run"}
21
22// launchB is F5: P2's hostile fixture, its parts trying every one of
23// F3's token sources too, built and tested by xcodebuild from the
24// protected script under the sandboxed-Xcode settings. It runs only while
25// P2 is denied: those settings give the shell the Mach services P2
26// recorded, which only P2's proof allows at all.
27func launchB(ctx context.Context, h Host) []wire.Probe {
28 sim, ok := mac.NewestIPhone(h.Simulators)
29 switch {
30 case !h.P2Denied:
31 return all(LaunchB, wire.ProbeSkipped, wire.ProbeDetail("f5_skipped"))
32 case h.Tools.Xcodebuild == "" || h.Tools.Xcrun == "":
33 return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("no_xcode"))
34 case !ok:
35 return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("no_simulator"))
36 }
37 d, err := newLaunchDir(h.Scratch)
38 if err != nil {
39 return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("tree_unmade"))
40 }
41 defer d.remove()
42 // The whole fixture, and the targets it reads, beside the script in
43 // bin: nothing in the launch can write there (#1). Its build writes
44 // go to the scratch ($TMPDIR), as P2's script puts them.
45 root, err := mac.CopyFixture(filepath.Join(d.bin, "f5"))
46 if err != nil {
47 return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("fixture_uncopied"))
48 }
49 facts := mac.P2Facts{Accepted: map[string]bool{}}
50 secret := strings.TrimPrefix(nonce(), "EQUIPO-NONCE-")
51 sentinel := filepath.Join(h.Paths.StateDir, "equipo-fprobe-f5-"+secret[:8])
52 if !filepath.IsAbs(sentinel) || os.WriteFile(sentinel, []byte(secret), 0o600) != nil {
53 return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("no_sentinel"))
54 }
55 defer os.Remove(sentinel)
56 token := "sk-ant-oat01-probe-" + hex.EncodeToString([]byte(secret[:8])) + secret
57 tokDir := filepath.Join(h.Paths.AccountsRoot, "equipo-fprobe-f5-"+secret[:8])
58 if filepath.IsAbs(tokDir) {
59 defer os.RemoveAll(tokDir)
60 facts.Token = os.MkdirAll(tokDir, 0o700) == nil && os.WriteFile(filepath.Join(tokDir, ".oauth-token"), []byte(token), 0o600) == nil
61 }
62 targets := []string{"state=" + sentinel, "token=" + token, "token_file=" + filepath.Join(tokDir, ".oauth-token"), "dns=" + dnsName, "helper=" + h.Runner,
63 "keychain_file=" + filepath.Join(h.Paths.Home, "Library", "Keychains", "login.keychain-db")}
64 if home := closedHome(h.Paths.OtherHomes, nil); home != "" {
65 facts.Home, facts.HomeUnix = true, h.Exposed != nil && !h.Exposed(home)
66 targets = append(targets, "home="+home)
67 }
68 var ports []*listener
69 for _, place := range []string{"script", "plugin", "test"} {
70 l, err := listen(h)
71 if err != nil {
72 return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("no_loopback"))
73 }
74 ports = append(ports, l)
75 defer l.close()
76 targets = append(targets, "port_"+place+"="+l.port())
77 }
78 c, cancel := context.WithTimeout(ctx, mac.QueryLimit)
79 facts.DNS = h.Resolve(c, dnsName)
80 cancel()
81 service := "io.amadan.equipo.fprobe." + secret[:12]
82 if _, err := h.Exec(ctx, "/usr/bin/security", "add-generic-password", "-a", "equipo-probe", "-s", service, "-w", secret, "-A", "-U"); err == nil {
83 facts.Keychain = true
84 defer func() {
85 _, _ = h.Exec(context.WithoutCancel(ctx), "/usr/bin/security", "delete-generic-password", "-a", "equipo-probe", "-s", service)
86 }()
87 }
88 targets = append(targets, "keychain="+service)
89 if err := os.WriteFile(filepath.Join(root, "equipo-targets.txt"), []byte(strings.Join(targets, "\n")+"\n"), 0o600); err != nil {
90 return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("fixture_unprepared"))
91 }
92 o := quote(filepath.Join(d.run, "out"))
93 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" +
94 "(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"
95 spec, err := d.spec(LaunchB, script, true)
96 if err == nil {
97 err = d.protect(&spec, root)
98 }
99 if err != nil {
100 return all(LaunchB, wire.ProbeUnavailable, wire.ProbeDetail("script_unwritten"))
101 }
102 spec.Limit = h.limit(LaunchB)
103 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" +
104 "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"
105 var ev evidence
106 out := h.Launch(ctx, spec, ev.observer())
107 for i, place := range []string{"script", "plugin", "test"} {
108 if ports[i].close() > 0 {
109 facts.Accepted[place] = true
110 }
111 }
112 if p := launched(LaunchB, out); p != nil {
113 return p
114 }
115 log := d.read("f5.log")
116 judge, groups := mac.JudgeP2(mac.ParseAttempts(log), facts)
117 var problems []string
118 for _, g := range []struct{ key, label string }{{"allowed", "allowed"}, {"unknown", "not_shown_denied"}} {
119 problems = said(problems, g.label, groups[g.key])
120 }
121 var unfinished []string
122 for _, phase := range p2Phases {
123 if !strings.Contains(log, "EQUIPO-PHASE "+phase+" 0\n") {
124 unfinished = append(unfinished, phase)
125 }
126 }
127 problems = said(problems, "incomplete", unfinished)
128 needles := map[string][][]byte{"state": {[]byte(secret)}, "token": {[]byte(token)}, "token-shape": {[]byte("sk-ant-oat01-")}}
129 if h.Secrets == nil {
130 problems = append(problems, wire.ProbeDetail("secrets_unreadable"))
131 } else if forms, err := h.Secrets(ctx); err != nil {
132 problems = append(problems, wire.ProbeDetail("secrets_unreadable"))
133 } else {
134 needles["secret"] = forms
135 }
136 found, whole := d.find(needles)
137 var toScratch, toTree []string
138 for _, k := range []string{"state", "token", "secret", "token-shape"} {
139 scratch, inTree := where(found[k])
140 if len(scratch) > 0 {
141 toScratch = append(toScratch, k)
142 }
143 if len(inTree) > 0 {
144 toTree = append(toTree, k)
145 }
146 }
147 problems = said(said(problems, "reached_scratch", toScratch), "reached_tree", toTree)
148 if !whole {
149 problems = append(problems, wire.ProbeDetail("tree_unsearched"))
150 }
151 if judge != wire.ProbeDenied && len(problems) == 0 {
152 problems = append(problems, wire.ProbeDetail("not_all_denied"))
153 }
154 detail := wire.ProbeDetail("f5_denied")
155 if len(groups["unix"]) > 0 {
156 detail = wire.ProbeDetails(detail, wire.ProbeDetail("unix_home"))
157 }
158 return ev.judged([]wire.Probe{verdict("F5", problems, detail)}, spec, d)
159}
160
161// closedHome is a person's home (not /Users/Shared) the runner user
162// cannot list by Unix permissions, as P4 shows it.
163func closedHome(homes []string, exposed func(string) bool) string {
164 for _, h := range sorted(homes) {
165 if filepath.Base(h) != "Shared" && (exposed == nil || !exposed(h)) {
166 return h
167 }
168 }
169 return ""
170}
171
172// childPoll is how often launch C looks for its child.
173const childPoll = 250 * time.Millisecond
174
175// launchC is F4: the protected script starts a child in a session of its
176// own (setsid, or perl's POSIX::setsid; there is no fallback) that
177// sleeps, then waits. Once the runner sees that child alive, in its own
178// session, it cancels the launch; the launch's stop must be proven, and
179// the child must be shown gone (its pid unused, or used again), not
180// merely unreadable.
181func launchC(ctx context.Context, h Host) []wire.Probe {
182 d, err := newLaunchDir(h.Scratch)
183 if err != nil {
184 return all(LaunchC, wire.ProbeUnavailable, wire.ProbeDetail("tree_unmade"))
185 }
186 defer d.remove()
187 o := quote(filepath.Join(d.run, "out"))
188 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" +
189 "if command -v setsid >/dev/null 2>&1; then setsid /bin/sleep 1000 </dev/null >/dev/null 2>&1 &\n" +
190 "elif [ -x /usr/bin/perl ]; then /usr/bin/perl -MPOSIX -e 'POSIX::setsid(); exec \"/bin/sleep\", \"1000\"' </dev/null >/dev/null 2>&1 &\n" +
191 "else exit 0; fi\n" +
192 "echo \"$!\" > " + o + "/f4.pid\n/bin/sleep 600\n"
193 spec, err := d.spec(LaunchC, script, false)
194 if err != nil {
195 return all(LaunchC, wire.ProbeUnavailable, wire.ProbeDetail("script_unwritten"))
196 }
197 spec.Limit = h.limit(LaunchC)
198 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" +
199 "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"
200 lctx, cancel := context.WithCancel(ctx)
201 defer cancel()
202 done := make(chan Outcome, 1)
203 var ev evidence
204 go func() { done <- h.Launch(lctx, spec, ev.observer()) }()
205 var child proc.Info
206 var out Outcome
207 ended := false
208 for deadline := time.Now().Add(h.limit(LaunchC)); child.PID == 0 && time.Now().Before(deadline); {
209 select {
210 case out = <-done:
211 ended = true
212 case <-time.After(childPoll):
213 }
214 if pid, err := strconv.Atoi(strings.TrimSpace(d.read("f4.pid"))); err == nil && pid > 1 {
215 if info, ok := h.Lookup(pid); ok {
216 child = info
217 }
218 }
219 if ended {
220 break
221 }
222 }
223 cancel()
224 if !ended {
225 out = <-done
226 }
227 if p := launched(LaunchC, out); p != nil {
228 return p
229 }
230 f4 := wire.Probe{ID: "F4", Verdict: wire.ProbePassed, Detail: wire.ProbeDetail("f4_passed")}
231 alive, known := h.alive(child.ID)
232 switch {
233 case child.PID == 0:
234 f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("child_not_started")}
235 case child.SID != child.PID:
236 f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("child_not_own_session")}
237 case alive:
238 f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("child_outlived")}
239 case !known:
240 f4 = wire.Probe{ID: "F4", Verdict: wire.ProbeFailed, Detail: wire.ProbeDetail("child_not_gone")}
241 }
242 return ev.judgedEnd([]wire.Probe{f4}, spec, d, false)
243}
244
245// alive is whether id still runs, and whether that is known.
246func (h Host) alive(id proc.ID) (bool, bool) {
247 if h.Alive != nil {
248 return h.Alive(id)
249 }
250 return proc.Alive(proc.Platform, id)
251}
252