package claude import ( "context" "encoding/json" "fmt" "io/fs" "os" "path/filepath" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/runner/provider" ) // withWalkHook runs hook after each batch of entries the Grep walk reads // and before it checks them, for one test. func withWalkHook(t *testing.T, hook func(dir string, names []string)) { t.Helper() walkHook = hook t.Cleanup(func() { walkHook = nil }) } // TestPermissionWalkFailsClosed: the Grep walk allows only what it could // verify. A directory it cannot list, an entry it cannot stat, an entry // whose type changed after it was listed (a file swapped for a link, a // directory swapped for one), a special file, or an error anywhere is a // refusal. func TestPermissionWalkFailsClosed(t *testing.T) { if os.Geteuid() == 0 { t.Skip("permissions do not bind root") } r := newDarwinRig(t) mk := func(parts ...string) string { d := filepath.Join(append([]string{r.root}, parts...)...) if err := os.MkdirAll(d, 0700); err != nil { t.Fatal(err) } return d } grep := func(path string) string { b, _ := r.answer(StepPermission, r.policy, "Grep", map[string]any{"pattern": "x", "path": path}) return b } // Unlistable and unsearchable directories. noread := mk("noread") os.WriteFile(filepath.Join(noread, "a"), []byte("a"), 0600) nosearch := mk("nosearch") os.WriteFile(filepath.Join(nosearch, "a"), []byte("a"), 0600) os.Chmod(noread, 0300) os.Chmod(nosearch, 0600) t.Cleanup(func() { os.Chmod(noread, 0700); os.Chmod(nosearch, 0700) }) locked := mk("locked", "inner") os.Chmod(locked, 0300) t.Cleanup(func() { os.Chmod(locked, 0700) }) for name, path := range map[string]string{"unlistable": noread, "unsearchable": nosearch, "inside unsearchable": filepath.Join(r.root, "nosearch", "a"), "holding an unopenable directory": filepath.Dir(locked)} { if grep(path) == "allow" { t.Errorf("%s: Grep allowed", name) } } if fileVerified(filepath.Join(nosearch, "a")) || fileVerified(filepath.Join(noread, "a")) { t.Error("a file that cannot be statted verified") } if grep(mk("fine")) != "allow" { t.Fatal("a plain directory refused") } // A listing that fails part way refuses. fails := mk("fails") os.WriteFile(filepath.Join(fails, "a"), []byte("a"), 0600) saved := readDir readDir = func(f *os.File, n int) ([]fs.DirEntry, error) { return nil, syscall.EIO } if grep(fails) == "allow" { t.Error("a failed listing allowed") } readDir = saved // A pipe has nothing to search, named or met. pipes := mk("pipes") if err := syscall.Mkfifo(filepath.Join(pipes, "p"), 0600); err != nil { t.Fatal(err) } if grep(pipes) == "allow" || grep(filepath.Join(pipes, "p")) == "allow" { t.Error("pipe allowed") } if b, _ := r.answer(StepPermission, r.policy, "Read", map[string]any{"file_path": filepath.Join(pipes, "p")}); b == "allow" { t.Error("Read of a pipe allowed") } // Swaps after the listing, before the check. swapFile := mk("swapfile") os.WriteFile(filepath.Join(swapFile, "a.txt"), []byte("a"), 0600) swapDir := mk("swapdir", "d") os.WriteFile(filepath.Join(swapDir, "a.txt"), []byte("a"), 0600) // Each case searches a directory that passes until its swap. for _, d := range []string{swapFile, filepath.Dir(swapDir)} { if grep(d) != "allow" { t.Fatalf("%s refused before any swap", d) } } for name, tc := range map[string]struct { dir, entry string swap func(path string) error }{ "file to an outward link": {swapFile, "a.txt", func(p string) error { os.Remove(p) return os.Symlink(filepath.Join(r.outside, "secret"), p) }}, "file to an inside link": {swapFile, "a.txt", func(p string) error { os.Remove(p) return os.Symlink(filepath.Join(r.root, "README.md"), p) }}, "file to a hard link": {swapFile, "a.txt", func(p string) error { os.Remove(p) return os.Link(filepath.Join(r.outside, "hard"), p) }}, "directory to a link": {filepath.Dir(swapDir), "d", func(p string) error { if err := os.Rename(p, p+".moved"); err != nil { return err } return os.Symlink(p+".moved", p) }}, } { t.Run(name, func(t *testing.T) { done := false withWalkHook(t, func(dir string, names []string) { if done || dir != tc.dir { return } done = true if err := tc.swap(filepath.Join(dir, tc.entry)); err != nil { t.Fatal(err) } }) if grep(tc.dir) == "allow" { t.Errorf("allowed after the swap") } if !done { t.Fatal("the walk never listed the directory") } }) // Undo for the next case. p := filepath.Join(tc.dir, tc.entry) os.Remove(p) if tc.entry == "d" { os.Rename(p+".moved", p) } else { os.WriteFile(p, []byte("a"), 0600) } } } // TestPermissionWalkOpensWhatItStatted: a directory replaced by another // between its stat and its open (no link involved) is refused. func TestPermissionWalkOpensWhatItStatted(t *testing.T) { r := newDarwinRig(t) parent := filepath.Join(r.root, "replaced") d := filepath.Join(parent, "d") os.MkdirAll(d, 0700) m, _ := policyManifest(r.policy) if !searchable(parent, r.root, deniedForms(m), 100) { t.Fatal("refused before the swap") } t.Cleanup(func() { openHook = nil }) openHook = func(path string) { if path == d { os.Rename(d, d+".old") os.Mkdir(d, 0700) } } if searchable(parent, r.root, deniedForms(m), 100) { t.Fatal("opened a directory other than the one statted") } // The same directory behind a link to itself: the inode matches, but // a link is never opened. os.RemoveAll(d) os.RemoveAll(d + ".old") os.Mkdir(d, 0700) openHook = func(path string) { if path == d { os.Rename(d, d+".real") os.Symlink(d+".real", d) } } if searchable(parent, r.root, deniedForms(m), 100) { t.Fatal("opened a directory through a link") } // The searched directory itself replaced between its stat and open. os.Remove(d) os.Rename(d+".real", d) openHook = func(path string) { if path == parent { os.Rename(parent, parent+".old") os.Mkdir(parent, 0700) } } if searchable(parent, r.root, deniedForms(m), 100) { t.Fatal("searched a directory other than the one statted") } } // TestPermissionWalkIsBounded: the walk reads entries in batches and // stops reading when its budget is spent, refusing, rather than listing // a whole directory first. func TestPermissionWalkIsBounded(t *testing.T) { r := newDarwinRig(t) big := filepath.Join(r.root, "big") os.MkdirAll(big, 0700) for i := range 1000 { os.WriteFile(filepath.Join(big, fmt.Sprintf("f%04d", i)), nil, 0600) } read := 0 withWalkHook(t, func(dir string, names []string) { read += len(names) }) m, _ := policyManifest(r.policy) if searchable(big, r.root, deniedForms(m), 10) { t.Fatal("past the budget, allowed") } if read > 10+walkBatch { t.Fatalf("read %d entries for a budget of 10", read) } read = 0 if !searchable(big, r.root, deniedForms(m), 2000) || read != 1000 { t.Fatalf("within the budget: read %d", read) } if walkBatch > 1024 || grepWalkLimit < 200000 { t.Fatalf("batch %d, bound %d", walkBatch, grepWalkLimit) } } // TestLauncherDarwinNeverAsks: through the launcher's own permission // endpoint, a Mac file action is decided once by the port and answered // at once, allow or deny; none reaches the person's event stream, even // when the tree changes while it is checked. A question still does. func TestLauncherDarwinNeverAsks(t *testing.T) { r := newDarwinRig(t) f := fixtureFor(t, "Engineering") s, events := openFixture(t, f) f.l.mu.Lock() st, _ := f.l.state(s) st.active = true st.turn = provider.Turn{ID: "turn"} st.launch.Policy = r.policy f.l.mu.Unlock() ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() ask := func(tool string, input map[string]any) string { t.Helper() in, _ := json.Marshal(input) raw, _ := json.Marshal(map[string]any{"tool_name": tool, "input": json.RawMessage(in)}) out, err := f.l.Permission(ctx, s, raw) if err != nil { t.Fatalf("%s %v: %v", tool, input, err) } select { case ev := <-events: t.Fatalf("%s %v reached a person: %s", tool, input, ev.Payload) default: } var v struct{ Behavior string } json.Unmarshal(out, &v) return v.Behavior } if ask("Read", map[string]any{"file_path": filepath.Join(r.root, "README.md")}) != "allow" { t.Fatal("inside read not allowed") } 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.root}}, {"Read", map[string]any{"file_path": filepath.Join(r.root, "inlink", "secret")}}, {"SandboxNetworkAccess", map[string]any{"host": "example.com"}}, } { if ask(tc.tool, tc.input) != "deny" { t.Fatalf("%s %v not denied", tc.tool, tc.input) } } // A listed file becomes a hard link while the walk runs: denied, not // relayed. (A name added after its directory was listed is the race // with the CLI's own read, which no walk can close; F6.) sub := filepath.Join(r.root, "sub") if ask("Grep", map[string]any{"pattern": "x", "path": sub}) != "allow" { t.Fatal("clean search refused") } withWalkHook(t, func(dir string, names []string) { if dir == sub { os.Remove(filepath.Join(sub, "a.go")) os.Link(filepath.Join(r.outside, "hard"), filepath.Join(sub, "a.go")) } }) if ask("Grep", map[string]any{"pattern": "x", "path": sub}) != "deny" { t.Fatal("a hard link made during the walk was allowed") } // A question is still the person's. raw := json.RawMessage(`{"tool_name":"AskUserQuestion","input":{"questions":[{"question":"Which?","options":[{"label":"blue"}]}]}}`) go f.l.Permission(ctx, s, raw) select { case ev := <-events: f.l.Respond(ctx, s, provider.Answer{TurnID: "turn", RequestID: ev.RequestID, Behavior: "deny"}) case <-ctx.Done(): t.Fatal("question not relayed") } }