package claude import ( "encoding/json" "errors" "io" "io/fs" "os" "path/filepath" "slices" "strings" "amadan.net/oficina/equipo/internal/runner/provider" "golang.org/x/sys/unix" "golang.org/x/text/cases" "golang.org/x/text/unicode/norm" ) // The native file permission port (Mac runners spec §4.4, "Native file // permissions, ported explicitly"). On Linux the CLI runs in a mount // namespace: it sees the workspace at /workspace and kept Research // images at /research, and nothing else Equipo cares about exists // there. On a Mac there is no namespace and the CLI itself runs // unsandboxed (only its Bash commands are in Seatbelt), so these rules // are what keep its native Read, Edit, Write, Glob and Grep inside the // worktree. The roots become policy fields, every requested path is // resolved against the real filesystem before it is answered, and the // policy's denied paths (the §4.2 list, denylist.DenyList) are checked again // after resolution. const ( // LinuxWorkspaceRoot and LinuxResearchRoot are where a Linux launch // mounts the workspace and the kept Research images. LinuxWorkspaceRoot = "/workspace" LinuxResearchRoot = "/research" // PlatformDarwin marks a Mac launch's manifest (NativeRoots.Platform). PlatformDarwin = "darwin" ) // NativeRoots are the manifest fields the permission port reads beyond // Linux's. A Linux manifest has none of them (so its bytes, and its // certified hashes, are unchanged); a darwin manifest embeds this struct. type NativeRoots struct { // Platform is "" for a Linux launch and PlatformDarwin for a Mac's. // Any other value refuses every native file action. Platform string `json:",omitempty"` // WorkspaceRoot is the directory the native file tools may use, as // the CLI sees it: on a Mac the worktree's real path (no /private // alias, no symlink anywhere in it). Empty on Linux (/workspace). WorkspaceRoot string `json:",omitempty"` // ResearchRoot is a read-only directory of kept Research images, real // as WorkspaceRoot is. Empty on Linux (/research) and on a Mac that // has none (a Mac gets the findings text only). ResearchRoot string `json:",omitempty"` } // nativeFileTools are the CLI's native file tools, in the order their // deny rules are written. var nativeFileTools = []string{"Read", "Write", "Edit", "Glob", "Grep"} // NativeDenyRules are the CLI permission deny rules for paths: for each, // Tool(/) and Tool(//**) for Read, Write, Edit, Glob and // Grep (the CLI reads "//" as an absolute path). A path that is not // absolute and clean, or that the rule syntax would read as a pattern, // is refused. Linux renders its settings with this; a darwin policy // passes the §4.2 list (denylist.DenyList) and the connection's homes. func NativeDenyRules(paths []string) ([]string, error) { var out []string for _, path := range paths { if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?[]()\n\r") { return nil, provider.ErrPolicy } for _, tool := range nativeFileTools { out = append(out, tool+"(/"+path+")", tool+"(/"+path+"/**)") } } return out, nil } // Roots are the workspace and research roots of a policy, as its prompts // name them: /workspace and /research for Linux; the policy's own for a // Mac (research "" when it has none). An unreadable policy gives "", "". func Roots(p provider.Policy) (workspace, research string) { m, ok := policyManifest(p) if !ok { return "", "" } if m.darwin() { return m.WorkspaceRoot, m.ResearchRoot } return LinuxWorkspaceRoot, LinuxResearchRoot } func policyManifest(p provider.Policy) (manifest, bool) { var m manifest if json.Unmarshal(p.Manifest, &m) != nil { return m, false } return m, true } func (m manifest) darwin() bool { return m.Platform == PlatformDarwin } // portable: a Linux manifest carries no root fields; a darwin one names // its own. Anything else is no policy the port can answer for. func (m manifest) portable() bool { switch m.Platform { case "": return m.WorkspaceRoot == "" && m.ResearchRoot == "" case PlatformDarwin: return true } return false } // say is a refusal's text with the policy's own roots in it. Linux keeps // the fixed words exactly. func (m manifest) say(rule string) string { if !m.darwin() { return rule } ws, rs := m.WorkspaceRoot, m.ResearchRoot switch rule { case refusePath: return "file tools need an absolute path under " + ws + "; for Glob and Grep, pass path, such as " + ws case refuseOutside: if rs == "" { return "this step can use files only under " + ws } return "this step can use files only under " + ws + " (and read " + rs + ")" case refuseResearch: return rs + " is read-only: use Read, Glob and Grep there" case refuseReadOnly: return "this step only reads: use Read, Glob and Grep under " + ws } return rule } // nativePlace is where a native file action's path lands. type nativePlace int const ( // placeBadPath: no absolute path ("", relative, ~). placeBadPath nativePlace = iota // placeProtected: never allowed and never asked: a denied path, a // link, an escape, or anything that could not be resolved. placeProtected // placeOutside: a real path outside both roots. placeOutside // placeWorkspace: inside the real workspace root. placeWorkspace // placeResearch: inside the real research root. placeResearch ) // darwinPlace resolves a native file action on a Mac against the real // filesystem. The path must be absolute with no ".." component (a ".." // after a link climbs from the link's target, so it is never cleaned // away lexically). It is walked from "/" one component at a time: a // symlink above the roots (macOS's /var and /tmp, which lead to // /private) is followed, a symlink inside either root is never followed // 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, 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 // link between the two. The CLI's own deny rules (NativeDenyRules on // the same paths, which it also checks on canonical paths) and the // Seatbelt denies are the second layer, and probe F6 proves the race // live on the Mac before Engineering is offered there. func darwinPlace(q permissionRequest, m manifest) nativePlace { var input map[string]json.RawMessage if json.Unmarshal(q.Input, &input) != nil || input == nil { return placeProtected } path, ok := nativePathField(input) if !ok { return placeProtected } if path == "" || strings.HasPrefix(path, "~") || !filepath.IsAbs(path) { return placeBadPath } if strings.ContainsAny(path, "\x00\n\r") || dotDot(path) { return placeProtected } var patternKey string switch q.Tool { case "Glob": patternKey = "pattern" case "Grep": patternKey = "glob" } if raw, ok := input[patternKey]; ok && patternKey != "" { var pattern string // A pattern never names a place by itself: no absolute pattern, // no home, and no ".." anywhere (not even inside braces). if json.Unmarshal(raw, &pattern) != nil || filepath.IsAbs(pattern) || strings.HasPrefix(pattern, "~") || strings.Contains(pattern, "..") || strings.ContainsAny(pattern, "\x00\n\r") { return placeProtected } if q.Tool == "Glob" { // The literal base is all that is known before Glob expands // the pattern; it is resolved with the path. for _, part := range strings.Split(pattern, "/") { if strings.ContainsAny(part, "*?[{\\") { break } path = filepath.Join(path, part) } } } root, ok := realDir(m.WorkspaceRoot) if !ok { return placeProtected } roots := []string{root} research := "" if m.ResearchRoot != "" { if research, ok = realDir(m.ResearchRoot); !ok { return placeProtected } roots = append(roots, research) } real, ok := resolveNative(path, roots) if !ok { return placeProtected } lexical := filepath.Clean(path) denied := deniedForms(m) for _, deny := range denied { if foldedWithin(deny, lexical) || foldedWithin(deny, real) { 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) && !fileVerified(real) { return placeProtected } place, in := placeOutside, "" switch { case within(root, real): place, in = placeWorkspace, root case research != "" && within(research, real): 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 // 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. 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 { 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 } if walkHook != nil && len(entries) > 0 { names := make([]string, len(entries)) for i, e := range entries { names[i] = e.Name() } walkHook(path, names) } for _, e := range entries { if w.budget--; w.budget < 0 || !w.entry(fd, path, e) { return false } } 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 } } 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 // 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 out } // nativePathField is the action's file_path or path ("" when it has // neither); false when the field is not a string. func nativePathField(input map[string]json.RawMessage) (string, bool) { for _, key := range []string{"file_path", "path"} { if raw, ok := input[key]; ok { var path string if json.Unmarshal(raw, &path) != nil { return "", false } return path, true } } return "", true } // dotDot reports a ".." component. func dotDot(path string) bool { return slices.Contains(strings.Split(path, "/"), "..") } // realDir is root when it is an absolute, clean directory path with no // symlink anywhere in it (its own realpath) and not "/". func realDir(root string) (string, bool) { if root == "" || root == "/" || !filepath.IsAbs(root) || filepath.Clean(root) != root { return "", false } real, err := filepath.EvalSymlinks(root) if err != nil || real != root { return "", false } info, err := os.Stat(real) if err != nil || !info.IsDir() { return "", false } return real, true } // resolveNative walks an absolute, clean path from "/" (see darwinPlace). func resolveNative(path string, roots []string) (string, bool) { cur := "/" parts := strings.Split(strings.TrimPrefix(filepath.Clean(path), "/"), "/") for i, part := range parts { if part == "" { continue } next := filepath.Join(cur, part) info, err := os.Lstat(next) if errors.Is(err, fs.ErrNotExist) { // Nothing below exists: the rest names what would be created. return filepath.Join(append([]string{next}, parts[i+1:]...)...), true } if err != nil { return "", false } if info.Mode()&os.ModeSymlink != 0 { for _, r := range roots { if within(r, next) { return "", false } } target, err := filepath.EvalSymlinks(next) if err != nil { return "", false } next = target } cur = next } return cur, true } // within reports path at or below root, exactly. func within(root, path string) bool { return path == root || strings.HasPrefix(path, strings.TrimSuffix(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, 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 }