| 1 | //go:build testbuild |
| 2 | |
| 3 | package thin |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "crypto/sha256" |
| 8 | "encoding/hex" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "log/slog" |
| 13 | "os" |
| 14 | "os/exec" |
| 15 | "path/filepath" |
| 16 | "slices" |
| 17 | "strconv" |
| 18 | "strings" |
| 19 | "sync" |
| 20 | "syscall" |
| 21 | "testing" |
| 22 | "time" |
| 23 | |
| 24 | "amadan.net/oficina/equipo/internal/fakeclaude" |
| 25 | "amadan.net/oficina/equipo/internal/runner" |
| 26 | "amadan.net/oficina/equipo/internal/runner/mac" |
| 27 | "amadan.net/oficina/equipo/internal/runner/mac/creds" |
| 28 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 29 | "amadan.net/oficina/equipo/internal/runner/provider/claude" |
| 30 | "amadan.net/oficina/equipo/internal/wire" |
| 31 | ) |
| 32 | |
| 33 | // A Mac's Claude credential (maccreds.go) on Linux: the pinned "CLI" is |
| 34 | // a shell script pinned by its own digest, provisioned and hashed before |
| 35 | // every start exactly as the real one is (ClaudeCLI.Launch), which |
| 36 | // records its argv, environment and directory and then runs the fake |
| 37 | // CLI; the executor and the turns are package mac's own; the Keychain is |
| 38 | // a fake listing. Test build only: mac.PinnedForTest exists only there. |
| 39 | |
| 40 | // launchScript is the pinned stand-in: %[1]s is the rig's directory. |
| 41 | // With <dir>/hang it never answers a check (-p): it says its pid and |
| 42 | // sleeps, as a hung CLI would. With <dir>/linger naming its first |
| 43 | // argument it leaves a child that ignores SIGTERM, so its end cannot be |
| 44 | // proven within a short Settle. |
| 45 | const launchScript = `#!/bin/sh |
| 46 | d=%[1]s |
| 47 | env > "$d/bin/launch.$$.env" |
| 48 | pwd > "$d/bin/launch.$$.cwd" |
| 49 | echo "$*" > "$d/bin/launch.$$.argv" |
| 50 | [ -f "$CLAUDE_CONFIG_DIR/equipo-settings.json" ] && cp "$CLAUDE_CONFIG_DIR/equipo-settings.json" "$d/bin/launch.$$.settings" |
| 51 | if [ "$1" = "-p" ] && [ -e "$d/hang" ]; then echo $$ > "$d/hang.pid"; exec /bin/sleep 600; fi |
| 52 | if [ -e "$d/linger" ] && [ "$1" = "$(cat "$d/linger")" ]; then (trap "" TERM HUP; exec /bin/sleep 5) & echo $! > "$d/linger.pid"; fi |
| 53 | exec "$d/bin/claude" "$@" |
| 54 | ` |
| 55 | |
| 56 | // keychainFake is the runner user's Keychains as security lists them. |
| 57 | type keychainFake struct { |
| 58 | mu sync.Mutex |
| 59 | items []creds.Item |
| 60 | lists int |
| 61 | deleted []creds.Item |
| 62 | fail bool |
| 63 | // stale keeps a deleted item in the next listing. |
| 64 | stale bool |
| 65 | ghost []creds.Item |
| 66 | // started, when set, says whether the CLI has started; startedAt is |
| 67 | // what it said at the first listing. |
| 68 | started func() bool |
| 69 | startedAt []bool |
| 70 | // asked is each keychain listed. create, when set, is what a CLI |
| 71 | // launch stored in the login keychain (it runs once per launch, at |
| 72 | // the first listing after it). |
| 73 | asked []string |
| 74 | create func(launched) []creds.Item |
| 75 | created map[int]bool |
| 76 | // appear, when set, is asked at each listing; what it returns is |
| 77 | // stored once (a write that comes later). |
| 78 | appear func() []creds.Item |
| 79 | r *darwinRig |
| 80 | } |
| 81 | |
| 82 | func (f *keychainFake) list(_ context.Context, keychain string) ([]creds.Item, error) { |
| 83 | f.mu.Lock() |
| 84 | defer f.mu.Unlock() |
| 85 | f.lists++ |
| 86 | f.asked = append(f.asked, keychain) |
| 87 | if f.started != nil { |
| 88 | f.startedAt = append(f.startedAt, f.started()) |
| 89 | } |
| 90 | if f.create != nil { |
| 91 | if f.created == nil { |
| 92 | f.created = map[int]bool{} |
| 93 | } |
| 94 | for _, l := range f.r.launches() { |
| 95 | if !f.created[l.pid] { |
| 96 | f.created[l.pid] = true |
| 97 | f.items = append(f.items, f.create(l)...) |
| 98 | } |
| 99 | } |
| 100 | } |
| 101 | if f.appear != nil { |
| 102 | if more := f.appear(); len(more) > 0 { |
| 103 | f.items, f.appear = append(f.items, more...), nil |
| 104 | } |
| 105 | } |
| 106 | var out []creds.Item |
| 107 | for _, i := range append(slices.Clone(f.items), f.ghost...) { |
| 108 | if i.Keychain == keychain { |
| 109 | out = append(out, i) |
| 110 | } |
| 111 | } |
| 112 | f.ghost = nil |
| 113 | return out, nil |
| 114 | } |
| 115 | |
| 116 | // creating makes each later launch whose argv starts with prefix store |
| 117 | // item(its CLAUDE_CONFIG_DIR), as a CLI writing to the Keychain would. |
| 118 | func (r *darwinRig) creating(prefix string, item func(dir string) creds.Item) { |
| 119 | f := r.kc |
| 120 | f.mu.Lock() |
| 121 | defer f.mu.Unlock() |
| 122 | f.created = map[int]bool{} |
| 123 | for _, l := range r.launches() { |
| 124 | f.created[l.pid] = true |
| 125 | } |
| 126 | f.create = func(l launched) []creds.Item { |
| 127 | if !strings.HasPrefix(l.argv, prefix) { |
| 128 | return nil |
| 129 | } |
| 130 | return []creds.Item{item(l.env["CLAUDE_CONFIG_DIR"])} |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | func (f *keychainFake) delete(_ context.Context, i creds.Item) error { |
| 135 | f.mu.Lock() |
| 136 | defer f.mu.Unlock() |
| 137 | f.deleted = append(f.deleted, i) |
| 138 | n := slices.Index(f.items, i) |
| 139 | if f.fail || n < 0 { |
| 140 | return errors.New("security: The specified item could not be found in the keychain.") |
| 141 | } |
| 142 | f.items = slices.Delete(f.items, n, n+1) |
| 143 | if f.stale { |
| 144 | f.ghost = append(f.ghost, i) |
| 145 | } |
| 146 | return nil |
| 147 | } |
| 148 | |
| 149 | func (f *keychainFake) add(i ...creds.Item) { |
| 150 | f.mu.Lock() |
| 151 | defer f.mu.Unlock() |
| 152 | f.items = append(f.items, i...) |
| 153 | } |
| 154 | |
| 155 | func (f *keychainFake) has(i creds.Item) bool { |
| 156 | f.mu.Lock() |
| 157 | defer f.mu.Unlock() |
| 158 | return slices.Contains(f.items, i) |
| 159 | } |
| 160 | |
| 161 | func (f *keychainFake) set(fail bool) { |
| 162 | f.mu.Lock() |
| 163 | defer f.mu.Unlock() |
| 164 | f.fail = fail |
| 165 | } |
| 166 | |
| 167 | // darwinRig is a token rig with a Mac's credential operations over it. |
| 168 | type darwinRig struct { |
| 169 | *tokenRig |
| 170 | m *macCreds |
| 171 | kc *keychainFake |
| 172 | opts ClaudeOptions |
| 173 | user string |
| 174 | mu sync.Mutex |
| 175 | // checks is what each real check (Conns.Verify) returned. |
| 176 | checks []checkSeen |
| 177 | } |
| 178 | |
| 179 | type checkSeen struct { |
| 180 | check TokenCheck |
| 181 | err error |
| 182 | } |
| 183 | |
| 184 | // shortDir is a private directory with a short path: a tool socket's |
| 185 | // path must fit sun_path. |
| 186 | func shortDir(t *testing.T) string { |
| 187 | t.Helper() |
| 188 | dir, err := os.MkdirTemp("", "dk") |
| 189 | if err == nil { |
| 190 | dir, err = filepath.EvalSymlinks(dir) |
| 191 | } |
| 192 | if err == nil { |
| 193 | err = os.Chmod(dir, 0o700) |
| 194 | } |
| 195 | if err != nil { |
| 196 | t.Fatal(err) |
| 197 | } |
| 198 | t.Cleanup(func() { os.RemoveAll(dir) }) |
| 199 | return dir |
| 200 | } |
| 201 | |
| 202 | func newDarwinRig(t *testing.T) *darwinRig { return darwinRigAt(t, shortDir(t)) } |
| 203 | |
| 204 | // darwinRigAt is the rig in dir (the home); a second rig in the same |
| 205 | // dir is the same runner after a restart. |
| 206 | func darwinRigAt(t *testing.T, dir string) *darwinRig { |
| 207 | t.Helper() |
| 208 | r := &darwinRig{tokenRig: newTokenRigAt(t, dir), kc: &keychainFake{}} |
| 209 | r.kc.r = r |
| 210 | r.cfg.StateDir = filepath.Join(dir, "state") |
| 211 | // A Mac has no Linux CLI path: only the pinned CLI, by Launch. |
| 212 | r.cfg.ClaudePath = "" |
| 213 | proxy := filepath.Join(dir, "bin", "equipo-tool-proxy") |
| 214 | if _, err := os.Lstat(proxy); err != nil { |
| 215 | self, _ := os.Executable() |
| 216 | if err := os.Symlink(self, proxy); err != nil { |
| 217 | t.Fatal(err) |
| 218 | } |
| 219 | } |
| 220 | r.cfg.Executable = proxy |
| 221 | install := filepath.Join(dir, "lib") |
| 222 | if err := os.MkdirAll(install, 0o700); err != nil { |
| 223 | t.Fatal(err) |
| 224 | } |
| 225 | script := fmt.Sprintf(launchScript, dir) |
| 226 | sum := sha256.Sum256([]byte(script)) |
| 227 | cli := mac.PinnedForTest(mac.NewClaudeCLI(dir, install), hex.EncodeToString(sum[:])) |
| 228 | if err := cli.Provision(context.Background(), func(context.Context, string) (io.ReadCloser, error) { |
| 229 | return io.NopCloser(strings.NewReader(script)), nil |
| 230 | }); err != nil { |
| 231 | t.Fatal(err) |
| 232 | } |
| 233 | out, err := exec.Command("/usr/bin/id", "-un").Output() |
| 234 | if err != nil { |
| 235 | t.Fatal(err) |
| 236 | } |
| 237 | r.user = strings.TrimSpace(string(out)) |
| 238 | turns := mac.NewTurns(filepath.Join(r.cfg.StateDir, "mac-gate.lock")) |
| 239 | m := &macCreds{turns: turns, exec: &mac.Executor{Turns: turns, Settle: 10 * time.Second}, cli: cli, |
| 240 | paths: mac.Paths{Home: dir, StateDir: r.cfg.StateDir, AccountsRoot: r.root, SessionRoot: filepath.Join(dir, "sessions"), InstallDir: install}, |
| 241 | configDir: filepath.Join(dir, "config"), runner: proxy, scratch: r.cfg.ScratchRoot, taint: loadTaint(filepath.Join(r.cfg.StateDir, "tainted")), |
| 242 | user: r.user, uid: os.Getuid(), log: slog.New(slog.NewTextHandler(&r.logs, nil))} |
| 243 | m.fact = func(p string) (creds.Fact, error) { return creds.Read(p, nil) } |
| 244 | m.keychain = &creds.Keychain{Dir: filepath.Join(r.cfg.StateDir, "keychain"), Login: filepath.Join(dir, "Library", "Keychains", "login.keychain-db"), User: r.user, List: r.kc.list, Delete: r.kc.delete} |
| 245 | r.m = m |
| 246 | r.opts = ClaudeOptions{Runner: r.cfg, State: r.state, Mac: m, LockWait: 5 * time.Second} |
| 247 | r.conns.Runner = r.cfg |
| 248 | r.conns.Verify = func(ctx context.Context, b runner.AccountBinding) error { |
| 249 | c, err := r.opts.CheckToken(ctx, b) |
| 250 | r.mu.Lock() |
| 251 | r.checks = append(r.checks, checkSeen{c, err}) |
| 252 | r.mu.Unlock() |
| 253 | return err |
| 254 | } |
| 255 | return r |
| 256 | } |
| 257 | |
| 258 | // connector is a Mac worker's connector: no terminal of its own, the |
| 259 | // Mac's credential operations. |
| 260 | func (r *darwinRig) connector() *Connector { |
| 261 | keys := r.keys |
| 262 | limit := time.Hour |
| 263 | if r.limit > 0 { |
| 264 | limit = r.limit |
| 265 | } |
| 266 | c := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &keys, RunnerID: tokenRunner, Limit: limit, Logger: slog.New(slog.NewTextHandler(&r.logs, nil)), Mac: r.m} |
| 267 | c.spawn = func(f func()) { f() } |
| 268 | if err := c.Start(r.ctx); err != nil { |
| 269 | r.t.Fatal(err) |
| 270 | } |
| 271 | return c |
| 272 | } |
| 273 | |
| 274 | // launches is every start of the pinned CLI so far: argv, environment |
| 275 | // and directory, by pid. |
| 276 | type launched struct { |
| 277 | pid int |
| 278 | argv, cwd string |
| 279 | env map[string]string |
| 280 | } |
| 281 | |
| 282 | func (r *darwinRig) launches() []launched { |
| 283 | var out []launched |
| 284 | matches, _ := filepath.Glob(filepath.Join(r.dir, "bin", "launch.*.argv")) |
| 285 | for _, path := range matches { |
| 286 | pid, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(filepath.Base(path), "launch."), ".argv")) |
| 287 | argv, _ := os.ReadFile(path) |
| 288 | cwd, _ := os.ReadFile(strings.TrimSuffix(path, ".argv") + ".cwd") |
| 289 | l := launched{pid: pid, argv: strings.TrimSpace(string(argv)), cwd: strings.TrimSpace(string(cwd)), env: map[string]string{}} |
| 290 | raw, _ := os.ReadFile(strings.TrimSuffix(path, ".argv") + ".env") |
| 291 | for _, line := range strings.Split(string(raw), "\n") { |
| 292 | if k, v, ok := strings.Cut(line, "="); ok { |
| 293 | l.env[k] = v |
| 294 | } |
| 295 | } |
| 296 | out = append(out, l) |
| 297 | } |
| 298 | return out |
| 299 | } |
| 300 | |
| 301 | // onlyIn fails if token is in any file under the rig's directory but |
| 302 | // home's token file ("" for none), or in the runner's log. |
| 303 | func (r *darwinRig) onlyIn(token, home string) { |
| 304 | r.t.Helper() |
| 305 | _ = filepath.WalkDir(r.dir, func(path string, d os.DirEntry, err error) error { |
| 306 | if err != nil || d.IsDir() || path == filepath.Join(home, provider.TokenFile) || filepath.Dir(path) == filepath.Join(r.dir, "bin") && d.Name() == "claude" { |
| 307 | return nil |
| 308 | } |
| 309 | if raw, _ := os.ReadFile(path); strings.Contains(string(raw), token) { |
| 310 | r.t.Fatalf("the token is in %s", path) |
| 311 | } |
| 312 | return nil |
| 313 | }) |
| 314 | if strings.Contains(r.logs.String(), token) { |
| 315 | r.t.Fatal("the token is in the runner's log") |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | // lastCheck is the last real check's result. |
| 320 | func (r *darwinRig) lastCheck() checkSeen { |
| 321 | r.mu.Lock() |
| 322 | defer r.mu.Unlock() |
| 323 | if len(r.checks) == 0 { |
| 324 | r.t.Fatal("no check ran") |
| 325 | } |
| 326 | return r.checks[len(r.checks)-1] |
| 327 | } |
| 328 | |
| 329 | // turnFree: nothing holds the Mac's turn. |
| 330 | func (r *darwinRig) turnFree() bool { |
| 331 | u, ok := r.m.turns.TryTake(mac.OpWarm) |
| 332 | if ok { |
| 333 | u.Give() |
| 334 | } |
| 335 | return ok |
| 336 | } |
| 337 | |
| 338 | // paste connects a pasted token on c and waits for the attempt's end. |
| 339 | func (r *darwinRig) paste(c *Connector, id, token string) (string, wire.ConnectionReport) { |
| 340 | r.t.Helper() |
| 341 | home := r.connect(c, id) |
| 342 | if !r.deliver(c, "f-"+id, r.sealed(id, token, nil)) { |
| 343 | r.t.Fatalf("delivery failed: %v", r.errs) |
| 344 | } |
| 345 | return home, r.ended(id) |
| 346 | } |
| 347 | |
| 348 | func pidAlive(pid int) bool { |
| 349 | if syscall.Kill(pid, 0) != nil { |
| 350 | return false |
| 351 | } |
| 352 | raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat") |
| 353 | return err == nil && !strings.Contains(string(raw), ") Z ") |
| 354 | } |
| 355 | |
| 356 | func waitPid(t *testing.T, path string) int { |
| 357 | t.Helper() |
| 358 | for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) { |
| 359 | if raw, err := os.ReadFile(path); err == nil { |
| 360 | if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil { |
| 361 | return pid |
| 362 | } |
| 363 | } |
| 364 | } |
| 365 | t.Fatal("the hung CLI never started") |
| 366 | return 0 |
| 367 | } |
| 368 | |
| 369 | // TestDarwinTokenCheck: the token check on a Mac, through the darwin |
| 370 | // launch with its check-only policy and the token by descriptor, gives |
| 371 | // Linux's outcomes, and a crash is settled by the next turn. |
| 372 | func TestDarwinTokenCheck(t *testing.T) { |
| 373 | t.Run("success", func(t *testing.T) { |
| 374 | r := newDarwinRig(t) |
| 375 | c := r.connector() |
| 376 | token := fakeclaude.Token("a@example.com") |
| 377 | home, _ := r.paste(c, "c1", token) |
| 378 | r.healthy("c1", home, token, "a@example.com") |
| 379 | if got := r.lastCheck(); got.err != nil || len(got.check.Rows) == 0 { |
| 380 | t.Fatalf("check %+v", got) |
| 381 | } |
| 382 | var check, status bool |
| 383 | for _, l := range r.launches() { |
| 384 | if v, ok := l.env["CLAUDE_CODE_OAUTH_TOKEN"]; ok { |
| 385 | t.Fatalf("the token was in the CLI's environment (%d chars)", len(v)) |
| 386 | } |
| 387 | if l.env[macTokenFDEnv] != "3" || !strings.HasPrefix(l.env["CLAUDE_CONFIG_DIR"], filepath.Join(r.cfg.ScratchRoot, "homes")+"/") || l.env["PATH"] != claude.DarwinPath { |
| 388 | t.Fatalf("launch %d: %v", l.pid, l.env) |
| 389 | } |
| 390 | switch { |
| 391 | case l.argv == "auth status --json": |
| 392 | status = true |
| 393 | case strings.HasPrefix(l.argv, "-p "): |
| 394 | check = true |
| 395 | if !strings.Contains(l.argv, "--tools ") || !strings.HasPrefix(l.env[claude.DarwinMarkerEnv], "check-") || !strings.HasPrefix(l.cwd, r.cfg.ScratchRoot+"/check-") { |
| 396 | t.Fatalf("the check's launch: %q in %s, %v", l.argv, l.cwd, l.env) |
| 397 | } |
| 398 | } |
| 399 | } |
| 400 | if !check || !status { |
| 401 | t.Fatalf("launches %+v", r.launches()) |
| 402 | } |
| 403 | r.onlyIn(token, home) |
| 404 | if !r.turnFree() { |
| 405 | t.Fatal("the check kept the Mac's turn") |
| 406 | } |
| 407 | }) |
| 408 | t.Run("signed out", func(t *testing.T) { |
| 409 | r := newDarwinRig(t) |
| 410 | _, end := r.paste(r.connector(), "c1", "sk-ant-oat01-fake-zz-ok") |
| 411 | if end.State != wire.ConnError || end.Reason != "provider_refused" || !errors.Is(r.lastCheck().err, provider.ErrLoginRequired) { |
| 412 | t.Fatalf("end %+v check %+v", end, r.lastCheck()) |
| 413 | } |
| 414 | }) |
| 415 | t.Run("limited", func(t *testing.T) { |
| 416 | r := newDarwinRig(t) |
| 417 | token := fakeclaude.Token("spent-a@example.com") |
| 418 | home, _ := r.paste(r.connector(), "c1", token) |
| 419 | r.healthy("c1", home, token, "spent-a@example.com") |
| 420 | if got := r.lastCheck(); got.err != nil || got.check.Seen == nil || !got.check.Seen.Limited { |
| 421 | t.Fatalf("a spent account's check %+v", got) |
| 422 | } |
| 423 | }) |
| 424 | t.Run("cancelled", func(t *testing.T) { |
| 425 | r := newDarwinRig(t) |
| 426 | home, _ := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com")) |
| 427 | b, ok := r.binding(filepath.Base(home)) |
| 428 | if !ok { |
| 429 | t.Fatal("no binding") |
| 430 | } |
| 431 | if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil { |
| 432 | t.Fatal(err) |
| 433 | } |
| 434 | ctx, cancel := context.WithCancel(context.Background()) |
| 435 | done := make(chan error, 1) |
| 436 | go func() { _, err := r.opts.CheckToken(ctx, b); done <- err }() |
| 437 | pid := waitPid(t, filepath.Join(r.dir, "hang.pid")) |
| 438 | cancel() |
| 439 | select { |
| 440 | case err := <-done: |
| 441 | if err == nil { |
| 442 | t.Fatal("a cancelled check answered") |
| 443 | } |
| 444 | case <-time.After(30 * time.Second): |
| 445 | t.Fatal("the cancelled check never returned") |
| 446 | } |
| 447 | if pidAlive(pid) || !r.turnFree() { |
| 448 | t.Fatalf("after the cancel: CLI alive=%v, turn free=%v", pidAlive(pid), r.turnFree()) |
| 449 | } |
| 450 | }) |
| 451 | t.Run("a crash then recovery", func(t *testing.T) { |
| 452 | r := newDarwinRig(t) |
| 453 | home, _ := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com")) |
| 454 | local := filepath.Base(home) |
| 455 | if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil { |
| 456 | t.Fatal(err) |
| 457 | } |
| 458 | // Another runner process starts a check on the same Mac and dies |
| 459 | // (SIGKILL) while its CLI runs. |
| 460 | helper := exec.Command(os.Args[0], "-test.run=^TestDarwinTokenCheckCrashHelper$", "-test.count=1") |
| 461 | helper.Env = append(os.Environ(), "EQUIPO_DARWIN_CRASH_DIR="+r.dir, "EQUIPO_DARWIN_CRASH_LOCAL="+local) |
| 462 | if err := helper.Start(); err != nil { |
| 463 | t.Fatal(err) |
| 464 | } |
| 465 | pid := waitPid(t, filepath.Join(r.dir, "hang.pid")) |
| 466 | _ = helper.Process.Kill() |
| 467 | _ = helper.Wait() |
| 468 | if !pidAlive(pid) { |
| 469 | t.Fatal("the dead runner's CLI did not outlive it (nothing to recover)") |
| 470 | } |
| 471 | os.Remove(filepath.Join(r.dir, "hang")) |
| 472 | b, _ := r.binding(local) |
| 473 | // Its end can never be proven (its turn's record is incomplete): |
| 474 | // connections stay closed until the Mac has booted since (fix |
| 475 | // round 2). |
| 476 | if _, err := r.opts.CheckToken(context.Background(), b); !errors.Is(err, errCredentialUnproven) { |
| 477 | t.Fatalf("the check after the crash: %v", err) |
| 478 | } |
| 479 | // A reboot ends the dead runner's CLI with everything else. |
| 480 | r.rebooted(t, pid) |
| 481 | r.connector() |
| 482 | if _, err := r.opts.CheckToken(context.Background(), b); err != nil { |
| 483 | t.Fatalf("the check after a reboot: %v", err) |
| 484 | } |
| 485 | }) |
| 486 | } |
| 487 | |
| 488 | // TestDarwinTokenCheckCrashHelper is the runner process that dies in |
| 489 | // TestDarwinTokenCheck: it runs one check and is killed during it. |
| 490 | func TestDarwinTokenCheckCrashHelper(t *testing.T) { |
| 491 | dir := os.Getenv("EQUIPO_DARWIN_CRASH_DIR") |
| 492 | if dir == "" { |
| 493 | t.Skip("run by TestDarwinTokenCheck") |
| 494 | } |
| 495 | r := darwinRigAt(t, dir) |
| 496 | b, ok := r.binding(os.Getenv("EQUIPO_DARWIN_CRASH_LOCAL")) |
| 497 | if !ok { |
| 498 | t.Fatal("no binding") |
| 499 | } |
| 500 | _, _ = r.opts.CheckToken(context.Background(), b) |
| 501 | t.Fatal("the hung check returned") |
| 502 | } |
| 503 | |
| 504 | // own is the item a sign-in's CLI would store for its config dir. |
| 505 | func (r *darwinRig) own(dir string) creds.Item { |
| 506 | return creds.Item{Keychain: r.m.keychain.Login, Service: creds.ServiceFor(dir), Account: r.user} |
| 507 | } |
| 508 | |
| 509 | // signInDir is the running sign-in's CLAUDE_CONFIG_DIR. |
| 510 | func (r *darwinRig) signInDir() string { |
| 511 | r.t.Helper() |
| 512 | for _, l := range r.launches() { |
| 513 | if l.argv == "setup-token" { |
| 514 | return l.env["CLAUDE_CONFIG_DIR"] |
| 515 | } |
| 516 | } |
| 517 | r.t.Fatal("no sign-in launched") |
| 518 | return "" |
| 519 | } |
| 520 | |
| 521 | // codeIn types the right code for email into the sign-in's card. |
| 522 | func (r *darwinRig) codeIn(c *Connector, id, link, email string) { |
| 523 | r.t.Helper() |
| 524 | if !r.deliver(c, "f-code-"+id, r.sealedCode(id, codeFor(link, email), 1, nil)) { |
| 525 | r.t.Fatalf("code delivery: %v", r.errs) |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | // TestDarwinSignIn: the sign-in on a Mac, in its turn, with its own |
| 530 | // config dir and the Keychain watched around it. |
| 531 | func TestDarwinSignIn(t *testing.T) { |
| 532 | t.Run("code delivered", func(t *testing.T) { |
| 533 | r := newDarwinRig(t) |
| 534 | wifi := creds.Item{Keychain: r.m.keychain.Login, Service: "Wi-Fi", Account: r.user} |
| 535 | r.kc.add(wifi) |
| 536 | r.kc.started = func() bool { |
| 537 | m, _ := filepath.Glob(filepath.Join(r.dir, "bin", "launch.*.argv")) |
| 538 | return len(m) > 0 |
| 539 | } |
| 540 | c := r.connector() |
| 541 | link, home := r.signIn(c, "s1") |
| 542 | if !r.m.Held() || len(r.kc.startedAt) == 0 || r.kc.startedAt[0] { |
| 543 | t.Fatalf("the Keychain was not listed and held before the CLI started: %v", r.kc.startedAt) |
| 544 | } |
| 545 | if r.turnFree() { |
| 546 | t.Fatal("the sign-in's terminal is open outside the Mac's turn") |
| 547 | } |
| 548 | dir := r.signInDir() |
| 549 | for _, l := range r.launches() { |
| 550 | if l.argv != "setup-token" { |
| 551 | continue |
| 552 | } |
| 553 | if !strings.HasPrefix(dir, filepath.Join(r.cfg.ScratchRoot, "homes")+"/signin-") || l.env["CLAUDE_SECURESTORAGE_CONFIG_DIR"] != dir || l.env["HOME"] != r.dir || l.env["PATH"] != claude.DarwinPath || l.env[claude.DarwinMarkerEnv] != filepath.Base(dir) || l.env["BROWSER"] != provider.SignInBrowser { |
| 554 | t.Fatalf("the sign-in's environment: %v", l.env) |
| 555 | } |
| 556 | if _, ok := l.env["CLAUDE_CODE_OAUTH_TOKEN"]; ok { |
| 557 | t.Fatal("a token in the sign-in's environment") |
| 558 | } |
| 559 | } |
| 560 | r.codeIn(c, "s1", link, "a@example.com") |
| 561 | token := fakeclaude.Token("a@example.com") |
| 562 | r.healthy("s1", home, token, "a@example.com") |
| 563 | if r.m.Held() || !r.kc.has(wifi) || len(r.kc.deleted) != 0 { |
| 564 | t.Fatalf("held=%v after a clean sign-in; deleted %v", r.m.Held(), r.kc.deleted) |
| 565 | } |
| 566 | if _, err := os.Lstat(dir); !os.IsNotExist(err) { |
| 567 | t.Fatalf("the sign-in's config dir was left: %v", err) |
| 568 | } |
| 569 | if !r.turnFree() { |
| 570 | t.Fatal("the turn was kept") |
| 571 | } |
| 572 | r.onlyIn(token, home) |
| 573 | }) |
| 574 | t.Run("timeout", func(t *testing.T) { |
| 575 | r := newDarwinRig(t) |
| 576 | r.limit = 2 * time.Second |
| 577 | c := r.connector() |
| 578 | r.signIn(c, "s1") |
| 579 | if end := r.ended("s1"); end.Reason != "timed_out" { |
| 580 | t.Fatalf("end %+v", end) |
| 581 | } |
| 582 | r.gone() |
| 583 | if r.m.Held() || !r.turnFree() { |
| 584 | t.Fatalf("after the time limit: held=%v turn free=%v", r.m.Held(), r.turnFree()) |
| 585 | } |
| 586 | }) |
| 587 | t.Run("cancel", func(t *testing.T) { |
| 588 | r := newDarwinRig(t) |
| 589 | c := r.connector() |
| 590 | r.signIn(c, "s1") |
| 591 | if err := c.Cancel(r.ctx, "f-cancel-s1", wire.CancelConnectCommand{Connection: "s1", Person: connPerson}); err != nil { |
| 592 | t.Fatal(err) |
| 593 | } |
| 594 | if end := r.ended("s1"); end.Reason != "cancelled" { |
| 595 | t.Fatalf("end %+v", end) |
| 596 | } |
| 597 | r.gone() |
| 598 | if r.m.Held() || !r.turnFree() { |
| 599 | t.Fatalf("after the cancel: held=%v turn free=%v", r.m.Held(), r.turnFree()) |
| 600 | } |
| 601 | }) |
| 602 | t.Run("a Keychain item created means refused, deleted by its exact attributes, held until a second listing shows it gone", func(t *testing.T) { |
| 603 | r := newDarwinRig(t) |
| 604 | r.kc.stale = true |
| 605 | c := r.connector() |
| 606 | link, home := r.signIn(c, "s1") |
| 607 | item := r.own(r.signInDir()) |
| 608 | r.kc.add(item) |
| 609 | r.codeIn(c, "s1", link, "a@example.com") |
| 610 | end := r.ended("s1") |
| 611 | if end.State != wire.ConnError || end.Reason != "provider_refused" { |
| 612 | t.Fatalf("end %+v", end) |
| 613 | } |
| 614 | if _, ok := r.binding(filepath.Base(home)); ok || exists(home) { |
| 615 | t.Fatal("a refused sign-in kept its connection") |
| 616 | } |
| 617 | if !slices.Equal(r.kc.deleted, []creds.Item{item}) || r.kc.has(item) { |
| 618 | t.Fatalf("deleted %+v", r.kc.deleted) |
| 619 | } |
| 620 | if !r.m.Held() || !slices.Equal(r.m.keychain.Residue(), []string{item.Service}) { |
| 621 | t.Fatal("released before a listing showed the item gone") |
| 622 | } |
| 623 | r.m.settle(r.ctx, false) |
| 624 | if r.m.Held() { |
| 625 | t.Fatal("held after a listing showed it gone") |
| 626 | } |
| 627 | }) |
| 628 | t.Run("a pre-existing item is untouched and refuses", func(t *testing.T) { |
| 629 | r := newDarwinRig(t) |
| 630 | left := creds.Item{Keychain: r.m.keychain.Login, Service: "Claude Code-credentials", Account: r.user} |
| 631 | r.kc.add(left) |
| 632 | c := r.connector() |
| 633 | if err := c.Accept(r.ctx, "f-connect-s1", wire.ConnectCommand{Connection: "s1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil { |
| 634 | t.Fatal(err) |
| 635 | } |
| 636 | if end := r.ended("s1"); end.Reason != "provider_refused" { |
| 637 | t.Fatalf("end %+v", end) |
| 638 | } |
| 639 | if len(r.pids()) != 0 || !r.kc.has(left) || len(r.kc.deleted) != 0 { |
| 640 | t.Fatalf("pids %v deleted %v", r.pids(), r.kc.deleted) |
| 641 | } |
| 642 | if !r.m.Held() || !slices.Equal(r.m.keychain.Residue(), []string{"Claude Code-credentials"}) { |
| 643 | t.Fatal("not held, or not named") |
| 644 | } |
| 645 | // A pasted token is refused too, before anything is written. |
| 646 | _, end := r.paste(c, "c2", fakeclaude.Token("a@example.com")) |
| 647 | if end.Reason != "provider_refused" || r.seals("c2") != 0 { |
| 648 | t.Fatalf("a pasted token with a Claude Code item there: %+v", end) |
| 649 | } |
| 650 | }) |
| 651 | t.Run("a failed delete keeps the flag", func(t *testing.T) { |
| 652 | r := newDarwinRig(t) |
| 653 | r.kc.set(true) |
| 654 | c := r.connector() |
| 655 | link, _ := r.signIn(c, "s1") |
| 656 | item := r.own(r.signInDir()) |
| 657 | r.kc.add(item) |
| 658 | r.codeIn(c, "s1", link, "a@example.com") |
| 659 | if end := r.ended("s1"); end.Reason != "provider_refused" { |
| 660 | t.Fatalf("end %+v", end) |
| 661 | } |
| 662 | if !r.kc.has(item) || !r.m.Held() { |
| 663 | t.Fatal("a failed delete released the hold") |
| 664 | } |
| 665 | r.m.settle(r.ctx, false) |
| 666 | if !r.m.Held() { |
| 667 | t.Fatal("released while the item is still there") |
| 668 | } |
| 669 | }) |
| 670 | t.Run("an unrelated item created at the same time is left, the hold kept", func(t *testing.T) { |
| 671 | r := newDarwinRig(t) |
| 672 | c := r.connector() |
| 673 | link, _ := r.signIn(c, "s1") |
| 674 | item := r.own(r.signInDir()) |
| 675 | other := creds.Item{Keychain: r.m.keychain.Login, Service: "Other App", Account: r.user} |
| 676 | r.kc.add(item, other) |
| 677 | r.codeIn(c, "s1", link, "a@example.com") |
| 678 | if end := r.ended("s1"); end.Reason != "provider_refused" { |
| 679 | t.Fatalf("end %+v", end) |
| 680 | } |
| 681 | if r.kc.has(item) || !r.kc.has(other) || slices.Contains(r.kc.deleted, other) { |
| 682 | t.Fatalf("deleted %+v", r.kc.deleted) |
| 683 | } |
| 684 | if !r.m.Held() || !slices.Equal(r.m.keychain.Residue(), []string{"Other App"}) { |
| 685 | t.Fatal("the unrelated item does not hold") |
| 686 | } |
| 687 | }) |
| 688 | // Only the login keychain is the watch's (fix round 1, #2): one |
| 689 | // elsewhere is never touched. |
| 690 | t.Run("matching attributes in another keychain are left alone", func(t *testing.T) { |
| 691 | r := newDarwinRig(t) |
| 692 | c := r.connector() |
| 693 | link, _ := r.signIn(c, "s1") |
| 694 | elsewhere := r.own(r.signInDir()) |
| 695 | elsewhere.Keychain = filepath.Join(r.dir, "Library", "Keychains", "other.keychain-db") |
| 696 | r.kc.add(elsewhere) |
| 697 | r.codeIn(c, "s1", link, "a@example.com") |
| 698 | r.ended("s1") |
| 699 | if !r.kc.has(elsewhere) || len(r.kc.deleted) != 0 { |
| 700 | t.Fatalf("deleted %+v", r.kc.deleted) |
| 701 | } |
| 702 | for _, kc := range r.kc.asked { |
| 703 | if kc != r.m.keychain.Login { |
| 704 | t.Fatalf("listed %q", kc) |
| 705 | } |
| 706 | } |
| 707 | }) |
| 708 | t.Run("restart", func(t *testing.T) { |
| 709 | r := newDarwinRig(t) |
| 710 | // A watch the runner never finished: its list written, its CLI |
| 711 | // gone with the process, an item of its own made meanwhile. |
| 712 | crashed := filepath.Join(r.cfg.ScratchRoot, "homes", "signin-crashed") |
| 713 | if err := r.m.keychain.Before(r.ctx, "signin-crashed", crashed); err != nil { |
| 714 | t.Fatal(err) |
| 715 | } |
| 716 | r.kc.set(true) |
| 717 | c := r.connector() |
| 718 | link, _ := r.signIn(c, "s1") |
| 719 | item := r.own(r.signInDir()) |
| 720 | r.kc.add(item) |
| 721 | r.codeIn(c, "s1", link, "a@example.com") |
| 722 | r.ended("s1") |
| 723 | left := r.own(crashed) |
| 724 | r.kc.add(left) |
| 725 | // The same runner after a restart: the hold is on disk, and the |
| 726 | // restart settles both now that deleting works. |
| 727 | again := darwinRigAt(t, r.dir) |
| 728 | again.kc = r.kc |
| 729 | again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete |
| 730 | if !again.m.Held() { |
| 731 | t.Fatal("the hold did not survive the restart") |
| 732 | } |
| 733 | r.kc.set(false) |
| 734 | again.connector() |
| 735 | if again.m.Held() || r.kc.has(item) || r.kc.has(left) { |
| 736 | t.Fatalf("after the restart: held=%v %v", again.m.Held(), again.m.keychain.Residue()) |
| 737 | } |
| 738 | }) |
| 739 | } |
| 740 | |
| 741 | // TestTaintBlocksConnections: a tainted runner (its own state, or the |
| 742 | // instance's word) stores no token, starts no sign-in, uses no token, |
| 743 | // and its Engineering status says tainted. |
| 744 | func TestTaintBlocksConnections(t *testing.T) { |
| 745 | t.Run("in its own state", func(t *testing.T) { |
| 746 | dir := shortDir(t) |
| 747 | if err := os.MkdirAll(filepath.Join(dir, "state"), 0o700); err != nil { |
| 748 | t.Fatal(err) |
| 749 | } |
| 750 | if err := os.WriteFile(filepath.Join(dir, "state", "tainted"), []byte("2026-11-11T00:00:00Z\n"), 0o600); err != nil { |
| 751 | t.Fatal(err) |
| 752 | } |
| 753 | r := darwinRigAt(t, dir) |
| 754 | c := r.connector() |
| 755 | token := fakeclaude.Token("a@example.com") |
| 756 | _, end := r.paste(c, "c1", token) |
| 757 | if end.State != wire.ConnError || end.Reason != "provider_refused" || r.seals("c1") != 0 || len(r.launches()) != 0 { |
| 758 | t.Fatalf("a tainted runner kept a token: %+v seals=%d launches=%d", end, r.seals("c1"), len(r.launches())) |
| 759 | } |
| 760 | r.onlyIn(token, "") |
| 761 | if err := c.Accept(r.ctx, "f-connect-s1", wire.ConnectCommand{Connection: "s1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil { |
| 762 | t.Fatal(err) |
| 763 | } |
| 764 | if end := r.ended("s1"); end.Reason != "provider_refused" || len(r.pids()) != 0 { |
| 765 | t.Fatalf("a tainted runner signed in: %+v", end) |
| 766 | } |
| 767 | if s := r.m.status(); s == nil || s.State != wire.EngineeringTainted { |
| 768 | t.Fatalf("status %+v", s) |
| 769 | } |
| 770 | }) |
| 771 | t.Run("by the instance, after a connection was made", func(t *testing.T) { |
| 772 | r := newDarwinRig(t) |
| 773 | home, _ := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com")) |
| 774 | b, _ := r.binding(filepath.Base(home)) |
| 775 | before := len(r.launches()) |
| 776 | r.m.taint.Set() |
| 777 | if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errTainted) || len(r.launches()) != before { |
| 778 | t.Fatalf("a tainted runner used its token: %v", err) |
| 779 | } |
| 780 | if s := r.m.status(); s == nil || s.State != wire.EngineeringTainted { |
| 781 | t.Fatalf("status %+v", s) |
| 782 | } |
| 783 | }) |
| 784 | } |
| 785 | |
| 786 | // TestHomeGuardChangedBetweenStoreAndUse: the home guard is read again |
| 787 | // before every use: a home opened after the token was stored stops its |
| 788 | // use, and closing it again lets it go on. |
| 789 | func TestHomeGuardChangedBetweenStoreAndUse(t *testing.T) { |
| 790 | r := newDarwinRig(t) |
| 791 | c := r.connector() |
| 792 | home, _ := r.paste(c, "c1", fakeclaude.Token("a@example.com")) |
| 793 | b, ok := r.binding(filepath.Base(home)) |
| 794 | if !ok || r.m.status() != nil { |
| 795 | t.Fatalf("not connected, or not ready: %+v", r.m.status()) |
| 796 | } |
| 797 | if err := os.Chmod(r.dir, 0o750); err != nil { |
| 798 | t.Fatal(err) |
| 799 | } |
| 800 | before := len(r.launches()) |
| 801 | var open *homeOpen |
| 802 | if _, err := r.opts.CheckToken(r.ctx, b); !errors.As(err, &open) || open.r.Fix() != "chmod 700 ~" || len(r.launches()) != before { |
| 803 | t.Fatalf("a check with the home open: %v", err) |
| 804 | } |
| 805 | if s := r.m.status(); s == nil || s.State != wire.EngineeringHomeOpen || s.Reason != creds.CodeHomeMode { |
| 806 | t.Fatalf("status %+v", s) |
| 807 | } |
| 808 | // Nor is a new token stored. |
| 809 | if _, end := r.paste(c, "c2", fakeclaude.Token("b@example.com")); end.Reason != "provider_refused" || r.seals("c2") != 0 { |
| 810 | t.Fatalf("stored with the home open: %+v", end) |
| 811 | } |
| 812 | if err := os.Chmod(r.dir, 0o700); err != nil { |
| 813 | t.Fatal(err) |
| 814 | } |
| 815 | if _, err := r.opts.CheckToken(r.ctx, b); err != nil { |
| 816 | t.Fatalf("closed again: %v", err) |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | // TestMacCapsSayTainted: the hello's Engineering status comes from the |
| 821 | // guards. |
| 822 | func TestMacCapsSayTainted(t *testing.T) { |
| 823 | r := newDarwinRig(t) |
| 824 | h := &macHost{creds: r.m, taint: r.m.taint} |
| 825 | r.m.taint.Set() |
| 826 | caps := wire.Capabilities{} |
| 827 | h.credentialCaps(r.ctx, &caps) |
| 828 | if caps.Engineering == nil || caps.Engineering.State != wire.EngineeringTainted || wire.ValidCapabilities(caps) != nil { |
| 829 | t.Fatalf("caps %+v", caps.Engineering) |
| 830 | } |
| 831 | } |
| 832 | |