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 "context"
5 "crypto/rand"
6 "crypto/sha256"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io"
11 "io/fs"
12 "net/http"
13 "os"
14 "path/filepath"
15 "strings"
16 "time"
17
18 "amadan.net/oficina/equipo/internal/runner/provider"
19 "amadan.net/oficina/equipo/internal/runner/provider/claude"
20 "amadan.net/oficina/equipo/internal/wire"
21)
22
23// The Claude Code a Mac worker runs (Mac runners spec §8.2): the official
24// 2.1.312 darwin-arm64 binary, which the worker fetches itself and checks
25// against claude.ExecutableSHA256DarwinArm64, compiled in. It never runs
26// a claude it finds on PATH or is pointed at, not even for --version.
27//
28// The URL is built from these constants and provider.ClaudeVersion, as
29// the official installer builds it (task 1, S1). The release manifest
30// beside it is not read: the pin is the only trust.
31const (
32 ClaudeReleaseBase = "https://downloads.claude.ai/claude-code-releases"
33 ClaudePlatform = "darwin-arm64"
34 // MaxClaudeBinary bounds the download (2.1.312's is 275988512 bytes).
35 MaxClaudeBinary = 512 << 20
36)
37
38// ClaudeURL is the pinned release's official download.
39func ClaudeURL() string {
40 return ClaudeReleaseBase + "/" + provider.ClaudeVersion + "/" + ClaudePlatform + "/claude"
41}
42
43// claudeRel is where the CLI lives under the install dir, as path
44// components: tools/claude-<version>/claude, beside the pinned Node and
45// ripgrep. Checks may not write the install dir (ChecksSettings).
46var claudeRel = []string{"tools", "claude-" + provider.ClaudeVersion}
47
48const claudeName = "claude"
49
50// downloadPrefix names a download being written beside the CLI; one a
51// crash left behind is removed by the next Provision.
52const downloadPrefix = ".claude-download-"
53
54// ClaudeDir is the pinned CLI's directory under installDir.
55func ClaudeDir(installDir string) string {
56 return filepath.Join(append([]string{installDir}, claudeRel...)...)
57}
58
59// ClaudePath is the pinned CLI under installDir. Never run it by this
60// path: Argv and Launch verify it first.
61func ClaudePath(installDir string) string {
62 return filepath.Join(ClaudeDir(installDir), claudeName)
63}
64
65var (
66 // ErrClaudeUnpinned: no pinned CLI at its place, or what is there is
67 // not a plain 0700 file, reached through no link, that matches the pin.
68 ErrClaudeUnpinned = errors.New("mac: the pinned Claude Code is not in place")
69 // ErrClaudeRefused: a download that does not match the pin, or is
70 // over MaxClaudeBinary.
71 ErrClaudeRefused = errors.New("mac: Claude Code download refused")
72)
73
74// ClaudeUnavailable stops a launch of the CLI before anything starts:
75// the step ends wire.ReasonEngineeringUnavailable.
76type ClaudeUnavailable struct{ Err error }
77
78func (e *ClaudeUnavailable) Error() string {
79 return "engineering unavailable: " + e.Err.Error()
80}
81
82func (e *ClaudeUnavailable) Unwrap() error { return e.Err }
83
84// Reason is the step reason a launch stopped by e reports.
85func (e *ClaudeUnavailable) Reason() string { return wire.ReasonEngineeringUnavailable }
86
87// ClaudeFetch opens url's body. Provision only ever asks for ClaudeURL.
88type ClaudeFetch func(ctx context.Context, url string) (io.ReadCloser, error)
89
90// ClaudeCLI is the pinned CLI under a runner's install dir. Nothing can
91// start it but Launch, which hashes the file and checks that the path
92// still names exactly what it hashed, immediately before start. The zero
93// value has no CLI: it verifies nothing and launches nothing.
94type ClaudeCLI struct {
95 // home is the trusted ancestor: the runner user's home. installDir
96 // must lie inside it; every directory from home down to the binary
97 // is checked (openClaudeDir).
98 home, installDir string
99 // pin is the digest the file must have (a test pins its own bytes).
100 pin string
101 // limit bounds a download; 0 is MaxClaudeBinary.
102 limit int64
103}
104
105// NewClaudeCLI is the pinned darwin-arm64 CLI under installDir
106// (~/.local/lib/equipo-runner on a Mac), which lies in home.
107func NewClaudeCLI(home, installDir string) ClaudeCLI {
108 return ClaudeCLI{home: home, installDir: installDir, pin: claude.ExecutableSHA256DarwinArm64}
109}
110
111// Seams. ownerOf is the uid owning a file; runnerUID the uid that must
112// own every directory and the binary. claudeDuringHash runs once in the
113// middle of a launch's hash, claudeBeforeStart after the hash and before
114// the final check (tests race a swap there; nil in a release).
115var (
116 ownerOf = fileOwner
117 runnerUID = os.Getuid()
118 claudeDuringHash, claudeBeforeStart func()
119)
120
121func (c ClaudeCLI) bound() int64 {
122 if c.limit > 0 {
123 return c.limit
124 }
125 return MaxClaudeBinary
126}
127
128// Verify hashes the CLI at its place, once, and returns its path when it
129// matches the pin: a plain 0700 file of the runner user, reached through
130// private directories and no symbolic link from the home. The path is
131// for reports and policy records only; start the CLI with Launch.
132func (c ClaudeCLI) Verify() (string, error) {
133 v, err := c.open()
134 if err != nil {
135 return "", err
136 }
137 v.close()
138 return v.path, nil
139}
140
141// Version is the pinned version while the CLI verifies, else "". It
142// runs nothing: what the capability report states about Claude Code.
143func (c ClaudeCLI) Version() string {
144 if _, err := c.Verify(); err != nil {
145 return ""
146 }
147 return provider.ClaudeVersion
148}
149
150// Launch starts the pinned CLI through start with argv [path, args...].
151// Every start of the CLI (an Engineering attempt, an ask, a token check,
152// a sign-in, a probe launch) goes through here. It opens the file and
153// hashes the open descriptor, then, immediately before start, checks
154// that the path still names that same file (device, inode, size,
155// modification and change times) and that it did not change while it
156// was hashed. The descriptor stays open until start returns, so the
157// inode cannot be reused by another file meanwhile; start should have
158// started the process when it returns. Nothing starts when any check
159// fails: *ClaudeUnavailable, engineering_unavailable.
160//
161// The honest limit: macOS cannot exec a descriptor, so the kernel looks
162// the path up again after the last check. Only the runner user can
163// rename inside the private chain, sandboxed commands cannot write the
164// install dir, and the runner user is dedicated to the runner.
165func (c ClaudeCLI) Launch(ctx context.Context, start func(ctx context.Context, argv []string) error, args ...string) error {
166 v, err := c.open()
167 if err != nil {
168 return &ClaudeUnavailable{Err: err}
169 }
170 defer v.close()
171 if claudeBeforeStart != nil {
172 claudeBeforeStart()
173 }
174 if err := v.still(); err != nil {
175 return &ClaudeUnavailable{Err: err}
176 }
177 return start(ctx, append([]string{v.path}, args...))
178}
179
180// verified is an open, hashed CLI: its descriptor and the state it had.
181type verified struct {
182 f *os.File
183 path string
184 key statKey
185}
186
187type statKey struct {
188 dev, ino uint64
189 size int64
190 mtime, ctime int64
191}
192
193func (v *verified) close() { v.f.Close() }
194
195// still: the path names the hashed file, unchanged.
196func (v *verified) still() error {
197 named, err := os.Lstat(v.path)
198 if err != nil {
199 return ErrClaudeUnpinned
200 }
201 held, err := v.f.Stat()
202 if err != nil || !named.Mode().IsRegular() || !os.SameFile(named, held) {
203 return fmt.Errorf("%w: replaced after it was hashed", ErrClaudeUnpinned)
204 }
205 nk, ok1 := fileKey(named)
206 hk, ok2 := fileKey(held)
207 if !ok1 || !ok2 || nk != v.key || hk != v.key {
208 return fmt.Errorf("%w: changed after it was hashed", ErrClaudeUnpinned)
209 }
210 return nil
211}
212
213// open validates the chain, opens the CLI and hashes the descriptor,
214// once: a regular file, not a link, mode 0700, the runner user's, the
215// file opened the one examined, unchanged from before the hash to after.
216func (c ClaudeCLI) open() (*verified, error) {
217 if c.installDir == "" || c.pin == "" {
218 return nil, ErrClaudeUnpinned
219 }
220 d, err := c.openDir(false)
221 if err != nil {
222 return nil, ErrClaudeUnpinned
223 }
224 defer d.Close()
225 f, err := c.hashIn(d, claudeDuringHash)
226 if err != nil {
227 return nil, err
228 }
229 return f, nil
230}
231
232func (c ClaudeCLI) hashIn(d *os.Root, during func()) (*verified, error) {
233 info, err := d.Lstat(claudeName)
234 if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0700 || ownerOf(info) != runnerUID || info.Size() > c.bound() {
235 return nil, ErrClaudeUnpinned
236 }
237 f, err := d.OpenFile(claudeName, os.O_RDONLY, 0)
238 if err != nil {
239 return nil, ErrClaudeUnpinned
240 }
241 before, err := f.Stat()
242 key, ok := fileKey(before)
243 if err != nil || !ok || !os.SameFile(info, before) {
244 f.Close()
245 return nil, ErrClaudeUnpinned
246 }
247 h := sha256.New()
248 var r io.Reader = io.LimitReader(f, c.bound()+1)
249 if during != nil {
250 r = &midway{r: r, at: during}
251 }
252 if _, err := io.Copy(h, r); err != nil || hex.EncodeToString(h.Sum(nil)) != c.pin {
253 f.Close()
254 return nil, ErrClaudeUnpinned
255 }
256 after, err := f.Stat()
257 if k, ok := fileKey(after); err != nil || !ok || k != key {
258 f.Close()
259 return nil, fmt.Errorf("%w: changed while it was hashed", ErrClaudeUnpinned)
260 }
261 return &verified{f: f, path: ClaudePath(c.installDir), key: key}, nil
262}
263
264// midway calls at once, after the first read.
265type midway struct {
266 r io.Reader
267 at func()
268}
269
270func (m *midway) Read(p []byte) (int, error) {
271 n, err := m.r.Read(p)
272 if m.at != nil && n > 0 {
273 m.at()
274 m.at = nil
275 }
276 return n, err
277}
278
279// Provision puts the pinned CLI in place unless it already verifies:
280// fetch(ClaudeURL()) is streamed into a new file beside it, mode 0600,
281// bounded by MaxClaudeBinary and hashed as it is written; only a match
282// is made 0700 and renamed into place, replacing whatever was there. A
283// refused download is removed. Every write goes through an os.Root on
284// the checked chain (openClaudeDir), whose tool directories it makes or
285// tightens to 0700.
286func (c ClaudeCLI) Provision(ctx context.Context, fetch ClaudeFetch) error {
287 if c.installDir == "" || c.pin == "" {
288 return ErrClaudeUnpinned
289 }
290 d, err := c.openDir(true)
291 if err != nil {
292 return err
293 }
294 defer d.Close()
295 removeDownloads(d)
296 if v, err := c.hashIn(d, nil); err == nil {
297 v.close()
298 return nil
299 }
300 body, err := fetch(ctx, ClaudeURL())
301 if err != nil {
302 return err
303 }
304 defer body.Close()
305 name, err := downloadName()
306 if err != nil {
307 return err
308 }
309 f, err := d.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
310 if err != nil {
311 return err
312 }
313 placed := false
314 defer func() {
315 // A second Close of a closed file is harmless.
316 if !placed {
317 _ = f.Close()
318 _ = d.Remove(name)
319 }
320 }()
321 h := sha256.New()
322 n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(body, c.bound()+1))
323 if err != nil {
324 return err
325 }
326 if n > c.bound() || hex.EncodeToString(h.Sum(nil)) != c.pin {
327 return ErrClaudeRefused
328 }
329 // Executable only now, by its descriptor.
330 if err := f.Chmod(0700); err != nil {
331 return err
332 }
333 if err := f.Sync(); err != nil {
334 return err
335 }
336 if err := f.Close(); err != nil {
337 return err
338 }
339 if err := d.Rename(name, claudeName); err != nil {
340 return err
341 }
342 placed = true
343 v, err := c.hashIn(d, nil)
344 if err != nil {
345 return err
346 }
347 v.close()
348 return nil
349}
350
351// openDir opens ClaudeDir(installDir) as an os.Root, walking from the
352// home one component at a time: each a real directory (Lstat, never a
353// symbolic link), owned by the runner user, that no group or other user
354// may write, and the one opened the one examined. The tool directories
355// (tools, claude-<version>) must be exactly 0700: create makes a missing
356// one 0700 and tightens a looser one of ours; without create a looser
357// one is refused. The install dir itself is never created.
358func (c ClaudeCLI) openDir(create bool) (*os.Root, error) {
359 rel, err := filepath.Rel(c.home, c.installDir)
360 if c.home == "" || !filepath.IsAbs(c.home) || !filepath.IsAbs(c.installDir) || err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
361 return nil, fmt.Errorf("%w: the install dir is not inside the home", ErrClaudeUnpinned)
362 }
363 info, err := os.Lstat(c.home)
364 if err != nil {
365 return nil, err
366 }
367 if err := private(info, "the home"); err != nil {
368 return nil, err
369 }
370 r, err := os.OpenRoot(c.home)
371 if err != nil {
372 return nil, err
373 }
374 if opened, err := r.Stat("."); err != nil || !os.SameFile(info, opened) {
375 r.Close()
376 return nil, fmt.Errorf("%w: the home moved while it was opened", ErrClaudeUnpinned)
377 }
378 install := strings.Split(rel, string(filepath.Separator))
379 for i, name := range append(install, claudeRel...) {
380 next, err := openSubdir(r, name, i >= len(install), create)
381 r.Close()
382 if err != nil {
383 return nil, err
384 }
385 r = next
386 }
387 return r, nil
388}
389
390// private: a real directory of the runner user that no group or other
391// user may write.
392func private(info fs.FileInfo, name string) error {
393 if !info.IsDir() || info.Mode()&fs.ModeSymlink != 0 || ownerOf(info) != runnerUID || info.Mode().Perm()&0022 != 0 {
394 return fmt.Errorf("%w: %s is not a private directory of this user", ErrClaudeUnpinned, name)
395 }
396 return nil
397}
398
399func openSubdir(parent *os.Root, name string, tool, create bool) (*os.Root, error) {
400 if create && tool {
401 if err := parent.Mkdir(name, 0700); err != nil && !errors.Is(err, fs.ErrExist) {
402 return nil, err
403 }
404 }
405 info, err := parent.Lstat(name)
406 if err != nil {
407 return nil, err
408 }
409 if err := private(info, name); err != nil {
410 return nil, err
411 }
412 sub, err := parent.OpenRoot(name)
413 if err != nil {
414 return nil, err
415 }
416 if opened, err := sub.Stat("."); err != nil || !os.SameFile(info, opened) {
417 sub.Close()
418 return nil, fmt.Errorf("%w: %s moved while it was opened", ErrClaudeUnpinned, name)
419 }
420 if tool && info.Mode().Perm() != 0700 {
421 if !create {
422 sub.Close()
423 return nil, fmt.Errorf("%w: %s is not 0700", ErrClaudeUnpinned, name)
424 }
425 if err := sub.Chmod(".", 0700); err != nil {
426 sub.Close()
427 return nil, err
428 }
429 }
430 return sub, nil
431}
432
433// removeDownloads removes what an interrupted download left in d.
434func removeDownloads(d *os.Root) {
435 dir, err := d.Open(".")
436 if err != nil {
437 return
438 }
439 names, _ := dir.Readdirnames(-1)
440 dir.Close()
441 for _, n := range names {
442 if strings.HasPrefix(n, downloadPrefix) {
443 _ = d.Remove(n)
444 }
445 }
446}
447
448func downloadName() (string, error) {
449 var b [8]byte
450 if _, err := rand.Read(b[:]); err != nil {
451 return "", err
452 }
453 return downloadPrefix + hex.EncodeToString(b[:]), nil
454}
455
456// ClaudeStandInEnv names a local file that stands in for the official
457// download, in a test build only (claude_testbuild.go). A release build
458// ignores it.
459const ClaudeStandInEnv = "EQUIPO_FAKE_CLAUDE_DARWIN"
460
461// claudeTransport carries the official download (tests stand in for the
462// network with their own).
463var claudeTransport http.RoundTripper = http.DefaultTransport
464
465// claudeDownloadLimit bounds the whole download, body included.
466const claudeDownloadLimit = 30 * time.Minute
467
468// OfficialClaude is the worker's ClaudeFetch: an HTTPS GET that follows
469// no redirect and takes only 200. In a test build, ClaudeStandInEnv may
470// name a local file to serve instead; the pin still decides.
471func OfficialClaude(getenv func(string) string) ClaudeFetch {
472 if f := claudeStandIn(getenv); f != nil {
473 return f
474 }
475 return fetchOfficialClaude
476}
477
478func fetchOfficialClaude(ctx context.Context, url string) (io.ReadCloser, error) {
479 c := http.Client{Transport: claudeTransport, Timeout: claudeDownloadLimit, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
480 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
481 if err != nil {
482 return nil, err
483 }
484 resp, err := c.Do(req)
485 if err != nil {
486 return nil, err
487 }
488 if resp.StatusCode != http.StatusOK {
489 resp.Body.Close()
490 return nil, errors.New("claude download: " + resp.Status)
491 }
492 return resp.Body, nil
493}
494
495// ClaudeRetry is the first wait after a failed provisioning, doubling to
496// ClaudeRecheck, how often a verified CLI is checked again.
497var ClaudeRetry, ClaudeRecheck = time.Minute, time.Hour
498
499// KeepClaude keeps the pinned CLI in place (spec §8.2), so the person
500// installs nothing: Provision at start, again after a failure, and every
501// ClaudeRecheck, fetching anew when it is missing or no longer matches.
502// It never runs it. refresh is called whenever it starts or stops
503// verifying, so the capability report follows. It returns with ctx.
504func KeepClaude(ctx context.Context, c ClaudeCLI, fetch ClaudeFetch, refresh func(), warn func(string, ...any)) {
505 wait, verified := ClaudeRetry, false
506 for {
507 err := c.Provision(ctx, fetch)
508 if ctx.Err() != nil {
509 return
510 }
511 next := ClaudeRecheck
512 if err != nil {
513 warn("claude code not provisioned", "version", provider.ClaudeVersion, "err", err)
514 next, wait = wait, min(wait*2, ClaudeRecheck)
515 } else {
516 wait = ClaudeRetry
517 }
518 if (err == nil) != verified {
519 verified = err == nil
520 refresh()
521 }
522 select {
523 case <-ctx.Done():
524 return
525 case <-time.After(next):
526 }
527 }
528}
529