Mac slice F task 7 fix 2: one Mac decision, verified bounded walk
Astra round 2. A darwin file action or network request is decided once by StepPermission (one classification, at most one walk) and Launcher.Permission returns that answer outside its lock, never relaying it; no approval can allow a darwin file action. The Grep walk opens every directory with openat O_NOFOLLOW checked by inode, stats each entry with fstatat no-follow, refuses a type that changed since the listing and any error, and reads entries 256 at a time, stopping at the 200000-entry budget. Read, Edit and Write verify the same way. Linux output and policy hashes are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4 files changed,
+594
−92
internal/runner/provider/claude/answers.go+77 −41internal/runner/provider/claude/answers_darwin_policy_test.go+8 −8internal/runner/provider/claude/answers_darwin_walk_test.go+303 −0internal/runner/provider/claude/native.go+206 −43
Intent
diff --git a/internal/runner/provider/claude/answers.go b/internal/runner/provider/claude/answers.go| index 023e2525..c8032df3 100644 |
| --- a/internal/runner/provider/claude/answers.go |
| +++ b/internal/runner/provider/claude/answers.go |
| @@ -49,6 +49,12 @@ func (l *Launcher) Permission(ctx context.Context, session provider.Session, raw |
| l.mu.Unlock() |
| return nil, errNotReady |
| } |
| + if policy := s.launch.Policy; darwinDecided(q, policy) { |
| + // A Mac's file actions and network requests are the port's alone: |
| + // decided once, outside the lock, allow or deny, never a person's. |
| + l.mu.Unlock() |
| + return StepPermission(raw, policy), nil |
| + } |
| if protectedNativePath(q, s.launch.Policy) { |
| l.mu.Unlock() |
| return permissionResult(q, provider.Answer{Behavior: "deny"}, s.launch.Policy) |
| @@ -126,51 +132,65 @@ func permissionResult(q permissionRequest, a provider.Answer, policy provider.Po |
| input["answers"], _ = json.Marshal(answers) |
| } else { |
| // Only the original native action can be allowed, under the unchanged policy. |
| - if len(a.Input) != 0 || !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep", "Bash"}, q.Tool) { |
| + if len(a.Input) != 0 { |
| return nil, provider.ErrPolicy |
| } |
| - var m manifest |
| - if json.Unmarshal(policy.Manifest, &m) != nil || !slices.Contains(m.Tools, q.Tool) { |
| - return nil, provider.ErrPolicy |
| + if e := nativeInput(q, input, policy); e != nil { |
| + return nil, e |
| } |
| - fields := map[string][]string{ |
| - "Read": {"file_path", "offset", "limit", "pages"}, |
| - "Write": {"file_path", "content"}, |
| - "Edit": {"file_path", "old_string", "new_string", "replace_all"}, |
| - "Glob": {"pattern", "path"}, |
| - "Grep": {"pattern", "path", "glob", "output_mode", "-A", "-B", "-C", "context", "-n", "-i", "type", "head_limit", "offset", "multiline"}, |
| - "Bash": {"command", "description", "timeout", "run_in_background"}, |
| + } |
| + return json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input}) |
| +} |
| + |
| +// nativeInput checks a native action's own fields against the policy: |
| +// a pinned tool the policy lists, only that tool's fields, nothing that |
| +// asks to leave the sandbox, and absolute paths outside the denied ones. |
| +// It reads no file; where the action lands is the path rules' question. |
| +func nativeInput(q permissionRequest, input map[string]json.RawMessage, policy provider.Policy) error { |
| + if !slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep", "Bash"}, q.Tool) { |
| + return provider.ErrPolicy |
| + } |
| + var m manifest |
| + if json.Unmarshal(policy.Manifest, &m) != nil || !slices.Contains(m.Tools, q.Tool) { |
| + return provider.ErrPolicy |
| + } |
| + fields := map[string][]string{ |
| + "Read": {"file_path", "offset", "limit", "pages"}, |
| + "Write": {"file_path", "content"}, |
| + "Edit": {"file_path", "old_string", "new_string", "replace_all"}, |
| + "Glob": {"pattern", "path"}, |
| + "Grep": {"pattern", "path", "glob", "output_mode", "-A", "-B", "-C", "context", "-n", "-i", "type", "head_limit", "offset", "multiline"}, |
| + "Bash": {"command", "description", "timeout", "run_in_background"}, |
| + } |
| + for key := range input { |
| + if !slices.Contains(fields[q.Tool], key) { |
| + return provider.ErrPolicy |
| } |
| - for key := range input { |
| - if !slices.Contains(fields[q.Tool], key) { |
| - return nil, provider.ErrPolicy |
| - } |
| + } |
| + for key := range input { |
| + switch key { |
| + case "dangerouslyDisableSandbox", "permissions", "sandbox", "permissionMode", "updatedPermissions": |
| + return provider.ErrPolicy |
| } |
| - for key := range input { |
| - switch key { |
| - case "dangerouslyDisableSandbox", "permissions", "sandbox", "permissionMode", "updatedPermissions": |
| - return nil, provider.ErrPolicy |
| + } |
| + for _, key := range []string{"file_path", "path"} { |
| + var path string |
| + if v, ok := input[key]; ok { |
| + if json.Unmarshal(v, &path) != nil { |
| + return provider.ErrPolicy |
| } |
| - } |
| - for _, key := range []string{"file_path", "path"} { |
| - var path string |
| - if v, ok := input[key]; ok { |
| - if json.Unmarshal(v, &path) != nil { |
| - return nil, provider.ErrPolicy |
| - } |
| - if !filepath.IsAbs(path) { |
| - return nil, provider.ErrPolicy |
| - } |
| - path = filepath.Clean(path) |
| - for _, deny := range m.DeniedPaths { |
| - if path == deny || strings.HasPrefix(path, deny+"/") { |
| - return nil, provider.ErrPolicy |
| - } |
| + if !filepath.IsAbs(path) { |
| + return provider.ErrPolicy |
| + } |
| + path = filepath.Clean(path) |
| + for _, deny := range m.DeniedPaths { |
| + if path == deny || strings.HasPrefix(path, deny+"/") { |
| + return provider.ErrPolicy |
| } |
| } |
| } |
| } |
| - return json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input}) |
| + return nil |
| } |
| // A step's permission callback refuses with a fixed reason: the rule |
| @@ -222,6 +242,15 @@ func StepPermission(raw json.RawMessage, policy provider.Policy) json.RawMessage |
| if rule := stepPathRule(q, policy); rule != "" { |
| return refusal(m.say(rule)) |
| } |
| + if m.darwin() { |
| + // Decided once by stepPathRule; only the fields remain. |
| + var input map[string]json.RawMessage |
| + if json.Unmarshal(q.Input, &input) != nil || input == nil || nativeInput(q, input, policy) != nil { |
| + return refusal(refuseFields) |
| + } |
| + out, _ := json.Marshal(map[string]any{"behavior": "allow", "updatedInput": input}) |
| + return out |
| + } |
| } |
| out, err := permissionResult(q, provider.Answer{Behavior: "allow"}, policy) |
| if err != nil { |
| @@ -383,10 +412,10 @@ func protectedNativePath(q permissionRequest, policy provider.Policy) bool { |
| return true |
| } |
| if m.darwin() { |
| - // Nobody is asked on a Mac: what is not provably inside a root, |
| - // for that root's tools, is never relayed and never allowed. |
| - place := darwinPlace(q, m) |
| - return place != placeWorkspace && !(place == placeResearch && slices.Contains([]string{"Read", "Glob", "Grep"}, q.Tool)) |
| + // Nobody is asked on a Mac: only the port's own decision |
| + // (StepPermission) allows a file action, so none is a person's |
| + // to approve and an approval allows none. |
| + return true |
| } |
| path := "" |
| for _, key := range []string{"file_path", "path"} { |
| @@ -451,6 +480,13 @@ func protectedNativePath(q permissionRequest, policy provider.Policy) bool { |
| return false |
| } |
| +// darwinDecided reports a request on a Mac policy that only the port |
| +// decides: a native file action or a sandboxed command's network request. |
| +func darwinDecided(q permissionRequest, policy provider.Policy) bool { |
| + m, ok := policyManifest(policy) |
| + return ok && m.darwin() && (q.Tool == "SandboxNetworkAccess" || slices.Contains([]string{"Read", "Write", "Edit", "Glob", "Grep"}, q.Tool)) |
| +} |
| + |
| // researchNativePath reports a read (Read, Glob or Grep) of /research, |
| // where containment binds a task's kept Research images read-only for |
| // Engineering and Review (a flat directory of regular files; nothing is |
| @@ -462,7 +498,7 @@ func researchNativePath(q permissionRequest, policy provider.Policy) bool { |
| if m, ok := policyManifest(policy); !ok || !m.portable() { |
| return false |
| } else if m.darwin() { |
| - return darwinPlace(q, m) == placeResearch |
| + return false |
| } |
| var input map[string]json.RawMessage |
| if json.Unmarshal(q.Input, &input) != nil { |
| @@ -496,7 +532,7 @@ func workspaceNativePath(q permissionRequest, policy provider.Policy) bool { |
| if m, ok := policyManifest(policy); !ok || !m.portable() { |
| return false |
| } else if m.darwin() { |
| - return darwinPlace(q, m) == placeWorkspace |
| + return false |
| } |
| var input map[string]json.RawMessage |
| if json.Unmarshal(q.Input, &input) != nil { |
diff --git a/internal/runner/provider/claude/answers_darwin_policy_test.go b/internal/runner/provider/claude/answers_darwin_policy_test.go| index 05adb3c0..9cbbf68e 100644 |
| --- a/internal/runner/provider/claude/answers_darwin_policy_test.go |
| +++ b/internal/runner/provider/claude/answers_darwin_policy_test.go |
| @@ -254,10 +254,6 @@ func TestPermissionRefusesEscapes(t *testing.T) { |
| t.Errorf("%s counted as the workspace", path) |
| } |
| } |
| - q := permissionRequest{Tool: "Read", Input: inputJSON(map[string]any{"file_path": filepath.Join(r.alias, "README.md")})} |
| - if !workspaceNativePath(q, r.policy) { |
| - t.Error("the root through its alias is not the workspace") |
| - } |
| } |
| // TestPermissionDeniedPathsGenerated: the CLI's own deny rules name each |
| @@ -412,7 +408,7 @@ func TestPermissionGrepReadsNoHardLink(t *testing.T) { |
| } |
| // 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), 2) { |
| + if !searchable(clean, r.root, deniedForms(m), 10) || searchable(clean, r.root, deniedForms(m), 1) { |
| t.Fatal("walk bound not applied") |
| } |
| if grepWalkLimit < 200000 { |
| @@ -474,9 +470,13 @@ func TestPermissionOutsideNeverApproved(t *testing.T) { |
| 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 an approval of the original action still works. |
| + // 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) { |
| - t.Fatalf("inside read: %v", err) |
| + 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") |
| } |
| } |
diff --git a/internal/runner/provider/claude/answers_darwin_walk_test.go b/internal/runner/provider/claude/answers_darwin_walk_test.go| new file mode 100644 |
| index 00000000..7b072acd |
| --- /dev/null |
| +++ b/internal/runner/provider/claude/answers_darwin_walk_test.go |
| @@ -0,0 +1,303 @@ |
| +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") |
| + } |
| +} |
diff --git a/internal/runner/provider/claude/native.go b/internal/runner/provider/claude/native.go| index e5c81555..47ad8fb4 100644 |
| --- a/internal/runner/provider/claude/native.go |
| +++ b/internal/runner/provider/claude/native.go |
| @@ -3,14 +3,15 @@ package claude |
| import ( |
| "encoding/json" |
| "errors" |
| + "io" |
| "io/fs" |
| "os" |
| "path/filepath" |
| "slices" |
| "strings" |
| - "syscall" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| + "golang.org/x/sys/unix" |
| "golang.org/x/text/cases" |
| "golang.org/x/text/unicode/norm" |
| ) |
| @@ -241,7 +242,7 @@ func darwinPlace(q permissionRequest, m manifest) nativePlace { |
| return placeProtected |
| } |
| } |
| - if slices.Contains([]string{"Read", "Edit", "Write"}, q.Tool) && hardLinked(real) { |
| + if slices.Contains([]string{"Read", "Edit", "Write"}, q.Tool) && !fileVerified(real) { |
| return placeProtected |
| } |
| place, in := placeOutside, "" |
| @@ -261,44 +262,216 @@ func darwinPlace(q permissionRequest, m manifest) nativePlace { |
| // large Xcode project with its packages checked out fits well inside. |
| const grepWalkLimit = 200000 |
| +// walkBatch is how many directory entries the walk reads at a time, so a |
| +// directory of millions costs no more than the budget before refusing. |
| +const walkBatch = 256 |
| + |
| +// walkHook, when set (tests only), sees each batch of names the walk |
| +// reads, before it checks them; openHook each directory between its stat |
| +// and its open. |
| +var ( |
| + walkHook func(dir string, names []string) |
| + openHook func(path string) |
| + // readDir reads the next batch of a directory (a seam for tests). |
| + readDir = func(f *os.File, n int) ([]fs.DirEntry, error) { return f.ReadDir(n) } |
| +) |
| + |
| // searchable reports that Grep may read target, a file or directory in |
| -// root: walked without following a link, it holds no regular file with |
| -// another hard link, no link that fails to resolve inside root or |
| -// resolves into a denied place, and at most limit entries. Anything the |
| -// walk cannot read refuses. A git checkout makes no hard links, so a |
| -// real worktree passes; the walk is the price of answering before the |
| -// CLI reads, and it still cannot close the race (darwinPlace). |
| +// root. Every step is verified or refuses: the target and each directory |
| +// are opened one component at a time from "/" with no link followed |
| +// (openat with O_NOFOLLOW, checked by device and inode against what was |
| +// statted); entries are read walkBatch at a time and each is statted |
| +// relative to its directory without following it. A regular file must |
| +// have one link; a link (which Grep does not follow) must resolve inside |
| +// root and not into a denied place; a directory is walked; anything else, |
| +// a type that differs from the one listed (a swap after the listing), an |
| +// error of any kind, or more than limit entries refuses. A git checkout |
| +// makes no hard links, so a real worktree passes. The walk cannot close |
| +// the race with the CLI's own read (darwinPlace). |
| func searchable(target, root string, denied []string, limit int) bool { |
| - n := 0 |
| - err := filepath.WalkDir(target, func(path string, d fs.DirEntry, err error) error { |
| - if err != nil { |
| - return err |
| - } |
| - if n++; n > limit { |
| - return fs.ErrInvalid |
| + st, err := lstatNoFollow(target) |
| + if err != nil { |
| + return false |
| + } |
| + switch uint32(st.Mode) & unix.S_IFMT { |
| + case unix.S_IFREG: |
| + return st.Nlink == 1 |
| + case unix.S_IFDIR: |
| + default: |
| + return false |
| + } |
| + if openHook != nil { |
| + openHook(target) |
| + } |
| + fd, err := openDirNoFollow(target) |
| + if err != nil { |
| + return false |
| + } |
| + if !sameInode(fd, st) { |
| + unix.Close(fd) |
| + return false |
| + } |
| + w := treeWalk{root: root, denied: denied, budget: limit} |
| + return w.dir(fd, target) |
| +} |
| + |
| +type treeWalk struct { |
| + root string |
| + denied []string |
| + budget int |
| +} |
| + |
| +// dir walks the open directory fd (closed on return) at path. |
| +func (w *treeWalk) dir(fd int, path string) bool { |
| + f := os.NewFile(uintptr(fd), path) |
| + defer f.Close() |
| + for { |
| + entries, err := readDir(f, walkBatch) |
| + if err != nil && err != io.EOF { |
| + return false |
| } |
| - switch { |
| - case d.Type()&fs.ModeSymlink != 0: |
| - resolved, err := filepath.EvalSymlinks(path) |
| - if err != nil || !within(root, resolved) { |
| - return fs.ErrPermission |
| + if walkHook != nil && len(entries) > 0 { |
| + names := make([]string, len(entries)) |
| + for i, e := range entries { |
| + names[i] = e.Name() |
| } |
| - for _, deny := range denied { |
| - if foldedWithin(deny, resolved) { |
| - return fs.ErrPermission |
| - } |
| + walkHook(path, names) |
| + } |
| + for _, e := range entries { |
| + if w.budget--; w.budget < 0 || !w.entry(fd, path, e) { |
| + return false |
| } |
| - case d.Type().IsRegular(): |
| - if hardLinked(path) { |
| - return fs.ErrPermission |
| + } |
| + if err == io.EOF || len(entries) == 0 { |
| + return true |
| + } |
| + } |
| +} |
| + |
| +// entry checks one listed entry of the directory fd at dir. |
| +func (w *treeWalk) entry(fd int, dir string, e fs.DirEntry) bool { |
| + var st unix.Stat_t |
| + if unix.Fstatat(fd, e.Name(), &st, unix.AT_SYMLINK_NOFOLLOW) != nil { |
| + return false |
| + } |
| + kind := uint32(st.Mode) & unix.S_IFMT |
| + if !sameKind(e.Type(), kind) { |
| + return false |
| + } |
| + path := filepath.Join(dir, e.Name()) |
| + switch kind { |
| + case unix.S_IFREG: |
| + return st.Nlink == 1 |
| + case unix.S_IFLNK: |
| + resolved, err := filepath.EvalSymlinks(path) |
| + if err != nil || !within(w.root, resolved) { |
| + return false |
| + } |
| + for _, deny := range w.denied { |
| + if foldedWithin(deny, resolved) { |
| + return false |
| } |
| - case !d.IsDir(): |
| - // Devices, sockets and pipes have nothing to search. |
| - return fs.ErrPermission |
| } |
| - return nil |
| - }) |
| - return err == nil |
| + return true |
| + case unix.S_IFDIR: |
| + if openHook != nil { |
| + openHook(path) |
| + } |
| + sub, err := unix.Openat(fd, e.Name(), unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return false |
| + } |
| + if !sameInode(sub, st) { |
| + unix.Close(sub) |
| + return false |
| + } |
| + return w.dir(sub, path) |
| + } |
| + return false |
| +} |
| + |
| +// sameKind reports that a listed type is the statted one. |
| +func sameKind(t fs.FileMode, kind uint32) bool { |
| + switch kind { |
| + case unix.S_IFREG: |
| + return t.IsRegular() |
| + case unix.S_IFDIR: |
| + return t.IsDir() |
| + case unix.S_IFLNK: |
| + return t&fs.ModeSymlink != 0 |
| + case unix.S_IFIFO: |
| + return t&fs.ModeNamedPipe != 0 |
| + case unix.S_IFSOCK: |
| + return t&fs.ModeSocket != 0 |
| + case unix.S_IFCHR: |
| + return t&fs.ModeCharDevice != 0 |
| + case unix.S_IFBLK: |
| + return t&fs.ModeDevice != 0 && t&fs.ModeCharDevice == 0 |
| + } |
| + return false |
| +} |
| + |
| +// sameInode reports that the open fd is the file st describes. |
| +func sameInode(fd int, st unix.Stat_t) bool { |
| + var opened unix.Stat_t |
| + return unix.Fstat(fd, &opened) == nil && opened.Dev == st.Dev && opened.Ino == st.Ino |
| +} |
| + |
| +// openDirNoFollow opens the directory at an absolute path one component |
| +// at a time from "/", following no link. |
| +func openDirNoFollow(path string) (int, error) { |
| + fd, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) |
| + if err != nil { |
| + return -1, err |
| + } |
| + for _, part := range strings.Split(strings.Trim(filepath.Clean(path), "/"), "/") { |
| + if part == "" { |
| + continue |
| + } |
| + next, err := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) |
| + unix.Close(fd) |
| + if err != nil { |
| + return -1, err |
| + } |
| + fd = next |
| + } |
| + return fd, nil |
| +} |
| + |
| +// lstatNoFollow stats path itself, its directory opened by |
| +// openDirNoFollow. |
| +func lstatNoFollow(path string) (unix.Stat_t, error) { |
| + var st unix.Stat_t |
| + path = filepath.Clean(path) |
| + if path == "/" { |
| + return st, unix.Lstat(path, &st) |
| + } |
| + fd, err := openDirNoFollow(filepath.Dir(path)) |
| + if err != nil { |
| + return st, err |
| + } |
| + defer unix.Close(fd) |
| + return st, unix.Fstatat(fd, filepath.Base(path), &st, unix.AT_SYMLINK_NOFOLLOW) |
| +} |
| + |
| +// fileVerified reports that a Read, Edit or Write of path reads nothing |
| +// unverified: nothing is there yet, or it is a directory, or a regular |
| +// file with one link. Any other answer, or any error, refuses. |
| +func fileVerified(path string) bool { |
| + st, err := lstatNoFollow(path) |
| + if errors.Is(err, unix.ENOENT) { |
| + return true |
| + } |
| + if err != nil { |
| + return false |
| + } |
| + switch uint32(st.Mode) & unix.S_IFMT { |
| + case unix.S_IFREG: |
| + return st.Nlink == 1 |
| + case unix.S_IFDIR: |
| + return true |
| + } |
| + return false |
| } |
| // deniedForms are the policy's denied paths, each also as resolved when |
| @@ -385,16 +558,6 @@ func resolveNative(path string, roots []string) (string, bool) { |
| return cur, true |
| } |
| -// hardLinked reports an existing regular file with more than one link. |
| -func hardLinked(path string) bool { |
| - info, err := os.Lstat(path) |
| - if err != nil || !info.Mode().IsRegular() { |
| - return false |
| - } |
| - st, ok := info.Sys().(*syscall.Stat_t) |
| - return !ok || uint64(st.Nlink) > 1 |
| -} |
| - |
| // within reports path at or below root, exactly. |
| func within(root, path string) bool { |
| return path == root || strings.HasPrefix(path, strings.TrimSuffix(root, "/")+"/") |