package mac import ( "context" "crypto/rand" "crypto/sha256" "encoding/hex" "errors" "fmt" "io" "io/fs" "net/http" "os" "path/filepath" "strings" "time" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/wire" ) // The Claude Code a Mac worker runs (Mac runners spec §8.2): the official // 2.1.312 darwin-arm64 binary, which the worker fetches itself and checks // against claude.ExecutableSHA256DarwinArm64, compiled in. It never runs // a claude it finds on PATH or is pointed at, not even for --version. // // The URL is built from these constants and provider.ClaudeVersion, as // the official installer builds it (task 1, S1). The release manifest // beside it is not read: the pin is the only trust. const ( ClaudeReleaseBase = "https://downloads.claude.ai/claude-code-releases" ClaudePlatform = "darwin-arm64" // MaxClaudeBinary bounds the download (2.1.312's is 275988512 bytes). MaxClaudeBinary = 512 << 20 ) // ClaudeURL is the pinned release's official download. func ClaudeURL() string { return ClaudeReleaseBase + "/" + provider.ClaudeVersion + "/" + ClaudePlatform + "/claude" } // claudeRel is where the CLI lives under the install dir, as path // components: tools/claude-/claude, beside the pinned Node and // ripgrep. Checks may not write the install dir (ChecksSettings). var claudeRel = []string{"tools", "claude-" + provider.ClaudeVersion} const claudeName = "claude" // downloadPrefix names a download being written beside the CLI; one a // crash left behind is removed by the next Provision. const downloadPrefix = ".claude-download-" // ClaudeDir is the pinned CLI's directory under installDir. func ClaudeDir(installDir string) string { return filepath.Join(append([]string{installDir}, claudeRel...)...) } // ClaudePath is the pinned CLI under installDir. Never run it by this // path: Argv and Launch verify it first. func ClaudePath(installDir string) string { return filepath.Join(ClaudeDir(installDir), claudeName) } var ( // ErrClaudeUnpinned: no pinned CLI at its place, or what is there is // not a plain 0700 file, reached through no link, that matches the pin. ErrClaudeUnpinned = errors.New("mac: the pinned Claude Code is not in place") // ErrClaudeRefused: a download that does not match the pin, or is // over MaxClaudeBinary. ErrClaudeRefused = errors.New("mac: Claude Code download refused") ) // ClaudeUnavailable stops a launch of the CLI before anything starts: // the step ends wire.ReasonEngineeringUnavailable. type ClaudeUnavailable struct{ Err error } func (e *ClaudeUnavailable) Error() string { return "engineering unavailable: " + e.Err.Error() } func (e *ClaudeUnavailable) Unwrap() error { return e.Err } // Reason is the step reason a launch stopped by e reports. func (e *ClaudeUnavailable) Reason() string { return wire.ReasonEngineeringUnavailable } // ClaudeFetch opens url's body. Provision only ever asks for ClaudeURL. type ClaudeFetch func(ctx context.Context, url string) (io.ReadCloser, error) // ClaudeCLI is the pinned CLI under a runner's install dir. Nothing can // start it but Launch, which hashes the file and checks that the path // still names exactly what it hashed, immediately before start. The zero // value has no CLI: it verifies nothing and launches nothing. type ClaudeCLI struct { // home is the trusted ancestor: the runner user's home. installDir // must lie inside it; every directory from home down to the binary // is checked (openClaudeDir). home, installDir string // pin is the digest the file must have (a test pins its own bytes). pin string // limit bounds a download; 0 is MaxClaudeBinary. limit int64 } // NewClaudeCLI is the pinned darwin-arm64 CLI under installDir // (~/.local/lib/equipo-runner on a Mac), which lies in home. func NewClaudeCLI(home, installDir string) ClaudeCLI { return ClaudeCLI{home: home, installDir: installDir, pin: claude.ExecutableSHA256DarwinArm64} } // Seams. ownerOf is the uid owning a file; runnerUID the uid that must // own every directory and the binary. claudeDuringHash runs once in the // middle of a launch's hash, claudeBeforeStart after the hash and before // the final check (tests race a swap there; nil in a release). var ( ownerOf = fileOwner runnerUID = os.Getuid() claudeDuringHash, claudeBeforeStart func() ) func (c ClaudeCLI) bound() int64 { if c.limit > 0 { return c.limit } return MaxClaudeBinary } // Verify hashes the CLI at its place, once, and returns its path when it // matches the pin: a plain 0700 file of the runner user, reached through // private directories and no symbolic link from the home. The path is // for reports and policy records only; start the CLI with Launch. func (c ClaudeCLI) Verify() (string, error) { v, err := c.open() if err != nil { return "", err } v.close() return v.path, nil } // Version is the pinned version while the CLI verifies, else "". It // runs nothing: what the capability report states about Claude Code. func (c ClaudeCLI) Version() string { if _, err := c.Verify(); err != nil { return "" } return provider.ClaudeVersion } // Launch starts the pinned CLI through start with argv [path, args...]. // Every start of the CLI (an Engineering attempt, an ask, a token check, // a sign-in, a probe launch) goes through here. It opens the file and // hashes the open descriptor, then, immediately before start, checks // that the path still names that same file (device, inode, size, // modification and change times) and that it did not change while it // was hashed. The descriptor stays open until start returns, so the // inode cannot be reused by another file meanwhile; start should have // started the process when it returns. Nothing starts when any check // fails: *ClaudeUnavailable, engineering_unavailable. // // The honest limit: macOS cannot exec a descriptor, so the kernel looks // the path up again after the last check. Only the runner user can // rename inside the private chain, sandboxed commands cannot write the // install dir, and the runner user is dedicated to the runner. func (c ClaudeCLI) Launch(ctx context.Context, start func(ctx context.Context, argv []string) error, args ...string) error { v, err := c.open() if err != nil { return &ClaudeUnavailable{Err: err} } defer v.close() if claudeBeforeStart != nil { claudeBeforeStart() } if err := v.still(); err != nil { return &ClaudeUnavailable{Err: err} } return start(ctx, append([]string{v.path}, args...)) } // verified is an open, hashed CLI: its descriptor and the state it had. type verified struct { f *os.File path string key statKey } type statKey struct { dev, ino uint64 size int64 mtime, ctime int64 } func (v *verified) close() { v.f.Close() } // still: the path names the hashed file, unchanged. func (v *verified) still() error { named, err := os.Lstat(v.path) if err != nil { return ErrClaudeUnpinned } held, err := v.f.Stat() if err != nil || !named.Mode().IsRegular() || !os.SameFile(named, held) { return fmt.Errorf("%w: replaced after it was hashed", ErrClaudeUnpinned) } nk, ok1 := fileKey(named) hk, ok2 := fileKey(held) if !ok1 || !ok2 || nk != v.key || hk != v.key { return fmt.Errorf("%w: changed after it was hashed", ErrClaudeUnpinned) } return nil } // open validates the chain, opens the CLI and hashes the descriptor, // once: a regular file, not a link, mode 0700, the runner user's, the // file opened the one examined, unchanged from before the hash to after. func (c ClaudeCLI) open() (*verified, error) { if c.installDir == "" || c.pin == "" { return nil, ErrClaudeUnpinned } d, err := c.openDir(false) if err != nil { return nil, ErrClaudeUnpinned } defer d.Close() f, err := c.hashIn(d, claudeDuringHash) if err != nil { return nil, err } return f, nil } func (c ClaudeCLI) hashIn(d *os.Root, during func()) (*verified, error) { info, err := d.Lstat(claudeName) if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0700 || ownerOf(info) != runnerUID || info.Size() > c.bound() { return nil, ErrClaudeUnpinned } f, err := d.OpenFile(claudeName, os.O_RDONLY, 0) if err != nil { return nil, ErrClaudeUnpinned } before, err := f.Stat() key, ok := fileKey(before) if err != nil || !ok || !os.SameFile(info, before) { f.Close() return nil, ErrClaudeUnpinned } h := sha256.New() var r io.Reader = io.LimitReader(f, c.bound()+1) if during != nil { r = &midway{r: r, at: during} } if _, err := io.Copy(h, r); err != nil || hex.EncodeToString(h.Sum(nil)) != c.pin { f.Close() return nil, ErrClaudeUnpinned } after, err := f.Stat() if k, ok := fileKey(after); err != nil || !ok || k != key { f.Close() return nil, fmt.Errorf("%w: changed while it was hashed", ErrClaudeUnpinned) } return &verified{f: f, path: ClaudePath(c.installDir), key: key}, nil } // midway calls at once, after the first read. type midway struct { r io.Reader at func() } func (m *midway) Read(p []byte) (int, error) { n, err := m.r.Read(p) if m.at != nil && n > 0 { m.at() m.at = nil } return n, err } // Provision puts the pinned CLI in place unless it already verifies: // fetch(ClaudeURL()) is streamed into a new file beside it, mode 0600, // bounded by MaxClaudeBinary and hashed as it is written; only a match // is made 0700 and renamed into place, replacing whatever was there. A // refused download is removed. Every write goes through an os.Root on // the checked chain (openClaudeDir), whose tool directories it makes or // tightens to 0700. func (c ClaudeCLI) Provision(ctx context.Context, fetch ClaudeFetch) error { if c.installDir == "" || c.pin == "" { return ErrClaudeUnpinned } d, err := c.openDir(true) if err != nil { return err } defer d.Close() removeDownloads(d) if v, err := c.hashIn(d, nil); err == nil { v.close() return nil } body, err := fetch(ctx, ClaudeURL()) if err != nil { return err } defer body.Close() name, err := downloadName() if err != nil { return err } f, err := d.OpenFile(name, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) if err != nil { return err } placed := false defer func() { // A second Close of a closed file is harmless. if !placed { _ = f.Close() _ = d.Remove(name) } }() h := sha256.New() n, err := io.Copy(io.MultiWriter(f, h), io.LimitReader(body, c.bound()+1)) if err != nil { return err } if n > c.bound() || hex.EncodeToString(h.Sum(nil)) != c.pin { return ErrClaudeRefused } // Executable only now, by its descriptor. if err := f.Chmod(0700); err != nil { return err } if err := f.Sync(); err != nil { return err } if err := f.Close(); err != nil { return err } if err := d.Rename(name, claudeName); err != nil { return err } placed = true v, err := c.hashIn(d, nil) if err != nil { return err } v.close() return nil } // openDir opens ClaudeDir(installDir) as an os.Root, walking from the // home one component at a time: each a real directory (Lstat, never a // symbolic link), owned by the runner user, that no group or other user // may write, and the one opened the one examined. The tool directories // (tools, claude-) must be exactly 0700: create makes a missing // one 0700 and tightens a looser one of ours; without create a looser // one is refused. The install dir itself is never created. func (c ClaudeCLI) openDir(create bool) (*os.Root, error) { rel, err := filepath.Rel(c.home, c.installDir) if c.home == "" || !filepath.IsAbs(c.home) || !filepath.IsAbs(c.installDir) || err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { return nil, fmt.Errorf("%w: the install dir is not inside the home", ErrClaudeUnpinned) } info, err := os.Lstat(c.home) if err != nil { return nil, err } if err := private(info, "the home"); err != nil { return nil, err } r, err := os.OpenRoot(c.home) if err != nil { return nil, err } if opened, err := r.Stat("."); err != nil || !os.SameFile(info, opened) { r.Close() return nil, fmt.Errorf("%w: the home moved while it was opened", ErrClaudeUnpinned) } install := strings.Split(rel, string(filepath.Separator)) for i, name := range append(install, claudeRel...) { next, err := openSubdir(r, name, i >= len(install), create) r.Close() if err != nil { return nil, err } r = next } return r, nil } // private: a real directory of the runner user that no group or other // user may write. func private(info fs.FileInfo, name string) error { if !info.IsDir() || info.Mode()&fs.ModeSymlink != 0 || ownerOf(info) != runnerUID || info.Mode().Perm()&0022 != 0 { return fmt.Errorf("%w: %s is not a private directory of this user", ErrClaudeUnpinned, name) } return nil } func openSubdir(parent *os.Root, name string, tool, create bool) (*os.Root, error) { if create && tool { if err := parent.Mkdir(name, 0700); err != nil && !errors.Is(err, fs.ErrExist) { return nil, err } } info, err := parent.Lstat(name) if err != nil { return nil, err } if err := private(info, name); err != nil { return nil, err } sub, err := parent.OpenRoot(name) if err != nil { return nil, err } if opened, err := sub.Stat("."); err != nil || !os.SameFile(info, opened) { sub.Close() return nil, fmt.Errorf("%w: %s moved while it was opened", ErrClaudeUnpinned, name) } if tool && info.Mode().Perm() != 0700 { if !create { sub.Close() return nil, fmt.Errorf("%w: %s is not 0700", ErrClaudeUnpinned, name) } if err := sub.Chmod(".", 0700); err != nil { sub.Close() return nil, err } } return sub, nil } // removeDownloads removes what an interrupted download left in d. func removeDownloads(d *os.Root) { dir, err := d.Open(".") if err != nil { return } names, _ := dir.Readdirnames(-1) dir.Close() for _, n := range names { if strings.HasPrefix(n, downloadPrefix) { _ = d.Remove(n) } } } func downloadName() (string, error) { var b [8]byte if _, err := rand.Read(b[:]); err != nil { return "", err } return downloadPrefix + hex.EncodeToString(b[:]), nil } // ClaudeStandInEnv names a local file that stands in for the official // download, in a test build only (claude_testbuild.go). A release build // ignores it. const ClaudeStandInEnv = "EQUIPO_FAKE_CLAUDE_DARWIN" // claudeTransport carries the official download (tests stand in for the // network with their own). var claudeTransport http.RoundTripper = http.DefaultTransport // claudeDownloadLimit bounds the whole download, body included. const claudeDownloadLimit = 30 * time.Minute // OfficialClaude is the worker's ClaudeFetch: an HTTPS GET that follows // no redirect and takes only 200. In a test build, ClaudeStandInEnv may // name a local file to serve instead; the pin still decides. func OfficialClaude(getenv func(string) string) ClaudeFetch { if f := claudeStandIn(getenv); f != nil { return f } return fetchOfficialClaude } func fetchOfficialClaude(ctx context.Context, url string) (io.ReadCloser, error) { c := http.Client{Transport: claudeTransport, Timeout: claudeDownloadLimit, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return nil, err } resp, err := c.Do(req) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { resp.Body.Close() return nil, errors.New("claude download: " + resp.Status) } return resp.Body, nil } // ClaudeRetry is the first wait after a failed provisioning, doubling to // ClaudeRecheck, how often a verified CLI is checked again. var ClaudeRetry, ClaudeRecheck = time.Minute, time.Hour // KeepClaude keeps the pinned CLI in place (spec §8.2), so the person // installs nothing: Provision at start, again after a failure, and every // ClaudeRecheck, fetching anew when it is missing or no longer matches. // It never runs it. refresh is called whenever it starts or stops // verifying, so the capability report follows. It returns with ctx. func KeepClaude(ctx context.Context, c ClaudeCLI, fetch ClaudeFetch, refresh func(), warn func(string, ...any)) { wait, verified := ClaudeRetry, false for { err := c.Provision(ctx, fetch) if ctx.Err() != nil { return } next := ClaudeRecheck if err != nil { warn("claude code not provisioned", "version", provider.ClaudeVersion, "err", err) next, wait = wait, min(wait*2, ClaudeRecheck) } else { wait = ClaudeRetry } if (err == nil) != verified { verified = err == nil refresh() } select { case <-ctx.Done(): return case <-time.After(next): } } }