//go:build testbuild package thin import ( "context" "errors" "os" "os/exec" "path/filepath" "strconv" "strings" "syscall" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "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/wire" "golang.org/x/sys/unix" ) // Task 10 fix round 1 (Astra round 1): the Keychain watch around the // token check and auth status (#3), the termination proof of a check // (#4), and direct tests of every guard the thin wiring added (#6). // connected is a rig with one healthy pasted-token connection: its // binding and token-home binding. func connected(t *testing.T, r *darwinRig, token string) (b, home string) { t.Helper() h, end := r.paste(r.connector(), "c1", token) if end.State != wire.ConnHealthy { t.Fatalf("not connected: %+v", end) } return filepath.Base(h), h } // statusBinding is the token home as auth status reads it. func statusBinding(local, home string) provider.Binding { return provider.Binding{ID: local, Home: home, Provider: wire.ProviderClaude, Token: true} } // lingering steers the next launch whose first argument is arg to leave // a child that ignores SIGTERM; its end then cannot be proven within a // short Settle. The child is killed at the test's end. func (r *darwinRig) lingering(t *testing.T, arg string) { t.Helper() r.m.exec.Settle, r.m.exec.Grace = 500*time.Millisecond, time.Minute if err := os.WriteFile(filepath.Join(r.dir, "linger"), []byte(arg), 0o600); err != nil { t.Fatal(err) } t.Cleanup(func() { if raw, err := os.ReadFile(filepath.Join(r.dir, "linger.pid")); err == nil { if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil { _ = syscall.Kill(pid, syscall.SIGKILL) } } }) } // TestDarwinCheckKeychainWatch (#3): the token check and auth status are // watched as the sign-in is: an item a launch leaves refuses it, its own // is deleted, anything else holds; a cancelled check is looked at too, // and a crash is settled at the restart. func TestDarwinCheckKeychainWatch(t *testing.T) { t.Run("the check's own item refuses it and is deleted", func(t *testing.T) { r := newDarwinRig(t) local, _ := connected(t, r, fakeclaude.Token("a@example.com")) r.creating("-p ", r.own) b, _ := r.binding(local) _, err := r.opts.CheckToken(r.ctx, b) if !errors.Is(err, errKeychain) || len(r.kc.deleted) != 1 || r.m.Held() { t.Fatalf("check: %v deleted %+v held=%v", err, r.kc.deleted, r.m.Held()) } if !strings.HasPrefix(r.kc.deleted[0].Service, "Claude Code-credentials-") || r.kc.deleted[0].Keychain != r.m.keychain.Login { t.Fatalf("deleted %+v", r.kc.deleted) } }) t.Run("an unrelated item during the check holds", func(t *testing.T) { r := newDarwinRig(t) local, _ := connected(t, r, fakeclaude.Token("a@example.com")) r.creating("-p ", func(string) creds.Item { return creds.Item{Keychain: r.m.keychain.Login, Service: "Other App", Account: r.user} }) b, _ := r.binding(local) if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errKeychain) || len(r.kc.deleted) != 0 || !r.m.Held() { t.Fatalf("check: %v deleted %+v held=%v", err, r.kc.deleted, r.m.Held()) } }) t.Run("auth status's own item refuses the connection", func(t *testing.T) { r := newDarwinRig(t) r.creating("auth status", r.own) _, end := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com")) if end.Reason != "provider_refused" || len(r.kc.deleted) != 1 || r.m.Held() { t.Fatalf("end %+v deleted %+v held=%v", end, r.kc.deleted, r.m.Held()) } }) t.Run("auth status called alone is watched", func(t *testing.T) { r := newDarwinRig(t) local, home := connected(t, r, fakeclaude.Token("a@example.com")) r.creating("auth status", r.own) if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.Is(err, errKeychain) || len(r.kc.deleted) != 1 { t.Fatalf("auth status: %v deleted %+v", err, r.kc.deleted) } }) t.Run("a cancelled check is looked at", func(t *testing.T) { r := newDarwinRig(t) local, _ := connected(t, r, fakeclaude.Token("a@example.com")) r.creating("-p ", r.own) if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil { t.Fatal(err) } b, _ := r.binding(local) ctx, cancel := context.WithCancel(r.ctx) done := make(chan error, 1) go func() { _, err := r.opts.CheckToken(ctx, b); done <- err }() waitPid(t, filepath.Join(r.dir, "hang.pid")) cancel() <-done if len(r.kc.deleted) != 1 || r.m.Held() { t.Fatalf("after the cancel: deleted %+v held=%v", r.kc.deleted, r.m.Held()) } }) t.Run("a crashed check's watch is held until a reboot", func(t *testing.T) { r := newDarwinRig(t) local, _ := connected(t, r, fakeclaude.Token("a@example.com")) if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil { t.Fatal(err) } helper := exec.Command(os.Args[0], "-test.run=^TestDarwinTokenCheckCrashHelper$", "-test.count=1") helper.Env = append(os.Environ(), "EQUIPO_DARWIN_CRASH_DIR="+r.dir, "EQUIPO_DARWIN_CRASH_LOCAL="+local) if err := helper.Start(); err != nil { t.Fatal(err) } pid := waitPid(t, filepath.Join(r.dir, "hang.pid")) _ = helper.Process.Kill() _ = helper.Wait() if !r.m.Held() { t.Fatal("the dead runner's check left no watch") } // What its CLI stored meanwhile (its launch is on disk already). r.creating("-p ", r.own) r.kc.mu.Lock() delete(r.kc.created, pid) r.kc.mu.Unlock() // The restart cannot prove it over (fix round 2): held. r.connector() if !r.m.Held() || len(r.kc.deleted) != 0 { t.Fatalf("after a restart without a reboot: held=%v deleted %+v", r.m.Held(), r.kc.deleted) } r.rebooted(t, pid) r.connector() if r.m.Held() || len(r.kc.deleted) != 1 { t.Fatalf("after a reboot: held=%v deleted %+v", r.m.Held(), r.kc.deleted) } }) } // TestDarwinCheckUnprovenIsNotSuccess (#4): a check that answered but // whose end cannot be proven fails with mac.ErrUnproven: the profile is // not read, and the watch and the turn's record stay for recovery. func TestDarwinCheckUnprovenIsNotSuccess(t *testing.T) { r := newDarwinRig(t) local, _ := connected(t, r, fakeclaude.Token("")) b, _ := r.binding(local) clock := time.Now() fake := newFakeProfile(t, "") fake.answer(200, "a@example.com") r.opts.Profile = fake.reader(&clock) r.lingering(t, "-p") _, err := r.opts.CheckToken(r.ctx, b) if !errors.Is(err, mac.ErrUnproven) { t.Fatalf("an unproven check: %v", err) } if fake.count() != 0 { t.Fatal("the profile was read after an unproven check") } if !r.m.Held() { t.Fatal("the check's watch was dropped with its end unproven") } if _, err := os.Stat(filepath.Join(r.cfg.StateDir, "mac-gate.lock.turn")); err != nil { t.Fatalf("the turn's record was dropped: %v", err) } // Control: once a restart proves it over, the check reads the // profile. os.Remove(filepath.Join(r.dir, "linger")) again := darwinRigAt(t, r.dir) again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete again.opts.Profile = fake.reader(&clock) again.connector() if _, err := again.opts.CheckToken(again.ctx, b); err != nil || fake.count() != 1 { t.Fatalf("a proven check: %v, %d profile reads", err, fake.count()) } t.Run("auth status", func(t *testing.T) { r := newDarwinRig(t) local, home := connected(t, r, fakeclaude.Token("a@example.com")) r.lingering(t, "auth") if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.Is(err, mac.ErrUnproven) || !r.m.Held() || len(unprovenOf(r.m)) != 1 { t.Fatalf("an unproven auth status: %v held=%v unproven=%v", err, r.m.Held(), unprovenOf(r.m)) } }) } // TestDarwinAuthStatusGates (#6): auth status, which madeToken calls on // its own, refuses a tainted runner and an open home before it starts // anything. func TestDarwinAuthStatusGates(t *testing.T) { t.Run("tainted", func(t *testing.T) { r := newDarwinRig(t) local, home := connected(t, r, fakeclaude.Token("a@example.com")) before := len(r.launches()) r.m.taint.Set() if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.Is(err, errTainted) || len(r.launches()) != before { t.Fatalf("a tainted auth status: %v", err) } }) t.Run("home open", func(t *testing.T) { r := newDarwinRig(t) local, home := connected(t, r, fakeclaude.Token("a@example.com")) before := len(r.launches()) if err := os.Chmod(r.dir, 0o750); err != nil { t.Fatal(err) } var open *homeOpen if _, err := r.m.authStatus(r.ctx, statusBinding(local, home)); !errors.As(err, &open) || len(r.launches()) != before { t.Fatalf("auth status with the home open: %v", err) } }) t.Run("not a token", func(t *testing.T) { r := newDarwinRig(t) if _, err := r.m.authStatus(r.ctx, provider.Binding{ID: "x", Home: r.root, Provider: wire.ProviderClaude}); !errors.Is(err, provider.ErrLoginUnavailable) { t.Fatalf("a subscription home: %v", err) } }) } // TestDarwinCheckRefusesBeforeTheLease (#6): the check's own gate // refuses before the account's lease is opened: with the account busy, // a tainted runner still says tainted at once. func TestDarwinCheckRefusesBeforeTheLease(t *testing.T) { r := newDarwinRig(t) local, home := connected(t, r, fakeclaude.Token("a@example.com")) b, _ := r.binding(local) lock, err := os.Open(home) if err != nil { t.Fatal(err) } defer lock.Close() if err := unix.Flock(int(lock.Fd()), unix.LOCK_EX); err != nil { t.Fatal(err) } r.m.taint.Set() start := time.Now() if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errTainted) || time.Since(start) > 2*time.Second { t.Fatalf("a tainted check with the account busy: %v after %s", err, time.Since(start)) } } // TestDarwinStoreWaitsForTheTurn (#6): a token is stored only in the // Mac's turn: while another operation holds it, the delivery waits, then // fails to be sent again, and nothing is written. func TestDarwinStoreWaitsForTheTurn(t *testing.T) { r := newDarwinRig(t) was := tokenStoreWait tokenStoreWait = 300 * time.Millisecond defer func() { tokenStoreWait = was }() c := r.connector() r.connect(c, "c1") u, ok := r.m.turns.TryTake(mac.OpWarm) if !ok { t.Fatal("the turn is busy") } cmd := r.sealed("c1", fakeclaude.Token("a@example.com"), nil) if r.deliver(c, "f-c1", cmd) || r.seals("c1") != 0 { t.Fatal("stored while another operation held the turn") } u.Give() if !r.deliver(c, "f-c1", cmd) || r.ended("c1").State != wire.ConnHealthy { t.Fatal("the resend after the turn was free did not connect") } } // TestDarwinSignInUnprovenKeepsTheWatch (#6): a sign-in whose CLI's end // cannot be proven keeps its watch (and its attempt, for the restart). func TestDarwinSignInUnprovenKeepsTheWatch(t *testing.T) { r := newDarwinRig(t) r.lingering(t, "setup-token") c := r.connector() r.signIn(c, "s1") if err := c.Cancel(r.ctx, "f-cancel-s1", wire.CancelConnectCommand{Connection: "s1", Person: connPerson}); err != nil { t.Fatal(err) } r.waitFor(func() bool { return r.turnFree() }, "the sign-in to stop") var state string _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id='s1'").Scan(&state) if !r.m.Held() || state != "running" || len(unprovenOf(r.m)) != 1 { t.Fatalf("an unproven sign-in: held=%v state=%s", r.m.Held(), state) } } // TestDarwinSignInRecoveredAtRestart (#6): a sign-in left running by a // dead runner has its CLI killed by its record at the restart, then // ends runner_offline. func TestDarwinSignInRecoveredAtRestart(t *testing.T) { r := newDarwinRig(t) marker := "signin-left" cmd := exec.Command("/bin/sleep", "600") cmd.Env = []string{"EQUIPO_ATTEMPT=" + marker} cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true} if err := cmd.Start(); err != nil { t.Fatal(err) } go func() { _ = cmd.Wait() }() defer func() { _ = cmd.Process.Kill() }() if _, err := r.state.db.Exec("INSERT INTO connect_attempts(id, person, provider, state, kind, namespace, created_at) VALUES(?,?,?,?,?,?,?)", "s1", connPerson, wire.ProviderClaude, "running", wire.KindSubscription, mac.RecordID(cmd.Process.Pid, marker), now()); err != nil { t.Fatal(err) } r.connector() if end := r.ended("s1"); end.Reason != "runner_offline" { t.Fatalf("end %+v", end) } r.waitFor(func() bool { return !pidAlive(cmd.Process.Pid) }, "the left CLI to be gone") } // TestDarwinStartRefusesABadToken (#6): the descriptor carries only a // token that fits one: no NUL, CR or LF, not empty, bounded. func TestDarwinStartRefusesABadToken(t *testing.T) { r := newDarwinRig(t) u, err := r.m.turns.Take(r.ctx, mac.OpTokenCheck) if err != nil { t.Fatal(err) } defer u.Give() dir, marker, err := r.m.place("status-") if err != nil { t.Fatal(err) } for _, tok := range [][]byte{{}, []byte("sk-ant\nx"), []byte("sk\x00"), make([]byte, mac.MaxToken+1)} { if _, err := r.m.start(u.Context(r.ctx), dir, marker, mac.Command{Env: r.m.env(dir, marker, true)}, tok, func(string) error { return nil }, "auth", "status", "--json"); !errors.Is(err, provider.ErrPolicy) { t.Fatalf("token %q: %v", tok, err) } } if len(r.launches()) != 0 { t.Fatal("a bad token started the CLI") } } // TestMacCapsSettleTheKeychain (#6): the hourly capability gathering // looks again for what the Keychain watch found, and lets go once it is // gone. func TestMacCapsSettleTheKeychain(t *testing.T) { r := newDarwinRig(t) h := &macHost{creds: r.m, taint: r.m.taint} other := creds.Item{Keychain: r.m.keychain.Login, Service: "Other App", Account: r.user} if err := r.m.keychain.Before(r.ctx, "signin-1", filepath.Join(r.cfg.ScratchRoot, "homes", "signin-1")); err != nil { t.Fatal(err) } r.kc.add(other) if _, err := r.m.keychain.After(r.ctx, "signin-1"); err != nil || !r.m.Held() { t.Fatalf("not held: %v", err) } r.kc.mu.Lock() r.kc.items = nil r.kc.mu.Unlock() caps := wire.Capabilities{} h.credentialCaps(r.ctx, &caps) if r.m.Held() { t.Fatal("the gathering did not look again") } } // TestMacKeychainListsLoginByPath (#2): the runner lists its login // keychain by its path, and refuses to decide when it is not there. func TestMacKeychainListsLoginByPath(t *testing.T) { dir := shortDir(t) args := filepath.Join(dir, "args") security := filepath.Join(dir, "security") login := filepath.Join(dir, "login.keychain-db") script := "#!/bin/sh\necho \"$@\" > " + args + "\nprintf 'keychain: \"%s\"\\nclass: \"genp\"\\nattributes:\\n \"acct\"=\"u\"\\n \"svce\"=\"Other App\"\\n' \"$2\"\n" if err := os.WriteFile(security, []byte(script), 0o700); err != nil { t.Fatal(err) } was, wasOn := macSecurity, macKeychains macSecurity, macKeychains = security, true defer func() { macSecurity, macKeychains = was, wasOn }() h := &macHost{} if _, err := h.keychainList(context.Background(), login); err == nil { t.Fatal("listed a login keychain that is not there") } if err := os.WriteFile(login, nil, 0o600); err != nil { t.Fatal(err) } items, err := h.keychainList(context.Background(), login) raw, _ := os.ReadFile(args) if err != nil || strings.TrimSpace(string(raw)) != "dump-keychain "+login || len(items) != 1 || items[0].Keychain != login { t.Fatalf("listed %q: %+v %v", raw, items, err) } }