package claude import ( "encoding/json" "os" "path/filepath" "slices" "strings" "testing" "amadan.net/oficina/equipo/internal/runner/mac/denylist" "amadan.net/oficina/equipo/internal/runner/provider" ) // The darwin permission port, on Linux: temp directories stand in for // the Mac's paths. base/var is a link to base/private/var, as /var is to // /private/var on macOS, and the worktree's real path is under // base/private/var. base/Users holds the runner user's home and one // other person's; base/outside holds files no step may reach. type darwinRig struct { t *testing.T base, root, alias, outside, home string research, other string // jose and zoe are two more homes: José in NFC, Zoë in NFD. jose, zoe string paths denylist.Paths policy provider.Policy } func newDarwinRig(t *testing.T) *darwinRig { t.Helper() base, err := filepath.EvalSymlinks(t.TempDir()) if err != nil { t.Fatal(err) } r := &darwinRig{t: t, base: base} real := filepath.Join(base, "private", "var", "folders", "zz", "T") r.root = filepath.Join(real, "equipo", "wt") r.alias = filepath.Join(base, "var", "folders", "zz", "T", "equipo", "wt") r.outside = filepath.Join(base, "outside") r.home = filepath.Join(base, "Users", "paulequipo") r.other = filepath.Join(base, "Users", "paulca") r.research = filepath.Join(real, "equipo", "research") r.jose = filepath.Join(base, "Users", "Jos\u00e9") r.zoe = filepath.Join(base, "Users", "Zoe\u0308") for _, d := range []string{r.jose, r.zoe, r.root, filepath.Join(r.root, "sub"), filepath.Join(real, "equipo", "sibling"), r.research, filepath.Join(r.outside, "dir"), filepath.Join(r.home, ".ssh"), filepath.Join(r.home, ".equipo", "state"), r.other} { if err := os.MkdirAll(d, 0700); err != nil { t.Fatal(err) } } if err := os.Symlink(filepath.Join(base, "private", "var"), filepath.Join(base, "var")); err != nil { t.Fatal(err) } write := func(path, text string) { if err := os.WriteFile(path, []byte(text), 0600); err != nil { t.Fatal(err) } } write(filepath.Join(r.root, "README.md"), "hello") write(filepath.Join(r.root, "sub", "a.go"), "package sub") write(filepath.Join(real, "equipo", "sibling", "x"), "sibling") write(filepath.Join(r.research, "img1.png"), "png") write(filepath.Join(r.outside, "secret"), "secret") write(filepath.Join(r.outside, "dir", "secret"), "secret") write(filepath.Join(r.outside, "hard"), "secret") write(filepath.Join(r.home, ".ssh", "id_ed25519"), "key") write(filepath.Join(r.other, "notes"), "theirs") links := map[string]string{ "inlink": filepath.Join(r.outside, "dir"), "filelink": filepath.Join(r.outside, "secret"), "dangle": filepath.Join(r.outside, "new"), "samelink": filepath.Join(r.root, "README.md"), } for name, target := range links { if err := os.Symlink(target, filepath.Join(r.root, name)); err != nil { t.Fatal(err) } } if err := os.Link(filepath.Join(r.outside, "hard"), filepath.Join(r.root, "hard")); err != nil { t.Fatal(err) } r.paths = denylist.Paths{Home: r.home, StateDir: filepath.Join(r.home, ".equipo", "state"), AccountsRoot: filepath.Join(r.home, ".equipo", "accounts"), SessionRoot: filepath.Join(r.home, ".equipo", "sessions"), InstallDir: filepath.Join(r.home, ".equipo", "bin"), OtherHomes: []string{r.other, r.jose, r.zoe}} r.policy = r.policyWith(r.root, r.research) return r } // policyWith is a darwin Engineering policy whose manifest carries the // fields the port reads: the platform, the roots, the §4.2 list as // DeniedPaths, the native tools and settings that keep every command // sandboxed with the generated deny rules. func (r *darwinRig) policyWith(root, research string) provider.Policy { r.t.Helper() denied := denylist.DenyList(r.paths) rules, err := NativeDenyRules(denied) if err != nil { r.t.Fatal(err) } settings, _ := json.Marshal(map[string]any{ "disableAllHooks": true, "sandbox": map[string]any{"enabled": true, "failIfUnavailable": true, "allowUnsandboxedCommands": false, "autoAllowBashIfSandboxed": true, "excludedCommands": []string{}, "filesystem": map[string]any{"denyRead": denied, "denyWrite": denied}, "network": map[string]any{"allowedDomains": []string{}, "strictAllowlist": true}}, "permissions": map[string]any{"deny": rules, "allow": []string{"mcp__equipo__submit_candidate"}, "ask": []string{}}, }) raw, _ := json.Marshal(map[string]any{ "Platform": PlatformDarwin, "WorkspaceRoot": root, "ResearchRoot": research, "Action": "implement", "DeniedPaths": denied, "Settings": json.RawMessage(settings), "Tools": []string{"Bash", "Read", "Write", "Edit", "Glob", "Grep", "mcp__equipo__permission", "mcp__equipo__submit_candidate"}, }) return provider.Policy{Manifest: raw} } // answer is the step's answer to one request built from tool and input. func (r *darwinRig) answer(check func(json.RawMessage, provider.Policy) json.RawMessage, p provider.Policy, tool string, input map[string]any) (string, string) { r.t.Helper() in, _ := json.Marshal(input) raw, _ := json.Marshal(map[string]any{"tool_name": tool, "input": json.RawMessage(in)}) var v struct{ Behavior, Message string } if out := check(raw, p); json.Unmarshal(out, &v) != nil { r.t.Fatalf("not JSON: %s", out) } return v.Behavior, v.Message } func (r *darwinRig) allowed(p provider.Policy, tool string, input map[string]any) bool { b, _ := r.answer(StepPermission, p, tool, input) return b == "allow" } // TestPermissionRootIsResolved: the worktree is named by its real path. // A path through a link above it (/var for /private/var) is allowed // only when it lands inside that real root; a policy whose root is // itself an alias answers nothing. func TestPermissionRootIsResolved(t *testing.T) { r := newDarwinRig(t) for _, dir := range []string{r.root, r.alias} { for _, tc := range []struct { tool string input map[string]any }{ {"Read", map[string]any{"file_path": filepath.Join(dir, "README.md")}}, {"Edit", map[string]any{"file_path": filepath.Join(dir, "sub", "a.go"), "old_string": "sub", "new_string": "pkg"}}, {"Write", map[string]any{"file_path": filepath.Join(dir, "new", "deeper", "b.go"), "content": "package b"}}, {"Glob", map[string]any{"pattern": "**/*.go", "path": dir}}, {"Grep", map[string]any{"pattern": "package", "path": filepath.Join(dir, "sub"), "glob": "*.go"}}, } { if !r.allowed(r.policy, tc.tool, tc.input) { t.Fatalf("refused inside the real root (%s): %s %v", dir, tc.tool, tc.input) } } } // The alias leads elsewhere too: only the real root's inside counts. sibling := filepath.Join(filepath.Dir(r.alias), "sibling", "x") if r.allowed(r.policy, "Read", map[string]any{"file_path": sibling}) { t.Fatal("an alias that lands beside the root was allowed") } // A root that is itself an alias, or not there, refuses everything. for _, root := range []string{r.alias, filepath.Join(r.root, "missing"), r.root + "/", "/", "", "relative/wt"} { p := r.policyWith(root, "") if r.allowed(p, "Read", map[string]any{"file_path": filepath.Join(r.root, "README.md")}) { t.Fatalf("policy root %q answered", root) } } if w, rs := Roots(r.policy); w != r.root || rs != r.research { t.Fatalf("darwin roots %q %q", w, rs) } // Research reads are allowed through the read-only callback too; // nothing writes there. for _, check := range []func(json.RawMessage, provider.Policy) json.RawMessage{StepPermission, ReadPermission} { if b, _ := r.answer(check, r.policy, "Read", map[string]any{"file_path": filepath.Join(r.research, "img1.png")}); b != "allow" { t.Fatal("research read refused") } } b, msg := r.answer(StepPermission, r.policy, "Write", map[string]any{"file_path": filepath.Join(r.research, "img2.png"), "content": "x"}) if b == "allow" || !strings.Contains(msg, r.research+" is read-only") { t.Fatalf("research write: %s %q", b, msg) } // A Mac without kept images has no research root to read. if r.allowed(r.policyWith(r.root, ""), "Read", map[string]any{"file_path": filepath.Join(r.research, "img1.png")}) { t.Fatal("read a research directory the policy does not name") } } // TestPermissionRefusesEscapes: "..", a glob that would expand outside // the root, an absolute path outside it, and every link inside the root // (one pointing out above all) are refused, whatever the tool. func TestPermissionRefusesEscapes(t *testing.T) { r := newDarwinRig(t) type req struct { tool string input map[string]any } for name, tc := range map[string]req{ // ".." even where the lexical result stays inside, and after a // link, where it climbs from the link's target. "dot-dot inside": {"Read", map[string]any{"file_path": r.root + "/sub/../README.md"}}, "dot-dot after a link": {"Read", map[string]any{"file_path": r.root + "/inlink/../secret"}}, "dot-dot write": {"Write", map[string]any{"file_path": r.root + "/sub/../../sibling/x", "content": "x"}}, "dot-dot through alias": {"Read", map[string]any{"file_path": r.alias + "/../sibling/x"}}, "glob dot-dot": {"Glob", map[string]any{"pattern": "../sibling/*", "path": r.root}}, "glob brace dot-dot": {"Glob", map[string]any{"pattern": "{..,sub}/*", "path": r.root}}, "glob absolute": {"Glob", map[string]any{"pattern": r.outside + "/*", "path": r.root}}, "glob home": {"Glob", map[string]any{"pattern": "~/.ssh/*", "path": r.root}}, "glob through a link": {"Glob", map[string]any{"pattern": "inlink/*", "path": r.root}}, "grep glob dot-dot": {"Grep", map[string]any{"pattern": "x", "path": r.root, "glob": "../**"}}, "grep glob absolute": {"Grep", map[string]any{"pattern": "x", "path": r.root, "glob": r.outside + "/*"}}, "absolute outside read": {"Read", map[string]any{"file_path": filepath.Join(r.outside, "secret")}}, "absolute outside write": {"Write", map[string]any{"file_path": filepath.Join(r.outside, "new"), "content": "x"}}, "outside search": {"Grep", map[string]any{"pattern": "x", "path": r.outside}}, "link pointing out": {"Read", map[string]any{"file_path": r.root + "/inlink/secret"}}, "file link pointing out": {"Read", map[string]any{"file_path": r.root + "/filelink"}}, "edit through a link": {"Edit", map[string]any{"file_path": r.root + "/filelink", "old_string": "a", "new_string": "b"}}, "dangling link write": {"Write", map[string]any{"file_path": r.root + "/dangle", "content": "x"}}, "search through a link": {"Grep", map[string]any{"pattern": "x", "path": r.root + "/inlink"}}, "link pointing inside": {"Read", map[string]any{"file_path": r.root + "/samelink"}}, "hard link": {"Read", map[string]any{"file_path": r.root + "/hard"}}, "relative": {"Read", map[string]any{"file_path": "README.md"}}, "home": {"Read", map[string]any{"file_path": "~/.ssh/id_ed25519"}}, "no path": {"Grep", map[string]any{"pattern": "x"}}, "nul": {"Read", map[string]any{"file_path": r.root + "/README.md\x00"}}, } { if r.allowed(r.policy, tc.tool, tc.input) { t.Errorf("%s: allowed %s %v", name, tc.tool, tc.input) } } // The §4.2 places are refused as protected, not merely outside: a // person is never asked about them, in any spelling of their case. for name, path := range map[string]string{ "ssh": filepath.Join(r.home, ".ssh", "id_ed25519"), "state": filepath.Join(r.home, ".equipo", "state", "key"), "other home": filepath.Join(r.other, "notes"), "case": filepath.Join(r.base, "USERS", "PaulCA", "notes"), "volumes": "/Volumes/Backup/x", } { b, msg := r.answer(StepPermission, r.policy, "Read", map[string]any{"file_path": path}) if b == "allow" || !strings.Contains(msg, "protected") { t.Errorf("%s: %s %q, want protected", name, b, msg) } q := permissionRequest{Tool: "Read", Input: inputJSON(map[string]any{"file_path": path})} if !protectedNativePath(q, r.policy) { t.Errorf("%s: not protected for the person's path", name) } } // A search of a directory holding one is protected too. if b, msg := r.answer(StepPermission, r.policy, "Grep", map[string]any{"pattern": "x", "path": filepath.Join(r.base, "Users")}); b == "allow" || !strings.Contains(msg, "protected") { t.Errorf("search over the homes: %s %q", b, msg) } // A person's approval cannot widen an escape either, and none counts // as the workspace (which Equipo would answer itself). for _, path := range []string{r.root + "/inlink/secret", r.root + "/filelink", r.root + "/sub/../README.md", r.alias + "/../sibling/x"} { q := permissionRequest{Tool: "Read", Input: inputJSON(map[string]any{"file_path": path})} if _, err := permissionResult(q, provider.Answer{Behavior: "allow"}, r.policy); err == nil { t.Errorf("approval allowed %s", path) } if workspaceNativePath(q, r.policy) { t.Errorf("%s counted as the workspace", path) } } } // TestPermissionDeniedPathsGenerated: the CLI's own deny rules name each // §4.2 path (denylist.DenyList, shared with checks) as Tool(/) and // Tool(//**) for all five native file tools. func TestPermissionDeniedPathsGenerated(t *testing.T) { r := newDarwinRig(t) denied := denylist.DenyList(r.paths) if len(denied) < 9 { t.Fatalf("deny list %v", denied) } rules, err := NativeDenyRules(denied) if err != nil { t.Fatal(err) } for _, path := range denied { for _, tool := range []string{"Read", "Edit", "Write", "Glob", "Grep"} { for _, want := range []string{tool + "(/" + path + ")", tool + "(/" + path + "/**)"} { if !slices.Contains(rules, want) { t.Errorf("missing %s", want) } } } } if len(rules) != 10*len(denied) { t.Fatalf("%d rules for %d paths", len(rules), len(denied)) } for _, bad := range [][]string{{"relative"}, {"/a/../b"}, {"/a/*"}, {"/a(b)"}, {"/a/"}} { if _, err := NativeDenyRules(bad); err == nil { t.Errorf("rule for %v", bad) } } } // TestDarwinPortShellAndNetwork: with the CLI's env scrub, a Mac's // sandboxed Bash commands reach the callback (no auto-allow), so the // port allows them under the same rule as Linux: the policy keeps every // command in the sandbox. A request for network access from inside the // sandbox is always denied. The read-only callback runs no shell and // writes nothing. func TestDarwinPortShellAndNetwork(t *testing.T) { r := newDarwinRig(t) if b, _ := r.answer(StepPermission, r.policy, "Bash", map[string]any{"command": "swift build", "description": "d"}); b != "allow" { t.Fatal("sandboxed shell refused") } if b, _ := r.answer(StepPermission, r.policy, "Bash", map[string]any{"command": "ls", "dangerouslyDisableSandbox": true}); b == "allow" { t.Fatal("unsandboxed shell allowed") } if b, _ := r.answer(StepPermission, withSandboxSettings(t, r.policy, func(s map[string]any) { s["allowUnsandboxedCommands"] = true }), "Bash", map[string]any{"command": "ls"}); b == "allow" { t.Fatal("shell allowed under a policy that lets commands leave the sandbox") } for _, check := range []func(json.RawMessage, provider.Policy) json.RawMessage{StepPermission, ReadPermission} { if b, _ := r.answer(check, r.policy, "SandboxNetworkAccess", map[string]any{"host": "example.com"}); b != "deny" { t.Fatal("network access allowed") } } for _, tc := range []struct { tool string input map[string]any }{ {"Bash", map[string]any{"command": "ls"}}, {"Write", map[string]any{"file_path": filepath.Join(r.root, "c.go"), "content": "x"}}, } { b, msg := r.answer(ReadPermission, r.policy, tc.tool, tc.input) if b == "allow" || !strings.Contains(msg, "under "+r.root) { t.Fatalf("read-only %s: %s %q", tc.tool, b, msg) } } if b, _ := r.answer(ReadPermission, r.policy, "Grep", map[string]any{"pattern": "package", "path": filepath.Join(r.root, "sub")}); b != "allow" { t.Fatal("read-only search refused") } // Refusals name the policy's own root, never /workspace. for _, input := range []map[string]any{{"file_path": filepath.Join(r.outside, "secret")}, {"file_path": "README.md"}} { _, msg := r.answer(StepPermission, r.policy, "Read", input) if !strings.Contains(msg, r.root) || strings.Contains(msg, "/workspace") { t.Fatalf("refusal %q", msg) } } // An unknown platform answers nothing. var m map[string]any json.Unmarshal(r.policy.Manifest, &m) m["Platform"] = "windows" odd := provider.Policy{} odd.Manifest, _ = json.Marshal(m) if r.allowed(odd, "Read", map[string]any{"file_path": filepath.Join(r.root, "README.md")}) { t.Fatal("unknown platform answered") } // Nor does a Linux manifest that names a root of its own. f := fixtureFor(t, "Engineering") var lm map[string]any json.Unmarshal(f.launch.Policy.Manifest, &lm) lm["WorkspaceRoot"] = r.root linux := f.launch.Policy linux.Manifest, _ = json.Marshal(lm) if b, _ := r.answer(StepPermission, linux, "Read", map[string]any{"file_path": "/workspace/README.md"}); b == "allow" { t.Fatal("Linux manifest with a root answered") } } func inputJSON(v any) json.RawMessage { raw, _ := json.Marshal(v) return raw } // TestPermissionGrepReadsNoHardLink: Grep reads file contents, so a // hard link in the worktree to a file elsewhere must not be searchable, // named directly or met inside a searched directory. Before answering a // directory search the port walks it, following no link, and refuses a // hard-linked file, a link that does not resolve inside the root, or // more entries than its bound. func TestPermissionGrepReadsNoHardLink(t *testing.T) { r := newDarwinRig(t) clean := filepath.Join(r.root, "clean") nested := filepath.Join(r.root, "deep", "a", "b") out := filepath.Join(r.root, "pointsout") dangling := filepath.Join(r.root, "dangling") for _, d := range []string{clean, nested, out, dangling} { if err := os.MkdirAll(d, 0700); err != nil { t.Fatal(err) } } os.WriteFile(filepath.Join(clean, "a.txt"), []byte("hello"), 0600) must := func(err error) { if err != nil { t.Fatal(err) } } must(os.Symlink(filepath.Join(clean, "a.txt"), filepath.Join(clean, "alias.txt"))) must(os.Link(filepath.Join(r.outside, "hard"), filepath.Join(nested, "x"))) must(os.Symlink(filepath.Join(r.outside, "secret"), filepath.Join(out, "s"))) must(os.Symlink(filepath.Join(r.outside, "gone"), filepath.Join(dangling, "s"))) for _, check := range []func(json.RawMessage, provider.Policy) json.RawMessage{StepPermission, ReadPermission} { for name, path := range map[string]string{ "the hard link itself": filepath.Join(r.root, "hard"), "the root holding it": r.root, "a deep hard link": filepath.Join(r.root, "deep"), "a link out": out, "a link to nowhere": dangling, "the alias of the root": r.alias, } { for _, mode := range []string{"content", "files_with_matches"} { if b, _ := r.answer(check, r.policy, "Grep", map[string]any{"pattern": ".*", "path": path, "output_mode": mode}); b == "allow" { t.Errorf("%s (%s): Grep allowed", name, mode) } } } // A directory with only its own files and a link inside the root // is searched. if b, _ := r.answer(check, r.policy, "Grep", map[string]any{"pattern": "hello", "path": clean}); b != "allow" { t.Error("clean directory refused") } } // The walk stops at its bound and refuses past it. m, _ := policyManifest(r.policy) if !searchable(clean, r.root, deniedForms(m), 10) || searchable(clean, r.root, deniedForms(m), 1) { t.Fatal("walk bound not applied") } if grepWalkLimit < 200000 { t.Fatalf("bound %d is too small for an Xcode project", grepWalkLimit) } } // TestPermissionDeniedUnicode: APFS treats NFC and NFD spellings, and // case, as the same name, so a denied home is protected in every // spelling: José's (denied in NFC) asked for in NFD, Zoë's (denied in // NFD) asked for in NFC, and either in capitals. None may be allowed, // by the step or by a person. func TestPermissionDeniedUnicode(t *testing.T) { r := newDarwinRig(t) for _, home := range []string{"Jose\u0301", "JOSE\u0301", "jos\u00e9", "Zo\u00eb", "ZO\u00cb", "zoe\u0308"} { path := filepath.Join(r.base, "Users", home, "notes") b, msg := r.answer(StepPermission, r.policy, "Read", map[string]any{"file_path": path}) if b == "allow" || !strings.Contains(msg, "protected") { t.Errorf("%q: %s %q, want protected", home, b, msg) } q := permissionRequest{Tool: "Read", Input: inputJSON(map[string]any{"file_path": path})} if !protectedNativePath(q, r.policy) { t.Errorf("%q would reach a person", home) } if _, err := permissionResult(q, provider.Answer{Behavior: "allow"}, r.policy); err == nil { t.Errorf("%q allowed by an approval", home) } } // Folding compares whole components, never a prefix of one. if foldedWithin("/Users/Jos\u00e9", "/Users/Jose\u0301x/notes") || !foldedWithin("/Users/Jos\u00e9", "/users/JOSE\u0301/notes") { t.Fatal("component comparison") } } // TestPermissionOutsideNeverApproved: on a Mac nobody is asked about a // file action outside the roots. Anything not provably inside is denied // outright: it never reaches a person, and an approval cannot allow it. func TestPermissionOutsideNeverApproved(t *testing.T) { r := newDarwinRig(t) for _, tc := range []struct { tool string input map[string]any }{ {"Read", map[string]any{"file_path": filepath.Join(r.outside, "secret")}}, {"Write", map[string]any{"file_path": "/etc/hosts", "content": "x"}}, {"Grep", map[string]any{"pattern": "x", "path": r.outside}}, {"Write", map[string]any{"file_path": filepath.Join(r.research, "img2.png"), "content": "x"}}, {"Edit", map[string]any{"file_path": filepath.Join(r.research, "img1.png"), "old_string": "p", "new_string": "q"}}, } { q := permissionRequest{Tool: tc.tool, Input: inputJSON(tc.input)} if !protectedNativePath(q, r.policy) { t.Errorf("%s %v would reach a person", tc.tool, tc.input) } if _, err := permissionResult(q, provider.Answer{Behavior: "allow"}, r.policy); err == nil { t.Errorf("%s %v allowed by an approval", tc.tool, tc.input) } } // The step still says which rule refused. if _, msg := r.answer(StepPermission, r.policy, "Read", map[string]any{"file_path": filepath.Join(r.outside, "secret")}); !strings.Contains(msg, "only under "+r.root) { t.Fatalf("outside refusal %q", msg) } // Inside the root only the port's own decision allows: a person's // approval allows no file action on a Mac, inside or out. q := permissionRequest{Tool: "Read", Input: inputJSON(map[string]any{"file_path": filepath.Join(r.root, "README.md")})} if _, err := permissionResult(q, provider.Answer{Behavior: "allow"}, r.policy); err == nil || !protectedNativePath(q, r.policy) || workspaceNativePath(q, r.policy) { t.Fatalf("inside read approvable: %v", err) } if !r.allowed(r.policy, "Read", map[string]any{"file_path": filepath.Join(r.root, "README.md")}) { t.Fatal("inside read refused by the step") } }