| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "log/slog" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "runtime" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/runner" |
| 18 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 19 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 20 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 21 | "amadan.net/oficina/equipo/internal/runner/mac/creds" |
| 22 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 23 | "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| 24 | "amadan.net/oficina/equipo/internal/wire" |
| 25 | ) |
| 26 | |
| 27 | // A Mac worker's Claude credential (Mac runners spec §8.3, §8.7; slice F |
| 28 | // task 10). Until slice F a Mac held only its runner identity; now it |
| 29 | // can hold a long-lived token, on a machine other people use. So: |
| 30 | // |
| 31 | // - The guards. A tainted runner (D2: a check once ran outside its |
| 32 | // sandbox, in its own state or by the instance's word) takes no model |
| 33 | // connection, and the home guard (creds.Check) must pass: nobody |
| 34 | // else can reach the home, the state dir, the config dir or the |
| 35 | // accounts root. Both are checked again when a token is stored and |
| 36 | // before every use, never once for good. |
| 37 | // - Every operation that puts the token in a process, or writes it, |
| 38 | // holds the Mac's one turn for its whole life (mac.Turns): the token |
| 39 | // check, the auth status read, the sign-in while its terminal is |
| 40 | // open, the store. |
| 41 | // - The token goes to the pinned CLI by descriptor only (fd 3, |
| 42 | // CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR): never in an environment, |
| 43 | // which a sandboxed command can read through KERN_PROCARGS2 (task 1, |
| 44 | // R4, S4). |
| 45 | // - The sign-in (`claude setup-token` on a pseudo-terminal, as on Linux) |
| 46 | // runs with CLAUDE_CONFIG_DIR of its own, so any Keychain item it |
| 47 | // makes is named for it, and the Keychain is watched around it |
| 48 | // (creds.Keychain): an item it left refuses the connection, and the |
| 49 | // Mac holds a credential until a listing shows it gone. |
| 50 | |
| 51 | var ( |
| 52 | // errTainted refuses a model connection on a tainted runner. |
| 53 | errTainted = errors.New("this runner is tainted, so it takes no model connection") |
| 54 | // errKeychain refuses a sign-in that left a Keychain item, or whose |
| 55 | // Keychain could not be listed again. |
| 56 | errKeychain = errors.New("the sign-in left an item in a Keychain") |
| 57 | // errCredentialUnproven refuses every Claude connection while an |
| 58 | // earlier credential launch's end is not proven. |
| 59 | errCredentialUnproven = errors.New("an earlier launch with a Claude credential was not proven ended") |
| 60 | // errMacRefused refuses to keep a token (the guards, or a Keychain |
| 61 | // item with Claude Code's name). |
| 62 | errMacRefused = errors.New("the Mac refused to keep the token") |
| 63 | ) |
| 64 | |
| 65 | // homeOpen refuses a credential while the home guard fails. It names |
| 66 | // what to change. |
| 67 | type homeOpen struct{ r creds.Result } |
| 68 | |
| 69 | func (e *homeOpen) Error() string { |
| 70 | return "other users could reach the runner's folders; as the runner user: " + strings.ReplaceAll(e.r.Fix(), "\n", "; ") |
| 71 | } |
| 72 | |
| 73 | // tokenStoreWait bounds how long keeping a token waits for the Mac's |
| 74 | // turn. A longer wait fails the delivery, which the instance sends again. |
| 75 | var tokenStoreWait = time.Minute |
| 76 | |
| 77 | // authStatusLimit bounds the CLI's auth status read, as on Linux. |
| 78 | const authStatusLimit = 30 * time.Second |
| 79 | |
| 80 | // macTokenFDEnv names the token's descriptor to the CLI. |
| 81 | const macTokenFDEnv = "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR" |
| 82 | |
| 83 | // macCreds is a Mac worker's credential operations. |
| 84 | type macCreds struct { |
| 85 | turns *mac.Turns |
| 86 | exec *mac.Executor |
| 87 | cli mac.ClaudeCLI |
| 88 | paths mac.Paths |
| 89 | // configDir is the runner's config dir (runner.env, the bindings); |
| 90 | // runner its binary (the CLI's MCP server); scratch its scratch root. |
| 91 | configDir, runner, scratch string |
| 92 | taint *macTaint |
| 93 | keychain *creds.Keychain |
| 94 | // fact reads one path's kind, mode, owner and ACL (ls -led and lstat |
| 95 | // on a Mac). |
| 96 | fact func(string) (creds.Fact, error) |
| 97 | // user and uid are the runner user (id -un, id -u at start). |
| 98 | user string |
| 99 | uid int |
| 100 | log *slog.Logger |
| 101 | // held is the worker's credential hold (Connector.credentialHeld), |
| 102 | // set once its connections open (openWorkerConns); nil until then. |
| 103 | held func(context.Context) bool |
| 104 | } |
| 105 | |
| 106 | // newCreds is h's credential operations for c. |
| 107 | func (h *macHost) newCreds(c runner.Config) *macCreds { |
| 108 | m := &macCreds{turns: h.turns, exec: &mac.Executor{Turns: h.turns}, cli: h.tools.Claude, paths: h.paths, configDir: macConfigDir(c, h.paths.Home), |
| 109 | runner: c.Executable, scratch: c.ScratchRoot, taint: h.taint, uid: -1, log: h.log} |
| 110 | ctx, cancel := context.WithTimeout(context.Background(), mac.QueryLimit) |
| 111 | defer cancel() |
| 112 | if a, err := mac.ReadAccount(ctx, h.run); err == nil { |
| 113 | m.user, m.uid = a.Name, a.UID |
| 114 | } |
| 115 | m.fact = func(p string) (creds.Fact, error) { return creds.Read(p, nil) } |
| 116 | if runtime.GOOS == "darwin" { |
| 117 | m.fact = func(p string) (creds.Fact, error) { |
| 118 | return creds.Read(p, func(p string) (string, error) { |
| 119 | ctx, cancel := context.WithTimeout(context.Background(), mac.QueryLimit) |
| 120 | defer cancel() |
| 121 | return h.run(ctx, "/bin/ls", "-led", "--", p) |
| 122 | }) |
| 123 | } |
| 124 | } |
| 125 | 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} |
| 126 | return m |
| 127 | } |
| 128 | |
| 129 | // macConfigDir is the runner's config dir: the bindings file's, or the |
| 130 | // installer's ~/.config/equipo-runner. |
| 131 | func macConfigDir(c runner.Config, home string) string { |
| 132 | if c.AccountBindingsPath != "" { |
| 133 | return filepath.Dir(c.AccountBindingsPath) |
| 134 | } |
| 135 | return filepath.Join(home, ".config", "equipo-runner") |
| 136 | } |
| 137 | |
| 138 | // macSecurity is security(1); macKeychains: this host has Keychains |
| 139 | // (tests stand in for both). |
| 140 | var ( |
| 141 | macSecurity = "/usr/bin/security" |
| 142 | macKeychains = runtime.GOOS == "darwin" |
| 143 | ) |
| 144 | |
| 145 | // keychainList is every generic password of the Keychain at keychain |
| 146 | // (the runner user's login Keychain, named by its path whatever the |
| 147 | // search list says), by attributes only (no -d: no secret is read). A |
| 148 | // Keychain file that is not there, or a listing that fails, is an |
| 149 | // error: nothing is decided from it. Off a Mac there is none. |
| 150 | func (h *macHost) keychainList(ctx context.Context, keychain string) ([]creds.Item, error) { |
| 151 | if !macKeychains { |
| 152 | return nil, nil |
| 153 | } |
| 154 | if info, err := os.Lstat(keychain); err != nil || !info.Mode().IsRegular() { |
| 155 | return nil, errKeychain |
| 156 | } |
| 157 | ctx, cancel := context.WithTimeout(ctx, mac.QueryLimit) |
| 158 | defer cancel() |
| 159 | out, err := h.run(ctx, macSecurity, "dump-keychain", keychain) |
| 160 | if err != nil { |
| 161 | return nil, err |
| 162 | } |
| 163 | return creds.ParseDump(out) |
| 164 | } |
| 165 | |
| 166 | // keychainDelete deletes one generic password by service, account and |
| 167 | // Keychain path. |
| 168 | func (h *macHost) keychainDelete(ctx context.Context, i creds.Item) error { |
| 169 | if !macKeychains || i.Unread { |
| 170 | return errKeychain |
| 171 | } |
| 172 | ctx, cancel := context.WithTimeout(ctx, mac.QueryLimit) |
| 173 | defer cancel() |
| 174 | _, err := h.run(ctx, macSecurity, "delete-generic-password", "-s", i.Service, "-a", i.Account, i.Keychain) |
| 175 | return err |
| 176 | } |
| 177 | |
| 178 | // guard is the home guard now: the home and the three roots, each made |
| 179 | // (0700) if it is missing, then read and decided. |
| 180 | func (m *macCreds) guard() creds.Result { |
| 181 | roots := []string{m.paths.StateDir, m.configDir, m.paths.AccountsRoot} |
| 182 | for _, r := range roots { |
| 183 | if r != "" && strings.HasPrefix(filepath.Clean(r), filepath.Clean(m.paths.Home)+"/") { |
| 184 | _ = os.MkdirAll(r, 0o700) |
| 185 | } |
| 186 | } |
| 187 | return creds.Check(creds.Input{User: m.user, UID: m.uid, Home: m.paths.Home, Roots: roots}, m.fact) |
| 188 | } |
| 189 | |
| 190 | // Gate is the guards, now: errTainted, or *homeOpen naming what to |
| 191 | // change, or nil. Every store and every use of a token passes it first. |
| 192 | func (m *macCreds) Gate() error { |
| 193 | if m.taint.Tainted() { |
| 194 | return errTainted |
| 195 | } |
| 196 | if left, err := m.keychain.Unproven(); err != nil || len(left) > 0 { |
| 197 | return errCredentialUnproven |
| 198 | } |
| 199 | if r := m.guard(); !r.OK() { |
| 200 | if m.log != nil { |
| 201 | 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", "; ")) |
| 202 | } |
| 203 | return &homeOpen{r} |
| 204 | } |
| 205 | return nil |
| 206 | } |
| 207 | |
| 208 | // status is the guards' Engineering status: tainted (it lasts, so it is |
| 209 | // said first), or home_open with the guard's first code; nil when both |
| 210 | // pass. |
| 211 | func (m *macCreds) status() *wire.EngineeringStatus { |
| 212 | if m.taint.Tainted() { |
| 213 | return &wire.EngineeringStatus{State: wire.EngineeringTainted} |
| 214 | } |
| 215 | if r := m.guard(); !r.OK() { |
| 216 | return &wire.EngineeringStatus{State: wire.EngineeringHomeOpen, Reason: r.Reason()} |
| 217 | } |
| 218 | return nil |
| 219 | } |
| 220 | |
| 221 | // checkTurn is the Mac's turn for a connection's refresh, taken before |
| 222 | // its home's lock (Conns.Turn). |
| 223 | func (m *macCreds) checkTurn(ctx context.Context) (context.Context, func(), error) { |
| 224 | return m.turns.Hold(ctx, mac.OpTokenCheck) |
| 225 | } |
| 226 | |
| 227 | // Held: a Keychain item a sign-in may have left is on record (the |
| 228 | // Keychain half of the credential hold; task 11 adds the files'). |
| 229 | func (m *macCreds) Held() bool { return m.keychain.Held() } |
| 230 | |
| 231 | // store is a token store's turn (OpTokenStore) and its guards; give |
| 232 | // ends it. errMacRefused (joined with why) refuses the token; any other |
| 233 | // error is a wait that ran out, and the delivery is tried again. |
| 234 | func (m *macCreds) store(ctx context.Context) (give func(), err error) { |
| 235 | wait, cancel := context.WithTimeout(ctx, tokenStoreWait) |
| 236 | defer cancel() |
| 237 | _, give, err = m.turns.Hold(wait, mac.OpTokenStore) |
| 238 | if err != nil { |
| 239 | return nil, err |
| 240 | } |
| 241 | err = m.Gate() |
| 242 | if err == nil { |
| 243 | err = m.keychain.Existing(ctx) |
| 244 | } |
| 245 | if err != nil { |
| 246 | give() |
| 247 | return nil, errors.Join(errMacRefused, err) |
| 248 | } |
| 249 | return give, nil |
| 250 | } |
| 251 | |
| 252 | // after is a launch's second look at the Keychain once its end is |
| 253 | // proven: errKeychain when it left an item (its own is deleted; the Mac |
| 254 | // holds until a listing shows every such item gone) or the Keychain |
| 255 | // could not be listed again. |
| 256 | func (m *macCreds) after(marker string) error { |
| 257 | ctx, cancel := context.WithTimeout(context.Background(), 3*mac.QueryLimit) |
| 258 | defer cancel() |
| 259 | out, err := m.keychain.After(ctx, marker) |
| 260 | if err == nil && out.Clean { |
| 261 | return nil |
| 262 | } |
| 263 | if m.log != nil { |
| 264 | 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) |
| 265 | } |
| 266 | return errKeychain |
| 267 | } |
| 268 | |
| 269 | // settle is the Keychain watch's settling: at a restart, every watch |
| 270 | // whose CLI is proven gone; otherwise only what was found left. |
| 271 | func (m *macCreds) settle(ctx context.Context, restart bool) { |
| 272 | err := m.keychain.Settle(ctx, restart, m.ended) |
| 273 | if err != nil && m.log != nil { |
| 274 | m.log.Warn("keychain not settled", "err", err) |
| 275 | } |
| 276 | if left := m.keychain.Residue(); len(left) > 0 && m.log != nil { |
| 277 | m.log.Warn("a Keychain item holds this Mac as having a credential; remove it in Keychain Access", "services", strings.Join(left, ", ")) |
| 278 | } |
| 279 | } |
| 280 | |
| 281 | // ended: the watched launch has surely ended, so its watch may take its |
| 282 | // second look. Only Executor.Verify says so (spec §8.8): its end proven |
| 283 | // by its process record, or a boot-qualified reboot clearance (another |
| 284 | // kern.bootsessionuuid and a later boot time, under the one proof |
| 285 | // deadline, acknowledged per consumer). A boot time alone moves with |
| 286 | // the clock and proves nothing. Anything else keeps the watch, the hold |
| 287 | // and the Mac's connections closed. |
| 288 | func (m *macCreds) ended(w creds.Watch) bool { return m.exec.Verify(watchRun(w)) } |
| 289 | |
| 290 | // acked: w's watch is settled durably (creds.Keychain.Acked), so the |
| 291 | // Keychain recovery's share of its launch's proof may go. |
| 292 | func (m *macCreds) acked(w creds.Watch) { m.exec.Acknowledge(watchRun(w), mac.ConsumerKeychain) } |
| 293 | |
| 294 | // watchRun is the process record of w's launch. |
| 295 | func watchRun(w creds.Watch) string { |
| 296 | if w.Run != "" { |
| 297 | return w.Run |
| 298 | } |
| 299 | return mac.RecordID(0, w.Marker) |
| 300 | } |
| 301 | |
| 302 | // place makes a launch's own CLAUDE_CONFIG_DIR under the runtime root |
| 303 | // (<scratch>/homes, which no sandboxed command reaches); its name is the |
| 304 | // launch's marker. |
| 305 | func (m *macCreds) place(prefix string) (dir, marker string, err error) { |
| 306 | root := filepath.Join(m.scratch, "homes") |
| 307 | if err = os.MkdirAll(root, 0o700); err != nil { |
| 308 | return "", "", err |
| 309 | } |
| 310 | if dir, err = os.MkdirTemp(root, prefix); err != nil { |
| 311 | return "", "", err |
| 312 | } |
| 313 | return dir, filepath.Base(dir), nil |
| 314 | } |
| 315 | |
| 316 | // env is a launch's whole environment: its own config dir (both names |
| 317 | // the CLI reads it by, so its Keychain service is named for it), the |
| 318 | // runner user's home, the CLI's PATH and locale, no updater and no |
| 319 | // nonessential traffic, the marker, and with a token only the number |
| 320 | // of the descriptor it is on. |
| 321 | func (m *macCreds) env(dir, marker string, token bool, extra ...string) []string { |
| 322 | env := []string{"HOME=" + m.paths.Home, "USER=" + m.user, "CLAUDE_CONFIG_DIR=" + dir, "CLAUDE_SECURESTORAGE_CONFIG_DIR=" + dir, "TMPDIR=" + dir, |
| 323 | "PATH=" + claude.DarwinPath, "LANG=" + claude.DarwinLang, "DISABLE_AUTOUPDATER=1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", claude.DarwinMarkerEnv + "=" + marker} |
| 324 | if token { |
| 325 | env = append(env, macTokenFDEnv+"="+strconv.Itoa(claude.DarwinTokenFD)) |
| 326 | } |
| 327 | return append(env, extra...) |
| 328 | } |
| 329 | |
| 330 | // start starts the pinned CLI with args (ClaudeCLI.Launch: hashed, then |
| 331 | // checked again just before) through the executor, in dir, as c says, |
| 332 | // with token (if any) in a pipe that is descriptor 3. ctx must hold the |
| 333 | // turn. |
| 334 | func (m *macCreds) start(ctx context.Context, dir, marker string, c mac.Command, token []byte, record func(string) error, args ...string) (*mac.Run, error) { |
| 335 | c.Dir = dir |
| 336 | if token != nil { |
| 337 | if len(token) == 0 || len(token) > mac.MaxToken || bytes.ContainsAny(token, "\x00\r\n") { |
| 338 | return nil, provider.ErrPolicy |
| 339 | } |
| 340 | read, write, err := os.Pipe() |
| 341 | if err != nil { |
| 342 | return nil, err |
| 343 | } |
| 344 | defer read.Close() |
| 345 | _, err = write.Write(token) |
| 346 | if cerr := write.Close(); err == nil { |
| 347 | err = cerr |
| 348 | } |
| 349 | if err != nil { |
| 350 | return nil, provider.ErrPolicy |
| 351 | } |
| 352 | c.Files = []*os.File{read} |
| 353 | } |
| 354 | var run *mac.Run |
| 355 | err := m.cli.Launch(ctx, func(ctx context.Context, argv []string) error { |
| 356 | c.Argv = argv |
| 357 | r, err := m.exec.Start(ctx, c, marker, record) |
| 358 | run = r |
| 359 | return err |
| 360 | }, args...) |
| 361 | return run, err |
| 362 | } |
| 363 | |
| 364 | // capped keeps the first 64 KiB written to it. |
| 365 | type capped struct{ b bytes.Buffer } |
| 366 | |
| 367 | func (c *capped) Write(p []byte) (int, error) { |
| 368 | if room := 64<<10 - c.b.Len(); room > 0 { |
| 369 | c.b.Write(p[:min(len(p), room)]) |
| 370 | } |
| 371 | return len(p), nil |
| 372 | } |
| 373 | |
| 374 | // authStatus is a token home's `claude auth status --json` on a Mac |
| 375 | // (Linux's provider.RefreshLogin), the token by descriptor, in the |
| 376 | // check's turn: the email, if the CLI names one. It proves nothing about |
| 377 | // the token. ClaudeOptions.Refresh and Conns.Refresh on a Mac. |
| 378 | func (m *macCreds) authStatus(ctx context.Context, b provider.Binding) (provider.Identity, error) { |
| 379 | if b.Provider != wire.ProviderClaude || !b.Token { |
| 380 | return provider.Identity{}, provider.ErrLoginUnavailable |
| 381 | } |
| 382 | ctx, give, err := m.turns.Hold(ctx, mac.OpTokenCheck) |
| 383 | if err != nil { |
| 384 | return provider.Identity{}, err |
| 385 | } |
| 386 | defer give() |
| 387 | if err := m.Gate(); err != nil { |
| 388 | return provider.Identity{}, err |
| 389 | } |
| 390 | raw, err := provider.ReadToken(b.Home) |
| 391 | if err != nil { |
| 392 | return provider.Identity{}, provider.ErrLoginRequired |
| 393 | } |
| 394 | defer clear(raw) |
| 395 | ctx, cancel := context.WithTimeout(ctx, authStatusLimit) |
| 396 | defer cancel() |
| 397 | dir, marker, err := m.place("status-") |
| 398 | if err != nil { |
| 399 | return provider.Identity{}, err |
| 400 | } |
| 401 | // Watched as a sign-in is: the list on record before the CLI starts, |
| 402 | // the second look once its end is proven (a crash leaves the watch |
| 403 | // for the restart). |
| 404 | if err = m.keychain.Before(ctx, marker, dir); err != nil { |
| 405 | os.RemoveAll(dir) |
| 406 | return provider.Identity{}, err |
| 407 | } |
| 408 | out := &capped{} |
| 409 | ran := func(id string) error { return m.keychain.Ran(marker, id) } |
| 410 | run, err := m.start(ctx, dir, marker, mac.Command{Env: m.env(dir, marker, true), Stdout: out}, raw, ran, "auth", "status", "--json") |
| 411 | if err != nil { |
| 412 | if errors.Is(err, mac.ErrUnproven) { |
| 413 | m.keychain.Abandon(marker) |
| 414 | } else { |
| 415 | err = errors.Join(err, m.after(marker)) |
| 416 | os.RemoveAll(dir) |
| 417 | } |
| 418 | return provider.Identity{}, err |
| 419 | } |
| 420 | select { |
| 421 | case <-run.Exited(): |
| 422 | case <-run.Aborted(): |
| 423 | case <-ctx.Done(): |
| 424 | } |
| 425 | proven := run.Stop() |
| 426 | if !run.Finish(context.WithoutCancel(ctx)) { |
| 427 | proven = false |
| 428 | } |
| 429 | if !proven { |
| 430 | // Not success: the watch and the turn's record stay, and the |
| 431 | // Mac's connections are closed until its end is proven. |
| 432 | m.keychain.Abandon(marker) |
| 433 | return provider.Identity{}, mac.ErrUnproven |
| 434 | } |
| 435 | kerr := m.after(marker) |
| 436 | os.RemoveAll(dir) |
| 437 | switch { |
| 438 | case kerr != nil: |
| 439 | return provider.Identity{}, kerr |
| 440 | case ctx.Err() != nil: |
| 441 | return provider.Identity{}, ctx.Err() |
| 442 | } |
| 443 | id, _, err := provider.ClaudeTokenIdentity(out.b.Bytes(), b.ID) |
| 444 | if err != nil || run.ExitErr() != nil { |
| 445 | return provider.Identity{}, provider.ErrLoginRequired |
| 446 | } |
| 447 | return id, nil |
| 448 | } |
| 449 | |
| 450 | // checkToken is the token check on a Mac (tokencheck.go's, the same |
| 451 | // prompt, outcomes and limit): the darwin launch's check-only policy (no |
| 452 | // native tool, no Equipo tool, an empty read-only workspace under the |
| 453 | // scratch root, no network for any shell), the token by descriptor, the |
| 454 | // whole check in one turn (OpTokenCheck). A crash leaves the turn's |
| 455 | // record, and the next turn settles what it left. |
| 456 | func (m *macCreds) checkToken(ctx context.Context, o ClaudeOptions, b runner.AccountBinding) (_ []wire.Usage, _ *connect.Limit, named bool, err error) { |
| 457 | if b.Provider != wire.ProviderClaude || b.Kind != wire.KindToken { |
| 458 | return nil, nil, false, provider.ErrPolicy |
| 459 | } |
| 460 | tctx, give, err := m.turns.Hold(ctx, mac.OpTokenCheck) |
| 461 | if err != nil { |
| 462 | return nil, nil, false, err |
| 463 | } |
| 464 | defer give() |
| 465 | if err = m.Gate(); err != nil { |
| 466 | return nil, nil, false, err |
| 467 | } |
| 468 | parent := tctx |
| 469 | ctx, cancel := context.WithTimeout(tctx, tokenCheckLimit) |
| 470 | defer cancel() |
| 471 | direct, err := o.Runner.DirectBinding(b) |
| 472 | if err != nil { |
| 473 | return nil, nil, false, err |
| 474 | } |
| 475 | lease, err := provider.OpenRuntimeCopy(ctx, direct, m.authStatus, o.LockWait) |
| 476 | if err != nil { |
| 477 | return nil, nil, false, err |
| 478 | } |
| 479 | defer lease.Close() |
| 480 | binding := lease.Binding() |
| 481 | scratch, err := os.MkdirTemp(o.Runner.ScratchRoot, "policy-") |
| 482 | if err != nil { |
| 483 | return nil, nil, false, err |
| 484 | } |
| 485 | defer os.RemoveAll(scratch) |
| 486 | // The empty workspace: under the scratch root, never SessionRoot (the |
| 487 | // §4.2 list denies it). |
| 488 | work, err := os.MkdirTemp(o.Runner.ScratchRoot, "check-") |
| 489 | if err != nil { |
| 490 | return nil, nil, false, err |
| 491 | } |
| 492 | defer os.RemoveAll(work) |
| 493 | root, err := toolRoot(o.Runner) |
| 494 | if err != nil { |
| 495 | return nil, nil, false, err |
| 496 | } |
| 497 | tool, err := openToolSocket(context.Background(), root, func(context.Context, string, string, json.RawMessage) (string, bool) { return toolNoTurn, true }) |
| 498 | if err != nil { |
| 499 | return nil, nil, false, err |
| 500 | } |
| 501 | defer tool.Close() |
| 502 | sel := provider.Selection{ConnectionID: b.LocalID, Provider: b.Provider, Family: b.Family, Model: b.Model, AccountID: b.AccountID} |
| 503 | session := uuid() |
| 504 | in := mac.EngineeringInput{Paths: m.paths, Action: claude.DarwinCheck, Model: firstNonEmpty(b.Model, firstNonEmpty(o.Runner.ClaudeModel, DefaultModels[wire.ProviderClaude])), |
| 505 | Worktree: work, Scratch: scratch, Runner: m.runner, ToolRoot: root, Socket: tool.Path, |
| 506 | ConfigDir: binding.Home, CredentialHome: b.ProviderHome, RuntimeRoot: direct.RuntimeRoot, Attempt: "check-" + filepath.Base(work), SessionID: session} |
| 507 | policy, err := mac.EngineeringPolicy(m.cli, in) |
| 508 | if err != nil { |
| 509 | return nil, nil, false, err |
| 510 | } |
| 511 | if err = lease.CheckCopy(ctx); err != nil { |
| 512 | return nil, nil, false, err |
| 513 | } |
| 514 | launch := provider.Launch{ToolSocket: tool.Path, AttemptKey: "check/" + uuid(), Workspace: work, Selection: sel, Binding: binding, Policy: policy} |
| 515 | env, err := provider.LaunchSecretEnv(launch) |
| 516 | if err != nil { |
| 517 | return nil, nil, false, err |
| 518 | } |
| 519 | token := []byte(env[provider.OAuthTokenEnv]) |
| 520 | // The account profile, once the provider answered, as on Linux. |
| 521 | defer func() { |
| 522 | if err == nil && o.Profile != nil { |
| 523 | named = o.readProfile(parent, b, token) |
| 524 | } |
| 525 | clear(token) |
| 526 | }() |
| 527 | // Watched as a sign-in is, the runtime copy its config dir. |
| 528 | if err = m.keychain.Before(ctx, in.Attempt, in.ConfigDir); err != nil { |
| 529 | return nil, nil, false, err |
| 530 | } |
| 531 | pctx, kill := context.WithCancel(context.WithoutCancel(tctx)) |
| 532 | defer kill() |
| 533 | s := &mac.Starter{Exec: m.exec, CLI: m.cli, Input: in, Token: bytes.Clone(token)} |
| 534 | ran := func(_ context.Context, r containment.Record) error { return m.keychain.Ran(in.Attempt, r.ID) } |
| 535 | proc, err := s.StartRecorded(pctx, launch, claude.DarwinArgv(policy), ran) |
| 536 | if err != nil { |
| 537 | if errors.Is(err, mac.ErrUnproven) { |
| 538 | m.keychain.Abandon(in.Attempt) |
| 539 | } else { |
| 540 | err = errors.Join(err, m.after(in.Attempt)) |
| 541 | } |
| 542 | return nil, nil, false, err |
| 543 | } |
| 544 | // Stopped at the limit (which ends the reads) and at the end. Only a |
| 545 | // proven end, then a clean second look at the Keychain, lets an |
| 546 | // answer count: unproven, the watch and the turn's record stay for |
| 547 | // recovery, and the profile is not read. |
| 548 | waited := make(chan error, 1) |
| 549 | go func() { _, err := proc.Wait(context.Background()); waited <- err }() |
| 550 | stop := context.AfterFunc(ctx, kill) |
| 551 | rows, seen, err := readCheck(ctx, proc, session, b) |
| 552 | stop() |
| 553 | kill() |
| 554 | if werr := <-waited; werr != nil { |
| 555 | m.keychain.Abandon(in.Attempt) |
| 556 | return rows, nil, false, errors.Join(mac.ErrUnproven, werr) |
| 557 | } |
| 558 | if kerr := m.after(in.Attempt); kerr != nil { |
| 559 | return rows, nil, false, kerr |
| 560 | } |
| 561 | return rows, seen, false, err |
| 562 | } |
| 563 | |
| 564 | // macSetupToken is a Mac's sign-in terminal for attempt (Connector's |
| 565 | // terminal): its run's record goes on the attempt's row. |
| 566 | func (c *Connector) macSetupToken(ctx context.Context, attempt string) (connect.Terminal, error) { |
| 567 | return c.Mac.terminal(ctx, func(id string) error { |
| 568 | _, err := c.State.db.ExecContext(context.WithoutCancel(ctx), "UPDATE connect_attempts SET namespace=? WHERE id=?", id, attempt) |
| 569 | return err |
| 570 | }) |
| 571 | } |
| 572 | |
| 573 | // terminal starts `claude setup-token` on a pseudo-terminal in the |
| 574 | // Mac's turn (OpSignIn), held until Stop: the guards, then its own |
| 575 | // config dir, then the Keychain listed and written down (before |
| 576 | // anything starts), then the CLI. |
| 577 | func (m *macCreds) terminal(ctx context.Context, record func(string) error) (connect.Terminal, error) { |
| 578 | u, err := m.turns.Take(ctx, mac.OpSignIn) |
| 579 | if err != nil { |
| 580 | return nil, err |
| 581 | } |
| 582 | kept := false |
| 583 | defer func() { |
| 584 | if !kept { |
| 585 | u.Give() |
| 586 | } |
| 587 | }() |
| 588 | if err = m.Gate(); err != nil { |
| 589 | return nil, err |
| 590 | } |
| 591 | dir, marker, err := m.place("signin-") |
| 592 | if err != nil { |
| 593 | return nil, err |
| 594 | } |
| 595 | if err = m.keychain.Before(ctx, marker, dir); err != nil { |
| 596 | os.RemoveAll(dir) |
| 597 | return nil, err |
| 598 | } |
| 599 | // What did not start (or whose end is proven) gets its second look now. |
| 600 | unstarted := func() { |
| 601 | _, _ = m.keychain.After(context.WithoutCancel(ctx), marker) |
| 602 | os.RemoveAll(dir) |
| 603 | } |
| 604 | pty, tty, err := creds.OpenTerminal() |
| 605 | if err != nil { |
| 606 | unstarted() |
| 607 | return nil, err |
| 608 | } |
| 609 | env := m.env(dir, marker, false, "TERM=xterm-256color", "BROWSER="+provider.SignInBrowser) |
| 610 | ran := func(id string) error { |
| 611 | if err := m.keychain.Ran(marker, id); err != nil { |
| 612 | return err |
| 613 | } |
| 614 | return record(id) |
| 615 | } |
| 616 | run, err := m.start(u.Context(ctx), dir, marker, mac.Command{Env: env, TTY: tty}, nil, ran, "setup-token") |
| 617 | tty.Close() |
| 618 | if err != nil { |
| 619 | pty.Close() |
| 620 | if errors.Is(err, mac.ErrUnproven) { |
| 621 | m.keychain.Abandon(marker) |
| 622 | } else { |
| 623 | unstarted() |
| 624 | } |
| 625 | return nil, err |
| 626 | } |
| 627 | kept = true |
| 628 | return &macTerminal{m: m, turn: u, run: run, pty: pty, marker: marker, dir: dir}, nil |
| 629 | } |
| 630 | |
| 631 | // macTerminal is a sign-in's terminal on a Mac. |
| 632 | type macTerminal struct { |
| 633 | m *macCreds |
| 634 | turn *mac.Turn |
| 635 | run *mac.Run |
| 636 | pty *os.File |
| 637 | marker, dir string |
| 638 | once sync.Once |
| 639 | err error |
| 640 | } |
| 641 | |
| 642 | func (t *macTerminal) Read(p []byte) (int, error) { return t.pty.Read(p) } |
| 643 | func (t *macTerminal) Write(p []byte) (int, error) { return t.pty.Write(p) } |
| 644 | func (t *macTerminal) Done() <-chan struct{} { return t.run.Exited() } |
| 645 | |
| 646 | // Stop stops the CLI and proves its end (its group and what it left), |
| 647 | // then looks at the Keychain again and gives the turn back. errUnproven: |
| 648 | // its end is not proven (the watch stays, held, for the restart); |
| 649 | // errKeychain: the sign-in left an item, so the connection is refused. |
| 650 | func (t *macTerminal) Stop() error { |
| 651 | t.once.Do(func() { |
| 652 | defer t.turn.Give() |
| 653 | proven := t.run.Stop() |
| 654 | if !t.run.Finish(context.Background()) { |
| 655 | proven = false |
| 656 | } |
| 657 | t.pty.Close() |
| 658 | if !proven { |
| 659 | t.m.keychain.Abandon(t.marker) |
| 660 | t.err = errUnproven |
| 661 | return |
| 662 | } |
| 663 | t.err = t.m.after(t.marker) |
| 664 | os.RemoveAll(t.dir) |
| 665 | }) |
| 666 | return t.err |
| 667 | } |
| 668 | |