| 1 | package claude |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "io/fs" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "syscall" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 15 | ) |
| 16 | |
| 17 | // withWalkHook runs hook after each batch of entries the Grep walk reads |
| 18 | // and before it checks them, for one test. |
| 19 | func withWalkHook(t *testing.T, hook func(dir string, names []string)) { |
| 20 | t.Helper() |
| 21 | walkHook = hook |
| 22 | t.Cleanup(func() { walkHook = nil }) |
| 23 | } |
| 24 | |
| 25 | // TestPermissionWalkFailsClosed: the Grep walk allows only what it could |
| 26 | // verify. A directory it cannot list, an entry it cannot stat, an entry |
| 27 | // whose type changed after it was listed (a file swapped for a link, a |
| 28 | // directory swapped for one), a special file, or an error anywhere is a |
| 29 | // refusal. |
| 30 | func TestPermissionWalkFailsClosed(t *testing.T) { |
| 31 | if os.Geteuid() == 0 { |
| 32 | t.Skip("permissions do not bind root") |
| 33 | } |
| 34 | r := newDarwinRig(t) |
| 35 | mk := func(parts ...string) string { |
| 36 | d := filepath.Join(append([]string{r.root}, parts...)...) |
| 37 | if err := os.MkdirAll(d, 0700); err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | return d |
| 41 | } |
| 42 | grep := func(path string) string { |
| 43 | b, _ := r.answer(StepPermission, r.policy, "Grep", map[string]any{"pattern": "x", "path": path}) |
| 44 | return b |
| 45 | } |
| 46 | // Unlistable and unsearchable directories. |
| 47 | noread := mk("noread") |
| 48 | os.WriteFile(filepath.Join(noread, "a"), []byte("a"), 0600) |
| 49 | nosearch := mk("nosearch") |
| 50 | os.WriteFile(filepath.Join(nosearch, "a"), []byte("a"), 0600) |
| 51 | os.Chmod(noread, 0300) |
| 52 | os.Chmod(nosearch, 0600) |
| 53 | t.Cleanup(func() { os.Chmod(noread, 0700); os.Chmod(nosearch, 0700) }) |
| 54 | locked := mk("locked", "inner") |
| 55 | os.Chmod(locked, 0300) |
| 56 | t.Cleanup(func() { os.Chmod(locked, 0700) }) |
| 57 | 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)} { |
| 58 | if grep(path) == "allow" { |
| 59 | t.Errorf("%s: Grep allowed", name) |
| 60 | } |
| 61 | } |
| 62 | if fileVerified(filepath.Join(nosearch, "a")) || fileVerified(filepath.Join(noread, "a")) { |
| 63 | t.Error("a file that cannot be statted verified") |
| 64 | } |
| 65 | if grep(mk("fine")) != "allow" { |
| 66 | t.Fatal("a plain directory refused") |
| 67 | } |
| 68 | // A listing that fails part way refuses. |
| 69 | fails := mk("fails") |
| 70 | os.WriteFile(filepath.Join(fails, "a"), []byte("a"), 0600) |
| 71 | saved := readDir |
| 72 | readDir = func(f *os.File, n int) ([]fs.DirEntry, error) { return nil, syscall.EIO } |
| 73 | if grep(fails) == "allow" { |
| 74 | t.Error("a failed listing allowed") |
| 75 | } |
| 76 | readDir = saved |
| 77 | // A pipe has nothing to search, named or met. |
| 78 | pipes := mk("pipes") |
| 79 | if err := syscall.Mkfifo(filepath.Join(pipes, "p"), 0600); err != nil { |
| 80 | t.Fatal(err) |
| 81 | } |
| 82 | if grep(pipes) == "allow" || grep(filepath.Join(pipes, "p")) == "allow" { |
| 83 | t.Error("pipe allowed") |
| 84 | } |
| 85 | if b, _ := r.answer(StepPermission, r.policy, "Read", map[string]any{"file_path": filepath.Join(pipes, "p")}); b == "allow" { |
| 86 | t.Error("Read of a pipe allowed") |
| 87 | } |
| 88 | // Swaps after the listing, before the check. |
| 89 | swapFile := mk("swapfile") |
| 90 | os.WriteFile(filepath.Join(swapFile, "a.txt"), []byte("a"), 0600) |
| 91 | swapDir := mk("swapdir", "d") |
| 92 | os.WriteFile(filepath.Join(swapDir, "a.txt"), []byte("a"), 0600) |
| 93 | // Each case searches a directory that passes until its swap. |
| 94 | for _, d := range []string{swapFile, filepath.Dir(swapDir)} { |
| 95 | if grep(d) != "allow" { |
| 96 | t.Fatalf("%s refused before any swap", d) |
| 97 | } |
| 98 | } |
| 99 | for name, tc := range map[string]struct { |
| 100 | dir, entry string |
| 101 | swap func(path string) error |
| 102 | }{ |
| 103 | "file to an outward link": {swapFile, "a.txt", func(p string) error { |
| 104 | os.Remove(p) |
| 105 | return os.Symlink(filepath.Join(r.outside, "secret"), p) |
| 106 | }}, |
| 107 | "file to an inside link": {swapFile, "a.txt", func(p string) error { |
| 108 | os.Remove(p) |
| 109 | return os.Symlink(filepath.Join(r.root, "README.md"), p) |
| 110 | }}, |
| 111 | "file to a hard link": {swapFile, "a.txt", func(p string) error { |
| 112 | os.Remove(p) |
| 113 | return os.Link(filepath.Join(r.outside, "hard"), p) |
| 114 | }}, |
| 115 | "directory to a link": {filepath.Dir(swapDir), "d", func(p string) error { |
| 116 | if err := os.Rename(p, p+".moved"); err != nil { |
| 117 | return err |
| 118 | } |
| 119 | return os.Symlink(p+".moved", p) |
| 120 | }}, |
| 121 | } { |
| 122 | t.Run(name, func(t *testing.T) { |
| 123 | done := false |
| 124 | withWalkHook(t, func(dir string, names []string) { |
| 125 | if done || dir != tc.dir { |
| 126 | return |
| 127 | } |
| 128 | done = true |
| 129 | if err := tc.swap(filepath.Join(dir, tc.entry)); err != nil { |
| 130 | t.Fatal(err) |
| 131 | } |
| 132 | }) |
| 133 | if grep(tc.dir) == "allow" { |
| 134 | t.Errorf("allowed after the swap") |
| 135 | } |
| 136 | if !done { |
| 137 | t.Fatal("the walk never listed the directory") |
| 138 | } |
| 139 | }) |
| 140 | // Undo for the next case. |
| 141 | p := filepath.Join(tc.dir, tc.entry) |
| 142 | os.Remove(p) |
| 143 | if tc.entry == "d" { |
| 144 | os.Rename(p+".moved", p) |
| 145 | } else { |
| 146 | os.WriteFile(p, []byte("a"), 0600) |
| 147 | } |
| 148 | } |
| 149 | } |
| 150 | |
| 151 | // TestPermissionWalkOpensWhatItStatted: a directory replaced by another |
| 152 | // between its stat and its open (no link involved) is refused. |
| 153 | func TestPermissionWalkOpensWhatItStatted(t *testing.T) { |
| 154 | r := newDarwinRig(t) |
| 155 | parent := filepath.Join(r.root, "replaced") |
| 156 | d := filepath.Join(parent, "d") |
| 157 | os.MkdirAll(d, 0700) |
| 158 | m, _ := policyManifest(r.policy) |
| 159 | if !searchable(parent, r.root, deniedForms(m), 100) { |
| 160 | t.Fatal("refused before the swap") |
| 161 | } |
| 162 | t.Cleanup(func() { openHook = nil }) |
| 163 | openHook = func(path string) { |
| 164 | if path == d { |
| 165 | os.Rename(d, d+".old") |
| 166 | os.Mkdir(d, 0700) |
| 167 | } |
| 168 | } |
| 169 | if searchable(parent, r.root, deniedForms(m), 100) { |
| 170 | t.Fatal("opened a directory other than the one statted") |
| 171 | } |
| 172 | // The same directory behind a link to itself: the inode matches, but |
| 173 | // a link is never opened. |
| 174 | os.RemoveAll(d) |
| 175 | os.RemoveAll(d + ".old") |
| 176 | os.Mkdir(d, 0700) |
| 177 | openHook = func(path string) { |
| 178 | if path == d { |
| 179 | os.Rename(d, d+".real") |
| 180 | os.Symlink(d+".real", d) |
| 181 | } |
| 182 | } |
| 183 | if searchable(parent, r.root, deniedForms(m), 100) { |
| 184 | t.Fatal("opened a directory through a link") |
| 185 | } |
| 186 | // The searched directory itself replaced between its stat and open. |
| 187 | os.Remove(d) |
| 188 | os.Rename(d+".real", d) |
| 189 | openHook = func(path string) { |
| 190 | if path == parent { |
| 191 | os.Rename(parent, parent+".old") |
| 192 | os.Mkdir(parent, 0700) |
| 193 | } |
| 194 | } |
| 195 | if searchable(parent, r.root, deniedForms(m), 100) { |
| 196 | t.Fatal("searched a directory other than the one statted") |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | // TestPermissionWalkIsBounded: the walk reads entries in batches and |
| 201 | // stops reading when its budget is spent, refusing, rather than listing |
| 202 | // a whole directory first. |
| 203 | func TestPermissionWalkIsBounded(t *testing.T) { |
| 204 | r := newDarwinRig(t) |
| 205 | big := filepath.Join(r.root, "big") |
| 206 | os.MkdirAll(big, 0700) |
| 207 | for i := range 1000 { |
| 208 | os.WriteFile(filepath.Join(big, fmt.Sprintf("f%04d", i)), nil, 0600) |
| 209 | } |
| 210 | read := 0 |
| 211 | withWalkHook(t, func(dir string, names []string) { read += len(names) }) |
| 212 | m, _ := policyManifest(r.policy) |
| 213 | if searchable(big, r.root, deniedForms(m), 10) { |
| 214 | t.Fatal("past the budget, allowed") |
| 215 | } |
| 216 | if read > 10+walkBatch { |
| 217 | t.Fatalf("read %d entries for a budget of 10", read) |
| 218 | } |
| 219 | read = 0 |
| 220 | if !searchable(big, r.root, deniedForms(m), 2000) || read != 1000 { |
| 221 | t.Fatalf("within the budget: read %d", read) |
| 222 | } |
| 223 | if walkBatch > 1024 || grepWalkLimit < 200000 { |
| 224 | t.Fatalf("batch %d, bound %d", walkBatch, grepWalkLimit) |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | // TestLauncherDarwinNeverAsks: through the launcher's own permission |
| 229 | // endpoint, a Mac file action is decided once by the port and answered |
| 230 | // at once, allow or deny; none reaches the person's event stream, even |
| 231 | // when the tree changes while it is checked. A question still does. |
| 232 | func TestLauncherDarwinNeverAsks(t *testing.T) { |
| 233 | r := newDarwinRig(t) |
| 234 | f := fixtureFor(t, "Engineering") |
| 235 | s, events := openFixture(t, f) |
| 236 | f.l.mu.Lock() |
| 237 | st, _ := f.l.state(s) |
| 238 | st.active = true |
| 239 | st.turn = provider.Turn{ID: "turn"} |
| 240 | st.launch.Policy = r.policy |
| 241 | f.l.mu.Unlock() |
| 242 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 243 | defer cancel() |
| 244 | ask := func(tool string, input map[string]any) string { |
| 245 | t.Helper() |
| 246 | in, _ := json.Marshal(input) |
| 247 | raw, _ := json.Marshal(map[string]any{"tool_name": tool, "input": json.RawMessage(in)}) |
| 248 | out, err := f.l.Permission(ctx, s, raw) |
| 249 | if err != nil { |
| 250 | t.Fatalf("%s %v: %v", tool, input, err) |
| 251 | } |
| 252 | select { |
| 253 | case ev := <-events: |
| 254 | t.Fatalf("%s %v reached a person: %s", tool, input, ev.Payload) |
| 255 | default: |
| 256 | } |
| 257 | var v struct{ Behavior string } |
| 258 | json.Unmarshal(out, &v) |
| 259 | return v.Behavior |
| 260 | } |
| 261 | if ask("Read", map[string]any{"file_path": filepath.Join(r.root, "README.md")}) != "allow" { |
| 262 | t.Fatal("inside read not allowed") |
| 263 | } |
| 264 | for _, tc := range []struct { |
| 265 | tool string |
| 266 | input map[string]any |
| 267 | }{ |
| 268 | {"Read", map[string]any{"file_path": filepath.Join(r.outside, "secret")}}, |
| 269 | {"Write", map[string]any{"file_path": "/etc/hosts", "content": "x"}}, |
| 270 | {"Grep", map[string]any{"pattern": "x", "path": r.root}}, |
| 271 | {"Read", map[string]any{"file_path": filepath.Join(r.root, "inlink", "secret")}}, |
| 272 | {"SandboxNetworkAccess", map[string]any{"host": "example.com"}}, |
| 273 | } { |
| 274 | if ask(tc.tool, tc.input) != "deny" { |
| 275 | t.Fatalf("%s %v not denied", tc.tool, tc.input) |
| 276 | } |
| 277 | } |
| 278 | // A listed file becomes a hard link while the walk runs: denied, not |
| 279 | // relayed. (A name added after its directory was listed is the race |
| 280 | // with the CLI's own read, which no walk can close; F6.) |
| 281 | sub := filepath.Join(r.root, "sub") |
| 282 | if ask("Grep", map[string]any{"pattern": "x", "path": sub}) != "allow" { |
| 283 | t.Fatal("clean search refused") |
| 284 | } |
| 285 | withWalkHook(t, func(dir string, names []string) { |
| 286 | if dir == sub { |
| 287 | os.Remove(filepath.Join(sub, "a.go")) |
| 288 | os.Link(filepath.Join(r.outside, "hard"), filepath.Join(sub, "a.go")) |
| 289 | } |
| 290 | }) |
| 291 | if ask("Grep", map[string]any{"pattern": "x", "path": sub}) != "deny" { |
| 292 | t.Fatal("a hard link made during the walk was allowed") |
| 293 | } |
| 294 | // A question is still the person's. |
| 295 | raw := json.RawMessage(`{"tool_name":"AskUserQuestion","input":{"questions":[{"question":"Which?","options":[{"label":"blue"}]}]}}`) |
| 296 | go f.l.Permission(ctx, s, raw) |
| 297 | select { |
| 298 | case ev := <-events: |
| 299 | f.l.Respond(ctx, s, provider.Answer{TurnID: "turn", RequestID: ev.RequestID, Behavior: "deny"}) |
| 300 | case <-ctx.Done(): |
| 301 | t.Fatal("question not relayed") |
| 302 | } |
| 303 | } |
| 304 | |