package mac import ( "bytes" "context" "errors" "io/fs" "os" "path/filepath" "slices" "sort" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" ) // Engineering on a Mac (spec §4.4, §8.2; slice F task 8): the pinned // CLI, unsandboxed as the runner user, with its Bash commands in // Seatbelt under the per-attempt settings claude.DarwinPolicy makes. // This file turns the runner's places into that policy's inputs and is // the one way to start the CLI with it: regenerate, compare byte for // byte, check the filesystem, then ClaudeCLI.Launch. // EngineeringInput is one Mac launch of the CLI: Engineering, an ask or // a token check. type EngineeringInput struct { // Paths are the §4.2 places (DenyList) and, for sandboxed Xcode // access, the user's T (UserTemp). Paths // Action is claude.DarwinImplement, DarwinAnswer or DarwinCheck. Action, Model string // Worktree is the task tree at its real path (the workspace root of // the permission port), Scratch the attempt's scratch (TMPDIR). Worktree, Scratch string // Runner is the runner binary (cfg.Executable), serving MCP in its // tool-proxy mode on Socket, which lies in ToolRoot (thin's toolRoot, // /t). Runner, ToolRoot, Socket string // ConfigDir is the connection's runtime copy (CLAUDE_CONFIG_DIR), // inside RuntimeRoot (/homes); CredentialHome is its // dedicated home. ConfigDir, CredentialHome, RuntimeRoot string // XcodeAccess is "" or wire.XcodeAccessSandboxed. Mach is the // P2-recorded service list (CheckMachServices narrowed by P2); it is // used only with sandboxed access. XcodeAccess string Mach []string // DeveloperDir is xcode-select -p ("" for none). Attempt is the // attempt's marker. SessionID starts the session, or resumes it. DeveloperDir, Attempt, SessionID string Resume bool } // EngineeringCommand is exactly what to start: Argv (the verified CLI's // path first), the whole environment Env (nothing inherited), in Dir. // Files[i] becomes descriptor 3+i in the child (exec.Cmd.ExtraFiles); // Files[0] is the read end of a pipe holding the token. type EngineeringCommand struct { Argv, Env []string Dir string Files []*os.File } // EngineeringStart starts c and returns once the process exists (task // 9's executor: its process group, marker and record). It is called // while ClaudeCLI.Launch holds the hashed CLI open. type EngineeringStart func(ctx context.Context, c EngineeringCommand) error // MaxToken bounds the token written to the descriptor: far above a // setup token, far below a pipe's buffer, so the write never blocks. const MaxToken = 4096 // credentialPlaces are where developer tools keep credentials in the // runner user's home by default, denied to Engineering's sandboxed // commands and native tools beyond §4.2 (the checks profile keeps §4.2 // alone). A repository's script runs as this user, and an earlier tool // run may have left any of them: Claude Code and Codex; GitHub's CLI // (and hub); git's credential store (both places) and netrc (also // SwiftPM's and CocoaPods'); Docker, npm, Yarn, PyPI, RubyGems, Cargo, // Gradle and Maven; Kubernetes, gcloud, Azure and Terraform; Firebase // (configstore) and Hugging Face; fastlane's sessions and App Store // Connect API keys (altool's three places); pass; and the shell // histories, where a token typed once stays. ~/.ssh, ~/.aws, ~/.gnupg, // ~/.config/op and the Keychains are §4.2's already. Every place is // denied whether or not it exists, so the policy never depends on the // home's contents. Xcode's DerivedData and SwiftPM's caches are not here. var credentialPlaces = []string{ ".claude", ".claude.json", ".codex", ".config/gh", ".config/hub", ".git-credentials", ".config/git/credentials", ".netrc", ".docker/config.json", ".npmrc", ".yarnrc.yml", ".pypirc", ".gem/credentials", ".cargo/credentials", ".cargo/credentials.toml", ".gradle/gradle.properties", ".m2/settings.xml", ".m2/settings-security.xml", ".kube", ".config/gcloud", ".azure", ".terraform.d", ".config/configstore", ".cache/huggingface/token", ".huggingface", ".fastlane", ".appstoreconnect", ".private_keys", "private_keys", ".password-store", ".bash_history", ".zsh_history", ".zsh_sessions", } // engineeringDenies is §4.2 plus the credential places in the home. func engineeringDenies(p Paths) []string { out := DenyList(p) for _, rel := range credentialPlaces { out = append(out, filepath.Join(p.Home, rel)) } return out } // darwinInputs fills claude.DarwinInputs from in and the pinned CLI. // Every place the deny list is made from is required: DenyList drops an // empty one, and a policy missing it would still be whole and byte-equal. func (c ClaudeCLI) darwinInputs(in EngineeringInput) (claude.DarwinInputs, error) { for _, required := range []string{in.Home, in.StateDir, in.AccountsRoot, in.SessionRoot, in.InstallDir} { if required == "" { return claude.DarwinInputs{}, provider.ErrPolicy } } if c.installDir == "" || c.pin == "" || c.installDir != in.InstallDir { return claude.DarwinInputs{}, provider.ErrPolicy } d := claude.DarwinInputs{Action: in.Action, Model: in.Model, CLI: ClaudePath(c.installDir), CLIDigest: c.pin, CLIDir: ClaudeDir(c.installDir), InstallDir: in.InstallDir, Runner: in.Runner, ToolRoot: in.ToolRoot, Socket: in.Socket, Workspace: in.Worktree, Scratch: in.Scratch, Home: in.Home, ConfigDir: in.ConfigDir, CredentialHome: in.CredentialHome, RuntimeRoot: in.RuntimeRoot, Denied: engineeringDenies(in.Paths), XcodeAccess: in.XcodeAccess, DeveloperDir: in.DeveloperDir, Attempt: in.Attempt, SessionID: in.SessionID, Resume: in.Resume} // Xcode's services and places only with sandboxed access (§8.2): the // caller's Mach list is not used otherwise. if in.XcodeAccess != "" { places, err := xcodePlaces(in.Paths) if err != nil || machNames(in.Mach) != nil { return claude.DarwinInputs{}, provider.ErrPolicy } d.XcodeWrites = append([]string{filepath.Join(in.Scratch, "DerivedData")}, places...) d.Mach = slices.Clone(in.Mach) } return d, nil } // EngineeringPolicy is the certified policy for in with the pinned CLI // cli: what a step records and what LaunchEngineering checks again. func EngineeringPolicy(cli ClaudeCLI, in EngineeringInput) (provider.Policy, error) { d, err := cli.darwinInputs(in) if err != nil { return provider.Policy{}, err } return claude.DarwinPolicy(d) } // ValidateEngineering regenerates the policy from cli and in and refuses // p on any difference (claude.ValidateDarwin). It reads no file: a seam // for a caller that checks a stored policy without launching. func ValidateEngineering(cli ClaudeCLI, in EngineeringInput, p provider.Policy) error { d, err := cli.darwinInputs(in) if err != nil { return err } return claude.ValidateDarwin(d, p) } // LaunchEngineering starts the pinned CLI under p, which must be exactly // the policy cli and in make. Then the filesystem must agree: the // worktree and scratch are real directories at their own real paths, // and the runtime copy is a real directory with no token file the CLI // would read on its own. The settings and MCP config are written into // the runtime copy (0600, renamed into place), the token into a pipe // whose read end is descriptor 3, and start runs the policy's argv and // environment, nothing else, through ClaudeCLI.Launch, which hashes the // CLI and checks it again immediately before start. Any refusal starts // nothing and names no token. func LaunchEngineering(ctx context.Context, cli ClaudeCLI, in EngineeringInput, p provider.Policy, token []byte, start EngineeringStart) error { if err := ValidateEngineering(cli, in, p); err != nil { return err } argv := claude.DarwinArgv(p) if len(argv) < 2 || len(token) == 0 || len(token) > MaxToken || bytes.ContainsAny(token, "\x00\r\n") { return provider.ErrPolicy } for _, dir := range []string{in.Worktree, in.Scratch} { if !realDir(dir) { return provider.ErrPolicy } } if info, err := os.Lstat(in.ConfigDir); err != nil || !info.IsDir() { return provider.ErrPolicy } // The CLI falls back to /.oauth_token when no descriptor is // named (task 1, S4), and .oauth-token is a dedicated home's: the // runtime copy holds neither. for _, name := range []string{".oauth_token", ".oauth-token"} { if _, err := os.Lstat(filepath.Join(in.ConfigDir, name)); !errors.Is(err, fs.ErrNotExist) { return provider.ErrPolicy } } for name, body := range map[string][]byte{claude.DarwinSettingsFile: p.Settings, claude.DarwinMCPFile: p.MCP} { if err := placeFile(in.ConfigDir, name, body); err != nil { return provider.ErrPolicy } } env := make([]string, 0, len(p.Env)) for k, v := range p.Env { env = append(env, k+"="+v) } sort.Strings(env) read, write, err := os.Pipe() if err != nil { return err } defer read.Close() _, err = write.Write(token) if cerr := write.Close(); err == nil { err = cerr } if err != nil { return provider.ErrPolicy } return cli.Launch(ctx, func(ctx context.Context, verified []string) error { // The verified path is the policy's CLI, and nothing else moved. if !slices.Equal(verified, argv) { return provider.ErrPolicy } return start(ctx, EngineeringCommand{Argv: slices.Clone(argv), Env: env, Dir: in.Worktree, Files: []*os.File{read}}) }, argv[1:]...) } // realDir: a directory, at its own real path (no link anywhere in it). func realDir(dir string) bool { real, err := filepath.EvalSymlinks(dir) if err != nil || real != dir { return false } info, err := os.Lstat(dir) return err == nil && info.IsDir() } // placeFile writes body as dir/name, mode 0600: a new file renamed over // whatever was there, so a link at the name is replaced, never followed. func placeFile(dir, name string, body []byte) error { f, err := os.CreateTemp(dir, "."+name+"-*") if err != nil { return err } tmp := f.Name() _, err = f.Write(body) if e := f.Chmod(0600); err == nil { err = e } if e := f.Sync(); err == nil { err = e } if e := f.Close(); err == nil { err = e } if err == nil { err = os.Rename(tmp, filepath.Join(dir, name)) } if err != nil { os.Remove(tmp) } return err }