package thin import ( "bytes" "context" "encoding/json" "errors" "log/slog" "os" "path/filepath" "runtime" "strconv" "strings" "sync" "time" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/mac" "amadan.net/oficina/equipo/internal/runner/mac/creds" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/provider/claude" "amadan.net/oficina/equipo/internal/wire" ) // A Mac worker's Claude credential (Mac runners spec §8.3, §8.7; slice F // task 10). Until slice F a Mac held only its runner identity; now it // can hold a long-lived token, on a machine other people use. So: // // - The guards. A tainted runner (D2: a check once ran outside its // sandbox, in its own state or by the instance's word) takes no model // connection, and the home guard (creds.Check) must pass: nobody // else can reach the home, the state dir, the config dir or the // accounts root. Both are checked again when a token is stored and // before every use, never once for good. // - Every operation that puts the token in a process, or writes it, // holds the Mac's one turn for its whole life (mac.Turns): the token // check, the auth status read, the sign-in while its terminal is // open, the store. // - The token goes to the pinned CLI by descriptor only (fd 3, // CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR): never in an environment, // which a sandboxed command can read through KERN_PROCARGS2 (task 1, // R4, S4). // - The sign-in (`claude setup-token` on a pseudo-terminal, as on Linux) // runs with CLAUDE_CONFIG_DIR of its own, so any Keychain item it // makes is named for it, and the Keychain is watched around it // (creds.Keychain): an item it left refuses the connection, and the // Mac holds a credential until a listing shows it gone. var ( // errTainted refuses a model connection on a tainted runner. errTainted = errors.New("this runner is tainted, so it takes no model connection") // errKeychain refuses a sign-in that left a Keychain item, or whose // Keychain could not be listed again. errKeychain = errors.New("the sign-in left an item in a Keychain") // errCredentialUnproven refuses every Claude connection while an // earlier credential launch's end is not proven. errCredentialUnproven = errors.New("an earlier launch with a Claude credential was not proven ended") // errMacRefused refuses to keep a token (the guards, or a Keychain // item with Claude Code's name). errMacRefused = errors.New("the Mac refused to keep the token") ) // homeOpen refuses a credential while the home guard fails. It names // what to change. type homeOpen struct{ r creds.Result } func (e *homeOpen) Error() string { return "other users could reach the runner's folders; as the runner user: " + strings.ReplaceAll(e.r.Fix(), "\n", "; ") } // tokenStoreWait bounds how long keeping a token waits for the Mac's // turn. A longer wait fails the delivery, which the instance sends again. var tokenStoreWait = time.Minute // authStatusLimit bounds the CLI's auth status read, as on Linux. const authStatusLimit = 30 * time.Second // macTokenFDEnv names the token's descriptor to the CLI. const macTokenFDEnv = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR" // macCreds is a Mac worker's credential operations. type macCreds struct { turns *mac.Turns exec *mac.Executor cli mac.ClaudeCLI paths mac.Paths // configDir is the runner's config dir (runner.env, the bindings); // runner its binary (the CLI's MCP server); scratch its scratch root. configDir, runner, scratch string taint *macTaint keychain *creds.Keychain // fact reads one path's kind, mode, owner and ACL (ls -led and lstat // on a Mac). fact func(string) (creds.Fact, error) // user and uid are the runner user (id -un, id -u at start). user string uid int log *slog.Logger // held is the worker's credential hold (Connector.credentialHeld), // set once its connections open (openWorkerConns); nil until then. held func(context.Context) bool } // newCreds is h's credential operations for c. func (h *macHost) newCreds(c runner.Config) *macCreds { m := &macCreds{turns: h.turns, exec: &mac.Executor{Turns: h.turns}, cli: h.tools.Claude, paths: h.paths, configDir: macConfigDir(c, h.paths.Home), runner: c.Executable, scratch: c.ScratchRoot, taint: h.taint, uid: -1, log: h.log} ctx, cancel := context.WithTimeout(context.Background(), mac.QueryLimit) defer cancel() if a, err := mac.ReadAccount(ctx, h.run); err == nil { m.user, m.uid = a.Name, a.UID } m.fact = func(p string) (creds.Fact, error) { return creds.Read(p, nil) } if runtime.GOOS == "darwin" { m.fact = func(p string) (creds.Fact, error) { return creds.Read(p, func(p string) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), mac.QueryLimit) defer cancel() return h.run(ctx, "/bin/ls", "-led", "--", p) }) } } m.keychain = &creds.Keychain{Dir: filepath.Join(c.StateDir, "keychain"), Login: filepath.Join(h.paths.Home, "Library", "Keychains", "login.keychain-db"), User: m.user, List: h.keychainList, Delete: h.keychainDelete, Acked: m.acked} return m } // macConfigDir is the runner's config dir: the bindings file's, or the // installer's ~/.config/equipo-runner. func macConfigDir(c runner.Config, home string) string { if c.AccountBindingsPath != "" { return filepath.Dir(c.AccountBindingsPath) } return filepath.Join(home, ".config", "equipo-runner") } // macSecurity is security(1); macKeychains: this host has Keychains // (tests stand in for both). var ( macSecurity = "/usr/bin/security" macKeychains = runtime.GOOS == "darwin" ) // keychainList is every generic password of the Keychain at keychain // (the runner user's login Keychain, named by its path whatever the // search list says), by attributes only (no -d: no secret is read). A // Keychain file that is not there, or a listing that fails, is an // error: nothing is decided from it. Off a Mac there is none. func (h *macHost) keychainList(ctx context.Context, keychain string) ([]creds.Item, error) { if !macKeychains { return nil, nil } if info, err := os.Lstat(keychain); err != nil || !info.Mode().IsRegular() { return nil, errKeychain } ctx, cancel := context.WithTimeout(ctx, mac.QueryLimit) defer cancel() out, err := h.run(ctx, macSecurity, "dump-keychain", keychain) if err != nil { return nil, err } return creds.ParseDump(out) } // keychainDelete deletes one generic password by service, account and // Keychain path. func (h *macHost) keychainDelete(ctx context.Context, i creds.Item) error { if !macKeychains || i.Unread { return errKeychain } ctx, cancel := context.WithTimeout(ctx, mac.QueryLimit) defer cancel() _, err := h.run(ctx, macSecurity, "delete-generic-password", "-s", i.Service, "-a", i.Account, i.Keychain) return err } // guard is the home guard now: the home and the three roots, each made // (0700) if it is missing, then read and decided. func (m *macCreds) guard() creds.Result { roots := []string{m.paths.StateDir, m.configDir, m.paths.AccountsRoot} for _, r := range roots { if r != "" && strings.HasPrefix(filepath.Clean(r), filepath.Clean(m.paths.Home)+"/") { _ = os.MkdirAll(r, 0o700) } } return creds.Check(creds.Input{User: m.user, UID: m.uid, Home: m.paths.Home, Roots: roots}, m.fact) } // Gate is the guards, now: errTainted, or *homeOpen naming what to // change, or nil. Every store and every use of a token passes it first. func (m *macCreds) Gate() error { if m.taint.Tainted() { return errTainted } if left, err := m.keychain.Unproven(); err != nil || len(left) > 0 { return errCredentialUnproven } if r := m.guard(); !r.OK() { if m.log != nil { m.log.Warn("other users could reach the runner's folders; no model connection is kept or used", "reason", r.Reason(), "change", strings.ReplaceAll(r.Fix(), "\n", "; ")) } return &homeOpen{r} } return nil } // status is the guards' Engineering status: tainted (it lasts, so it is // said first), or home_open with the guard's first code; nil when both // pass. func (m *macCreds) status() *wire.EngineeringStatus { if m.taint.Tainted() { return &wire.EngineeringStatus{State: wire.EngineeringTainted} } if r := m.guard(); !r.OK() { return &wire.EngineeringStatus{State: wire.EngineeringHomeOpen, Reason: r.Reason()} } return nil } // checkTurn is the Mac's turn for a connection's refresh, taken before // its home's lock (Conns.Turn). func (m *macCreds) checkTurn(ctx context.Context) (context.Context, func(), error) { return m.turns.Hold(ctx, mac.OpTokenCheck) } // Held: a Keychain item a sign-in may have left is on record (the // Keychain half of the credential hold; task 11 adds the files'). func (m *macCreds) Held() bool { return m.keychain.Held() } // store is a token store's turn (OpTokenStore) and its guards; give // ends it. errMacRefused (joined with why) refuses the token; any other // error is a wait that ran out, and the delivery is tried again. func (m *macCreds) store(ctx context.Context) (give func(), err error) { wait, cancel := context.WithTimeout(ctx, tokenStoreWait) defer cancel() _, give, err = m.turns.Hold(wait, mac.OpTokenStore) if err != nil { return nil, err } err = m.Gate() if err == nil { err = m.keychain.Existing(ctx) } if err != nil { give() return nil, errors.Join(errMacRefused, err) } return give, nil } // after is a launch's second look at the Keychain once its end is // proven: errKeychain when it left an item (its own is deleted; the Mac // holds until a listing shows every such item gone) or the Keychain // could not be listed again. func (m *macCreds) after(marker string) error { ctx, cancel := context.WithTimeout(context.Background(), 3*mac.QueryLimit) defer cancel() out, err := m.keychain.After(ctx, marker) if err == nil && out.Clean { return nil } if m.log != nil { m.log.Warn("a launch left a Keychain item, or the Keychain could not be listed; refused", "marker", marker, "deleted", len(out.Deleted), "left", len(out.Left), "err", err) } return errKeychain } // settle is the Keychain watch's settling: at a restart, every watch // whose CLI is proven gone; otherwise only what was found left. func (m *macCreds) settle(ctx context.Context, restart bool) { err := m.keychain.Settle(ctx, restart, m.ended) if err != nil && m.log != nil { m.log.Warn("keychain not settled", "err", err) } if left := m.keychain.Residue(); len(left) > 0 && m.log != nil { m.log.Warn("a Keychain item holds this Mac as having a credential; remove it in Keychain Access", "services", strings.Join(left, ", ")) } } // ended: the watched launch has surely ended, so its watch may take its // second look. Only Executor.Verify says so (spec §8.8): its end proven // by its process record, or a boot-qualified reboot clearance (another // kern.bootsessionuuid and a later boot time, under the one proof // deadline, acknowledged per consumer). A boot time alone moves with // the clock and proves nothing. Anything else keeps the watch, the hold // and the Mac's connections closed. func (m *macCreds) ended(w creds.Watch) bool { return m.exec.Verify(watchRun(w)) } // acked: w's watch is settled durably (creds.Keychain.Acked), so the // Keychain recovery's share of its launch's proof may go. func (m *macCreds) acked(w creds.Watch) { m.exec.Acknowledge(watchRun(w), mac.ConsumerKeychain) } // watchRun is the process record of w's launch. func watchRun(w creds.Watch) string { if w.Run != "" { return w.Run } return mac.RecordID(0, w.Marker) } // place makes a launch's own CLAUDE_CONFIG_DIR under the runtime root // (/homes, which no sandboxed command reaches); its name is the // launch's marker. func (m *macCreds) place(prefix string) (dir, marker string, err error) { root := filepath.Join(m.scratch, "homes") if err = os.MkdirAll(root, 0o700); err != nil { return "", "", err } if dir, err = os.MkdirTemp(root, prefix); err != nil { return "", "", err } return dir, filepath.Base(dir), nil } // env is a launch's whole environment: its own config dir (both names // the CLI reads it by, so its Keychain service is named for it), the // runner user's home, the CLI's PATH and locale, no updater and no // nonessential traffic, the marker, and with a token only the number // of the descriptor it is on. func (m *macCreds) env(dir, marker string, token bool, extra ...string) []string { env := []string{"HOME=" + m.paths.Home, "USER=" + m.user, "CLAUDE_CONFIG_DIR=" + dir, "CLAUDE_SECURESTORAGE_CONFIG_DIR=" + dir, "TMPDIR=" + dir, "PATH=" + claude.DarwinPath, "LANG=" + claude.DarwinLang, "DISABLE_AUTOUPDATER=1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", claude.DarwinMarkerEnv + "=" + marker} if token { env = append(env, macTokenFDEnv+"="+strconv.Itoa(claude.DarwinTokenFD)) } return append(env, extra...) } // start starts the pinned CLI with args (ClaudeCLI.Launch: hashed, then // checked again just before) through the executor, in dir, as c says, // with token (if any) in a pipe that is descriptor 3. ctx must hold the // turn. func (m *macCreds) start(ctx context.Context, dir, marker string, c mac.Command, token []byte, record func(string) error, args ...string) (*mac.Run, error) { c.Dir = dir if token != nil { if len(token) == 0 || len(token) > mac.MaxToken || bytes.ContainsAny(token, "\x00\r\n") { return nil, provider.ErrPolicy } read, write, err := os.Pipe() if err != nil { return nil, err } defer read.Close() _, err = write.Write(token) if cerr := write.Close(); err == nil { err = cerr } if err != nil { return nil, provider.ErrPolicy } c.Files = []*os.File{read} } var run *mac.Run err := m.cli.Launch(ctx, func(ctx context.Context, argv []string) error { c.Argv = argv r, err := m.exec.Start(ctx, c, marker, record) run = r return err }, args...) return run, err } // capped keeps the first 64 KiB written to it. type capped struct{ b bytes.Buffer } func (c *capped) Write(p []byte) (int, error) { if room := 64<<10 - c.b.Len(); room > 0 { c.b.Write(p[:min(len(p), room)]) } return len(p), nil } // authStatus is a token home's `claude auth status --json` on a Mac // (Linux's provider.RefreshLogin), the token by descriptor, in the // check's turn: the email, if the CLI names one. It proves nothing about // the token. ClaudeOptions.Refresh and Conns.Refresh on a Mac. func (m *macCreds) authStatus(ctx context.Context, b provider.Binding) (provider.Identity, error) { if b.Provider != wire.ProviderClaude || !b.Token { return provider.Identity{}, provider.ErrLoginUnavailable } ctx, give, err := m.turns.Hold(ctx, mac.OpTokenCheck) if err != nil { return provider.Identity{}, err } defer give() if err := m.Gate(); err != nil { return provider.Identity{}, err } raw, err := provider.ReadToken(b.Home) if err != nil { return provider.Identity{}, provider.ErrLoginRequired } defer clear(raw) ctx, cancel := context.WithTimeout(ctx, authStatusLimit) defer cancel() dir, marker, err := m.place("status-") if err != nil { return provider.Identity{}, err } // Watched as a sign-in is: the list on record before the CLI starts, // the second look once its end is proven (a crash leaves the watch // for the restart). if err = m.keychain.Before(ctx, marker, dir); err != nil { os.RemoveAll(dir) return provider.Identity{}, err } out := &capped{} ran := func(id string) error { return m.keychain.Ran(marker, id) } run, err := m.start(ctx, dir, marker, mac.Command{Env: m.env(dir, marker, true), Stdout: out}, raw, ran, "auth", "status", "--json") if err != nil { if errors.Is(err, mac.ErrUnproven) { m.keychain.Abandon(marker) } else { err = errors.Join(err, m.after(marker)) os.RemoveAll(dir) } return provider.Identity{}, err } select { case <-run.Exited(): case <-run.Aborted(): case <-ctx.Done(): } proven := run.Stop() if !run.Finish(context.WithoutCancel(ctx)) { proven = false } if !proven { // Not success: the watch and the turn's record stay, and the // Mac's connections are closed until its end is proven. m.keychain.Abandon(marker) return provider.Identity{}, mac.ErrUnproven } kerr := m.after(marker) os.RemoveAll(dir) switch { case kerr != nil: return provider.Identity{}, kerr case ctx.Err() != nil: return provider.Identity{}, ctx.Err() } id, _, err := provider.ClaudeTokenIdentity(out.b.Bytes(), b.ID) if err != nil || run.ExitErr() != nil { return provider.Identity{}, provider.ErrLoginRequired } return id, nil } // checkToken is the token check on a Mac (tokencheck.go's, the same // prompt, outcomes and limit): the darwin launch's check-only policy (no // native tool, no Equipo tool, an empty read-only workspace under the // scratch root, no network for any shell), the token by descriptor, the // whole check in one turn (OpTokenCheck). A crash leaves the turn's // record, and the next turn settles what it left. func (m *macCreds) checkToken(ctx context.Context, o ClaudeOptions, b runner.AccountBinding) (_ []wire.Usage, _ *connect.Limit, named bool, err error) { if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken { return nil, nil, false, provider.ErrPolicy } tctx, give, err := m.turns.Hold(ctx, mac.OpTokenCheck) if err != nil { return nil, nil, false, err } defer give() if err = m.Gate(); err != nil { return nil, nil, false, err } parent := tctx ctx, cancel := context.WithTimeout(tctx, tokenCheckLimit) defer cancel() direct, err := o.Runner.DirectBinding(b) if err != nil { return nil, nil, false, err } lease, err := provider.OpenRuntimeCopy(ctx, direct, m.authStatus, o.LockWait) if err != nil { return nil, nil, false, err } defer lease.Close() binding := lease.Binding() scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") if err != nil { return nil, nil, false, err } defer os.RemoveAll(scratch) // The empty workspace: under the scratch root, never SessionRoot (the // §4.2 list denies it). work, err := os.MkdirTemp(o.Runner.ScratchRoot, "check-") if err != nil { return nil, nil, false, err } defer os.RemoveAll(work) root, err := toolRoot(o.Runner) if err != nil { return nil, nil, false, err } tool, err := openToolSocket(context.Background(), root, func(context.Context, string, string, json.RawMessage) (string, bool) { return toolNoTurn, true }) if err != nil { return nil, nil, false, err } defer tool.Close() sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} session := uuid() in := mac.EngineeringInput{Paths: m.paths, Action: claude.DarwinCheck, Model: firstNonEmpty(b.Model, firstNonEmpty(o.Runner.ClaudeModel, DefaultModels[wire.ProviderClaude])), Worktree: work, Scratch: scratch, Runner: m.runner, ToolRoot: root, Socket: tool.Path, ConfigDir: binding.Home, CredentialHome: b.ProviderHome, RuntimeRoot: direct.RuntimeRoot, Attempt: "check-" + filepath.Base(work), SessionID: session} policy, err := mac.EngineeringPolicy(m.cli, in) if err != nil { return nil, nil, false, err } if err = lease.CheckCopy(ctx); err != nil { return nil, nil, false, err } launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "check/" + uuid(), Workspace: work, Selection: sel, Binding: binding, Policy: policy} env, err := provider.LaunchSecretEnv(launch) if err != nil { return nil, nil, false, err } token := []byte(env[provider.OAuthTokenEnv]) // The account profile, once the provider answered, as on Linux. defer func() { if err == nil && o.Profile != nil { named = o.readProfile(parent, b, token) } clear(token) }() // Watched as a sign-in is, the runtime copy its config dir. if err = m.keychain.Before(ctx, in.Attempt, in.ConfigDir); err != nil { return nil, nil, false, err } pctx, kill := context.WithCancel(context.WithoutCancel(tctx)) defer kill() s := &mac.Starter{Exec: m.exec, CLI: m.cli, Input: in, Token: bytes.Clone(token)} ran := func(_ context.Context, r containment.Record) error { return m.keychain.Ran(in.Attempt, r.ID) } proc, err := s.StartRecorded(pctx, launch, claude.DarwinArgv(policy), ran) if err != nil { if errors.Is(err, mac.ErrUnproven) { m.keychain.Abandon(in.Attempt) } else { err = errors.Join(err, m.after(in.Attempt)) } return nil, nil, false, err } // Stopped at the limit (which ends the reads) and at the end. Only a // proven end, then a clean second look at the Keychain, lets an // answer count: unproven, the watch and the turn's record stay for // recovery, and the profile is not read. waited := make(chan error, 1) go func() { _, err := proc.Wait(context.Background()); waited <- err }() stop := context.AfterFunc(ctx, kill) rows, seen, err := readCheck(ctx, proc, session, b) stop() kill() if werr := <-waited; werr != nil { m.keychain.Abandon(in.Attempt) return rows, nil, false, errors.Join(mac.ErrUnproven, werr) } if kerr := m.after(in.Attempt); kerr != nil { return rows, nil, false, kerr } return rows, seen, false, err } // macSetupToken is a Mac's sign-in terminal for attempt (Connector's // terminal): its run's record goes on the attempt's row. func (c *Connector) macSetupToken(ctx context.Context, attempt string) (connect.Terminal, error) { return c.Mac.terminal(ctx, func(id string) error { _, err := c.State.db.ExecContext(context.WithoutCancel(ctx), "UPDATE connect_attempts SET namespace=? WHERE id=?", id, attempt) return err }) } // terminal starts `claude setup-token` on a pseudo-terminal in the // Mac's turn (OpSignIn), held until Stop: the guards, then its own // config dir, then the Keychain listed and written down (before // anything starts), then the CLI. func (m *macCreds) terminal(ctx context.Context, record func(string) error) (connect.Terminal, error) { u, err := m.turns.Take(ctx, mac.OpSignIn) if err != nil { return nil, err } kept := false defer func() { if !kept { u.Give() } }() if err = m.Gate(); err != nil { return nil, err } dir, marker, err := m.place("signin-") if err != nil { return nil, err } if err = m.keychain.Before(ctx, marker, dir); err != nil { os.RemoveAll(dir) return nil, err } // What did not start (or whose end is proven) gets its second look now. unstarted := func() { _, _ = m.keychain.After(context.WithoutCancel(ctx), marker) os.RemoveAll(dir) } pty, tty, err := creds.OpenTerminal() if err != nil { unstarted() return nil, err } env := m.env(dir, marker, false, "TERM=xterm-256color", "BROWSER="+provider.SignInBrowser) ran := func(id string) error { if err := m.keychain.Ran(marker, id); err != nil { return err } return record(id) } run, err := m.start(u.Context(ctx), dir, marker, mac.Command{Env: env, TTY: tty}, nil, ran, "setup-token") tty.Close() if err != nil { pty.Close() if errors.Is(err, mac.ErrUnproven) { m.keychain.Abandon(marker) } else { unstarted() } return nil, err } kept = true return &macTerminal{m: m, turn: u, run: run, pty: pty, marker: marker, dir: dir}, nil } // macTerminal is a sign-in's terminal on a Mac. type macTerminal struct { m *macCreds turn *mac.Turn run *mac.Run pty *os.File marker, dir string once sync.Once err error } func (t *macTerminal) Read(p []byte) (int, error) { return t.pty.Read(p) } func (t *macTerminal) Write(p []byte) (int, error) { return t.pty.Write(p) } func (t *macTerminal) Done() <-chan struct{} { return t.run.Exited() } // Stop stops the CLI and proves its end (its group and what it left), // then looks at the Keychain again and gives the turn back. errUnproven: // its end is not proven (the watch stays, held, for the restart); // errKeychain: the sign-in left an item, so the connection is refused. func (t *macTerminal) Stop() error { t.once.Do(func() { defer t.turn.Give() proven := t.run.Stop() if !t.run.Finish(context.Background()) { proven = false } t.pty.Close() if !proven { t.m.keychain.Abandon(t.marker) t.err = errUnproven return } t.err = t.m.after(t.marker) os.RemoveAll(t.dir) }) return t.err }