package mac import ( "context" "errors" "io/fs" "os" "path/filepath" "strings" "syscall" ) // The runner user's DARWIN_USER_TEMP_DIR ("T"). Xcode writes there // whatever $TMPDIR says: Foundation's temporary directory under Seatbelt // (Swift Build's swbuild.tmp.*, swift-driver's TemporaryDirectory.*) and // NSItemReplacementDirectory's TemporaryItems/NSIRD_* (atomic saves of // logs and result bundles). The checks profile lets a gate write it // (the coordinator's ruling); this file finds it, refuses one it cannot // trust, and removes what an attempt left there. // UserTempPrefix is where macOS keeps every user's T. const UserTempPrefix = "/private/var/folders" // ErrUserTemp says T was not found or is not the runner user's own. var ErrUserTemp = errors.New("mac: user temp folder refused") // UserTemp resolves the runner user's T: `getconf DARWIN_USER_TEMP_DIR`, // its symlinks resolved (/var is /private/var), no trailing slash. It // must be a directory under prefix (UserTempPrefix), owned by uid, mode // 0700; otherwise the error says why and no checks profile can be made. func UserTemp(ctx context.Context, x Exec, uid int, prefix string) (string, error) { ctx, cancel := context.WithTimeout(ctx, QueryLimit) defer cancel() out, err := x(ctx, "/usr/bin/getconf", "DARWIN_USER_TEMP_DIR") raw := strings.TrimSpace(out) if err != nil || raw == "" || !filepath.IsAbs(raw) { return "", refuse("getconf did not name it") } path, err := filepath.EvalSymlinks(raw) if err != nil { return "", refuse("it does not exist") } path = filepath.Clean(path) if !within(prefix, path) || path == prefix || !literalPath(path) { return "", refuse("it is not under the system's user folders") } info, err := os.Lstat(path) if err != nil || !info.IsDir() { return "", refuse("it is not a directory") } st, ok := info.Sys().(*syscall.Stat_t) if !ok || int(st.Uid) != uid { return "", refuse("another user owns it") } if info.Mode().Perm() != 0700 { return "", refuse("its mode is not 0700") } return path, nil } // UserTempError is a refused T, with why in words (no path). type UserTempError struct{ Why string } func (e *UserTempError) Error() string { return ErrUserTemp.Error() + ": " + e.Why } func (e *UserTempError) Is(target error) bool { return target == ErrUserTemp } func refuse(why string) error { return &UserTempError{Why: why} } // tempItems is NSItemReplacementDirectory's folder in T. const tempItems = "TemporaryItems" // tempEntry is one name in T or T/TemporaryItems and the file it was. type tempEntry struct { Dev uint64 `json:"dev"` Ino uint64 `json:"ino"` Kind fs.FileMode `json:"kind"` } func entryOf(info fs.FileInfo) tempEntry { e := tempEntry{Kind: info.Mode().Type()} if st, ok := info.Sys().(*syscall.Stat_t); ok { e.Dev, e.Ino = uint64(st.Dev), uint64(st.Ino) } return e } // tempListing is what was in T (keys "name") and T/TemporaryItems (keys // "TemporaryItems/name") right before an attempt. type tempListing map[string]tempEntry // tempState is T held open for one attempt: the directory listed, by // handle (os.Root), so a T replaced meanwhile (by a symlink, say) is // never what the cleanup reads or removes in; and the same for // T/TemporaryItems, held only when it was a real directory. type tempState struct { root, items *os.Root before tempListing } // openTemp opens T for an attempt and lists it. T must still be a real // directory (not a symlink), this user's own, mode 0700, and the // directory opened must be the one at the path. func openTemp(dir string, before tempListing) (*tempState, error) { info, err := os.Lstat(dir) if err != nil { return nil, err } if st, ok := info.Sys().(*syscall.Stat_t); !info.IsDir() || !ok || int(st.Uid) != os.Getuid() || info.Mode().Perm() != 0700 { return nil, ErrUserTemp } root, err := os.OpenRoot(dir) if err != nil { return nil, err } s := &tempState{root: root, before: before} if self, err := root.Stat("."); err != nil || entryOf(self) != entryOf(info) { s.close() return nil, ErrUserTemp } now, err := list(root, "") if err != nil { s.close() return nil, err } // TemporaryItems by handle, and only the directory that was there // before (a fresh listing: the one there now). want, had := now[tempItems], true if before != nil { want, had = before[tempItems] } if items, ok := now[tempItems]; ok && had && items == want && items.Kind == fs.ModeDir { if s.items, err = root.OpenRoot(tempItems); err == nil { if self, err := s.items.Stat("."); err != nil || entryOf(self) != items { s.items.Close() s.items = nil } } else if !errors.Is(err, fs.ErrNotExist) { s.close() return nil, err } } if s.items != nil { in, err := list(s.items, tempItems+"/") if err != nil { s.close() return nil, err } for k, v := range in { now[k] = v } } if s.before == nil { s.before = now } return s, nil } func (s *tempState) close() { if s.items != nil { s.items.Close() } s.root.Close() } // list names what is in dir (by handle), keyed with prefix. A name gone // between the listing and the look is not there; any other error is. func list(dir *os.Root, prefix string) (tempListing, error) { f, err := dir.Open(".") if err != nil { return nil, err } names, err := f.Readdirnames(-1) f.Close() if err != nil { return nil, err } l := tempListing{} for _, n := range names { info, err := dir.Lstat(n) if errors.Is(err, fs.ErrNotExist) { continue } if err != nil { return nil, err } l[prefix+n] = entryOf(info) } return l, nil } // clean removes what appeared in T and T/TemporaryItems since before: // every name not listed then, or listed as another file (same name, // other device, file number or kind). Each name is removed by the handle of // its own directory, one path element, so no symlink is followed: a // symlink goes as itself. A folder the attempt made unreadable is made // the owner's again to be removed. What vanishes meanwhile is not an // error; anything else is. func (s *tempState) clean() error { var errs []error for _, d := range []struct { root *os.Root prefix string }{{s.root, ""}, {s.items, tempItems + "/"}} { if d.root == nil { continue } now, err := list(d.root, d.prefix) if d.prefix != "" && errors.Is(err, fs.ErrNotExist) { // TemporaryItems itself is gone (removed while the run // lasted): nothing is left in it to clean. continue } if err != nil { errs = append(errs, err) continue } for name, e := range now { if old, ok := s.before[name]; ok && old == e { continue } if err := remove(d.root, strings.TrimPrefix(name, d.prefix)); err != nil { errs = append(errs, err) } } } return errors.Join(errs...) } // remove removes name in dir and all below it, never through a symlink; // a folder that cannot be read or written is given back to its owner // (this user) first. func remove(dir *os.Root, name string) error { err := dir.RemoveAll(name) if err == nil || errors.Is(err, fs.ErrNotExist) { return nil } if info, lerr := dir.Lstat(name); lerr == nil && info.IsDir() { _ = unlock(dir, name, 0) } if err := dir.RemoveAll(name); err != nil && !errors.Is(err, fs.ErrNotExist) { return err } return nil } // unlock makes the folder name (and the folders below it) 0700 again, // opening each by handle so no symlink is followed. func unlock(dir *os.Root, name string, depth int) error { if depth > 64 { return errors.New("mac: too deep") } if err := dir.Chmod(name, 0700); err != nil { return err } sub, err := dir.OpenRoot(name) if err != nil { return err } defer sub.Close() in, err := list(sub, "") if err != nil { return err } for n, e := range in { if e.Kind == fs.ModeDir { _ = unlock(sub, n, depth+1) } } return nil }