oficina / equipo Public

Mac slice F task 7 fix 1: Grep walk, NFC folding, no Mac approvals

Astra round 1. Grep on a Mac now walks its target first (no links
followed) and refuses a hard-linked file, a link that does not resolve
inside the root or resolves into a denied place, or more than
grepWalkLimit (200000) entries. Denied-path comparison is per component
in NFC and case-folded (golang.org/x/text, already in go.mod, now a
direct requirement). On darwin anything not provably inside a root is
protected, so it never reaches a person and an approval cannot allow it.
Linux output and policy hashes are unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 0418722d0fd36d58431fdcc678f647d62583c809 parent af27061
4 files changed, +229 −33
  • go.mod +1 −1
  • internal/runner/provider/claude/answers.go +3 −1
  • internal/runner/provider/claude/answers_darwin_policy_test.go +129 −6
  • internal/runner/provider/claude/native.go +96 −25
diff --git a/go.mod b/go.mod
index 5d1886d1..b85d4302 100644
--- a/go.mod
+++ b/go.mod
@@ -119,7 +119,7 @@ require (
github.com/zricethezav/gitleaks/v8 v8.30.1
golang.org/x/mod v0.38.0
golang.org/x/sync v0.22.0 // indirect
- golang.org/x/text v0.41.0 // indirect
+ golang.org/x/text v0.41.0
golang.org/x/tools v0.48.0 // indirect
modernc.org/libc v1.74.1 // indirect
modernc.org/mathutil v1.7.1 // indirect
diff --git a/internal/runner/provider/claude/answers.go b/internal/runner/provider/claude/answers.go
index 5648982e..023e2525 100644
--- a/internal/runner/provider/claude/answers.go
+++ b/internal/runner/provider/claude/answers.go
@@ -383,8 +383,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 == placeBadPath || place == placeProtected
+ return place != placeWorkspace && !(place == placeResearch && slices.Contains([]string{"Read", "Glob", "Grep"}, q.Tool))
}
path := ""
for _, key := range []string{"file_path", "path"} {
diff --git a/internal/runner/provider/claude/answers_darwin_policy_test.go b/internal/runner/provider/claude/answers_darwin_policy_test.go
index 19ef5c75..05adb3c0 100644
--- a/internal/runner/provider/claude/answers_darwin_policy_test.go
+++ b/internal/runner/provider/claude/answers_darwin_policy_test.go
@@ -21,8 +21,10 @@ type darwinRig struct {
t *testing.T
base, root, alias, outside, home string
research, other string
- paths mac.Paths
- policy provider.Policy
+ // jose and zoe are two more homes: José in NFC, Zoë in NFD.
+ jose, zoe string
+ paths mac.Paths
+ policy provider.Policy
}
func newDarwinRig(t *testing.T) *darwinRig {
@@ -39,7 +41,9 @@ func newDarwinRig(t *testing.T) *darwinRig {
r.home = filepath.Join(base, "Users", "paulequipo")
r.other = filepath.Join(base, "Users", "paulca")
r.research = filepath.Join(real, "equipo", "research")
- for _, d := range []string{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} {
+ 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)
}
@@ -75,7 +79,7 @@ func newDarwinRig(t *testing.T) *darwinRig {
if err := os.Link(filepath.Join(r.outside, "hard"), filepath.Join(r.root, "hard")); err != nil {
t.Fatal(err)
}
- r.paths = mac.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.paths = mac.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
}
@@ -136,7 +140,7 @@ func TestPermissionRootIsResolved(t *testing.T) {
{"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": "hello", "path": dir, "glob": "*.md"}},
+ {"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)
@@ -322,7 +326,7 @@ func TestDarwinPortShellAndNetwork(t *testing.T) {
t.Fatalf("read-only %s: %s %q", tc.tool, b, msg)
}
}
- if b, _ := r.answer(ReadPermission, r.policy, "Grep", map[string]any{"pattern": "hello", "path": r.root}); b != "allow" {
+ 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.
@@ -357,3 +361,122 @@ 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), 2) {
+ 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 an approval of the original action still works.
+ 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)
+ }
+}
diff --git a/internal/runner/provider/claude/native.go b/internal/runner/provider/claude/native.go
index 0fc2d99f..e5c81555 100644
--- a/internal/runner/provider/claude/native.go
+++ b/internal/runner/provider/claude/native.go
@@ -11,6 +11,8 @@ import (
"syscall"
"amadan.net/oficina/equipo/internal/runner/provider"
+ "golang.org/x/text/cases"
+ "golang.org/x/text/unicode/norm"
)
// The native file permission port (Mac runners spec §4.4, "Native file
@@ -159,10 +161,12 @@ const (
// and refuses the action (as Linux refuses links in /workspace), and the
// first missing component ends the walk (what a Write would create).
// The result must land inside the real root; it is then checked against
-// the policy's denied paths, both as given and as resolved, without
-// regard to case (APFS is case-insensitive by default). A Read, Edit or
-// Write of a regular file with another hard link is refused: a link
-// made in the worktree to a file elsewhere would pass every path check.
+// the policy's denied paths, both as given and as resolved, component by
+// component in NFC and case-folded (APFS ignores both by default). A
+// Read, Edit or Write of a regular file with another hard link is
+// refused: a link made in the worktree to a file elsewhere would pass
+// every path check. Grep reads contents too, so its target is walked
+// first (searchable).
//
// What this cannot do is make the check and the CLI's own open one
// atomic step: a sandboxed command can swap a checked directory for a
@@ -227,31 +231,87 @@ func darwinPlace(q permissionRequest, m manifest) nativePlace {
return placeProtected
}
lexical := filepath.Clean(path)
- for _, d := range m.DeniedPaths {
- forms := []string{d}
- if r, err := filepath.EvalSymlinks(d); err == nil && r != d {
- forms = append(forms, r)
+ denied := deniedForms(m)
+ for _, deny := range denied {
+ if foldedWithin(deny, lexical) || foldedWithin(deny, real) {
+ return placeProtected
}
- for _, deny := range forms {
- if withinFold(deny, lexical) || withinFold(deny, real) {
- return placeProtected
- }
- // A search of a directory holding a denied place would reach it.
- if (q.Tool == "Glob" || q.Tool == "Grep") && (withinFold(lexical, deny) || withinFold(real, deny)) {
- return placeProtected
- }
+ // A search of a directory holding a denied place would reach it.
+ if (q.Tool == "Glob" || q.Tool == "Grep") && (foldedWithin(lexical, deny) || foldedWithin(real, deny)) {
+ return placeProtected
}
}
if slices.Contains([]string{"Read", "Edit", "Write"}, q.Tool) && hardLinked(real) {
return placeProtected
}
+ place, in := placeOutside, ""
switch {
case within(root, real):
- return placeWorkspace
+ place, in = placeWorkspace, root
case research != "" && within(research, real):
- return placeResearch
+ place, in = placeResearch, research
+ }
+ if q.Tool == "Grep" && place != placeOutside && !searchable(real, in, denied, grepWalkLimit) {
+ return placeProtected
+ }
+ return place
+}
+
+// grepWalkLimit bounds the entries searchable walks before it refuses: a
+// large Xcode project with its packages checked out fits well inside.
+const grepWalkLimit = 200000
+
+// 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).
+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
+ }
+ switch {
+ case d.Type()&fs.ModeSymlink != 0:
+ resolved, err := filepath.EvalSymlinks(path)
+ if err != nil || !within(root, resolved) {
+ return fs.ErrPermission
+ }
+ for _, deny := range denied {
+ if foldedWithin(deny, resolved) {
+ return fs.ErrPermission
+ }
+ }
+ case d.Type().IsRegular():
+ if hardLinked(path) {
+ return fs.ErrPermission
+ }
+ case !d.IsDir():
+ // Devices, sockets and pipes have nothing to search.
+ return fs.ErrPermission
+ }
+ return nil
+ })
+ return err == nil
+}
+
+// deniedForms are the policy's denied paths, each also as resolved when
+// it resolves elsewhere.
+func deniedForms(m manifest) []string {
+ var out []string
+ for _, d := range m.DeniedPaths {
+ out = append(out, d)
+ if r, err := filepath.EvalSymlinks(d); err == nil && r != d {
+ out = append(out, r)
+ }
}
- return placeOutside
+ return out
}
// nativePathField is the action's file_path or path ("" when it has
@@ -340,12 +400,23 @@ func within(root, path string) bool {
return path == root || strings.HasPrefix(path, strings.TrimSuffix(root, "/")+"/")
}
-// withinFold is within without regard to case: a denied place matches
-// more widely, never less.
-func withinFold(root, path string) bool {
- if root == "" {
+// foldedWithin is within as APFS compares names: component by
+// component, each in NFC and case-folded, so a denied place matches in
+// every spelling of it, never fewer.
+func foldedWithin(root, path string) bool {
+ if root == "" || path == "" {
return false
}
- r := strings.TrimSuffix(root, "/")
- return strings.EqualFold(path, root) || len(path) > len(r) && path[len(r)] == '/' && strings.EqualFold(path[:len(r)], r)
+ r, p := foldedPath(root), foldedPath(path)
+ return len(p) >= len(r) && slices.Equal(p[:len(r)], r)
+}
+
+// foldedPath is a clean path's components, each NFC, folded, NFC again.
+func foldedPath(path string) []string {
+ fold := cases.Fold() // a Caser is not safe to share between goroutines
+ parts := strings.Split(strings.Trim(filepath.Clean(path), "/"), "/")
+ for i, part := range parts {
+ parts[i] = norm.NFC.String(fold.String(norm.NFC.String(part)))
+ }
+ return parts
}