oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package claude
2
3import (
4 "encoding/json"
5 "errors"
6 "io"
7 "io/fs"
8 "os"
9 "path/filepath"
10 "slices"
11 "strings"
12
13 "amadan.net/oficina/equipo/internal/runner/provider"
14 "golang.org/x/sys/unix"
15 "golang.org/x/text/cases"
16 "golang.org/x/text/unicode/norm"
17)
18
19// The native file permission port (Mac runners spec §4.4, "Native file
20// permissions, ported explicitly"). On Linux the CLI runs in a mount
21// namespace: it sees the workspace at /workspace and kept Research
22// images at /research, and nothing else Equipo cares about exists
23// there. On a Mac there is no namespace and the CLI itself runs
24// unsandboxed (only its Bash commands are in Seatbelt), so these rules
25// are what keep its native Read, Edit, Write, Glob and Grep inside the
26// worktree. The roots become policy fields, every requested path is
27// resolved against the real filesystem before it is answered, and the
28// policy's denied paths (the §4.2 list, denylist.DenyList) are checked again
29// after resolution.
30
31const (
32 // LinuxWorkspaceRoot and LinuxResearchRoot are where a Linux launch
33 // mounts the workspace and the kept Research images.
34 LinuxWorkspaceRoot = "/workspace"
35 LinuxResearchRoot = "/research"
36 // PlatformDarwin marks a Mac launch's manifest (NativeRoots.Platform).
37 PlatformDarwin = "darwin"
38)
39
40// NativeRoots are the manifest fields the permission port reads beyond
41// Linux's. A Linux manifest has none of them (so its bytes, and its
42// certified hashes, are unchanged); a darwin manifest embeds this struct.
43type NativeRoots struct {
44 // Platform is "" for a Linux launch and PlatformDarwin for a Mac's.
45 // Any other value refuses every native file action.
46 Platform string `json:",omitempty"`
47 // WorkspaceRoot is the directory the native file tools may use, as
48 // the CLI sees it: on a Mac the worktree's real path (no /private
49 // alias, no symlink anywhere in it). Empty on Linux (/workspace).
50 WorkspaceRoot string `json:",omitempty"`
51 // ResearchRoot is a read-only directory of kept Research images, real
52 // as WorkspaceRoot is. Empty on Linux (/research) and on a Mac that
53 // has none (a Mac gets the findings text only).
54 ResearchRoot string `json:",omitempty"`
55}
56
57// nativeFileTools are the CLI's native file tools, in the order their
58// deny rules are written.
59var nativeFileTools = []string{"Read", "Write", "Edit", "Glob", "Grep"}
60
61// NativeDenyRules are the CLI permission deny rules for paths: for each,
62// Tool(/<path>) and Tool(/<path>/**) for Read, Write, Edit, Glob and
63// Grep (the CLI reads "//" as an absolute path). A path that is not
64// absolute and clean, or that the rule syntax would read as a pattern,
65// is refused. Linux renders its settings with this; a darwin policy
66// passes the §4.2 list (denylist.DenyList) and the connection's homes.
67func NativeDenyRules(paths []string) ([]string, error) {
68 var out []string
69 for _, path := range paths {
70 if !filepath.IsAbs(path) || filepath.Clean(path) != path || strings.ContainsAny(path, "*?[]()\n\r") {
71 return nil, provider.ErrPolicy
72 }
73 for _, tool := range nativeFileTools {
74 out = append(out, tool+"(/"+path+")", tool+"(/"+path+"/**)")
75 }
76 }
77 return out, nil
78}
79
80// Roots are the workspace and research roots of a policy, as its prompts
81// name them: /workspace and /research for Linux; the policy's own for a
82// Mac (research "" when it has none). An unreadable policy gives "", "".
83func Roots(p provider.Policy) (workspace, research string) {
84 m, ok := policyManifest(p)
85 if !ok {
86 return "", ""
87 }
88 if m.darwin() {
89 return m.WorkspaceRoot, m.ResearchRoot
90 }
91 return LinuxWorkspaceRoot, LinuxResearchRoot
92}
93
94func policyManifest(p provider.Policy) (manifest, bool) {
95 var m manifest
96 if json.Unmarshal(p.Manifest, &m) != nil {
97 return m, false
98 }
99 return m, true
100}
101
102func (m manifest) darwin() bool { return m.Platform == PlatformDarwin }
103
104// portable: a Linux manifest carries no root fields; a darwin one names
105// its own. Anything else is no policy the port can answer for.
106func (m manifest) portable() bool {
107 switch m.Platform {
108 case "":
109 return m.WorkspaceRoot == "" && m.ResearchRoot == ""
110 case PlatformDarwin:
111 return true
112 }
113 return false
114}
115
116// say is a refusal's text with the policy's own roots in it. Linux keeps
117// the fixed words exactly.
118func (m manifest) say(rule string) string {
119 if !m.darwin() {
120 return rule
121 }
122 ws, rs := m.WorkspaceRoot, m.ResearchRoot
123 switch rule {
124 case refusePath:
125 return "file tools need an absolute path under " + ws + "; for Glob and Grep, pass path, such as " + ws
126 case refuseOutside:
127 if rs == "" {
128 return "this step can use files only under " + ws
129 }
130 return "this step can use files only under " + ws + " (and read " + rs + ")"
131 case refuseResearch:
132 return rs + " is read-only: use Read, Glob and Grep there"
133 case refuseReadOnly:
134 return "this step only reads: use Read, Glob and Grep under " + ws
135 }
136 return rule
137}
138
139// nativePlace is where a native file action's path lands.
140type nativePlace int
141
142const (
143 // placeBadPath: no absolute path ("", relative, ~).
144 placeBadPath nativePlace = iota
145 // placeProtected: never allowed and never asked: a denied path, a
146 // link, an escape, or anything that could not be resolved.
147 placeProtected
148 // placeOutside: a real path outside both roots.
149 placeOutside
150 // placeWorkspace: inside the real workspace root.
151 placeWorkspace
152 // placeResearch: inside the real research root.
153 placeResearch
154)
155
156// darwinPlace resolves a native file action on a Mac against the real
157// filesystem. The path must be absolute with no ".." component (a ".."
158// after a link climbs from the link's target, so it is never cleaned
159// away lexically). It is walked from "/" one component at a time: a
160// symlink above the roots (macOS's /var and /tmp, which lead to
161// /private) is followed, a symlink inside either root is never followed
162// and refuses the action (as Linux refuses links in /workspace), and the
163// first missing component ends the walk (what a Write would create).
164// The result must land inside the real root; it is then checked against
165// the policy's denied paths, both as given and as resolved, component by
166// component in NFC and case-folded (APFS ignores both by default). A
167// Read, Edit or Write of a regular file with another hard link is
168// refused: a link made in the worktree to a file elsewhere would pass
169// every path check. Grep reads contents too, so its target is walked
170// first (searchable).
171//
172// What this cannot do is make the check and the CLI's own open one
173// atomic step: a sandboxed command can swap a checked directory for a
174// link between the two. The CLI's own deny rules (NativeDenyRules on
175// the same paths, which it also checks on canonical paths) and the
176// Seatbelt denies are the second layer, and probe F6 proves the race
177// live on the Mac before Engineering is offered there.
178func darwinPlace(q permissionRequest, m manifest) nativePlace {
179 var input map[string]json.RawMessage
180 if json.Unmarshal(q.Input, &input) != nil || input == nil {
181 return placeProtected
182 }
183 path, ok := nativePathField(input)
184 if !ok {
185 return placeProtected
186 }
187 if path == "" || strings.HasPrefix(path, "~") || !filepath.IsAbs(path) {
188 return placeBadPath
189 }
190 if strings.ContainsAny(path, "\x00\n\r") || dotDot(path) {
191 return placeProtected
192 }
193 var patternKey string
194 switch q.Tool {
195 case "Glob":
196 patternKey = "pattern"
197 case "Grep":
198 patternKey = "glob"
199 }
200 if raw, ok := input[patternKey]; ok && patternKey != "" {
201 var pattern string
202 // A pattern never names a place by itself: no absolute pattern,
203 // no home, and no ".." anywhere (not even inside braces).
204 if json.Unmarshal(raw, &pattern) != nil || filepath.IsAbs(pattern) || strings.HasPrefix(pattern, "~") || strings.Contains(pattern, "..") || strings.ContainsAny(pattern, "\x00\n\r") {
205 return placeProtected
206 }
207 if q.Tool == "Glob" {
208 // The literal base is all that is known before Glob expands
209 // the pattern; it is resolved with the path.
210 for _, part := range strings.Split(pattern, "/") {
211 if strings.ContainsAny(part, "*?[{\\") {
212 break
213 }
214 path = filepath.Join(path, part)
215 }
216 }
217 }
218 root, ok := realDir(m.WorkspaceRoot)
219 if !ok {
220 return placeProtected
221 }
222 roots := []string{root}
223 research := ""
224 if m.ResearchRoot != "" {
225 if research, ok = realDir(m.ResearchRoot); !ok {
226 return placeProtected
227 }
228 roots = append(roots, research)
229 }
230 real, ok := resolveNative(path, roots)
231 if !ok {
232 return placeProtected
233 }
234 lexical := filepath.Clean(path)
235 denied := deniedForms(m)
236 for _, deny := range denied {
237 if foldedWithin(deny, lexical) || foldedWithin(deny, real) {
238 return placeProtected
239 }
240 // A search of a directory holding a denied place would reach it.
241 if (q.Tool == "Glob" || q.Tool == "Grep") && (foldedWithin(lexical, deny) || foldedWithin(real, deny)) {
242 return placeProtected
243 }
244 }
245 if slices.Contains([]string{"Read", "Edit", "Write"}, q.Tool) && !fileVerified(real) {
246 return placeProtected
247 }
248 place, in := placeOutside, ""
249 switch {
250 case within(root, real):
251 place, in = placeWorkspace, root
252 case research != "" && within(research, real):
253 place, in = placeResearch, research
254 }
255 if q.Tool == "Grep" && place != placeOutside && !searchable(real, in, denied, grepWalkLimit) {
256 return placeProtected
257 }
258 return place
259}
260
261// grepWalkLimit bounds the entries searchable walks before it refuses: a
262// large Xcode project with its packages checked out fits well inside.
263const grepWalkLimit = 200000
264
265// walkBatch is how many directory entries the walk reads at a time, so a
266// directory of millions costs no more than the budget before refusing.
267const walkBatch = 256
268
269// walkHook, when set (tests only), sees each batch of names the walk
270// reads, before it checks them; openHook each directory between its stat
271// and its open.
272var (
273 walkHook func(dir string, names []string)
274 openHook func(path string)
275 // readDir reads the next batch of a directory (a seam for tests).
276 readDir = func(f *os.File, n int) ([]fs.DirEntry, error) { return f.ReadDir(n) }
277)
278
279// searchable reports that Grep may read target, a file or directory in
280// root. Every step is verified or refuses: the target and each directory
281// are opened one component at a time from "/" with no link followed
282// (openat with O_NOFOLLOW, checked by device and inode against what was
283// statted); entries are read walkBatch at a time and each is statted
284// relative to its directory without following it. A regular file must
285// have one link; a link (which Grep does not follow) must resolve inside
286// root and not into a denied place; a directory is walked; anything else,
287// a type that differs from the one listed (a swap after the listing), an
288// error of any kind, or more than limit entries refuses. A git checkout
289// makes no hard links, so a real worktree passes. The walk cannot close
290// the race with the CLI's own read (darwinPlace).
291func searchable(target, root string, denied []string, limit int) bool {
292 st, err := lstatNoFollow(target)
293 if err != nil {
294 return false
295 }
296 switch uint32(st.Mode) & unix.S_IFMT {
297 case unix.S_IFREG:
298 return st.Nlink == 1
299 case unix.S_IFDIR:
300 default:
301 return false
302 }
303 if openHook != nil {
304 openHook(target)
305 }
306 fd, err := openDirNoFollow(target)
307 if err != nil {
308 return false
309 }
310 if !sameInode(fd, st) {
311 unix.Close(fd)
312 return false
313 }
314 w := treeWalk{root: root, denied: denied, budget: limit}
315 return w.dir(fd, target)
316}
317
318type treeWalk struct {
319 root string
320 denied []string
321 budget int
322}
323
324// dir walks the open directory fd (closed on return) at path.
325func (w *treeWalk) dir(fd int, path string) bool {
326 f := os.NewFile(uintptr(fd), path)
327 defer f.Close()
328 for {
329 entries, err := readDir(f, walkBatch)
330 if err != nil && err != io.EOF {
331 return false
332 }
333 if walkHook != nil && len(entries) > 0 {
334 names := make([]string, len(entries))
335 for i, e := range entries {
336 names[i] = e.Name()
337 }
338 walkHook(path, names)
339 }
340 for _, e := range entries {
341 if w.budget--; w.budget < 0 || !w.entry(fd, path, e) {
342 return false
343 }
344 }
345 if err == io.EOF || len(entries) == 0 {
346 return true
347 }
348 }
349}
350
351// entry checks one listed entry of the directory fd at dir.
352func (w *treeWalk) entry(fd int, dir string, e fs.DirEntry) bool {
353 var st unix.Stat_t
354 if unix.Fstatat(fd, e.Name(), &st, unix.AT_SYMLINK_NOFOLLOW) != nil {
355 return false
356 }
357 kind := uint32(st.Mode) & unix.S_IFMT
358 if !sameKind(e.Type(), kind) {
359 return false
360 }
361 path := filepath.Join(dir, e.Name())
362 switch kind {
363 case unix.S_IFREG:
364 return st.Nlink == 1
365 case unix.S_IFLNK:
366 resolved, err := filepath.EvalSymlinks(path)
367 if err != nil || !within(w.root, resolved) {
368 return false
369 }
370 for _, deny := range w.denied {
371 if foldedWithin(deny, resolved) {
372 return false
373 }
374 }
375 return true
376 case unix.S_IFDIR:
377 if openHook != nil {
378 openHook(path)
379 }
380 sub, err := unix.Openat(fd, e.Name(), unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
381 if err != nil {
382 return false
383 }
384 if !sameInode(sub, st) {
385 unix.Close(sub)
386 return false
387 }
388 return w.dir(sub, path)
389 }
390 return false
391}
392
393// sameKind reports that a listed type is the statted one.
394func sameKind(t fs.FileMode, kind uint32) bool {
395 switch kind {
396 case unix.S_IFREG:
397 return t.IsRegular()
398 case unix.S_IFDIR:
399 return t.IsDir()
400 case unix.S_IFLNK:
401 return t&fs.ModeSymlink != 0
402 case unix.S_IFIFO:
403 return t&fs.ModeNamedPipe != 0
404 case unix.S_IFSOCK:
405 return t&fs.ModeSocket != 0
406 case unix.S_IFCHR:
407 return t&fs.ModeCharDevice != 0
408 case unix.S_IFBLK:
409 return t&fs.ModeDevice != 0 && t&fs.ModeCharDevice == 0
410 }
411 return false
412}
413
414// sameInode reports that the open fd is the file st describes.
415func sameInode(fd int, st unix.Stat_t) bool {
416 var opened unix.Stat_t
417 return unix.Fstat(fd, &opened) == nil && opened.Dev == st.Dev && opened.Ino == st.Ino
418}
419
420// openDirNoFollow opens the directory at an absolute path one component
421// at a time from "/", following no link.
422func openDirNoFollow(path string) (int, error) {
423 fd, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
424 if err != nil {
425 return -1, err
426 }
427 for _, part := range strings.Split(strings.Trim(filepath.Clean(path), "/"), "/") {
428 if part == "" {
429 continue
430 }
431 next, err := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
432 unix.Close(fd)
433 if err != nil {
434 return -1, err
435 }
436 fd = next
437 }
438 return fd, nil
439}
440
441// lstatNoFollow stats path itself, its directory opened by
442// openDirNoFollow.
443func lstatNoFollow(path string) (unix.Stat_t, error) {
444 var st unix.Stat_t
445 path = filepath.Clean(path)
446 if path == "/" {
447 return st, unix.Lstat(path, &st)
448 }
449 fd, err := openDirNoFollow(filepath.Dir(path))
450 if err != nil {
451 return st, err
452 }
453 defer unix.Close(fd)
454 return st, unix.Fstatat(fd, filepath.Base(path), &st, unix.AT_SYMLINK_NOFOLLOW)
455}
456
457// fileVerified reports that a Read, Edit or Write of path reads nothing
458// unverified: nothing is there yet, or it is a directory, or a regular
459// file with one link. Any other answer, or any error, refuses.
460func fileVerified(path string) bool {
461 st, err := lstatNoFollow(path)
462 if errors.Is(err, unix.ENOENT) {
463 return true
464 }
465 if err != nil {
466 return false
467 }
468 switch uint32(st.Mode) & unix.S_IFMT {
469 case unix.S_IFREG:
470 return st.Nlink == 1
471 case unix.S_IFDIR:
472 return true
473 }
474 return false
475}
476
477// deniedForms are the policy's denied paths, each also as resolved when
478// it resolves elsewhere.
479func deniedForms(m manifest) []string {
480 var out []string
481 for _, d := range m.DeniedPaths {
482 out = append(out, d)
483 if r, err := filepath.EvalSymlinks(d); err == nil && r != d {
484 out = append(out, r)
485 }
486 }
487 return out
488}
489
490// nativePathField is the action's file_path or path ("" when it has
491// neither); false when the field is not a string.
492func nativePathField(input map[string]json.RawMessage) (string, bool) {
493 for _, key := range []string{"file_path", "path"} {
494 if raw, ok := input[key]; ok {
495 var path string
496 if json.Unmarshal(raw, &path) != nil {
497 return "", false
498 }
499 return path, true
500 }
501 }
502 return "", true
503}
504
505// dotDot reports a ".." component.
506func dotDot(path string) bool {
507 return slices.Contains(strings.Split(path, "/"), "..")
508}
509
510// realDir is root when it is an absolute, clean directory path with no
511// symlink anywhere in it (its own realpath) and not "/".
512func realDir(root string) (string, bool) {
513 if root == "" || root == "/" || !filepath.IsAbs(root) || filepath.Clean(root) != root {
514 return "", false
515 }
516 real, err := filepath.EvalSymlinks(root)
517 if err != nil || real != root {
518 return "", false
519 }
520 info, err := os.Stat(real)
521 if err != nil || !info.IsDir() {
522 return "", false
523 }
524 return real, true
525}
526
527// resolveNative walks an absolute, clean path from "/" (see darwinPlace).
528func resolveNative(path string, roots []string) (string, bool) {
529 cur := "/"
530 parts := strings.Split(strings.TrimPrefix(filepath.Clean(path), "/"), "/")
531 for i, part := range parts {
532 if part == "" {
533 continue
534 }
535 next := filepath.Join(cur, part)
536 info, err := os.Lstat(next)
537 if errors.Is(err, fs.ErrNotExist) {
538 // Nothing below exists: the rest names what would be created.
539 return filepath.Join(append([]string{next}, parts[i+1:]...)...), true
540 }
541 if err != nil {
542 return "", false
543 }
544 if info.Mode()&os.ModeSymlink != 0 {
545 for _, r := range roots {
546 if within(r, next) {
547 return "", false
548 }
549 }
550 target, err := filepath.EvalSymlinks(next)
551 if err != nil {
552 return "", false
553 }
554 next = target
555 }
556 cur = next
557 }
558 return cur, true
559}
560
561// within reports path at or below root, exactly.
562func within(root, path string) bool {
563 return path == root || strings.HasPrefix(path, strings.TrimSuffix(root, "/")+"/")
564}
565
566// foldedWithin is within as APFS compares names: component by
567// component, each in NFC and case-folded, so a denied place matches in
568// every spelling of it, never fewer.
569func foldedWithin(root, path string) bool {
570 if root == "" || path == "" {
571 return false
572 }
573 r, p := foldedPath(root), foldedPath(path)
574 return len(p) >= len(r) && slices.Equal(p[:len(r)], r)
575}
576
577// foldedPath is a clean path's components, each NFC, folded, NFC again.
578func foldedPath(path string) []string {
579 fold := cases.Fold() // a Caser is not safe to share between goroutines
580 parts := strings.Split(strings.Trim(filepath.Clean(path), "/"), "/")
581 for i, part := range parts {
582 parts[i] = norm.NFC.String(fold.String(norm.NFC.String(part)))
583 }
584 return parts
585}
586