oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package mac
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "errors"
10 "io"
11 "io/fs"
12 "maps"
13 "os"
14 "path/filepath"
15 "slices"
16 "strings"
17 "testing"
18
19 "amadan.net/oficina/equipo/internal/runner/provider"
20 "amadan.net/oficina/equipo/internal/runner/provider/claude"
21 "amadan.net/oficina/equipo/internal/wire"
22)
23
24// The darwin Engineering launch's certified shape (task 8): the settings
25// the pinned CLI and its sandboxed Bash run under on a Mac, the argv,
26// the MCP config and the environment, checked byte for byte before
27// anything starts. The golden files are this code's output on fixed
28// inputs (testPaths, /Users/equipo-paul), reviewed by hand on
29// 2026-11-28 (docs-t1, linux/amd64); EQUIPO_UPDATE_GOLDEN=1 rewrites them.
30
31const goldenScratchRoot = "/Users/equipo-paul/.local/share/equipo-runner/scratch"
32
33func goldenCLI() ClaudeCLI {
34 return NewClaudeCLI("/Users/equipo-paul", "/Users/equipo-paul/.local/lib/equipo-runner")
35}
36
37func goldenInput(action, xcode string) EngineeringInput {
38 s := goldenScratchRoot
39 return EngineeringInput{Paths: testPaths(), Action: action, Model: "claude-haiku-5-5",
40 Worktree: s + "/worker-steps/k/tree", Scratch: s + "/policy-1",
41 Runner: "/Users/equipo-paul/.local/lib/equipo-runner/equipo-runner", ToolRoot: s + "/t", Socket: s + "/t/1234567890/s",
42 ConfigDir: s + "/homes/account-1", CredentialHome: "/Users/equipo-paul/.local/share/equipo/accounts/claude-1", RuntimeRoot: s + "/homes",
43 XcodeAccess: xcode, Mach: CheckMachServices, DeveloperDir: "/Applications/Xcode.app/Contents/Developer",
44 Attempt: "attempt-7f3a", SessionID: "00000000-0000-4000-8000-000000000001"}
45}
46
47// darwinSettings is the part of the CLI's settings the tests read.
48type darwinSettings struct {
49 DisableAllHooks, AutoMemoryEnabled, AutoDreamEnabled *bool
50 EnabledPlugins map[string]bool
51 Sandbox struct {
52 Enabled, FailIfUnavailable, AllowUnsandboxedCommands, AutoAllowBashIfSandboxed *bool
53 ExcludedCommands []string
54 Filesystem struct{ AllowWrite, DenyRead, DenyWrite []string }
55 Network struct {
56 AllowedDomains, AllowUnixSockets, AllowMachLookup []string
57 StrictAllowlist, AllowLocalBinding, AllowAllUnixSockets *bool
58 }
59 }
60 Permissions struct{ Allow, Ask, Deny []string }
61}
62
63func settingsOf(t *testing.T, p provider.Policy) (darwinSettings, map[string]any) {
64 t.Helper()
65 var s darwinSettings
66 var generic map[string]any
67 if err := json.Unmarshal(p.Settings, &s); err != nil {
68 t.Fatal(err)
69 }
70 if err := json.Unmarshal(p.Settings, &generic); err != nil {
71 t.Fatal(err)
72 }
73 return s, generic
74}
75
76func is(b *bool, want bool) bool { return b != nil && *b == want }
77
78// TestEngineeringSettingsExact: the golden policy for Engineering with
79// and without sandboxed Xcode access, the read-only ask and the token
80// check; then what each part of it means, read back.
81func TestEngineeringSettingsExact(t *testing.T) {
82 cases := []struct {
83 name, action, xcode string
84 tools []string
85 native string
86 }{
87 {"implement", claude.DarwinImplement, "", []string{"mcp__equipo__submit_candidate", "mcp__equipo__ask_person", "mcp__equipo__submit_render"}, "Bash,Read,Write,Edit,Glob,Grep"},
88 {"implement-xcode", claude.DarwinImplement, wire.XcodeAccessSandboxed, []string{"mcp__equipo__submit_candidate", "mcp__equipo__ask_person", "mcp__equipo__submit_render"}, "Bash,Read,Write,Edit,Glob,Grep"},
89 {"answer", claude.DarwinAnswer, "", []string{"mcp__equipo__git_log", "mcp__equipo__git_diff", "mcp__equipo__git_show"}, "Read,Glob,Grep"},
90 {"check", claude.DarwinCheck, "", []string{}, ""},
91 }
92 for _, c := range cases {
93 t.Run(c.name, func(t *testing.T) {
94 in := goldenInput(c.action, c.xcode)
95 p, err := EngineeringPolicy(goldenCLI(), in)
96 if err != nil {
97 t.Fatal(err)
98 }
99 // Byte for byte against the golden file, after the meaning
100 // below is checked (a regenerated golden cannot hide it).
101 defer func() {
102 var pretty bytes.Buffer
103 if err := json.Indent(&pretty, p.Manifest, "", " "); err != nil {
104 t.Error(err)
105 return
106 }
107 pretty.WriteByte('\n')
108 golden := filepath.Join("testdata", "engineering-2026-11-28-"+c.name+".json")
109 if os.Getenv("EQUIPO_UPDATE_GOLDEN") == "1" {
110 if err := os.WriteFile(golden, pretty.Bytes(), 0644); err != nil {
111 t.Error(err)
112 }
113 }
114 want, err := os.ReadFile(golden)
115 if err != nil {
116 t.Error(err)
117 } else if !bytes.Equal(pretty.Bytes(), want) {
118 t.Errorf("policy differs from %s:\n%s", golden, pretty.Bytes())
119 }
120 }()
121 if sum := sha256.Sum256(p.Manifest); p.Hash != hex.EncodeToString(sum[:]) || p.ManifestHash != p.Hash {
122 t.Fatalf("hash %s / %s", p.Hash, p.ManifestHash)
123 }
124
125 s, generic := settingsOf(t, p)
126 readOnly := c.action != claude.DarwinImplement
127 // Hooks, plugins and memory off.
128 if !is(s.DisableAllHooks, true) || !is(s.AutoMemoryEnabled, false) || !is(s.AutoDreamEnabled, false) || len(s.EnabledPlugins) != 2 || s.EnabledPlugins["agents-md@builtin"] || s.EnabledPlugins["plugin-authoring@builtin"] {
129 t.Fatalf("hooks, plugins or memory: %s", p.Settings)
130 }
131 // Every command sandboxed, no way out, the sandbox required.
132 sb := s.Sandbox
133 if !is(sb.Enabled, true) || !is(sb.FailIfUnavailable, true) || !is(sb.AllowUnsandboxedCommands, false) || !is(sb.AutoAllowBashIfSandboxed, true) || sb.ExcludedCommands == nil || len(sb.ExcludedCommands) != 0 {
134 t.Fatalf("sandbox: %s", p.Settings)
135 }
136 if _, ok := generic["sandbox"].(map[string]any)["enableWeakerNestedSandbox"]; ok {
137 t.Fatalf("enableWeakerNestedSandbox is Linux only: %s", p.Settings)
138 }
139 // No network: an empty list, and strict, so a host is denied
140 // without asking anyone; no sockets, no local ports.
141 n := sb.Network
142 if n.AllowedDomains == nil || len(n.AllowedDomains) != 0 || !is(n.StrictAllowlist, true) || n.AllowUnixSockets == nil || len(n.AllowUnixSockets) != 0 || !is(n.AllowLocalBinding, false) || !is(n.AllowAllUnixSockets, false) {
143 t.Fatalf("network: %s", p.Settings)
144 }
145 // §4.2, both ways, plus the developer tools' credential
146 // places in the home, the connection's homes and the step
147 // socket's directory.
148 fsys := sb.Filesystem
149 denied := append(append(DenyList(in.Paths), wantCredentialPlaces(in.Home)...), in.CredentialHome, in.ConfigDir, in.RuntimeRoot, in.ToolRoot)
150 for _, d := range denied {
151 if !slices.Contains(fsys.DenyRead, d) || !slices.Contains(fsys.DenyWrite, d) {
152 t.Fatalf("%s not denied both ways: %s", d, p.Settings)
153 }
154 }
155 if len(fsys.DenyRead) != len(denied) {
156 t.Fatalf("denyRead %v, want exactly %v", fsys.DenyRead, denied)
157 }
158 // The runner's install dir and the pinned CLI's own directory:
159 // no sandboxed command may replace the binary the launcher
160 // hashed (macOS execs it by path).
161 for _, d := range []string{in.InstallDir, ClaudeDir(in.InstallDir)} {
162 if !slices.Contains(fsys.DenyWrite, d) || slices.Contains(fsys.DenyRead, d) {
163 t.Fatalf("%s: writes denied, reads allowed: %s", d, p.Settings)
164 }
165 }
166 wantWrite := []string{in.Worktree, in.Scratch}
167 if readOnly {
168 wantWrite = []string{in.Scratch}
169 if !slices.Contains(fsys.DenyWrite, in.Worktree) {
170 t.Fatalf("a read-only launch may write the worktree: %s", p.Settings)
171 }
172 } else if slices.Contains(fsys.DenyWrite, in.Worktree) {
173 t.Fatalf("Engineering cannot write its worktree: %s", p.Settings)
174 }
175 if c.xcode == wire.XcodeAccessSandboxed {
176 wantWrite = append(wantWrite, in.Scratch+"/DerivedData", in.UserTemp, in.Home+"/Library/Developer/Xcode/DerivedData", in.Home+"/Library/Caches/org.swift.swiftpm", in.Home+"/Library/org.swift.swiftpm")
177 }
178 if !slices.Equal(fsys.AllowWrite, wantWrite) {
179 t.Fatalf("allowWrite %v, want %v", fsys.AllowWrite, wantWrite)
180 }
181 // The CLI's own rules: the generated denies, the native tools
182 // asked about on the worktree, the step's tools allowed, no
183 // shell rule.
184 // Native Write and Edit run unsandboxed: every place denied to
185 // writes only (the install dir, the CLI's, a read-only
186 // worktree) gets its own native Write and Edit denies, the
187 // place and below it, and no read deny.
188 writeOnly := []string{in.InstallDir, ClaudeDir(in.InstallDir)}
189 if readOnly {
190 writeOnly = append(writeOnly, in.Worktree)
191 }
192 slices.Sort(writeOnly)
193 var gotWriteOnly []string
194 for _, d := range fsys.DenyWrite {
195 if !slices.Contains(fsys.DenyRead, d) {
196 gotWriteOnly = append(gotWriteOnly, d)
197 }
198 }
199 if !slices.Equal(gotWriteOnly, writeOnly) {
200 t.Fatalf("write-only denies %v, want %v", gotWriteOnly, writeOnly)
201 }
202 rules, err := claude.NativeDenyRules(fsys.DenyRead)
203 for _, d := range writeOnly {
204 rules = append(rules, "Write(/"+d+")", "Write(/"+d+"/**)", "Edit(/"+d+")", "Edit(/"+d+"/**)")
205 }
206 if err != nil || !slices.Equal(s.Permissions.Deny, rules) {
207 t.Fatalf("deny rules %v\nwant %v", s.Permissions.Deny, rules)
208 }
209 for _, d := range writeOnly {
210 if slices.Contains(s.Permissions.Deny, "Read(/"+d+")") {
211 t.Fatalf("%s read-denied natively", d)
212 }
213 }
214 var ask []string
215 for _, tool := range []string{"Read", "Write", "Edit", "Glob", "Grep"} {
216 if strings.Contains(","+c.native+",", ","+tool+",") {
217 ask = append(ask, tool+"(/"+in.Worktree+"/**)")
218 }
219 }
220 if !slices.Equal(s.Permissions.Ask, ask) && !(len(ask) == 0 && len(s.Permissions.Ask) == 0) || !slices.Equal(s.Permissions.Allow, c.tools) && !(len(c.tools) == 0 && len(s.Permissions.Allow) == 0) {
221 t.Fatalf("permissions ask %v allow %v", s.Permissions.Ask, s.Permissions.Allow)
222 }
223 // The argv: the pinned CLI, no settings or MCP but Equipo's,
224 // manual permissions through the port, the role's tools.
225 argv := claude.DarwinArgv(p)
226 cfg := in.ConfigDir
227 wantArgv := []string{ClaudePath(in.InstallDir), "-p", "--verbose", "--include-hook-events", "--input-format", "stream-json", "--output-format", "stream-json", "--model", in.Model, "--setting-sources", "", "--disable-slash-commands", "--strict-mcp-config", "--mcp-config", cfg + "/equipo-mcp.json", "--settings", cfg + "/equipo-settings.json", "--permission-mode", "manual", "--permission-prompt-tool", "mcp__equipo__permission", "--tools", c.native}
228 if readOnly {
229 wantArgv = append(wantArgv, "--include-partial-messages")
230 }
231 wantArgv = append(wantArgv, "--session-id", in.SessionID)
232 if !slices.Equal(argv, wantArgv) {
233 t.Fatalf("argv %q\nwant %q", argv, wantArgv)
234 }
235 mcp, _ := provider.DarwinToolMCP(in.Runner, in.Socket)
236 if !bytes.Equal(p.MCP, mcp) {
237 t.Fatalf("mcp %s", p.MCP)
238 }
239 // The permission port reads this policy: the worktree is its
240 // root, and on Engineering a shell command is the sandbox's.
241 if w, r := claude.Roots(p); w != in.Worktree || r != "" {
242 t.Fatalf("roots %q %q", w, r)
243 }
244 bash := json.RawMessage(`{"tool_name":"Bash","input":{"command":"ls"}}`)
245 var answer struct{ Behavior string }
246 json.Unmarshal(claude.StepPermission(bash, p), &answer)
247 if (answer.Behavior == "allow") != (c.action == claude.DarwinImplement) {
248 t.Fatalf("Bash answered %q", answer.Behavior)
249 }
250 })
251 }
252 // A fix round or an ask resumes its session; nothing else changes.
253 in := goldenInput(claude.DarwinImplement, "")
254 start, _ := EngineeringPolicy(goldenCLI(), in)
255 in.Resume = true
256 resume, err := EngineeringPolicy(goldenCLI(), in)
257 a, b := claude.DarwinArgv(start), claude.DarwinArgv(resume)
258 if err != nil || !slices.Equal(a[:len(a)-2], b[:len(b)-2]) || !slices.Equal(b[len(b)-2:], []string{"--resume", in.SessionID}) || !bytes.Equal(start.Settings, resume.Settings) {
259 t.Fatalf("resume argv %q (%v)", b, err)
260 }
261}
262
263// TestEngineeringSettingsRefuses: a policy that would not mean what it
264// says is never made.
265func TestEngineeringSettingsRefuses(t *testing.T) {
266 if _, err := EngineeringPolicy(goldenCLI(), goldenInput(claude.DarwinImplement, wire.XcodeAccessSandboxed)); err != nil {
267 t.Fatal(err)
268 }
269 s := goldenScratchRoot
270 cases := map[string]func(*EngineeringInput, *ClaudeCLI){
271 "worktree in the state dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.StateDir + "/tree" },
272 "worktree in the accounts root": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.AccountsRoot + "/tree" },
273 "worktree in another home": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = "/Users/paul/tree" },
274 "worktree on a volume": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = "/Volumes/x/tree" },
275 "worktree in the install dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.InstallDir + "/tree" },
276 "worktree in the step socket dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.ToolRoot + "/tree" },
277 "worktree holding ~/.ssh": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.Home },
278 "worktree in an unknown /Users": func(in *EngineeringInput, _ *ClaudeCLI) { in.HomesUnknown = true },
279 "no state dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.StateDir = "" },
280 "no accounts root": func(in *EngineeringInput, _ *ClaudeCLI) { in.AccountsRoot = "" },
281 "no session root": func(in *EngineeringInput, _ *ClaudeCLI) { in.SessionRoot = "" },
282 "no home": func(in *EngineeringInput, _ *ClaudeCLI) { in.Home = "" },
283 "no install dir": func(in *EngineeringInput, c *ClaudeCLI) {
284 in.InstallDir, *c = "", NewClaudeCLI("/Users/equipo-paul", "")
285 },
286 "relative worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = "tree" },
287 "relative scratch": func(in *EngineeringInput, _ *ClaudeCLI) { in.Scratch = "policy-1" },
288 "unclean worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = s + "/x/../tree" },
289 "glob worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = s + "/worker-steps/*" },
290 "glob other home": func(in *EngineeringInput, _ *ClaudeCLI) { in.OtherHomes = []string{"/Users/*"} },
291 "brace scratch": func(in *EngineeringInput, _ *ClaudeCLI) { in.Scratch = s + "/policy-{1,2}" },
292 "newline in a path": func(in *EngineeringInput, _ *ClaudeCLI) { in.Scratch = s + "/policy\n1" },
293 "root as worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = "/" },
294 "scratch inside the worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Scratch = in.Worktree + "/tmp" },
295 "worktree inside the scratch": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.Scratch + "/tree" },
296 "token home inside the worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.CredentialHome = in.Worktree + "/.home" },
297 "runtime copy inside the worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.ConfigDir = in.Worktree + "/.claude" },
298 "runtime copy outside its root": func(in *EngineeringInput, _ *ClaudeCLI) { in.ConfigDir = s + "/elsewhere/account-1" },
299 "socket outside the socket dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.Socket = s + "/sock" },
300 "socket path too long": func(in *EngineeringInput, _ *ClaudeCLI) {
301 in.Socket = in.ToolRoot + "/" + strings.Repeat("d", 90) + "/s"
302 },
303 "user temp outside the folders": func(in *EngineeringInput, _ *ClaudeCLI) { in.UserTemp = "/tmp/T" },
304 "no user temp": func(in *EngineeringInput, _ *ClaudeCLI) { in.UserTemp = "" },
305 "a Mach wildcard": func(in *EngineeringInput, _ *ClaudeCLI) { in.Mach = []string{"*"} },
306 "a Mach inner wildcard": func(in *EngineeringInput, _ *ClaudeCLI) { in.Mach = []string{"com.apple.*.x"} },
307 "unknown Xcode access": func(in *EngineeringInput, _ *ClaudeCLI) { in.XcodeAccess = "full" },
308 "unknown action": func(in *EngineeringInput, _ *ClaudeCLI) { in.Action = "copy" },
309 "no model": func(in *EngineeringInput, _ *ClaudeCLI) { in.Model = "" },
310 "a flag as model": func(in *EngineeringInput, _ *ClaudeCLI) { in.Model = "--dangerously-skip-permissions" },
311 "no session": func(in *EngineeringInput, _ *ClaudeCLI) { in.SessionID = "" },
312 "a session with a space": func(in *EngineeringInput, _ *ClaudeCLI) { in.SessionID = "a b" },
313 "no marker": func(in *EngineeringInput, _ *ClaudeCLI) { in.Attempt = "" },
314 "a marker with credentials": func(in *EngineeringInput, _ *ClaudeCLI) { in.Attempt = "https://user:pass@host" },
315 "a relative developer dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.DeveloperDir = "Xcode.app" },
316 "a relative runner": func(in *EngineeringInput, _ *ClaudeCLI) { in.Runner = "equipo-runner" },
317 "no CLI": func(_ *EngineeringInput, c *ClaudeCLI) { *c = ClaudeCLI{} },
318 "a CLI in another install dir": func(_ *EngineeringInput, c *ClaudeCLI) {
319 *c = NewClaudeCLI("/Users/equipo-paul", "/Users/equipo-paul/other")
320 },
321 "an ask with Xcode access": func(in *EngineeringInput, _ *ClaudeCLI) { in.Action = claude.DarwinAnswer },
322 "a check with Xcode access": func(in *EngineeringInput, _ *ClaudeCLI) { in.Action = claude.DarwinCheck },
323 }
324 for name, mutate := range cases {
325 t.Run(name, func(t *testing.T) {
326 in, cli := goldenInput(claude.DarwinImplement, wire.XcodeAccessSandboxed), goldenCLI()
327 mutate(&in, &cli)
328 if p, err := EngineeringPolicy(cli, in); !errors.Is(err, provider.ErrPolicy) {
329 t.Fatalf("made %s (%v)", p.Settings, err)
330 }
331 })
332 }
333}
334
335// TestEngineeringNoMachWithoutAccess: Xcode's services and caches come
336// only with sandboxed Xcode access; without it the list the caller holds
337// is not used, and the policy layer refuses one handed to it anyway.
338func TestEngineeringNoMachWithoutAccess(t *testing.T) {
339 in := goldenInput(claude.DarwinImplement, "")
340 in.Mach = []string{"com.apple.CoreSimulator.*", "com.apple.dt.*"}
341 p, err := EngineeringPolicy(goldenCLI(), in)
342 if err != nil {
343 t.Fatal(err)
344 }
345 s, _ := settingsOf(t, p)
346 if m := s.Sandbox.Network.AllowMachLookup; m == nil || len(m) != 0 {
347 t.Fatalf("Mach without access: %v", m)
348 }
349 for _, w := range s.Sandbox.Filesystem.AllowWrite {
350 if w != in.Worktree && w != in.Scratch {
351 t.Fatalf("an Xcode place without access: %v", s.Sandbox.Filesystem.AllowWrite)
352 }
353 }
354 var m struct{ XcodeAccess *string }
355 if json.Unmarshal(p.Manifest, &m) != nil || m.XcodeAccess == nil || *m.XcodeAccess != "" {
356 t.Fatalf("xcode access not recorded: %s", p.Manifest)
357 }
358 in.XcodeAccess = wire.XcodeAccessSandboxed
359 p, err = EngineeringPolicy(goldenCLI(), in)
360 if err != nil {
361 t.Fatal(err)
362 }
363 if s, _ = settingsOf(t, p); !slices.Equal(s.Sandbox.Network.AllowMachLookup, in.Mach) {
364 t.Fatalf("sandboxed access: %v", s.Sandbox.Network.AllowMachLookup)
365 }
366 // The policy layer on its own: services or Xcode writes with no
367 // access are refused, not quietly kept.
368 d := claudeInputs(t, goldenInput(claude.DarwinImplement, ""))
369 for name, mutate := range map[string]func(*claude.DarwinInputs){
370 "mach": func(d *claude.DarwinInputs) { d.Mach = []string{"com.apple.dt.*"} },
371 "writes": func(d *claude.DarwinInputs) {
372 d.XcodeWrites = []string{"/Users/equipo-paul/Library/Developer/Xcode/DerivedData"}
373 },
374 } {
375 c := d
376 mutate(&c)
377 if _, err := claude.DarwinPolicy(c); !errors.Is(err, provider.ErrPolicy) {
378 t.Fatalf("%s without access: %v", name, err)
379 }
380 }
381}
382
383func claudeInputs(t *testing.T, in EngineeringInput) claude.DarwinInputs {
384 t.Helper()
385 d, err := goldenCLI().darwinInputs(in)
386 if err != nil {
387 t.Fatal(err)
388 }
389 return d
390}
391
392// engRig is a launch on this machine's filesystem: a provisioned fake
393// CLI in a private home, a real worktree, scratch and runtime copy.
394type engRig struct {
395 t *testing.T
396 cli ClaudeCLI
397 in EngineeringInput
398 token []byte
399 started []EngineeringCommand
400 read [][]byte
401}
402
403func newEngRig(t *testing.T) *engRig { t.Helper(); return newEngRigWith(t, fakeClaude()) }
404
405// newEngRigWith is the rig with body as the pinned CLI.
406func newEngRigWith(t *testing.T, body []byte) *engRig {
407 t.Helper()
408 home, err := filepath.EvalSymlinks(t.TempDir())
409 if err != nil {
410 t.Fatal(err)
411 }
412 if err := os.Chmod(home, 0700); err != nil {
413 t.Fatal(err)
414 }
415 install := filepath.Join(home, ".local", "lib", "equipo-runner")
416 share := filepath.Join(home, ".local", "share", "equipo-runner")
417 scratch := filepath.Join(share, "scratch")
418 in := EngineeringInput{
419 Paths: Paths{Home: home, StateDir: filepath.Join(share, "state"), AccountsRoot: filepath.Join(home, ".local", "share", "equipo", "accounts"), SessionRoot: filepath.Join(share, "sessions"), InstallDir: install, OtherHomes: []string{"/Users/paul"}},
420 Action: claude.DarwinImplement, Model: "claude-haiku-5-5",
421 Worktree: filepath.Join(scratch, "worker-steps", "k", "tree"), Scratch: filepath.Join(scratch, "policy-1"),
422 // The socket is never dialled here, and a temporary home is too
423 // deep for sun_path: a short path stands for it.
424 Runner: filepath.Join(install, "equipo-runner"), ToolRoot: "/private/tmp/equipo-t", Socket: "/private/tmp/equipo-t/1/s",
425 ConfigDir: filepath.Join(scratch, "homes", "account-1"), CredentialHome: filepath.Join(home, ".local", "share", "equipo", "accounts", "claude-1"), RuntimeRoot: filepath.Join(scratch, "homes"),
426 DeveloperDir: "/Applications/Xcode.app/Contents/Developer", Attempt: "attempt-7f3a", SessionID: "00000000-0000-4000-8000-000000000001",
427 }
428 for _, d := range []string{install, in.Worktree, in.Scratch, in.ConfigDir, in.CredentialHome, in.StateDir} {
429 if err := os.MkdirAll(d, 0700); err != nil {
430 t.Fatal(err)
431 }
432 }
433 cli := homeCLI(home, install, body)
434 if err := cli.Provision(context.Background(), serve(body, nil)); err != nil {
435 t.Fatal(err)
436 }
437 return &engRig{t: t, cli: cli, in: in, token: []byte("sk-ant-oat01-SENTINEL-the-token-goes-by-descriptor-only-AA")}
438}
439
440func (r *engRig) policy() provider.Policy {
441 r.t.Helper()
442 p, err := EngineeringPolicy(r.cli, r.in)
443 if err != nil {
444 r.t.Fatal(err)
445 }
446 return p
447}
448
449// launch runs LaunchEngineering with a start that records the command
450// and reads the token descriptor to its end, as the CLI does.
451func (r *engRig) launch(p provider.Policy) error {
452 return LaunchEngineering(context.Background(), r.cli, r.in, p, slices.Clone(r.token), func(_ context.Context, c EngineeringCommand) error {
453 r.started = append(r.started, c)
454 var got []byte
455 if len(c.Files) > 0 {
456 got, _ = io.ReadAll(c.Files[0])
457 }
458 r.read = append(r.read, got)
459 return nil
460 })
461}
462
463// rehashed is p with its manifest changed by edit and every hash
464// recomputed, as someone forging a policy would.
465func rehashed(t *testing.T, p provider.Policy, edit func(m map[string]json.RawMessage)) provider.Policy {
466 t.Helper()
467 var m map[string]json.RawMessage
468 if err := json.Unmarshal(p.Manifest, &m); err != nil {
469 t.Fatal(err)
470 }
471 edit(m)
472 raw, err := json.Marshal(m)
473 if err != nil {
474 t.Fatal(err)
475 }
476 sum := sha256.Sum256(raw)
477 p.Manifest, p.Hash, p.ManifestHash = raw, hex.EncodeToString(sum[:]), hex.EncodeToString(sum[:])
478 p.Settings = bytes.Clone(m["Settings"])
479 var env map[string]string
480 json.Unmarshal(m["Env"], &env)
481 p.Env = env
482 return p
483}
484
485// TestEngineeringPolicyValidatedBeforeLaunch: the launcher regenerates
486// the policy from its inputs and starts nothing on any difference.
487func TestEngineeringPolicyValidatedBeforeLaunch(t *testing.T) {
488 r := newEngRig(t)
489 p := r.policy()
490 if err := r.launch(p); err != nil {
491 t.Fatal(err)
492 }
493 if len(r.started) != 1 || !slices.Equal(r.started[0].Argv, claude.DarwinArgv(p)) || r.started[0].Argv[0] != ClaudePath(r.in.InstallDir) || r.started[0].Dir != r.in.Worktree {
494 t.Fatalf("started %+v", r.started)
495 }
496 settings := filepath.Join(r.in.ConfigDir, "equipo-settings.json")
497 mcp := filepath.Join(r.in.ConfigDir, "equipo-mcp.json")
498 for path, want := range map[string][]byte{settings: p.Settings, mcp: p.MCP} {
499 got, err := os.ReadFile(path)
500 info, _ := os.Lstat(path)
501 if err != nil || !bytes.Equal(got, want) || info.Mode() != 0600 {
502 t.Fatalf("%s: %v %s", path, err, got)
503 }
504 }
505 other := r.in
506 other.SessionID = "00000000-0000-4000-8000-000000000002"
507 forOther, err := EngineeringPolicy(r.cli, other)
508 if err != nil {
509 t.Fatal(err)
510 }
511 cases := map[string]func(provider.Policy) provider.Policy{
512 "one byte of settings": func(p provider.Policy) provider.Policy {
513 p.Settings = bytes.Replace(bytes.Clone(p.Settings), []byte("600000"), []byte("600001"), 1)
514 return p
515 },
516 "one byte of the manifest's settings, rehashed": func(p provider.Policy) provider.Policy {
517 return rehashed(t, p, func(m map[string]json.RawMessage) {
518 m["Settings"] = bytes.Replace(m["Settings"], []byte(`"strictAllowlist":true`), []byte(`"strictAllowlist":0 `), 1)
519 })
520 },
521 "a different argv, rehashed": func(p provider.Policy) provider.Policy {
522 return rehashed(t, p, func(m map[string]json.RawMessage) {
523 m["Argv"] = bytes.Replace(m["Argv"], []byte(`"manual"`), []byte(`"bypassPermissions"`), 1)
524 })
525 },
526 "an extra environment key": func(p provider.Policy) provider.Policy {
527 p.Env = maps.Clone(p.Env)
528 p.Env["NODE_OPTIONS"] = "--require /tmp/x.js"
529 return p
530 },
531 "an extra environment key, rehashed": func(p provider.Policy) provider.Policy {
532 return rehashed(t, p, func(m map[string]json.RawMessage) {
533 m["Env"] = bytes.Replace(m["Env"], []byte(`{`), []byte(`{"NODE_OPTIONS":"--require /tmp/x.js",`), 1)
534 })
535 },
536 "a changed hash": func(p provider.Policy) provider.Policy {
537 p.Hash = strings.Repeat("0", 64)
538 return p
539 },
540 "a mount added": func(p provider.Policy) provider.Policy {
541 p.Mounts = []provider.Mount{{Source: "/", Target: "/x"}}
542 return p
543 },
544 "another attempt's policy": func(provider.Policy) provider.Policy { return forOther },
545 }
546 for name, mutate := range cases {
547 t.Run(name, func(t *testing.T) {
548 r.started = nil
549 os.Remove(settings)
550 if err := r.launch(mutate(p)); !errors.Is(err, provider.ErrPolicy) || len(r.started) != 0 {
551 t.Fatalf("launched (%v, %d)", err, len(r.started))
552 }
553 if _, err := os.Lstat(settings); !errors.Is(err, fs.ErrNotExist) {
554 t.Fatalf("settings written for a refused launch: %v", err)
555 }
556 })
557 }
558 // What the filesystem must show at the start: a worktree that is its
559 // own real path, and no token file the CLI would read by itself.
560 t.Run("a token file in the runtime copy", func(t *testing.T) {
561 for _, name := range []string{".oauth_token", ".oauth-token"} {
562 r.started = nil
563 path := filepath.Join(r.in.ConfigDir, name)
564 if err := os.WriteFile(path, []byte("x"), 0600); err != nil {
565 t.Fatal(err)
566 }
567 if err := r.launch(p); !errors.Is(err, provider.ErrPolicy) || len(r.started) != 0 {
568 t.Fatalf("%s: launched (%v)", name, err)
569 }
570 os.Remove(path)
571 }
572 })
573 t.Run("a worktree that is a link", func(t *testing.T) {
574 r.started = nil
575 real := r.in.Worktree + ".real"
576 if err := os.Rename(r.in.Worktree, real); err != nil {
577 t.Fatal(err)
578 }
579 if err := os.Symlink(real, r.in.Worktree); err != nil {
580 t.Fatal(err)
581 }
582 defer func() { os.Remove(r.in.Worktree); os.Rename(real, r.in.Worktree) }()
583 if err := r.launch(p); !errors.Is(err, provider.ErrPolicy) || len(r.started) != 0 {
584 t.Fatalf("launched (%v)", err)
585 }
586 })
587 // The CLI itself is still checked by ClaudeCLI.Launch.
588 t.Run("an unpinned CLI", func(t *testing.T) {
589 r.started = nil
590 if err := os.Chmod(ClaudePath(r.in.InstallDir), 0755); err != nil {
591 t.Fatal(err)
592 }
593 defer os.Chmod(ClaudePath(r.in.InstallDir), 0700)
594 var u *ClaudeUnavailable
595 if err := r.launch(p); !errors.As(err, &u) || len(r.started) != 0 {
596 t.Fatalf("launched (%v)", err)
597 }
598 })
599}
600
601// TestEngineeringEnvFromScratch: the CLI's environment is exactly the
602// certified one; nothing of the runner's own is inherited.
603func TestEngineeringEnvFromScratch(t *testing.T) {
604 t.Setenv("EQUIPO_INHERITED_SENTINEL", "inherited")
605 t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "inherited-token")
606 t.Setenv("ANTHROPIC_API_KEY", "inherited-key")
607 t.Setenv("SSH_AUTH_SOCK", "/private/tmp/agent.sock")
608 r := newEngRig(t)
609 p := r.policy()
610 if err := r.launch(p); err != nil {
611 t.Fatal(err)
612 }
613 want := []string{
614 "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1",
615 "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3",
616 "CLAUDE_CODE_PROJECT_DIR_NAME=-workspace",
617 "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1",
618 "CLAUDE_CONFIG_DIR=" + r.in.ConfigDir,
619 "DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer",
620 "DISABLE_AUTOUPDATER=1",
621 "EQUIPO_ATTEMPT=attempt-7f3a",
622 "HOME=" + r.in.Home,
623 "LANG=en_US.UTF-8",
624 "PATH=/usr/bin:/bin:/usr/sbin:/sbin",
625 "TMPDIR=" + r.in.Scratch,
626 }
627 if len(r.started) != 1 || !slices.Equal(r.started[0].Env, want) {
628 t.Fatalf("env %+v\nwant %q", r.started, want)
629 }
630 // The policy records the same environment, and the marker's name is
631 // one the CLI's scrub keeps (task 1, S5).
632 var rec []string
633 for k, v := range p.Env {
634 rec = append(rec, k+"="+v)
635 }
636 slices.Sort(rec)
637 if !slices.Equal(rec, want) {
638 t.Fatalf("policy env %q", rec)
639 }
640 for _, word := range []string{"TOKEN", "KEY", "AUTH", "PAT", "SECRET"} {
641 if strings.Contains("EQUIPO_ATTEMPT", word) {
642 t.Fatalf("marker name has %s", word)
643 }
644 }
645 // No developer dir: no DEVELOPER_DIR, nothing else changes.
646 r.in.DeveloperDir = ""
647 r.started = nil
648 if err := r.launch(r.policy()); err != nil {
649 t.Fatal(err)
650 }
651 if !slices.Equal(r.started[0].Env, slices.DeleteFunc(slices.Clone(want), func(s string) bool { return strings.HasPrefix(s, "DEVELOPER_DIR=") })) {
652 t.Fatalf("env without a developer dir: %q", r.started[0].Env)
653 }
654}
655
656// TestEngineeringTokenNotInArgvOrPolicy: the token reaches the CLI only
657// on its descriptor. It is in no argv, no policy, no environment (a
658// sandboxed command can read the CLI's initial environment), no file and
659// no refusal's words.
660func TestEngineeringTokenNotInArgvOrPolicy(t *testing.T) {
661 r := newEngRig(t)
662 p := r.policy()
663 if err := r.launch(p); err != nil {
664 t.Fatal(err)
665 }
666 token := string(r.token)
667 c := r.started[0]
668 if strings.Contains(strings.Join(c.Argv, "\x00"), token) || strings.Contains(strings.Join(c.Env, "\x00"), token) {
669 t.Fatal("token in argv or environment")
670 }
671 for _, kv := range c.Env {
672 k, _, _ := strings.Cut(kv, "=")
673 if k == "CLAUDE_CODE_OAUTH_TOKEN" || k == "ANTHROPIC_API_KEY" || k == "ANTHROPIC_AUTH_TOKEN" {
674 t.Fatalf("a token variable in the environment: %s", k)
675 }
676 }
677 stored, _ := json.Marshal(p)
678 if bytes.Contains(stored, r.token) || bytes.Contains(p.Manifest, r.token) {
679 t.Fatal("token in the policy")
680 }
681 if len(c.Files) != 1 || !bytes.Equal(r.read[0], r.token) || !slices.Contains(c.Env, "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3") {
682 t.Fatalf("token not on descriptor 3: %q", r.read)
683 }
684 // Nothing on disk under the runner's home holds it.
685 filepath.WalkDir(r.in.Home, func(path string, d fs.DirEntry, err error) error {
686 if err == nil && d.Type().IsRegular() {
687 if b, _ := os.ReadFile(path); bytes.Contains(b, r.token) {
688 t.Fatalf("token written to %s", path)
689 }
690 }
691 return nil
692 })
693 // Refusals neither start nor say it.
694 for name, bad := range map[string][]byte{
695 "empty": nil,
696 "a newline": []byte(token + "\nmore"),
697 "too long": bytes.Repeat([]byte("a"), 4097),
698 } {
699 r.started = nil
700 err := LaunchEngineering(context.Background(), r.cli, r.in, p, bad, func(context.Context, EngineeringCommand) error {
701 r.started = append(r.started, EngineeringCommand{})
702 return nil
703 })
704 if err == nil || len(r.started) != 0 || strings.Contains(err.Error(), token) {
705 t.Fatalf("%s token: %v", name, err)
706 }
707 }
708 r.started = nil
709 bad := p
710 bad.Hash = ""
711 if err := r.launch(bad); err == nil || strings.Contains(err.Error(), token) || len(r.started) != 0 {
712 t.Fatalf("refused policy: %v", err)
713 }
714}
715
716// wantCredentialPlaces is the test's own list of where developer tools keep
717// credentials in a home by default (fix round 1's audit): Claude Code,
718// Codex, GitHub's CLI, git, netrc, Docker, npm, Yarn, PyPI, RubyGems,
719// Cargo, Gradle, Maven, Kubernetes, the cloud CLIs, Terraform, Firebase,
720// Hugging Face, fastlane and App Store Connect keys, pass, and the shell
721// histories (a token typed once stays there).
722func wantCredentialPlaces(home string) []string {
723 var out []string
724 for _, rel := range []string{".claude", ".claude.json", ".codex", ".config/gh", ".config/hub", ".git-credentials", ".config/git/credentials", ".netrc",
725 ".docker/config.json", ".npmrc", ".yarnrc.yml", ".pypirc", ".gem/credentials", ".cargo/credentials", ".cargo/credentials.toml",
726 ".gradle/gradle.properties", ".m2/settings.xml", ".m2/settings-security.xml", ".kube", ".config/gcloud", ".azure", ".terraform.d",
727 ".config/configstore", ".cache/huggingface/token", ".huggingface", ".fastlane", ".appstoreconnect", ".private_keys", "private_keys",
728 ".password-store", ".bash_history", ".zsh_history", ".zsh_sessions"} {
729 out = append(out, home+"/"+rel)
730 }
731 return out
732}
733
734// TestEngineeringCredentialPlacesDenied: sentinel credentials where the
735// tools write them by default are denied to sandboxed commands both
736// ways and to the native tools, whether or not they exist at launch;
737// Xcode's own places in the home stay writable with sandboxed access.
738func TestEngineeringCredentialPlacesDenied(t *testing.T) {
739 r := newEngRig(t)
740 r.in.XcodeAccess = wire.XcodeAccessSandboxed
741 r.in.UserTemp = "/private/var/folders/4m/abc123_def/T"
742 r.in.Mach = CheckMachServices
743 before := r.policy()
744 sentinels := []string{".claude/.credentials.json", ".claude.json", ".codex/auth.json", ".config/gh/hosts.yml", ".git-credentials", ".netrc",
745 ".docker/config.json", ".npmrc", ".aws/credentials", ".ssh/id_ed25519", ".kube/config", ".zsh_history", ".appstoreconnect/private_keys/AuthKey_X.p8"}
746 for _, rel := range sentinels {
747 path := filepath.Join(r.in.Home, rel)
748 if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
749 t.Fatal(err)
750 }
751 if err := os.WriteFile(path, []byte("SENTINEL-credential"), 0600); err != nil {
752 t.Fatal(err)
753 }
754 }
755 p := r.policy()
756 if !bytes.Equal(before.Manifest, p.Manifest) {
757 t.Fatal("the policy depends on what exists in the home")
758 }
759 s, _ := settingsOf(t, p)
760 fsys := s.Sandbox.Filesystem
761 covered := func(list []string, path string) bool {
762 for _, d := range list {
763 if path == d || strings.HasPrefix(path, d+"/") {
764 return true
765 }
766 }
767 return false
768 }
769 for _, rel := range sentinels {
770 path := filepath.Join(r.in.Home, rel)
771 if !covered(fsys.DenyRead, path) || !covered(fsys.DenyWrite, path) {
772 t.Fatalf("%s readable or writable by sandboxed commands", rel)
773 }
774 native := false
775 for _, d := range fsys.DenyRead {
776 if covered([]string{d}, path) && slices.Contains(s.Permissions.Deny, "Read(/"+d+"/**)") && slices.Contains(s.Permissions.Deny, "Grep(/"+d+")") {
777 native = true
778 }
779 }
780 raw, _ := json.Marshal(map[string]any{"tool_name": "Read", "input": map[string]string{"file_path": path}})
781 var v struct{ Behavior string }
782 json.Unmarshal(claude.StepPermission(raw, p), &v)
783 if !native || v.Behavior != "deny" {
784 t.Fatalf("%s: native deny %v, port %q", rel, native, v.Behavior)
785 }
786 }
787 for _, w := range []string{r.in.Home + "/Library/Developer/Xcode/DerivedData", r.in.Home + "/Library/Caches/org.swift.swiftpm", r.in.Home + "/Library/org.swift.swiftpm"} {
788 if !slices.Contains(fsys.AllowWrite, w) || covered(fsys.DenyWrite, w) || covered(fsys.DenyRead, w) {
789 t.Fatalf("Xcode's %s denied", w)
790 }
791 }
792}
793