package mac import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "io" "io/fs" "maps" "os" "path/filepath" "slices" "strings" "testing" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/wire" ) // The darwin Engineering launch's certified shape (task 8): the settings // the pinned CLI and its sandboxed Bash run under on a Mac, the argv, // the MCP config and the environment, checked byte for byte before // anything starts. The golden files are this code's output on fixed // inputs (testPaths, /Users/equipo-paul), reviewed by hand on // 2026-11-28 (docs-t1, linux/amd64); EQUIPO_UPDATE_GOLDEN=1 rewrites them. const goldenScratchRoot = "/Users/equipo-paul/.local/share/equipo-runner/scratch" func goldenCLI() ClaudeCLI { return NewClaudeCLI("/Users/equipo-paul", "/Users/equipo-paul/.local/lib/equipo-runner") } func goldenInput(action, xcode string) EngineeringInput { s := goldenScratchRoot return EngineeringInput{Paths: testPaths(), Action: action, Model: "claude-haiku-5-5", Worktree: s + "/worker-steps/k/tree", Scratch: s + "/policy-1", Runner: "/Users/equipo-paul/.local/lib/equipo-runner/equipo-runner", ToolRoot: s + "/t", Socket: s + "/t/1234567890/s", ConfigDir: s + "/homes/account-1", CredentialHome: "/Users/equipo-paul/.local/share/equipo/accounts/claude-1", RuntimeRoot: s + "/homes", XcodeAccess: xcode, Mach: CheckMachServices, DeveloperDir: "/Applications/Xcode.app/Contents/Developer", Attempt: "attempt-7f3a", SessionID: "00000000-0000-4000-8000-000000000001"} } // darwinSettings is the part of the CLI's settings the tests read. type darwinSettings struct { DisableAllHooks, AutoMemoryEnabled, AutoDreamEnabled *bool EnabledPlugins map[string]bool Sandbox struct { Enabled, FailIfUnavailable, AllowUnsandboxedCommands, AutoAllowBashIfSandboxed *bool ExcludedCommands []string Filesystem struct{ AllowWrite, DenyRead, DenyWrite []string } Network struct { AllowedDomains, AllowUnixSockets, AllowMachLookup []string StrictAllowlist, AllowLocalBinding, AllowAllUnixSockets *bool } } Permissions struct{ Allow, Ask, Deny []string } } func settingsOf(t *testing.T, p provider.Policy) (darwinSettings, map[string]any) { t.Helper() var s darwinSettings var generic map[string]any if err := json.Unmarshal(p.Settings, &s); err != nil { t.Fatal(err) } if err := json.Unmarshal(p.Settings, &generic); err != nil { t.Fatal(err) } return s, generic } func is(b *bool, want bool) bool { return b != nil && *b == want } // TestEngineeringSettingsExact: the golden policy for Engineering with // and without sandboxed Xcode access, the read-only ask and the token // check; then what each part of it means, read back. func TestEngineeringSettingsExact(t *testing.T) { cases := []struct { name, action, xcode string tools []string native string }{ {"implement", claude.DarwinImplement, "", []string{"mcp__equipo__submit_candidate", "mcp__equipo__ask_person", "mcp__equipo__submit_render"}, "Bash,Read,Write,Edit,Glob,Grep"}, {"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"}, {"answer", claude.DarwinAnswer, "", []string{"mcp__equipo__git_log", "mcp__equipo__git_diff", "mcp__equipo__git_show"}, "Read,Glob,Grep"}, {"check", claude.DarwinCheck, "", []string{}, ""}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { in := goldenInput(c.action, c.xcode) p, err := EngineeringPolicy(goldenCLI(), in) if err != nil { t.Fatal(err) } // Byte for byte against the golden file, after the meaning // below is checked (a regenerated golden cannot hide it). defer func() { var pretty bytes.Buffer if err := json.Indent(&pretty, p.Manifest, "", " "); err != nil { t.Error(err) return } pretty.WriteByte('\n') golden := filepath.Join("testdata", "engineering-2026-11-28-"+c.name+".json") if os.Getenv("EQUIPO_UPDATE_GOLDEN") == "1" { if err := os.WriteFile(golden, pretty.Bytes(), 0644); err != nil { t.Error(err) } } want, err := os.ReadFile(golden) if err != nil { t.Error(err) } else if !bytes.Equal(pretty.Bytes(), want) { t.Errorf("policy differs from %s:\n%s", golden, pretty.Bytes()) } }() if sum := sha256.Sum256(p.Manifest); p.Hash != hex.EncodeToString(sum[:]) || p.ManifestHash != p.Hash { t.Fatalf("hash %s / %s", p.Hash, p.ManifestHash) } s, generic := settingsOf(t, p) readOnly := c.action != claude.DarwinImplement // Hooks, plugins and memory off. 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"] { t.Fatalf("hooks, plugins or memory: %s", p.Settings) } // Every command sandboxed, no way out, the sandbox required. sb := s.Sandbox if !is(sb.Enabled, true) || !is(sb.FailIfUnavailable, true) || !is(sb.AllowUnsandboxedCommands, false) || !is(sb.AutoAllowBashIfSandboxed, true) || sb.ExcludedCommands == nil || len(sb.ExcludedCommands) != 0 { t.Fatalf("sandbox: %s", p.Settings) } if _, ok := generic["sandbox"].(map[string]any)["enableWeakerNestedSandbox"]; ok { t.Fatalf("enableWeakerNestedSandbox is Linux only: %s", p.Settings) } // No network: an empty list, and strict, so a host is denied // without asking anyone; no sockets, no local ports. n := sb.Network 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) { t.Fatalf("network: %s", p.Settings) } // ยง4.2, both ways, plus the developer tools' credential // places in the home, the connection's homes and the step // socket's directory. fsys := sb.Filesystem denied := append(append(DenyList(in.Paths), wantCredentialPlaces(in.Home)...), in.CredentialHome, in.ConfigDir, in.RuntimeRoot, in.ToolRoot) for _, d := range denied { if !slices.Contains(fsys.DenyRead, d) || !slices.Contains(fsys.DenyWrite, d) { t.Fatalf("%s not denied both ways: %s", d, p.Settings) } } if len(fsys.DenyRead) != len(denied) { t.Fatalf("denyRead %v, want exactly %v", fsys.DenyRead, denied) } // The runner's install dir and the pinned CLI's own directory: // no sandboxed command may replace the binary the launcher // hashed (macOS execs it by path). for _, d := range []string{in.InstallDir, ClaudeDir(in.InstallDir)} { if !slices.Contains(fsys.DenyWrite, d) || slices.Contains(fsys.DenyRead, d) { t.Fatalf("%s: writes denied, reads allowed: %s", d, p.Settings) } } wantWrite := []string{in.Worktree, in.Scratch} if readOnly { wantWrite = []string{in.Scratch} if !slices.Contains(fsys.DenyWrite, in.Worktree) { t.Fatalf("a read-only launch may write the worktree: %s", p.Settings) } } else if slices.Contains(fsys.DenyWrite, in.Worktree) { t.Fatalf("Engineering cannot write its worktree: %s", p.Settings) } if c.xcode == wire.XcodeAccessSandboxed { 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") } if !slices.Equal(fsys.AllowWrite, wantWrite) { t.Fatalf("allowWrite %v, want %v", fsys.AllowWrite, wantWrite) } // The CLI's own rules: the generated denies, the native tools // asked about on the worktree, the step's tools allowed, no // shell rule. // Native Write and Edit run unsandboxed: every place denied to // writes only (the install dir, the CLI's, a read-only // worktree) gets its own native Write and Edit denies, the // place and below it, and no read deny. writeOnly := []string{in.InstallDir, ClaudeDir(in.InstallDir)} if readOnly { writeOnly = append(writeOnly, in.Worktree) } slices.Sort(writeOnly) var gotWriteOnly []string for _, d := range fsys.DenyWrite { if !slices.Contains(fsys.DenyRead, d) { gotWriteOnly = append(gotWriteOnly, d) } } if !slices.Equal(gotWriteOnly, writeOnly) { t.Fatalf("write-only denies %v, want %v", gotWriteOnly, writeOnly) } rules, err := claude.NativeDenyRules(fsys.DenyRead) for _, d := range writeOnly { rules = append(rules, "Write(/"+d+")", "Write(/"+d+"/**)", "Edit(/"+d+")", "Edit(/"+d+"/**)") } if err != nil || !slices.Equal(s.Permissions.Deny, rules) { t.Fatalf("deny rules %v\nwant %v", s.Permissions.Deny, rules) } for _, d := range writeOnly { if slices.Contains(s.Permissions.Deny, "Read(/"+d+")") { t.Fatalf("%s read-denied natively", d) } } var ask []string for _, tool := range []string{"Read", "Write", "Edit", "Glob", "Grep"} { if strings.Contains(","+c.native+",", ","+tool+",") { ask = append(ask, tool+"(/"+in.Worktree+"/**)") } } 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) { t.Fatalf("permissions ask %v allow %v", s.Permissions.Ask, s.Permissions.Allow) } // The argv: the pinned CLI, no settings or MCP but Equipo's, // manual permissions through the port, the role's tools. argv := claude.DarwinArgv(p) cfg := in.ConfigDir 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} if readOnly { wantArgv = append(wantArgv, "--include-partial-messages") } wantArgv = append(wantArgv, "--session-id", in.SessionID) if !slices.Equal(argv, wantArgv) { t.Fatalf("argv %q\nwant %q", argv, wantArgv) } mcp, _ := provider.DarwinToolMCP(in.Runner, in.Socket) if !bytes.Equal(p.MCP, mcp) { t.Fatalf("mcp %s", p.MCP) } // The permission port reads this policy: the worktree is its // root, and on Engineering a shell command is the sandbox's. if w, r := claude.Roots(p); w != in.Worktree || r != "" { t.Fatalf("roots %q %q", w, r) } bash := json.RawMessage(`{"tool_name":"Bash","input":{"command":"ls"}}`) var answer struct{ Behavior string } json.Unmarshal(claude.StepPermission(bash, p), &answer) if (answer.Behavior == "allow") != (c.action == claude.DarwinImplement) { t.Fatalf("Bash answered %q", answer.Behavior) } }) } // A fix round or an ask resumes its session; nothing else changes. in := goldenInput(claude.DarwinImplement, "") start, _ := EngineeringPolicy(goldenCLI(), in) in.Resume = true resume, err := EngineeringPolicy(goldenCLI(), in) a, b := claude.DarwinArgv(start), claude.DarwinArgv(resume) 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) { t.Fatalf("resume argv %q (%v)", b, err) } } // TestEngineeringSettingsRefuses: a policy that would not mean what it // says is never made. func TestEngineeringSettingsRefuses(t *testing.T) { if _, err := EngineeringPolicy(goldenCLI(), goldenInput(claude.DarwinImplement, wire.XcodeAccessSandboxed)); err != nil { t.Fatal(err) } s := goldenScratchRoot cases := map[string]func(*EngineeringInput, *ClaudeCLI){ "worktree in the state dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.StateDir + "/tree" }, "worktree in the accounts root": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.AccountsRoot + "/tree" }, "worktree in another home": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = "/Users/paul/tree" }, "worktree on a volume": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = "/Volumes/x/tree" }, "worktree in the install dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.InstallDir + "/tree" }, "worktree in the step socket dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.ToolRoot + "/tree" }, "worktree holding ~/.ssh": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.Home }, "worktree in an unknown /Users": func(in *EngineeringInput, _ *ClaudeCLI) { in.HomesUnknown = true }, "no state dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.StateDir = "" }, "no accounts root": func(in *EngineeringInput, _ *ClaudeCLI) { in.AccountsRoot = "" }, "no session root": func(in *EngineeringInput, _ *ClaudeCLI) { in.SessionRoot = "" }, "no home": func(in *EngineeringInput, _ *ClaudeCLI) { in.Home = "" }, "no install dir": func(in *EngineeringInput, c *ClaudeCLI) { in.InstallDir, *c = "", NewClaudeCLI("/Users/equipo-paul", "") }, "relative worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = "tree" }, "relative scratch": func(in *EngineeringInput, _ *ClaudeCLI) { in.Scratch = "policy-1" }, "unclean worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = s + "/x/../tree" }, "glob worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = s + "/worker-steps/*" }, "glob other home": func(in *EngineeringInput, _ *ClaudeCLI) { in.OtherHomes = []string{"/Users/*"} }, "brace scratch": func(in *EngineeringInput, _ *ClaudeCLI) { in.Scratch = s + "/policy-{1,2}" }, "newline in a path": func(in *EngineeringInput, _ *ClaudeCLI) { in.Scratch = s + "/policy\n1" }, "root as worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = "/" }, "scratch inside the worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.Scratch = in.Worktree + "/tmp" }, "worktree inside the scratch": func(in *EngineeringInput, _ *ClaudeCLI) { in.Worktree = in.Scratch + "/tree" }, "token home inside the worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.CredentialHome = in.Worktree + "/.home" }, "runtime copy inside the worktree": func(in *EngineeringInput, _ *ClaudeCLI) { in.ConfigDir = in.Worktree + "/.claude" }, "runtime copy outside its root": func(in *EngineeringInput, _ *ClaudeCLI) { in.ConfigDir = s + "/elsewhere/account-1" }, "socket outside the socket dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.Socket = s + "/sock" }, "socket path too long": func(in *EngineeringInput, _ *ClaudeCLI) { in.Socket = in.ToolRoot + "/" + strings.Repeat("d", 90) + "/s" }, "user temp outside the folders": func(in *EngineeringInput, _ *ClaudeCLI) { in.UserTemp = "/tmp/T" }, "no user temp": func(in *EngineeringInput, _ *ClaudeCLI) { in.UserTemp = "" }, "a Mach wildcard": func(in *EngineeringInput, _ *ClaudeCLI) { in.Mach = []string{"*"} }, "a Mach inner wildcard": func(in *EngineeringInput, _ *ClaudeCLI) { in.Mach = []string{"com.apple.*.x"} }, "unknown Xcode access": func(in *EngineeringInput, _ *ClaudeCLI) { in.XcodeAccess = "full" }, "unknown action": func(in *EngineeringInput, _ *ClaudeCLI) { in.Action = "copy" }, "no model": func(in *EngineeringInput, _ *ClaudeCLI) { in.Model = "" }, "a flag as model": func(in *EngineeringInput, _ *ClaudeCLI) { in.Model = "--dangerously-skip-permissions" }, "no session": func(in *EngineeringInput, _ *ClaudeCLI) { in.SessionID = "" }, "a session with a space": func(in *EngineeringInput, _ *ClaudeCLI) { in.SessionID = "a b" }, "no marker": func(in *EngineeringInput, _ *ClaudeCLI) { in.Attempt = "" }, "a marker with credentials": func(in *EngineeringInput, _ *ClaudeCLI) { in.Attempt = "https://user:pass@host" }, "a relative developer dir": func(in *EngineeringInput, _ *ClaudeCLI) { in.DeveloperDir = "Xcode.app" }, "a relative runner": func(in *EngineeringInput, _ *ClaudeCLI) { in.Runner = "equipo-runner" }, "no CLI": func(_ *EngineeringInput, c *ClaudeCLI) { *c = ClaudeCLI{} }, "a CLI in another install dir": func(_ *EngineeringInput, c *ClaudeCLI) { *c = NewClaudeCLI("/Users/equipo-paul", "/Users/equipo-paul/other") }, "an ask with Xcode access": func(in *EngineeringInput, _ *ClaudeCLI) { in.Action = claude.DarwinAnswer }, "a check with Xcode access": func(in *EngineeringInput, _ *ClaudeCLI) { in.Action = claude.DarwinCheck }, } for name, mutate := range cases { t.Run(name, func(t *testing.T) { in, cli := goldenInput(claude.DarwinImplement, wire.XcodeAccessSandboxed), goldenCLI() mutate(&in, &cli) if p, err := EngineeringPolicy(cli, in); !errors.Is(err, provider.ErrPolicy) { t.Fatalf("made %s (%v)", p.Settings, err) } }) } } // TestEngineeringNoMachWithoutAccess: Xcode's services and caches come // only with sandboxed Xcode access; without it the list the caller holds // is not used, and the policy layer refuses one handed to it anyway. func TestEngineeringNoMachWithoutAccess(t *testing.T) { in := goldenInput(claude.DarwinImplement, "") in.Mach = []string{"com.apple.CoreSimulator.*", "com.apple.dt.*"} p, err := EngineeringPolicy(goldenCLI(), in) if err != nil { t.Fatal(err) } s, _ := settingsOf(t, p) if m := s.Sandbox.Network.AllowMachLookup; m == nil || len(m) != 0 { t.Fatalf("Mach without access: %v", m) } for _, w := range s.Sandbox.Filesystem.AllowWrite { if w != in.Worktree && w != in.Scratch { t.Fatalf("an Xcode place without access: %v", s.Sandbox.Filesystem.AllowWrite) } } var m struct{ XcodeAccess *string } if json.Unmarshal(p.Manifest, &m) != nil || m.XcodeAccess == nil || *m.XcodeAccess != "" { t.Fatalf("xcode access not recorded: %s", p.Manifest) } in.XcodeAccess = wire.XcodeAccessSandboxed p, err = EngineeringPolicy(goldenCLI(), in) if err != nil { t.Fatal(err) } if s, _ = settingsOf(t, p); !slices.Equal(s.Sandbox.Network.AllowMachLookup, in.Mach) { t.Fatalf("sandboxed access: %v", s.Sandbox.Network.AllowMachLookup) } // The policy layer on its own: services or Xcode writes with no // access are refused, not quietly kept. d := claudeInputs(t, goldenInput(claude.DarwinImplement, "")) for name, mutate := range map[string]func(*claude.DarwinInputs){ "mach": func(d *claude.DarwinInputs) { d.Mach = []string{"com.apple.dt.*"} }, "writes": func(d *claude.DarwinInputs) { d.XcodeWrites = []string{"/Users/equipo-paul/Library/Developer/Xcode/DerivedData"} }, } { c := d mutate(&c) if _, err := claude.DarwinPolicy(c); !errors.Is(err, provider.ErrPolicy) { t.Fatalf("%s without access: %v", name, err) } } } func claudeInputs(t *testing.T, in EngineeringInput) claude.DarwinInputs { t.Helper() d, err := goldenCLI().darwinInputs(in) if err != nil { t.Fatal(err) } return d } // engRig is a launch on this machine's filesystem: a provisioned fake // CLI in a private home, a real worktree, scratch and runtime copy. type engRig struct { t *testing.T cli ClaudeCLI in EngineeringInput token []byte started []EngineeringCommand read [][]byte } func newEngRig(t *testing.T) *engRig { t.Helper(); return newEngRigWith(t, fakeClaude()) } // newEngRigWith is the rig with body as the pinned CLI. func newEngRigWith(t *testing.T, body []byte) *engRig { t.Helper() home, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { t.Fatal(err) } if err := os.Chmod(home, 0700); err != nil { t.Fatal(err) } install := filepath.Join(home, ".local", "lib", "equipo-runner") share := filepath.Join(home, ".local", "share", "equipo-runner") scratch := filepath.Join(share, "scratch") in := EngineeringInput{ 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"}}, Action: claude.DarwinImplement, Model: "claude-haiku-5-5", Worktree: filepath.Join(scratch, "worker-steps", "k", "tree"), Scratch: filepath.Join(scratch, "policy-1"), // The socket is never dialled here, and a temporary home is too // deep for sun_path: a short path stands for it. Runner: filepath.Join(install, "equipo-runner"), ToolRoot: "/private/tmp/equipo-t", Socket: "/private/tmp/equipo-t/1/s", ConfigDir: filepath.Join(scratch, "homes", "account-1"), CredentialHome: filepath.Join(home, ".local", "share", "equipo", "accounts", "claude-1"), RuntimeRoot: filepath.Join(scratch, "homes"), DeveloperDir: "/Applications/Xcode.app/Contents/Developer", Attempt: "attempt-7f3a", SessionID: "00000000-0000-4000-8000-000000000001", } for _, d := range []string{install, in.Worktree, in.Scratch, in.ConfigDir, in.CredentialHome, in.StateDir} { if err := os.MkdirAll(d, 0700); err != nil { t.Fatal(err) } } cli := homeCLI(home, install, body) if err := cli.Provision(context.Background(), serve(body, nil)); err != nil { t.Fatal(err) } return &engRig{t: t, cli: cli, in: in, token: []byte("sk-ant-oat01-SENTINEL-the-token-goes-by-descriptor-only-AA")} } func (r *engRig) policy() provider.Policy { r.t.Helper() p, err := EngineeringPolicy(r.cli, r.in) if err != nil { r.t.Fatal(err) } return p } // launch runs LaunchEngineering with a start that records the command // and reads the token descriptor to its end, as the CLI does. func (r *engRig) launch(p provider.Policy) error { return LaunchEngineering(context.Background(), r.cli, r.in, p, slices.Clone(r.token), func(_ context.Context, c EngineeringCommand) error { r.started = append(r.started, c) var got []byte if len(c.Files) > 0 { got, _ = io.ReadAll(c.Files[0]) } r.read = append(r.read, got) return nil }) } // rehashed is p with its manifest changed by edit and every hash // recomputed, as someone forging a policy would. func rehashed(t *testing.T, p provider.Policy, edit func(m map[string]json.RawMessage)) provider.Policy { t.Helper() var m map[string]json.RawMessage if err := json.Unmarshal(p.Manifest, &m); err != nil { t.Fatal(err) } edit(m) raw, err := json.Marshal(m) if err != nil { t.Fatal(err) } sum := sha256.Sum256(raw) p.Manifest, p.Hash, p.ManifestHash = raw, hex.EncodeToString(sum[:]), hex.EncodeToString(sum[:]) p.Settings = bytes.Clone(m["Settings"]) var env map[string]string json.Unmarshal(m["Env"], &env) p.Env = env return p } // TestEngineeringPolicyValidatedBeforeLaunch: the launcher regenerates // the policy from its inputs and starts nothing on any difference. func TestEngineeringPolicyValidatedBeforeLaunch(t *testing.T) { r := newEngRig(t) p := r.policy() if err := r.launch(p); err != nil { t.Fatal(err) } 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 { t.Fatalf("started %+v", r.started) } settings := filepath.Join(r.in.ConfigDir, "equipo-settings.json") mcp := filepath.Join(r.in.ConfigDir, "equipo-mcp.json") for path, want := range map[string][]byte{settings: p.Settings, mcp: p.MCP} { got, err := os.ReadFile(path) info, _ := os.Lstat(path) if err != nil || !bytes.Equal(got, want) || info.Mode() != 0600 { t.Fatalf("%s: %v %s", path, err, got) } } other := r.in other.SessionID = "00000000-0000-4000-8000-000000000002" forOther, err := EngineeringPolicy(r.cli, other) if err != nil { t.Fatal(err) } cases := map[string]func(provider.Policy) provider.Policy{ "one byte of settings": func(p provider.Policy) provider.Policy { p.Settings = bytes.Replace(bytes.Clone(p.Settings), []byte("600000"), []byte("600001"), 1) return p }, "one byte of the manifest's settings, rehashed": func(p provider.Policy) provider.Policy { return rehashed(t, p, func(m map[string]json.RawMessage) { m["Settings"] = bytes.Replace(m["Settings"], []byte(`"strictAllowlist":true`), []byte(`"strictAllowlist":0 `), 1) }) }, "a different argv, rehashed": func(p provider.Policy) provider.Policy { return rehashed(t, p, func(m map[string]json.RawMessage) { m["Argv"] = bytes.Replace(m["Argv"], []byte(`"manual"`), []byte(`"bypassPermissions"`), 1) }) }, "an extra environment key": func(p provider.Policy) provider.Policy { p.Env = maps.Clone(p.Env) p.Env["NODE_OPTIONS"] = "--require /tmp/x.js" return p }, "an extra environment key, rehashed": func(p provider.Policy) provider.Policy { return rehashed(t, p, func(m map[string]json.RawMessage) { m["Env"] = bytes.Replace(m["Env"], []byte(`{`), []byte(`{"NODE_OPTIONS":"--require /tmp/x.js",`), 1) }) }, "a changed hash": func(p provider.Policy) provider.Policy { p.Hash = strings.Repeat("0", 64) return p }, "a mount added": func(p provider.Policy) provider.Policy { p.Mounts = []provider.Mount{{Source: "/", Target: "/x"}} return p }, "another attempt's policy": func(provider.Policy) provider.Policy { return forOther }, } for name, mutate := range cases { t.Run(name, func(t *testing.T) { r.started = nil os.Remove(settings) if err := r.launch(mutate(p)); !errors.Is(err, provider.ErrPolicy) || len(r.started) != 0 { t.Fatalf("launched (%v, %d)", err, len(r.started)) } if _, err := os.Lstat(settings); !errors.Is(err, fs.ErrNotExist) { t.Fatalf("settings written for a refused launch: %v", err) } }) } // What the filesystem must show at the start: a worktree that is its // own real path, and no token file the CLI would read by itself. t.Run("a token file in the runtime copy", func(t *testing.T) { for _, name := range []string{".oauth_token", ".oauth-token"} { r.started = nil path := filepath.Join(r.in.ConfigDir, name) if err := os.WriteFile(path, []byte("x"), 0600); err != nil { t.Fatal(err) } if err := r.launch(p); !errors.Is(err, provider.ErrPolicy) || len(r.started) != 0 { t.Fatalf("%s: launched (%v)", name, err) } os.Remove(path) } }) t.Run("a worktree that is a link", func(t *testing.T) { r.started = nil real := r.in.Worktree + ".real" if err := os.Rename(r.in.Worktree, real); err != nil { t.Fatal(err) } if err := os.Symlink(real, r.in.Worktree); err != nil { t.Fatal(err) } defer func() { os.Remove(r.in.Worktree); os.Rename(real, r.in.Worktree) }() if err := r.launch(p); !errors.Is(err, provider.ErrPolicy) || len(r.started) != 0 { t.Fatalf("launched (%v)", err) } }) // The CLI itself is still checked by ClaudeCLI.Launch. t.Run("an unpinned CLI", func(t *testing.T) { r.started = nil if err := os.Chmod(ClaudePath(r.in.InstallDir), 0755); err != nil { t.Fatal(err) } defer os.Chmod(ClaudePath(r.in.InstallDir), 0700) var u *ClaudeUnavailable if err := r.launch(p); !errors.As(err, &u) || len(r.started) != 0 { t.Fatalf("launched (%v)", err) } }) } // TestEngineeringEnvFromScratch: the CLI's environment is exactly the // certified one; nothing of the runner's own is inherited. func TestEngineeringEnvFromScratch(t *testing.T) { t.Setenv("EQUIPO_INHERITED_SENTINEL", "inherited") t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "inherited-token") t.Setenv("ANTHROPIC_API_KEY", "inherited-key") t.Setenv("SSH_AUTH_SOCK", "/private/tmp/agent.sock") r := newEngRig(t) p := r.policy() if err := r.launch(p); err != nil { t.Fatal(err) } want := []string{ "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3", "CLAUDE_CODE_PROJECT_DIR_NAME=-workspace", "CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1", "CLAUDE_CONFIG_DIR=" + r.in.ConfigDir, "DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer", "DISABLE_AUTOUPDATER=1", "EQUIPO_ATTEMPT=attempt-7f3a", "HOME=" + r.in.Home, "LANG=en_US.UTF-8", "PATH=/usr/bin:/bin:/usr/sbin:/sbin", "TMPDIR=" + r.in.Scratch, } if len(r.started) != 1 || !slices.Equal(r.started[0].Env, want) { t.Fatalf("env %+v\nwant %q", r.started, want) } // The policy records the same environment, and the marker's name is // one the CLI's scrub keeps (task 1, S5). var rec []string for k, v := range p.Env { rec = append(rec, k+"="+v) } slices.Sort(rec) if !slices.Equal(rec, want) { t.Fatalf("policy env %q", rec) } for _, word := range []string{"TOKEN", "KEY", "AUTH", "PAT", "SECRET"} { if strings.Contains("EQUIPO_ATTEMPT", word) { t.Fatalf("marker name has %s", word) } } // No developer dir: no DEVELOPER_DIR, nothing else changes. r.in.DeveloperDir = "" r.started = nil if err := r.launch(r.policy()); err != nil { t.Fatal(err) } if !slices.Equal(r.started[0].Env, slices.DeleteFunc(slices.Clone(want), func(s string) bool { return strings.HasPrefix(s, "DEVELOPER_DIR=") })) { t.Fatalf("env without a developer dir: %q", r.started[0].Env) } } // TestEngineeringTokenNotInArgvOrPolicy: the token reaches the CLI only // on its descriptor. It is in no argv, no policy, no environment (a // sandboxed command can read the CLI's initial environment), no file and // no refusal's words. func TestEngineeringTokenNotInArgvOrPolicy(t *testing.T) { r := newEngRig(t) p := r.policy() if err := r.launch(p); err != nil { t.Fatal(err) } token := string(r.token) c := r.started[0] if strings.Contains(strings.Join(c.Argv, "\x00"), token) || strings.Contains(strings.Join(c.Env, "\x00"), token) { t.Fatal("token in argv or environment") } for _, kv := range c.Env { k, _, _ := strings.Cut(kv, "=") if k == "CLAUDE_CODE_OAUTH_TOKEN" || k == "ANTHROPIC_API_KEY" || k == "ANTHROPIC_AUTH_TOKEN" { t.Fatalf("a token variable in the environment: %s", k) } } stored, _ := json.Marshal(p) if bytes.Contains(stored, r.token) || bytes.Contains(p.Manifest, r.token) { t.Fatal("token in the policy") } if len(c.Files) != 1 || !bytes.Equal(r.read[0], r.token) || !slices.Contains(c.Env, "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR=3") { t.Fatalf("token not on descriptor 3: %q", r.read) } // Nothing on disk under the runner's home holds it. filepath.WalkDir(r.in.Home, func(path string, d fs.DirEntry, err error) error { if err == nil && d.Type().IsRegular() { if b, _ := os.ReadFile(path); bytes.Contains(b, r.token) { t.Fatalf("token written to %s", path) } } return nil }) // Refusals neither start nor say it. for name, bad := range map[string][]byte{ "empty": nil, "a newline": []byte(token + "\nmore"), "too long": bytes.Repeat([]byte("a"), 4097), } { r.started = nil err := LaunchEngineering(context.Background(), r.cli, r.in, p, bad, func(context.Context, EngineeringCommand) error { r.started = append(r.started, EngineeringCommand{}) return nil }) if err == nil || len(r.started) != 0 || strings.Contains(err.Error(), token) { t.Fatalf("%s token: %v", name, err) } } r.started = nil bad := p bad.Hash = "" if err := r.launch(bad); err == nil || strings.Contains(err.Error(), token) || len(r.started) != 0 { t.Fatalf("refused policy: %v", err) } } // wantCredentialPlaces is the test's own list of where developer tools keep // credentials in a home by default (fix round 1's audit): Claude Code, // Codex, GitHub's CLI, git, netrc, Docker, npm, Yarn, PyPI, RubyGems, // Cargo, Gradle, Maven, Kubernetes, the cloud CLIs, Terraform, Firebase, // Hugging Face, fastlane and App Store Connect keys, pass, and the shell // histories (a token typed once stays there). func wantCredentialPlaces(home string) []string { var out []string for _, rel := range []string{".claude", ".claude.json", ".codex", ".config/gh", ".config/hub", ".git-credentials", ".config/git/credentials", ".netrc", ".docker/config.json", ".npmrc", ".yarnrc.yml", ".pypirc", ".gem/credentials", ".cargo/credentials", ".cargo/credentials.toml", ".gradle/gradle.properties", ".m2/settings.xml", ".m2/settings-security.xml", ".kube", ".config/gcloud", ".azure", ".terraform.d", ".config/configstore", ".cache/huggingface/token", ".huggingface", ".fastlane", ".appstoreconnect", ".private_keys", "private_keys", ".password-store", ".bash_history", ".zsh_history", ".zsh_sessions"} { out = append(out, home+"/"+rel) } return out } // TestEngineeringCredentialPlacesDenied: sentinel credentials where the // tools write them by default are denied to sandboxed commands both // ways and to the native tools, whether or not they exist at launch; // Xcode's own places in the home stay writable with sandboxed access. func TestEngineeringCredentialPlacesDenied(t *testing.T) { r := newEngRig(t) r.in.XcodeAccess = wire.XcodeAccessSandboxed r.in.UserTemp = "/private/var/folders/4m/abc123_def/T" r.in.Mach = CheckMachServices before := r.policy() sentinels := []string{".claude/.credentials.json", ".claude.json", ".codex/auth.json", ".config/gh/hosts.yml", ".git-credentials", ".netrc", ".docker/config.json", ".npmrc", ".aws/credentials", ".ssh/id_ed25519", ".kube/config", ".zsh_history", ".appstoreconnect/private_keys/AuthKey_X.p8"} for _, rel := range sentinels { path := filepath.Join(r.in.Home, rel) if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { t.Fatal(err) } if err := os.WriteFile(path, []byte("SENTINEL-credential"), 0600); err != nil { t.Fatal(err) } } p := r.policy() if !bytes.Equal(before.Manifest, p.Manifest) { t.Fatal("the policy depends on what exists in the home") } s, _ := settingsOf(t, p) fsys := s.Sandbox.Filesystem covered := func(list []string, path string) bool { for _, d := range list { if path == d || strings.HasPrefix(path, d+"/") { return true } } return false } for _, rel := range sentinels { path := filepath.Join(r.in.Home, rel) if !covered(fsys.DenyRead, path) || !covered(fsys.DenyWrite, path) { t.Fatalf("%s readable or writable by sandboxed commands", rel) } native := false for _, d := range fsys.DenyRead { if covered([]string{d}, path) && slices.Contains(s.Permissions.Deny, "Read(/"+d+"/**)") && slices.Contains(s.Permissions.Deny, "Grep(/"+d+")") { native = true } } raw, _ := json.Marshal(map[string]any{"tool_name": "Read", "input": map[string]string{"file_path": path}}) var v struct{ Behavior string } json.Unmarshal(claude.StepPermission(raw, p), &v) if !native || v.Behavior != "deny" { t.Fatalf("%s: native deny %v, port %q", rel, native, v.Behavior) } } 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"} { if !slices.Contains(fsys.AllowWrite, w) || covered(fsys.DenyWrite, w) || covered(fsys.DenyRead, w) { t.Fatalf("Xcode's %s denied", w) } } }