oficina / equipo Public

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

Plain git — no account needed to clone.

Download

Download this file

1package mac
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "io/fs"
8 "os"
9 "path/filepath"
10 "slices"
11 "sort"
12
13 "amadan.net/oficina/equipo/internal/runner/provider"
14 "amadan.net/oficina/equipo/internal/runner/provider/claude"
15)
16
17// Engineering on a Mac (spec §4.4, §8.2; slice F task 8): the pinned
18// CLI, unsandboxed as the runner user, with its Bash commands in
19// Seatbelt under the per-attempt settings claude.DarwinPolicy makes.
20// This file turns the runner's places into that policy's inputs and is
21// the one way to start the CLI with it: regenerate, compare byte for
22// byte, check the filesystem, then ClaudeCLI.Launch.
23
24// EngineeringInput is one Mac launch of the CLI: Engineering, an ask or
25// a token check.
26type EngineeringInput struct {
27 // Paths are the §4.2 places (DenyList) and, for sandboxed Xcode
28 // access, the user's T (UserTemp).
29 Paths
30 // Action is claude.DarwinImplement, DarwinAnswer or DarwinCheck.
31 Action, Model string
32 // Worktree is the task tree at its real path (the workspace root of
33 // the permission port), Scratch the attempt's scratch (TMPDIR).
34 Worktree, Scratch string
35 // Runner is the runner binary (cfg.Executable), serving MCP in its
36 // tool-proxy mode on Socket, which lies in ToolRoot (thin's toolRoot,
37 // <scratch root>/t).
38 Runner, ToolRoot, Socket string
39 // ConfigDir is the connection's runtime copy (CLAUDE_CONFIG_DIR),
40 // inside RuntimeRoot (<scratch root>/homes); CredentialHome is its
41 // dedicated home.
42 ConfigDir, CredentialHome, RuntimeRoot string
43 // XcodeAccess is "" or wire.XcodeAccessSandboxed. Mach is the
44 // P2-recorded service list (CheckMachServices narrowed by P2); it is
45 // used only with sandboxed access.
46 XcodeAccess string
47 Mach []string
48 // DeveloperDir is xcode-select -p ("" for none). Attempt is the
49 // attempt's marker. SessionID starts the session, or resumes it.
50 DeveloperDir, Attempt, SessionID string
51 Resume bool
52}
53
54// EngineeringCommand is exactly what to start: Argv (the verified CLI's
55// path first), the whole environment Env (nothing inherited), in Dir.
56// Files[i] becomes descriptor 3+i in the child (exec.Cmd.ExtraFiles);
57// Files[0] is the read end of a pipe holding the token.
58type EngineeringCommand struct {
59 Argv, Env []string
60 Dir string
61 Files []*os.File
62}
63
64// EngineeringStart starts c and returns once the process exists (task
65// 9's executor: its process group, marker and record). It is called
66// while ClaudeCLI.Launch holds the hashed CLI open.
67type EngineeringStart func(ctx context.Context, c EngineeringCommand) error
68
69// MaxToken bounds the token written to the descriptor: far above a
70// setup token, far below a pipe's buffer, so the write never blocks.
71const MaxToken = 4096
72
73// credentialPlaces are where developer tools keep credentials in the
74// runner user's home by default, denied to Engineering's sandboxed
75// commands and native tools beyond §4.2 (the checks profile keeps §4.2
76// alone). A repository's script runs as this user, and an earlier tool
77// run may have left any of them: Claude Code and Codex; GitHub's CLI
78// (and hub); git's credential store (both places) and netrc (also
79// SwiftPM's and CocoaPods'); Docker, npm, Yarn, PyPI, RubyGems, Cargo,
80// Gradle and Maven; Kubernetes, gcloud, Azure and Terraform; Firebase
81// (configstore) and Hugging Face; fastlane's sessions and App Store
82// Connect API keys (altool's three places); pass; and the shell
83// histories, where a token typed once stays. ~/.ssh, ~/.aws, ~/.gnupg,
84// ~/.config/op and the Keychains are §4.2's already. Every place is
85// denied whether or not it exists, so the policy never depends on the
86// home's contents. Xcode's DerivedData and SwiftPM's caches are not here.
87var credentialPlaces = []string{
88 ".claude", ".claude.json", ".codex",
89 ".config/gh", ".config/hub",
90 ".git-credentials", ".config/git/credentials", ".netrc",
91 ".docker/config.json", ".npmrc", ".yarnrc.yml", ".pypirc", ".gem/credentials", ".cargo/credentials", ".cargo/credentials.toml",
92 ".gradle/gradle.properties", ".m2/settings.xml", ".m2/settings-security.xml",
93 ".kube", ".config/gcloud", ".azure", ".terraform.d",
94 ".config/configstore", ".cache/huggingface/token", ".huggingface",
95 ".fastlane", ".appstoreconnect", ".private_keys", "private_keys",
96 ".password-store", ".bash_history", ".zsh_history", ".zsh_sessions",
97}
98
99// engineeringDenies is §4.2 plus the credential places in the home.
100func engineeringDenies(p Paths) []string {
101 out := DenyList(p)
102 for _, rel := range credentialPlaces {
103 out = append(out, filepath.Join(p.Home, rel))
104 }
105 return out
106}
107
108// darwinInputs fills claude.DarwinInputs from in and the pinned CLI.
109// Every place the deny list is made from is required: DenyList drops an
110// empty one, and a policy missing it would still be whole and byte-equal.
111func (c ClaudeCLI) darwinInputs(in EngineeringInput) (claude.DarwinInputs, error) {
112 for _, required := range []string{in.Home, in.StateDir, in.AccountsRoot, in.SessionRoot, in.InstallDir} {
113 if required == "" {
114 return claude.DarwinInputs{}, provider.ErrPolicy
115 }
116 }
117 if c.installDir == "" || c.pin == "" || c.installDir != in.InstallDir {
118 return claude.DarwinInputs{}, provider.ErrPolicy
119 }
120 d := claude.DarwinInputs{Action: in.Action, Model: in.Model,
121 CLI: ClaudePath(c.installDir), CLIDigest: c.pin, CLIDir: ClaudeDir(c.installDir), InstallDir: in.InstallDir,
122 Runner: in.Runner, ToolRoot: in.ToolRoot, Socket: in.Socket,
123 Workspace: in.Worktree, Scratch: in.Scratch, Home: in.Home,
124 ConfigDir: in.ConfigDir, CredentialHome: in.CredentialHome, RuntimeRoot: in.RuntimeRoot,
125 Denied: engineeringDenies(in.Paths), XcodeAccess: in.XcodeAccess,
126 DeveloperDir: in.DeveloperDir, Attempt: in.Attempt, SessionID: in.SessionID, Resume: in.Resume}
127 // Xcode's services and places only with sandboxed access (§8.2): the
128 // caller's Mach list is not used otherwise.
129 if in.XcodeAccess != "" {
130 places, err := xcodePlaces(in.Paths)
131 if err != nil || machNames(in.Mach) != nil {
132 return claude.DarwinInputs{}, provider.ErrPolicy
133 }
134 d.XcodeWrites = append([]string{filepath.Join(in.Scratch, "DerivedData")}, places...)
135 d.Mach = slices.Clone(in.Mach)
136 }
137 return d, nil
138}
139
140// EngineeringPolicy is the certified policy for in with the pinned CLI
141// cli: what a step records and what LaunchEngineering checks again.
142func EngineeringPolicy(cli ClaudeCLI, in EngineeringInput) (provider.Policy, error) {
143 d, err := cli.darwinInputs(in)
144 if err != nil {
145 return provider.Policy{}, err
146 }
147 return claude.DarwinPolicy(d)
148}
149
150// ValidateEngineering regenerates the policy from cli and in and refuses
151// p on any difference (claude.ValidateDarwin). It reads no file: a seam
152// for a caller that checks a stored policy without launching.
153func ValidateEngineering(cli ClaudeCLI, in EngineeringInput, p provider.Policy) error {
154 d, err := cli.darwinInputs(in)
155 if err != nil {
156 return err
157 }
158 return claude.ValidateDarwin(d, p)
159}
160
161// LaunchEngineering starts the pinned CLI under p, which must be exactly
162// the policy cli and in make. Then the filesystem must agree: the
163// worktree and scratch are real directories at their own real paths,
164// and the runtime copy is a real directory with no token file the CLI
165// would read on its own. The settings and MCP config are written into
166// the runtime copy (0600, renamed into place), the token into a pipe
167// whose read end is descriptor 3, and start runs the policy's argv and
168// environment, nothing else, through ClaudeCLI.Launch, which hashes the
169// CLI and checks it again immediately before start. Any refusal starts
170// nothing and names no token.
171func LaunchEngineering(ctx context.Context, cli ClaudeCLI, in EngineeringInput, p provider.Policy, token []byte, start EngineeringStart) error {
172 if err := ValidateEngineering(cli, in, p); err != nil {
173 return err
174 }
175 argv := claude.DarwinArgv(p)
176 if len(argv) < 2 || len(token) == 0 || len(token) > MaxToken || bytes.ContainsAny(token, "\x00\r\n") {
177 return provider.ErrPolicy
178 }
179 for _, dir := range []string{in.Worktree, in.Scratch} {
180 if !realDir(dir) {
181 return provider.ErrPolicy
182 }
183 }
184 if info, err := os.Lstat(in.ConfigDir); err != nil || !info.IsDir() {
185 return provider.ErrPolicy
186 }
187 // The CLI falls back to <config>/.oauth_token when no descriptor is
188 // named (task 1, S4), and .oauth-token is a dedicated home's: the
189 // runtime copy holds neither.
190 for _, name := range []string{".oauth_token", ".oauth-token"} {
191 if _, err := os.Lstat(filepath.Join(in.ConfigDir, name)); !errors.Is(err, fs.ErrNotExist) {
192 return provider.ErrPolicy
193 }
194 }
195 for name, body := range map[string][]byte{claude.DarwinSettingsFile: p.Settings, claude.DarwinMCPFile: p.MCP} {
196 if err := placeFile(in.ConfigDir, name, body); err != nil {
197 return provider.ErrPolicy
198 }
199 }
200 env := make([]string, 0, len(p.Env))
201 for k, v := range p.Env {
202 env = append(env, k+"="+v)
203 }
204 sort.Strings(env)
205 read, write, err := os.Pipe()
206 if err != nil {
207 return err
208 }
209 defer read.Close()
210 _, err = write.Write(token)
211 if cerr := write.Close(); err == nil {
212 err = cerr
213 }
214 if err != nil {
215 return provider.ErrPolicy
216 }
217 return cli.Launch(ctx, func(ctx context.Context, verified []string) error {
218 // The verified path is the policy's CLI, and nothing else moved.
219 if !slices.Equal(verified, argv) {
220 return provider.ErrPolicy
221 }
222 return start(ctx, EngineeringCommand{Argv: slices.Clone(argv), Env: env, Dir: in.Worktree, Files: []*os.File{read}})
223 }, argv[1:]...)
224}
225
226// realDir: a directory, at its own real path (no link anywhere in it).
227func realDir(dir string) bool {
228 real, err := filepath.EvalSymlinks(dir)
229 if err != nil || real != dir {
230 return false
231 }
232 info, err := os.Lstat(dir)
233 return err == nil && info.IsDir()
234}
235
236// placeFile writes body as dir/name, mode 0600: a new file renamed over
237// whatever was there, so a link at the name is replaced, never followed.
238func placeFile(dir, name string, body []byte) error {
239 f, err := os.CreateTemp(dir, "."+name+"-*")
240 if err != nil {
241 return err
242 }
243 tmp := f.Name()
244 _, err = f.Write(body)
245 if e := f.Chmod(0600); err == nil {
246 err = e
247 }
248 if e := f.Sync(); err == nil {
249 err = e
250 }
251 if e := f.Close(); err == nil {
252 err = e
253 }
254 if err == nil {
255 err = os.Rename(tmp, filepath.Join(dir, name))
256 }
257 if err != nil {
258 os.Remove(tmp)
259 }
260 return err
261}
262