//go:build testbuild
package thin
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"log/slog"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"syscall"
"testing"
"time"
"amadan.net/oficina/equipo/internal/fakeclaude"
"amadan.net/oficina/equipo/internal/runner"
"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's Claude credential (maccreds.go) on Linux: the pinned "CLI" is
// a shell script pinned by its own digest, provisioned and hashed before
// every start exactly as the real one is (ClaudeCLI.Launch), which
// records its argv, environment and directory and then runs the fake
// CLI; the executor and the turns are package mac's own; the Keychain is
// a fake listing. Test build only: mac.PinnedForTest exists only there.
// launchScript is the pinned stand-in: %[1]s is the rig's directory.
// With
/hang it never answers a check (-p): it says its pid and
// sleeps, as a hung CLI would. With /linger naming its first
// argument it leaves a child that ignores SIGTERM, so its end cannot be
// proven within a short Settle.
const launchScript = `#!/bin/sh
d=%[1]s
env > "$d/bin/launch.$$.env"
pwd > "$d/bin/launch.$$.cwd"
echo "$*" > "$d/bin/launch.$$.argv"
[ -f "$CLAUDE_CONFIG_DIR/equipo-settings.json" ] && cp "$CLAUDE_CONFIG_DIR/equipo-settings.json" "$d/bin/launch.$$.settings"
if [ "$1" = "-p" ] && [ -e "$d/hang" ]; then echo $$ > "$d/hang.pid"; exec /bin/sleep 600; fi
if [ -e "$d/linger" ] && [ "$1" = "$(cat "$d/linger")" ]; then (trap "" TERM HUP; exec /bin/sleep 5) & echo $! > "$d/linger.pid"; fi
exec "$d/bin/claude" "$@"
`
// keychainFake is the runner user's Keychains as security lists them.
type keychainFake struct {
mu sync.Mutex
items []creds.Item
lists int
deleted []creds.Item
fail bool
// stale keeps a deleted item in the next listing.
stale bool
ghost []creds.Item
// started, when set, says whether the CLI has started; startedAt is
// what it said at the first listing.
started func() bool
startedAt []bool
// asked is each keychain listed. create, when set, is what a CLI
// launch stored in the login keychain (it runs once per launch, at
// the first listing after it).
asked []string
create func(launched) []creds.Item
created map[int]bool
// appear, when set, is asked at each listing; what it returns is
// stored once (a write that comes later).
appear func() []creds.Item
r *darwinRig
}
func (f *keychainFake) list(_ context.Context, keychain string) ([]creds.Item, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.lists++
f.asked = append(f.asked, keychain)
if f.started != nil {
f.startedAt = append(f.startedAt, f.started())
}
if f.create != nil {
if f.created == nil {
f.created = map[int]bool{}
}
for _, l := range f.r.launches() {
if !f.created[l.pid] {
f.created[l.pid] = true
f.items = append(f.items, f.create(l)...)
}
}
}
if f.appear != nil {
if more := f.appear(); len(more) > 0 {
f.items, f.appear = append(f.items, more...), nil
}
}
var out []creds.Item
for _, i := range append(slices.Clone(f.items), f.ghost...) {
if i.Keychain == keychain {
out = append(out, i)
}
}
f.ghost = nil
return out, nil
}
// creating makes each later launch whose argv starts with prefix store
// item(its CLAUDE_CONFIG_DIR), as a CLI writing to the Keychain would.
func (r *darwinRig) creating(prefix string, item func(dir string) creds.Item) {
f := r.kc
f.mu.Lock()
defer f.mu.Unlock()
f.created = map[int]bool{}
for _, l := range r.launches() {
f.created[l.pid] = true
}
f.create = func(l launched) []creds.Item {
if !strings.HasPrefix(l.argv, prefix) {
return nil
}
return []creds.Item{item(l.env["CLAUDE_CONFIG_DIR"])}
}
}
func (f *keychainFake) delete(_ context.Context, i creds.Item) error {
f.mu.Lock()
defer f.mu.Unlock()
f.deleted = append(f.deleted, i)
n := slices.Index(f.items, i)
if f.fail || n < 0 {
return errors.New("security: The specified item could not be found in the keychain.")
}
f.items = slices.Delete(f.items, n, n+1)
if f.stale {
f.ghost = append(f.ghost, i)
}
return nil
}
func (f *keychainFake) add(i ...creds.Item) {
f.mu.Lock()
defer f.mu.Unlock()
f.items = append(f.items, i...)
}
func (f *keychainFake) has(i creds.Item) bool {
f.mu.Lock()
defer f.mu.Unlock()
return slices.Contains(f.items, i)
}
func (f *keychainFake) set(fail bool) {
f.mu.Lock()
defer f.mu.Unlock()
f.fail = fail
}
// darwinRig is a token rig with a Mac's credential operations over it.
type darwinRig struct {
*tokenRig
m *macCreds
kc *keychainFake
opts ClaudeOptions
user string
mu sync.Mutex
// checks is what each real check (Conns.Verify) returned.
checks []checkSeen
}
type checkSeen struct {
check TokenCheck
err error
}
// shortDir is a private directory with a short path: a tool socket's
// path must fit sun_path.
func shortDir(t *testing.T) string {
t.Helper()
dir, err := os.MkdirTemp("", "dk")
if err == nil {
dir, err = filepath.EvalSymlinks(dir)
}
if err == nil {
err = os.Chmod(dir, 0o700)
}
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
return dir
}
func newDarwinRig(t *testing.T) *darwinRig { return darwinRigAt(t, shortDir(t)) }
// darwinRigAt is the rig in dir (the home); a second rig in the same
// dir is the same runner after a restart.
func darwinRigAt(t *testing.T, dir string) *darwinRig {
t.Helper()
r := &darwinRig{tokenRig: newTokenRigAt(t, dir), kc: &keychainFake{}}
r.kc.r = r
r.cfg.StateDir = filepath.Join(dir, "state")
// A Mac has no Linux CLI path: only the pinned CLI, by Launch.
r.cfg.ClaudePath = ""
proxy := filepath.Join(dir, "bin", "equipo-tool-proxy")
if _, err := os.Lstat(proxy); err != nil {
self, _ := os.Executable()
if err := os.Symlink(self, proxy); err != nil {
t.Fatal(err)
}
}
r.cfg.Executable = proxy
install := filepath.Join(dir, "lib")
if err := os.MkdirAll(install, 0o700); err != nil {
t.Fatal(err)
}
script := fmt.Sprintf(launchScript, dir)
sum := sha256.Sum256([]byte(script))
cli := mac.PinnedForTest(mac.NewClaudeCLI(dir, install), hex.EncodeToString(sum[:]))
if err := cli.Provision(context.Background(), func(context.Context, string) (io.ReadCloser, error) {
return io.NopCloser(strings.NewReader(script)), nil
}); err != nil {
t.Fatal(err)
}
out, err := exec.Command("/usr/bin/id", "-un").Output()
if err != nil {
t.Fatal(err)
}
r.user = strings.TrimSpace(string(out))
turns := mac.NewTurns(filepath.Join(r.cfg.StateDir, "mac-gate.lock"))
m := &macCreds{turns: turns, exec: &mac.Executor{Turns: turns, Settle: 10 * time.Second}, cli: cli,
paths: mac.Paths{Home: dir, StateDir: r.cfg.StateDir, AccountsRoot: r.root, SessionRoot: filepath.Join(dir, "sessions"), InstallDir: install},
configDir: filepath.Join(dir, "config"), runner: proxy, scratch: r.cfg.ScratchRoot, taint: loadTaint(filepath.Join(r.cfg.StateDir, "tainted")),
user: r.user, uid: os.Getuid(), log: slog.New(slog.NewTextHandler(&r.logs, nil))}
m.fact = func(p string) (creds.Fact, error) { return creds.Read(p, nil) }
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}
r.m = m
r.opts = ClaudeOptions{Runner: r.cfg, State: r.state, Mac: m, LockWait: 5 * time.Second}
r.conns.Runner = r.cfg
r.conns.Verify = func(ctx context.Context, b runner.AccountBinding) error {
c, err := r.opts.CheckToken(ctx, b)
r.mu.Lock()
r.checks = append(r.checks, checkSeen{c, err})
r.mu.Unlock()
return err
}
return r
}
// connector is a Mac worker's connector: no terminal of its own, the
// Mac's credential operations.
func (r *darwinRig) connector() *Connector {
keys := r.keys
limit := time.Hour
if r.limit > 0 {
limit = r.limit
}
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}
c.spawn = func(f func()) { f() }
if err := c.Start(r.ctx); err != nil {
r.t.Fatal(err)
}
return c
}
// launches is every start of the pinned CLI so far: argv, environment
// and directory, by pid.
type launched struct {
pid int
argv, cwd string
env map[string]string
}
func (r *darwinRig) launches() []launched {
var out []launched
matches, _ := filepath.Glob(filepath.Join(r.dir, "bin", "launch.*.argv"))
for _, path := range matches {
pid, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(filepath.Base(path), "launch."), ".argv"))
argv, _ := os.ReadFile(path)
cwd, _ := os.ReadFile(strings.TrimSuffix(path, ".argv") + ".cwd")
l := launched{pid: pid, argv: strings.TrimSpace(string(argv)), cwd: strings.TrimSpace(string(cwd)), env: map[string]string{}}
raw, _ := os.ReadFile(strings.TrimSuffix(path, ".argv") + ".env")
for _, line := range strings.Split(string(raw), "\n") {
if k, v, ok := strings.Cut(line, "="); ok {
l.env[k] = v
}
}
out = append(out, l)
}
return out
}
// onlyIn fails if token is in any file under the rig's directory but
// home's token file ("" for none), or in the runner's log.
func (r *darwinRig) onlyIn(token, home string) {
r.t.Helper()
_ = filepath.WalkDir(r.dir, func(path string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() || path == filepath.Join(home, provider.TokenFile) || filepath.Dir(path) == filepath.Join(r.dir, "bin") && d.Name() == "claude" {
return nil
}
if raw, _ := os.ReadFile(path); strings.Contains(string(raw), token) {
r.t.Fatalf("the token is in %s", path)
}
return nil
})
if strings.Contains(r.logs.String(), token) {
r.t.Fatal("the token is in the runner's log")
}
}
// lastCheck is the last real check's result.
func (r *darwinRig) lastCheck() checkSeen {
r.mu.Lock()
defer r.mu.Unlock()
if len(r.checks) == 0 {
r.t.Fatal("no check ran")
}
return r.checks[len(r.checks)-1]
}
// turnFree: nothing holds the Mac's turn.
func (r *darwinRig) turnFree() bool {
u, ok := r.m.turns.TryTake(mac.OpWarm)
if ok {
u.Give()
}
return ok
}
// paste connects a pasted token on c and waits for the attempt's end.
func (r *darwinRig) paste(c *Connector, id, token string) (string, wire.ConnectionReport) {
r.t.Helper()
home := r.connect(c, id)
if !r.deliver(c, "f-"+id, r.sealed(id, token, nil)) {
r.t.Fatalf("delivery failed: %v", r.errs)
}
return home, r.ended(id)
}
func pidAlive(pid int) bool {
if syscall.Kill(pid, 0) != nil {
return false
}
raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat")
return err == nil && !strings.Contains(string(raw), ") Z ")
}
func waitPid(t *testing.T, path string) int {
t.Helper()
for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
if raw, err := os.ReadFile(path); err == nil {
if pid, err := strconv.Atoi(strings.TrimSpace(string(raw))); err == nil {
return pid
}
}
}
t.Fatal("the hung CLI never started")
return 0
}
// TestDarwinTokenCheck: the token check on a Mac, through the darwin
// launch with its check-only policy and the token by descriptor, gives
// Linux's outcomes, and a crash is settled by the next turn.
func TestDarwinTokenCheck(t *testing.T) {
t.Run("success", func(t *testing.T) {
r := newDarwinRig(t)
c := r.connector()
token := fakeclaude.Token("a@example.com")
home, _ := r.paste(c, "c1", token)
r.healthy("c1", home, token, "a@example.com")
if got := r.lastCheck(); got.err != nil || len(got.check.Rows) == 0 {
t.Fatalf("check %+v", got)
}
var check, status bool
for _, l := range r.launches() {
if v, ok := l.env["CLAUDE_CODE_OAUTH_TOKEN"]; ok {
t.Fatalf("the token was in the CLI's environment (%d chars)", len(v))
}
if l.env[macTokenFDEnv] != "3" || !strings.HasPrefix(l.env["CLAUDE_CONFIG_DIR"], filepath.Join(r.cfg.ScratchRoot, "homes")+"/") || l.env["PATH"] != claude.DarwinPath {
t.Fatalf("launch %d: %v", l.pid, l.env)
}
switch {
case l.argv == "auth status --json":
status = true
case strings.HasPrefix(l.argv, "-p "):
check = true
if !strings.Contains(l.argv, "--tools ") || !strings.HasPrefix(l.env[claude.DarwinMarkerEnv], "check-") || !strings.HasPrefix(l.cwd, r.cfg.ScratchRoot+"/check-") {
t.Fatalf("the check's launch: %q in %s, %v", l.argv, l.cwd, l.env)
}
}
}
if !check || !status {
t.Fatalf("launches %+v", r.launches())
}
r.onlyIn(token, home)
if !r.turnFree() {
t.Fatal("the check kept the Mac's turn")
}
})
t.Run("signed out", func(t *testing.T) {
r := newDarwinRig(t)
_, end := r.paste(r.connector(), "c1", "sk-ant-oat01-fake-zz-ok")
if end.State != wire.ConnError || end.Reason != "provider_refused" || !errors.Is(r.lastCheck().err, provider.ErrLoginRequired) {
t.Fatalf("end %+v check %+v", end, r.lastCheck())
}
})
t.Run("limited", func(t *testing.T) {
r := newDarwinRig(t)
token := fakeclaude.Token("spent-a@example.com")
home, _ := r.paste(r.connector(), "c1", token)
r.healthy("c1", home, token, "spent-a@example.com")
if got := r.lastCheck(); got.err != nil || got.check.Seen == nil || !got.check.Seen.Limited {
t.Fatalf("a spent account's check %+v", got)
}
})
t.Run("cancelled", func(t *testing.T) {
r := newDarwinRig(t)
home, _ := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com"))
b, ok := r.binding(filepath.Base(home))
if !ok {
t.Fatal("no binding")
}
if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { _, err := r.opts.CheckToken(ctx, b); done <- err }()
pid := waitPid(t, filepath.Join(r.dir, "hang.pid"))
cancel()
select {
case err := <-done:
if err == nil {
t.Fatal("a cancelled check answered")
}
case <-time.After(30 * time.Second):
t.Fatal("the cancelled check never returned")
}
if pidAlive(pid) || !r.turnFree() {
t.Fatalf("after the cancel: CLI alive=%v, turn free=%v", pidAlive(pid), r.turnFree())
}
})
t.Run("a crash then recovery", func(t *testing.T) {
r := newDarwinRig(t)
home, _ := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com"))
local := filepath.Base(home)
if err := os.WriteFile(filepath.Join(r.dir, "hang"), nil, 0o600); err != nil {
t.Fatal(err)
}
// Another runner process starts a check on the same Mac and dies
// (SIGKILL) while its CLI runs.
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 !pidAlive(pid) {
t.Fatal("the dead runner's CLI did not outlive it (nothing to recover)")
}
os.Remove(filepath.Join(r.dir, "hang"))
b, _ := r.binding(local)
// Its end can never be proven (its turn's record is incomplete):
// connections stay closed until the Mac has booted since (fix
// round 2).
if _, err := r.opts.CheckToken(context.Background(), b); !errors.Is(err, errCredentialUnproven) {
t.Fatalf("the check after the crash: %v", err)
}
// A reboot ends the dead runner's CLI with everything else.
r.rebooted(t, pid)
r.connector()
if _, err := r.opts.CheckToken(context.Background(), b); err != nil {
t.Fatalf("the check after a reboot: %v", err)
}
})
}
// TestDarwinTokenCheckCrashHelper is the runner process that dies in
// TestDarwinTokenCheck: it runs one check and is killed during it.
func TestDarwinTokenCheckCrashHelper(t *testing.T) {
dir := os.Getenv("EQUIPO_DARWIN_CRASH_DIR")
if dir == "" {
t.Skip("run by TestDarwinTokenCheck")
}
r := darwinRigAt(t, dir)
b, ok := r.binding(os.Getenv("EQUIPO_DARWIN_CRASH_LOCAL"))
if !ok {
t.Fatal("no binding")
}
_, _ = r.opts.CheckToken(context.Background(), b)
t.Fatal("the hung check returned")
}
// own is the item a sign-in's CLI would store for its config dir.
func (r *darwinRig) own(dir string) creds.Item {
return creds.Item{Keychain: r.m.keychain.Login, Service: creds.ServiceFor(dir), Account: r.user}
}
// signInDir is the running sign-in's CLAUDE_CONFIG_DIR.
func (r *darwinRig) signInDir() string {
r.t.Helper()
for _, l := range r.launches() {
if l.argv == "setup-token" {
return l.env["CLAUDE_CONFIG_DIR"]
}
}
r.t.Fatal("no sign-in launched")
return ""
}
// codeIn types the right code for email into the sign-in's card.
func (r *darwinRig) codeIn(c *Connector, id, link, email string) {
r.t.Helper()
if !r.deliver(c, "f-code-"+id, r.sealedCode(id, codeFor(link, email), 1, nil)) {
r.t.Fatalf("code delivery: %v", r.errs)
}
}
// TestDarwinSignIn: the sign-in on a Mac, in its turn, with its own
// config dir and the Keychain watched around it.
func TestDarwinSignIn(t *testing.T) {
t.Run("code delivered", func(t *testing.T) {
r := newDarwinRig(t)
wifi := creds.Item{Keychain: r.m.keychain.Login, Service: "Wi-Fi", Account: r.user}
r.kc.add(wifi)
r.kc.started = func() bool {
m, _ := filepath.Glob(filepath.Join(r.dir, "bin", "launch.*.argv"))
return len(m) > 0
}
c := r.connector()
link, home := r.signIn(c, "s1")
if !r.m.Held() || len(r.kc.startedAt) == 0 || r.kc.startedAt[0] {
t.Fatalf("the Keychain was not listed and held before the CLI started: %v", r.kc.startedAt)
}
if r.turnFree() {
t.Fatal("the sign-in's terminal is open outside the Mac's turn")
}
dir := r.signInDir()
for _, l := range r.launches() {
if l.argv != "setup-token" {
continue
}
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 {
t.Fatalf("the sign-in's environment: %v", l.env)
}
if _, ok := l.env["CLAUDE_CODE_OAUTH_TOKEN"]; ok {
t.Fatal("a token in the sign-in's environment")
}
}
r.codeIn(c, "s1", link, "a@example.com")
token := fakeclaude.Token("a@example.com")
r.healthy("s1", home, token, "a@example.com")
if r.m.Held() || !r.kc.has(wifi) || len(r.kc.deleted) != 0 {
t.Fatalf("held=%v after a clean sign-in; deleted %v", r.m.Held(), r.kc.deleted)
}
if _, err := os.Lstat(dir); !os.IsNotExist(err) {
t.Fatalf("the sign-in's config dir was left: %v", err)
}
if !r.turnFree() {
t.Fatal("the turn was kept")
}
r.onlyIn(token, home)
})
t.Run("timeout", func(t *testing.T) {
r := newDarwinRig(t)
r.limit = 2 * time.Second
c := r.connector()
r.signIn(c, "s1")
if end := r.ended("s1"); end.Reason != "timed_out" {
t.Fatalf("end %+v", end)
}
r.gone()
if r.m.Held() || !r.turnFree() {
t.Fatalf("after the time limit: held=%v turn free=%v", r.m.Held(), r.turnFree())
}
})
t.Run("cancel", func(t *testing.T) {
r := newDarwinRig(t)
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)
}
if end := r.ended("s1"); end.Reason != "cancelled" {
t.Fatalf("end %+v", end)
}
r.gone()
if r.m.Held() || !r.turnFree() {
t.Fatalf("after the cancel: held=%v turn free=%v", r.m.Held(), r.turnFree())
}
})
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) {
r := newDarwinRig(t)
r.kc.stale = true
c := r.connector()
link, home := r.signIn(c, "s1")
item := r.own(r.signInDir())
r.kc.add(item)
r.codeIn(c, "s1", link, "a@example.com")
end := r.ended("s1")
if end.State != wire.ConnError || end.Reason != "provider_refused" {
t.Fatalf("end %+v", end)
}
if _, ok := r.binding(filepath.Base(home)); ok || exists(home) {
t.Fatal("a refused sign-in kept its connection")
}
if !slices.Equal(r.kc.deleted, []creds.Item{item}) || r.kc.has(item) {
t.Fatalf("deleted %+v", r.kc.deleted)
}
if !r.m.Held() || !slices.Equal(r.m.keychain.Residue(), []string{item.Service}) {
t.Fatal("released before a listing showed the item gone")
}
r.m.settle(r.ctx, false)
if r.m.Held() {
t.Fatal("held after a listing showed it gone")
}
})
t.Run("a pre-existing item is untouched and refuses", func(t *testing.T) {
r := newDarwinRig(t)
left := creds.Item{Keychain: r.m.keychain.Login, Service: "Claude Code-credentials", Account: r.user}
r.kc.add(left)
c := r.connector()
if err := c.Accept(r.ctx, "f-connect-s1", wire.ConnectCommand{Connection: "s1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil {
t.Fatal(err)
}
if end := r.ended("s1"); end.Reason != "provider_refused" {
t.Fatalf("end %+v", end)
}
if len(r.pids()) != 0 || !r.kc.has(left) || len(r.kc.deleted) != 0 {
t.Fatalf("pids %v deleted %v", r.pids(), r.kc.deleted)
}
if !r.m.Held() || !slices.Equal(r.m.keychain.Residue(), []string{"Claude Code-credentials"}) {
t.Fatal("not held, or not named")
}
// A pasted token is refused too, before anything is written.
_, end := r.paste(c, "c2", fakeclaude.Token("a@example.com"))
if end.Reason != "provider_refused" || r.seals("c2") != 0 {
t.Fatalf("a pasted token with a Claude Code item there: %+v", end)
}
})
t.Run("a failed delete keeps the flag", func(t *testing.T) {
r := newDarwinRig(t)
r.kc.set(true)
c := r.connector()
link, _ := r.signIn(c, "s1")
item := r.own(r.signInDir())
r.kc.add(item)
r.codeIn(c, "s1", link, "a@example.com")
if end := r.ended("s1"); end.Reason != "provider_refused" {
t.Fatalf("end %+v", end)
}
if !r.kc.has(item) || !r.m.Held() {
t.Fatal("a failed delete released the hold")
}
r.m.settle(r.ctx, false)
if !r.m.Held() {
t.Fatal("released while the item is still there")
}
})
t.Run("an unrelated item created at the same time is left, the hold kept", func(t *testing.T) {
r := newDarwinRig(t)
c := r.connector()
link, _ := r.signIn(c, "s1")
item := r.own(r.signInDir())
other := creds.Item{Keychain: r.m.keychain.Login, Service: "Other App", Account: r.user}
r.kc.add(item, other)
r.codeIn(c, "s1", link, "a@example.com")
if end := r.ended("s1"); end.Reason != "provider_refused" {
t.Fatalf("end %+v", end)
}
if r.kc.has(item) || !r.kc.has(other) || slices.Contains(r.kc.deleted, other) {
t.Fatalf("deleted %+v", r.kc.deleted)
}
if !r.m.Held() || !slices.Equal(r.m.keychain.Residue(), []string{"Other App"}) {
t.Fatal("the unrelated item does not hold")
}
})
// Only the login keychain is the watch's (fix round 1, #2): one
// elsewhere is never touched.
t.Run("matching attributes in another keychain are left alone", func(t *testing.T) {
r := newDarwinRig(t)
c := r.connector()
link, _ := r.signIn(c, "s1")
elsewhere := r.own(r.signInDir())
elsewhere.Keychain = filepath.Join(r.dir, "Library", "Keychains", "other.keychain-db")
r.kc.add(elsewhere)
r.codeIn(c, "s1", link, "a@example.com")
r.ended("s1")
if !r.kc.has(elsewhere) || len(r.kc.deleted) != 0 {
t.Fatalf("deleted %+v", r.kc.deleted)
}
for _, kc := range r.kc.asked {
if kc != r.m.keychain.Login {
t.Fatalf("listed %q", kc)
}
}
})
t.Run("restart", func(t *testing.T) {
r := newDarwinRig(t)
// A watch the runner never finished: its list written, its CLI
// gone with the process, an item of its own made meanwhile.
crashed := filepath.Join(r.cfg.ScratchRoot, "homes", "signin-crashed")
if err := r.m.keychain.Before(r.ctx, "signin-crashed", crashed); err != nil {
t.Fatal(err)
}
r.kc.set(true)
c := r.connector()
link, _ := r.signIn(c, "s1")
item := r.own(r.signInDir())
r.kc.add(item)
r.codeIn(c, "s1", link, "a@example.com")
r.ended("s1")
left := r.own(crashed)
r.kc.add(left)
// The same runner after a restart: the hold is on disk, and the
// restart settles both now that deleting works.
again := darwinRigAt(t, r.dir)
again.kc = r.kc
again.m.keychain.List, again.m.keychain.Delete = r.kc.list, r.kc.delete
if !again.m.Held() {
t.Fatal("the hold did not survive the restart")
}
r.kc.set(false)
again.connector()
if again.m.Held() || r.kc.has(item) || r.kc.has(left) {
t.Fatalf("after the restart: held=%v %v", again.m.Held(), again.m.keychain.Residue())
}
})
}
// TestTaintBlocksConnections: a tainted runner (its own state, or the
// instance's word) stores no token, starts no sign-in, uses no token,
// and its Engineering status says tainted.
func TestTaintBlocksConnections(t *testing.T) {
t.Run("in its own state", func(t *testing.T) {
dir := shortDir(t)
if err := os.MkdirAll(filepath.Join(dir, "state"), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "state", "tainted"), []byte("2026-11-11T00:00:00Z\n"), 0o600); err != nil {
t.Fatal(err)
}
r := darwinRigAt(t, dir)
c := r.connector()
token := fakeclaude.Token("a@example.com")
_, end := r.paste(c, "c1", token)
if end.State != wire.ConnError || end.Reason != "provider_refused" || r.seals("c1") != 0 || len(r.launches()) != 0 {
t.Fatalf("a tainted runner kept a token: %+v seals=%d launches=%d", end, r.seals("c1"), len(r.launches()))
}
r.onlyIn(token, "")
if err := c.Accept(r.ctx, "f-connect-s1", wire.ConnectCommand{Connection: "s1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil {
t.Fatal(err)
}
if end := r.ended("s1"); end.Reason != "provider_refused" || len(r.pids()) != 0 {
t.Fatalf("a tainted runner signed in: %+v", end)
}
if s := r.m.status(); s == nil || s.State != wire.EngineeringTainted {
t.Fatalf("status %+v", s)
}
})
t.Run("by the instance, after a connection was made", func(t *testing.T) {
r := newDarwinRig(t)
home, _ := r.paste(r.connector(), "c1", fakeclaude.Token("a@example.com"))
b, _ := r.binding(filepath.Base(home))
before := len(r.launches())
r.m.taint.Set()
if _, err := r.opts.CheckToken(r.ctx, b); !errors.Is(err, errTainted) || len(r.launches()) != before {
t.Fatalf("a tainted runner used its token: %v", err)
}
if s := r.m.status(); s == nil || s.State != wire.EngineeringTainted {
t.Fatalf("status %+v", s)
}
})
}
// TestHomeGuardChangedBetweenStoreAndUse: the home guard is read again
// before every use: a home opened after the token was stored stops its
// use, and closing it again lets it go on.
func TestHomeGuardChangedBetweenStoreAndUse(t *testing.T) {
r := newDarwinRig(t)
c := r.connector()
home, _ := r.paste(c, "c1", fakeclaude.Token("a@example.com"))
b, ok := r.binding(filepath.Base(home))
if !ok || r.m.status() != nil {
t.Fatalf("not connected, or not ready: %+v", r.m.status())
}
if err := os.Chmod(r.dir, 0o750); err != nil {
t.Fatal(err)
}
before := len(r.launches())
var open *homeOpen
if _, err := r.opts.CheckToken(r.ctx, b); !errors.As(err, &open) || open.r.Fix() != "chmod 700 ~" || len(r.launches()) != before {
t.Fatalf("a check with the home open: %v", err)
}
if s := r.m.status(); s == nil || s.State != wire.EngineeringHomeOpen || s.Reason != creds.CodeHomeMode {
t.Fatalf("status %+v", s)
}
// Nor is a new token stored.
if _, end := r.paste(c, "c2", fakeclaude.Token("b@example.com")); end.Reason != "provider_refused" || r.seals("c2") != 0 {
t.Fatalf("stored with the home open: %+v", end)
}
if err := os.Chmod(r.dir, 0o700); err != nil {
t.Fatal(err)
}
if _, err := r.opts.CheckToken(r.ctx, b); err != nil {
t.Fatalf("closed again: %v", err)
}
}
// TestMacCapsSayTainted: the hello's Engineering status comes from the
// guards.
func TestMacCapsSayTainted(t *testing.T) {
r := newDarwinRig(t)
h := &macHost{creds: r.m, taint: r.m.taint}
r.m.taint.Set()
caps := wire.Capabilities{}
h.credentialCaps(r.ctx, &caps)
if caps.Engineering == nil || caps.Engineering.State != wire.EngineeringTainted || wire.ValidCapabilities(caps) != nil {
t.Fatalf("caps %+v", caps.Engineering)
}
}