package thin import ( "bytes" "context" "crypto/ed25519" "crypto/rand" "encoding/json" "errors" "log/slog" "os" "path/filepath" "strings" "sync" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/wire" ) const tokenRunner = "run_token_1" // lockedBuffer is a log the connector's goroutines write to. type lockedBuffer struct { mu sync.Mutex b bytes.Buffer } func (l *lockedBuffer) Write(p []byte) (int, error) { l.mu.Lock() defer l.mu.Unlock() return l.b.Write(p) } func (l *lockedBuffer) Bytes() []byte { l.mu.Lock() defer l.mu.Unlock() return bytes.Clone(l.b.Bytes()) } func (l *lockedBuffer) Len() int { return len(l.Bytes()) } func (l *lockedBuffer) String() string { return string(l.Bytes()) } // tokenRig is a runner state with no connections, the fake claude for // the status probe, a seal key, and connectors over them that a test // can stop and start again as the runner process would. type tokenRig struct { t *testing.T dir, root string // limit is the next connector's attempt limit (default an hour). limit time.Duration state *State cfg runner.Config conns *Conns keys sealbox.Keys logs lockedBuffer errs []error ctx context.Context // checks counts the real-request checks (verify); refuse makes the // next ones fail for another reason than the token. checks atomic.Int64 refuse atomic.Pointer[error] } func newTokenRig(t *testing.T) *tokenRig { return newTokenRigAt(t, t.TempDir()) } // newTokenRigAt is the rig in dir. func newTokenRigAt(t *testing.T, dir string) *tokenRig { r := &tokenRig{t: t, dir: dir, root: filepath.Join(dir, "accounts")} for _, d := range []string{r.root, filepath.Join(dir, "config"), filepath.Join(dir, "state"), filepath.Join(dir, "bin"), filepath.Join(dir, "scratch")} { if err := os.MkdirAll(d, 0700); err != nil { t.Fatal(err) } } self, _ := os.Executable() raw, err := os.ReadFile(self) if err != nil { t.Fatal(err) } claudePath := filepath.Join(dir, "bin", "claude") if err = os.WriteFile(claudePath, raw, 0755); err != nil { t.Fatal(err) } if r.state, err = OpenState(context.Background(), filepath.Join(dir, "state")); err != nil { t.Fatal(err) } t.Cleanup(func() { r.state.Close() }) r.cfg = runner.Config{AccountBindingsPath: filepath.Join(dir, "config", "bindings.json"), ClaudePath: claudePath, CodexPath: "/bin/true", ScratchRoot: filepath.Join(dir, "scratch")} r.conns = &Conns{Runner: r.cfg, State: r.state, Verify: r.verify} _, key, _ := ed25519.GenerateKey(rand.Reader) if r.keys, err = sealbox.FromEd25519(key); err != nil { t.Fatal(err) } ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) r.ctx = ctx return r } // verify is the token check as the provider answers a real request: the // fake CLI's turn runs only on a token fakeclaude.Token made. (The // contained launch itself is TestHeadlessTokenRejected's.) func (r *tokenRig) verify(ctx context.Context, b runner.AccountBinding) error { r.checks.Add(1) if err := r.refuse.Load(); err != nil { return *err } raw, err := provider.ReadToken(b.ProviderHome) if err != nil { return err } defer clear(raw) if !fakeclaude.Accepts(string(raw)) { return provider.ErrLoginRequired } return nil } // connector starts a connector, as a runner process does. func (r *tokenRig) 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))} c.spawn = func(f func()) { f() } c.terminal = r.execTerminal if err := c.Start(r.ctx); err != nil { r.t.Fatal(err) } return c } // connect starts a token attempt and waits for its card. func (r *tokenRig) connect(c *Connector, id string) string { r.t.Helper() if err := c.Accept(r.ctx, "f-connect-"+id, wire.ConnectCommand{Connection: id, Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}); err != nil { r.t.Fatal(err) } r.waitFor(func() bool { for _, v := range r.reports(id) { if v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == wire.PromptToken && v.Prompt.Code == "claude setup-token" { return true } } return false }, "the token card") var home string _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home) if home == "" || filepath.Dir(home) != r.root { r.t.Fatalf("attempt home %q", home) } return home } // sealed is a box for the attempt, as the app seals it. func (r *tokenRig) sealed(id, token string, change func(*wire.SealedPayload)) wire.SecretCommand { r.t.Helper() p := wire.SealedPayload{Secret: token, RunnerID: tokenRunner, ConnectionID: id, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().Add(5 * time.Minute).UTC()} if change != nil { change(&p) } s, err := sealbox.Seal(r.keys.PublicString(), p) if err != nil { r.t.Fatal(err) } return wire.SecretCommand{Connection: id, Person: connPerson, Sealed: s} } // deliver is the link's handling of one secret frame: the handler, and // an ack only when it returns nil. func (r *tokenRig) deliver(c *Connector, frame string, cmd wire.SecretCommand) bool { err := c.Secret(r.ctx, frame, cmd) if err != nil { r.errs = append(r.errs, err) } return err == nil } func (r *tokenRig) reports(id string) []wire.ConnectionReport { frames, _, err := r.state.Unacked(context.Background(), 0) if err != nil { r.t.Fatal(err) } var out []wire.ConnectionReport for _, f := range frames { var v wire.ConnectionReport if f.Type == wire.FrameConnection && json.Unmarshal(f.Data, &v) == nil && v.Connection == id { out = append(out, v) } } return out } // ended waits for the attempt's final report. func (r *tokenRig) ended(id string) wire.ConnectionReport { r.t.Helper() var last wire.ConnectionReport r.waitFor(func() bool { var state string _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id=?", id).Scan(&state) rs := r.reports(id) // done, or removed once the sign-out it owed has run. if state != "done" && state != "removed" || len(rs) == 0 { return false } last = rs[len(rs)-1] return last.State != wire.ConnConnecting }, "the attempt's end") return last } func (r *tokenRig) waitFor(ok func() bool, what string) { r.t.Helper() deadline := time.Now().Add(20 * time.Second) for !ok() { if time.Now().After(deadline) { r.t.Fatalf("no %s", what) } time.Sleep(20 * time.Millisecond) } } func (r *tokenRig) seals(id string) int { var n int if err := r.state.db.QueryRow("SELECT count(*) FROM seen_seals WHERE connection_id=?", id).Scan(&n); err != nil { r.t.Fatal(err) } return n } func (r *tokenRig) binding(local string) (runner.AccountBinding, bool) { return r.conns.Binding(local) } // healthy checks a delivered attempt ended as one token connection. func (r *tokenRig) healthy(id, home, token, email string) { r.t.Helper() end := r.ended(id) local := filepath.Base(home) if end.State != wire.ConnHealthy || end.LocalID != local || end.Label != email { r.t.Fatalf("end %+v", end) } b, ok := r.binding(local) if !ok || b.Kind != wire.KindToken || b.Provider != wire.ProviderClaude || b.PersonID != connPerson { r.t.Fatalf("binding %+v %v", b, ok) } raw, err := os.ReadFile(filepath.Join(home, provider.TokenFile)) info, serr := os.Stat(filepath.Join(home, provider.TokenFile)) if err != nil || serr != nil || string(raw) != token || info.Mode().Perm() != 0600 { r.t.Fatalf("token file: %v %v", err, serr) } if _, err = os.Lstat(filepath.Join(home, provider.TokenStaging)); !os.IsNotExist(err) { r.t.Fatalf("staging file left: %v", err) } healthy := 0 for _, v := range r.reports(id) { if v.State == wire.ConnHealthy { healthy++ } } if healthy != 1 || r.seals(id) != 1 { r.t.Fatalf("%d healthy reports, %d seen_seals rows", healthy, r.seals(id)) } for _, h := range r.conns.Held() { if h.LocalID == local { if h.Kind != wire.KindToken || h.Label != email || h.ExpiresAt == nil || !h.ExpiresEstimated || time.Until(*h.ExpiresAt) < wire.TokenLifetime-time.Hour { r.t.Fatalf("held %+v", h) } return } } r.t.Fatal("not held") } // A pasted token: the card, the box delivered once, the probe, the // binding, healthy with the account's email and a year to run. func TestTokenConnect(t *testing.T) { r := newTokenRig(t) c := r.connector() home := r.connect(c, "cn_t1") token := fakeclaude.Token("t@example.com") if !r.deliver(c, "f-secret", r.sealed("cn_t1", token, nil)) { t.Fatal(r.errs) } r.healthy("cn_t1", home, token, "t@example.com") // The expiry stays the same across a restart. before := r.conns.Held()[0].ExpiresAt r.conns = &Conns{Runner: r.cfg, State: r.state, Verify: r.verify} r.connector() if after := r.conns.Held()[0].ExpiresAt; after == nil || !after.Equal(*before) { t.Fatalf("expiry moved: %v %v", before, after) } } // A token whose CLI names no account: healthy, no label. func TestTokenConnectWithoutEmail(t *testing.T) { r := newTokenRig(t) c := r.connector() home := r.connect(c, "cn_t2") token := fakeclaude.Token("") r.deliver(c, "f-secret", r.sealed("cn_t2", token, nil)) r.healthy("cn_t2", home, token, "") if b, _ := r.binding(filepath.Base(home)); b.AccountID != "token:"+filepath.Base(home) { t.Fatalf("account %q", b.AccountID) } } // A token the provider does not accept: the CLI's status says signed in // (it says so for any token), so only the real request finds it out. // The attempt ends provider_refused (the app's "This token was // rejected"), nothing kept, never healthy. func TestTokenRejected(t *testing.T) { r := newTokenRig(t) c := r.connector() home := r.connect(c, "cn_t3") r.deliver(c, "f-secret", r.sealed("cn_t3", "sk-ant-oat01-revoked", nil)) if end := r.ended("cn_t3"); end.State != wire.ConnError || end.Reason != "provider_refused" || end.LocalID != "" { t.Fatalf("end %+v", end) } if r.checks.Load() != 1 { t.Fatalf("%d checks", r.checks.Load()) } for _, v := range r.reports("cn_t3") { if v.State == wire.ConnHealthy { t.Fatal("a rejected token was healthy") } } // The sign-out recorded with the end deletes the home. r.waitFor(func() bool { _, err := os.Lstat(home) var owed int _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&owed) return os.IsNotExist(err) && owed == 0 }, "the rejected token's home deleted") if bs, _ := runner.LoadBindings(r.cfg.AccountBindingsPath); len(bs) != 0 || len(r.conns.Held()) != 0 { t.Fatal("a rejected token was bound") } } // A check that cannot finish (no reply, no refusal) proves nothing: the // attempt ends in error and nothing is kept. func TestTokenCheckUnfinished(t *testing.T) { r := newTokenRig(t) stopped := errCheckFailed r.refuse.Store(&stopped) c := r.connector() home := r.connect(c, "cn_t4") r.deliver(c, "f-secret", r.sealed("cn_t4", fakeclaude.Token("u@example.com"), nil)) if end := r.ended("cn_t4"); end.State != wire.ConnError || end.Reason != "provider_refused" || end.LocalID != "" { t.Fatalf("end %+v", end) } // The sign-out recorded with the end deletes the home. r.waitFor(func() bool { _, err := os.Lstat(home) return os.IsNotExist(err) }, "the unchecked token's home deleted") if bs, _ := runner.LoadBindings(r.cfg.AccountBindingsPath); len(bs) != 0 { t.Fatal("an unchecked token stayed bound") } } // The hourly pass never clears a real rejection, and never spends a // request: it asks only the CLI's local status, which says signed in for // any token. A turn's refusal marks a token connection sign_in_again; a // Check again (one small request) that fails for any reason keeps it; // one the provider answers clears it, and so does any answered run. func TestTokenRejectionSurvivesHourlyCheck(t *testing.T) { r := newTokenRig(t) c := r.connector() home := r.connect(c, "cn_h1") r.deliver(c, "f-secret", r.sealed("cn_h1", fakeclaude.Token(""), nil)) r.ended("cn_h1") local := filepath.Base(home) state := func() string { for _, h := range r.conns.Held() { if h.LocalID == local { return h.State } } return "gone" } if state() != wire.ConnHealthy { t.Fatalf("state %s", state()) } // The provider revokes the token: a turn is refused. if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte("sk-ant-oat01-revoked-later"), 0600); err != nil { t.Fatal(err) } r.conns.SignInAgain(local) // The hourly pass, with the CLI's own status as the refresh: it says // signed in, spends no request and decides nothing. paths := provider.LoginOptions{ClaudePath: r.cfg.ClaudePath, CodexPath: r.cfg.CodexPath} r.conns.Refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) { return provider.RefreshLogin(ctx, b, paths) } before := r.checks.Load() for i := 0; i < 3; i++ { r.conns.Check(r.ctx) } if state() != wire.ConnSignInAgain || r.checks.Load() != before { t.Fatalf("after the hourly passes: %s, %d real checks", state(), r.checks.Load()-before) } // Check again that does not finish, or with no checker: unchanged. busy := errors.New("the check did not finish") r.refuse.Store(&busy) r.conns.CheckAgain(r.ctx, local) if state() != wire.ConnSignInAgain || r.checks.Load() != before+1 { t.Fatalf("an unfinished check changed the rejection: %s", state()) } verify := r.conns.Verify r.conns.Verify = nil r.conns.CheckAgain(r.ctx, local) if state() != wire.ConnSignInAgain { t.Fatalf("without a check: %s", state()) } // The provider answers again: Check again clears it. r.conns.Verify = verify r.refuse.Store(nil) if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(fakeclaude.Token("")), 0600); err != nil { t.Fatal(err) } r.conns.CheckAgain(r.ctx, local) if state() != wire.ConnHealthy { t.Fatalf("after an answered check: %s", state()) } // Refused again, then a run on it is answered: that clears it too. r.conns.SignInAgain(local) r.conns.Answered(local) if state() != wire.ConnHealthy { t.Fatalf("after an answered run: %s", state()) } } // A stop after the binding is saved and before the attempt is marked // done. The restarted runner finds its own binding (same home, same // attempt): it is not a second connection of the same account. Without // a cancel the attempt finishes healthy, once; with a cancel recorded, // the sign-out it owes is recorded durably and the home and its token // are deleted. func TestTokenRecoversSavedBinding(t *testing.T) { for _, cancelled := range []bool{false, true} { t.Run(map[bool]string{false: "kept", true: "cancelled"}[cancelled], func(t *testing.T) { r := newTokenRig(t) first := r.connector() stopped := make(chan struct{}) first.fault = func(at string) error { if at == "bound" { close(stopped) return errStopped } return nil } id := "cn_b_" + map[bool]string{false: "kept", true: "cancelled"}[cancelled] home := r.connect(first, id) token := fakeclaude.Token("b@example.com") if !r.deliver(first, "f-secret", r.sealed(id, token, nil)) { t.Fatal(r.errs) } select { case <-stopped: case <-time.After(20 * time.Second): t.Fatal("never reached the saved binding") } local := filepath.Base(home) r.waitFor(func() bool { var state string _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id=?", id).Scan(&state) _, ok := r.binding(local) return ok && state == "running" }, "the stop between the binding and the attempt's end") if cancelled { if err := first.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: id, Person: connPerson}); err != nil { t.Fatal(err) } } r.connector() for _, v := range r.reports(id) { if v.Reason == "already_connected" { t.Fatalf("its own binding called a second connection: %+v", v) } } if !cancelled { r.healthy(id, home, token, "b@example.com") return } if end := r.ended(id); end.State != wire.ConnError || end.Reason != "cancelled" || end.LocalID != "" { t.Fatalf("end %+v", end) } r.waitFor(func() bool { _, err := os.Lstat(home) var owed int _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&owed) return os.IsNotExist(err) && owed == 0 }, "the cancelled token's home deleted and nothing owed") if _, ok := r.binding(local); ok || len(r.conns.Held()) != 0 { t.Fatal("the cancelled token stayed bound") } }) } } // A stop after the cancelled attempt's end and sign-out are recorded, // before the sign-out ran: the next start does it from the record. func TestTokenCancelledCleanupIsDurable(t *testing.T) { r := newTokenRig(t) first := r.connector() stopped := make(chan struct{}) first.fault = func(at string) error { if at == "bound" { close(stopped) return errStopped } return nil } home := r.connect(first, "cn_d1") r.deliver(first, "f-secret", r.sealed("cn_d1", fakeclaude.Token("d@example.com"), nil)) <-stopped r.waitFor(func() bool { _, ok := r.binding(filepath.Base(home)); return ok }, "the binding") if err := first.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_d1", Person: connPerson}); err != nil { t.Fatal(err) } // The second process records the end and the sign-out it owes, and // stops before the sign-out runs. second := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &r.keys, RunnerID: tokenRunner, Limit: time.Hour} second.spawn = func(func()) {} owed := make(chan struct{}) second.fault = func(at string) error { if at == "owed" { close(owed) return errStopped } return nil } if err := second.Start(r.ctx); err != nil { t.Fatal(err) } <-owed var n int _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups WHERE connection='cn_d1'").Scan(&n) if _, err := os.Lstat(home); err != nil || n != 1 { t.Fatalf("after the stop: home %v, %d owed", err, n) } r.connector() r.waitFor(func() bool { _, err := os.Lstat(home) var n int _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&n) return os.IsNotExist(err) && n == 0 }, "the home deleted from the record") } // Crash at each delivery boundary: the process stops after the staging // file is synced, inside the seen_seals transaction, or after the commit // and before the ack. The restarted runner recovers and the instance's // resend ends with one token file, one seen_seals row, one ack and a // healthy connection. func TestTokenDeliverySurvivesCrashes(t *testing.T) { for _, stage := range []string{"staged", "transaction", "committed"} { t.Run(stage, func(t *testing.T) { r := newTokenRig(t) first := r.connector() first.fault = func(at string) error { if at == stage { return errStopped } return nil } id := "cn_c_" + stage home := r.connect(first, id) token := fakeclaude.Token("c@example.com") cmd := r.sealed(id, token, nil) if r.deliver(first, "f-secret", cmd) { t.Fatal("acked through a stop") } committed := r.seals(id) if stage == "committed" && committed != 1 || stage != "committed" && committed != 0 { t.Fatalf("%d seen_seals rows after a stop at %s", committed, stage) } // What the stop left: the staged file; the token file renamed // in a transaction that never committed; the committed file. left := map[string]string{"staged": provider.TokenStaging, "transaction": provider.TokenFile, "committed": provider.TokenFile}[stage] if got := tokenFiles(home); len(got) != 1 || got[0] != left { t.Fatalf("after the stop: %v", got) } // The first process is gone (its attempt never wakes again); a // new one starts on the same state. Recovery keeps only a // committed token. second := r.connector() want := []string{} if stage == "committed" { want = []string{provider.TokenFile} } if got := tokenFiles(home); strings.Join(got, ",") != strings.Join(want, ",") { t.Fatalf("after recovery: %v", got) } acks := 0 if r.deliver(second, "f-secret", cmd) { acks++ } r.healthy(id, home, token, "c@example.com") if acks != 1 { t.Fatalf("%d acks", acks) } entries, _ := os.ReadDir(home) files := 0 for _, e := range entries { if e.Name() == provider.TokenFile || e.Name() == provider.TokenStaging { files++ } } if files != 1 { t.Fatalf("%d token files", files) } }) } } // The same box again is acked and changes nothing; a box for another // attempt, an expired box, one sealed for another runner and one whose // clear fields were changed are refused, ending the attempt. func TestTokenReplayAndRefusals(t *testing.T) { r := newTokenRig(t) c := r.connector() home := r.connect(c, "cn_r1") token := fakeclaude.Token("r@example.com") cmd := r.sealed("cn_r1", token, nil) r.deliver(c, "f-1", cmd) r.healthy("cn_r1", home, token, "r@example.com") before, _ := os.Stat(filepath.Join(home, provider.TokenFile)) reports := len(r.reports("cn_r1")) // The resend, and the same box in another frame: acked, nothing else // (not even opened or looked at as a refusal). logged := r.logs.Len() for _, frame := range []string{"f-1", "f-1-again"} { if !r.deliver(c, frame, cmd) { t.Fatal(r.errs) } } if r.logs.Len() != logged { t.Fatalf("a delivered pair was handled again: %s", r.logs.String()[logged:]) } // A later attempt's box for a connection already made: dropped. r.deliver(c, "f-2", r.sealed("cn_r1", fakeclaude.Token("x@example.com"), func(p *wire.SealedPayload) { p.Attempt = 2 })) after, _ := os.Stat(filepath.Join(home, provider.TokenFile)) if !os.SameFile(before, after) || !after.ModTime().Equal(before.ModTime()) || len(r.reports("cn_r1")) != reports || r.seals("cn_r1") != 1 { t.Fatal("a replay changed the connection") } refusals := []struct { name, reason string box func(id string) wire.SecretCommand }{ {"another attempt's box", "provider_refused", func(id string) wire.SecretCommand { other := r.sealed("cn_other", token, nil) other.Connection = id return other }}, {"clear fields changed", "provider_refused", func(id string) wire.SecretCommand { s := r.sealed(id, token, nil) s.Sealed.Attempt = 7 return s }}, {"expired", "timed_out", func(id string) wire.SecretCommand { return r.sealed(id, token, func(p *wire.SealedPayload) { p.ExpiresAt = time.Now().Add(-time.Second).UTC() }) }}, {"another runner's key", "provider_refused", func(id string) wire.SecretCommand { _, key, _ := ed25519.GenerateKey(rand.Reader) k, _ := sealbox.FromEd25519(key) s, _ := sealbox.Seal(k.PublicString(), wire.SealedPayload{Secret: token, RunnerID: tokenRunner, ConnectionID: id, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().Add(time.Minute).UTC()}) return wire.SecretCommand{Connection: id, Person: connPerson, Sealed: s} }}, {"another runner's id", "provider_refused", func(id string) wire.SecretCommand { return r.sealed(id, token, func(p *wire.SealedPayload) { p.RunnerID = "run_other" }) }}, {"another endpoint", "provider_refused", func(id string) wire.SecretCommand { return r.sealed(id, token, func(p *wire.SealedPayload) { p.Endpoint = "https://api.example.com:443" }) }}, {"another person", "provider_refused", func(id string) wire.SecretCommand { s := r.sealed(id, token, nil) s.Person = "q@example.com" return s }}, } for i, x := range refusals { t.Run(x.name, func(t *testing.T) { id := "cn_x" + string(rune('a'+i)) home := r.connect(c, id) if !r.deliver(c, "f-x-"+id, x.box(id)) { t.Fatal("a refused box was not acked") } if end := r.ended(id); end.State != wire.ConnError || end.Reason != x.reason { t.Fatalf("end %+v", end) } if _, err := os.Stat(home); !os.IsNotExist(err) || r.seals(id) != 0 { t.Fatalf("home %v, %d seals", err, r.seals(id)) } }) } } // A cancel before the box arrives: the attempt ends cancelled and the // late box is acked and dropped, nothing written. func TestTokenCancelBeforeSecret(t *testing.T) { r := newTokenRig(t) c := r.connector() home := r.connect(c, "cn_k1") if err := c.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_k1", Person: connPerson}); err != nil { t.Fatal(err) } if end := r.ended("cn_k1"); end.State != wire.ConnError || end.Reason != "cancelled" { t.Fatalf("end %+v", end) } if !r.deliver(c, "f-secret", r.sealed("cn_k1", fakeclaude.Token("k@example.com"), nil)) { t.Fatal(r.errs) } if _, err := os.Stat(home); !os.IsNotExist(err) || r.seals("cn_k1") != 0 { t.Fatalf("home %v after a cancel", err) } } // Sign-out deletes the home with its token, the binding and the expiry. func TestTokenSignOut(t *testing.T) { r := newTokenRig(t) c := r.connector() home := r.connect(c, "cn_s1") token := fakeclaude.Token("s@example.com") r.deliver(c, "f-secret", r.sealed("cn_s1", token, nil)) r.healthy("cn_s1", home, token, "s@example.com") local := filepath.Base(home) if err := c.Disconnect(r.ctx, "f-out", wire.DisconnectCommand{Connection: "cn_s1", Person: connPerson, LocalID: local}); err != nil { t.Fatal(err) } if _, err := os.Stat(home); !os.IsNotExist(err) { t.Fatal("the home stayed") } if _, ok := r.binding(local); ok { t.Fatal("still bound") } var n int _ = r.state.db.QueryRow("SELECT count(*) FROM conn_expiry WHERE id=?", local).Scan(&n) if n != 0 || len(r.conns.Held()) != 0 { t.Fatal("the expiry stayed") } signedOut := false for _, v := range r.reports("cn_s1") { signedOut = signedOut || v.State == wire.ConnSignedOut } if !signedOut { t.Fatal("no signed_out report") } } // The canary: whatever happens to a token, nothing the runner sends the // instance, logs, returns as an error or reports in hello carries it. func TestTokenNeverLeaves(t *testing.T) { r := newTokenRig(t) c := r.connector() good := fakeclaude.Token("canary@example.com") bad := "sk-ant-oat01-canary-rejected-91c2" r.connect(c, "cn_g") r.deliver(c, "f-g", r.sealed("cn_g", good, nil)) r.ended("cn_g") r.connect(c, "cn_b") r.deliver(c, "f-b", r.sealed("cn_b", bad, nil)) r.ended("cn_b") r.connect(c, "cn_e") r.deliver(c, "f-e", r.sealed("cn_e", good, func(p *wire.SealedPayload) { p.ExpiresAt = time.Now().Add(-time.Minute).UTC() })) r.ended("cn_e") r.connect(c, "cn_w") r.deliver(c, "f-w", r.sealed("cn_w", good, func(p *wire.SealedPayload) { p.Endpoint = "https://api.example.com:443" })) r.ended("cn_w") // A stop mid-delivery returns an error the link logs. c.fault = func(string) error { return errStopped } r.connect(c, "cn_f") r.deliver(c, "f-f", r.sealed("cn_f", good, nil)) c.fault = nil frames, _, err := r.state.Unacked(context.Background(), 0) if err != nil { t.Fatal(err) } var sent bytes.Buffer for _, f := range frames { sent.Write(f.Data) } held, _ := json.Marshal(r.conns.Held()) sent.Write(held) sent.Write(r.logs.Bytes()) for _, e := range r.errs { sent.WriteString(e.Error()) } var rows bytes.Buffer for _, q := range []string{"SELECT id||person||home||state||kind||secret FROM connect_attempts", "SELECT connection_id||attempt||frame_id FROM seen_seals", "SELECT value FROM meta"} { rs, err := r.state.db.Query(q) if err != nil { t.Fatal(err) } for rs.Next() { var v string _ = rs.Scan(&v) rows.WriteString(v) } rs.Close() } for _, tok := range []string{good, bad} { for name, b := range map[string][]byte{"sent, logged, held or returned": sent.Bytes(), "runner state": rows.Bytes()} { if bytes.Contains(b, []byte(tok)) || strings.Contains(string(b), strings.TrimPrefix(tok, "sk-ant-oat01-")) { t.Fatalf("a token is in what the runner %s", name) } } } if len(r.errs) != 1 || !errors.Is(r.errs[0], errStopped) { t.Fatalf("errors %v", r.errs) } } // tokenFiles are the token's files in a home, by name. func tokenFiles(home string) []string { got := []string{} for _, name := range []string{provider.TokenStaging, provider.TokenFile} { if _, err := os.Lstat(filepath.Join(home, name)); err == nil { got = append(got, name) } } return got } // The secret frame read right after the connect frame, before the // attempt's card went out: the attempt is ready for it. func TestTokenSecretRightAfterConnect(t *testing.T) { r := newTokenRig(t) c := r.connector() if err := c.Accept(r.ctx, "f-connect", wire.ConnectCommand{Connection: "cn_q1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}); err != nil { t.Fatal(err) } token := fakeclaude.Token("q@example.com") if !r.deliver(c, "f-secret", r.sealed("cn_q1", token, nil)) { t.Fatal(r.errs) } var home string _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id='cn_q1'").Scan(&home) r.healthy("cn_q1", home, token, "q@example.com") } // stopAtBound runs a token attempt to its saved binding and stops the // runner there (before the real check and the attempt's end). func (r *tokenRig) stopAtBound(id, token string) string { r.t.Helper() first := r.connector() stopped := make(chan struct{}) first.fault = func(at string) error { if at == "bound" { close(stopped) return errStopped } return nil } home := r.connect(first, id) if !r.deliver(first, "f-secret-"+id, r.sealed(id, token, nil)) { r.t.Fatal(r.errs) } select { case <-stopped: case <-time.After(20 * time.Second): r.t.Fatal("never reached the saved binding") } r.waitFor(func() bool { _, ok := r.binding(filepath.Base(home)) return ok }, "the saved binding") return home } // Astra round 2: the hourly pass between the saved binding and the real // check never makes the token a connection (its CLI status says signed in // for any token), and the resumed attempt still makes the real request. func TestTokenHourlyPassBeforeTheCheck(t *testing.T) { r := newTokenRig(t) token := fakeclaude.Token("race@example.com") home := r.stopAtBound("cn_race", token) local := filepath.Base(home) paths := provider.LoginOptions{ClaudePath: r.cfg.ClaudePath, CodexPath: r.cfg.CodexPath} r.conns.Refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) { return provider.RefreshLogin(ctx, b, paths) } before := r.checks.Load() r.conns.Check(r.ctx) if len(r.conns.Held()) != 0 || !r.conns.ValidatedAt(local).IsZero() { t.Fatalf("the CLI's status made the token a connection: %+v", r.conns.Held()) } if _, _, err := r.conns.Choose(r.ctx, connPerson, "coordinator", "", nil); err == nil { t.Fatal("an unvalidated token was chosen") } r.connector() r.healthy("cn_race", home, token, "race@example.com") if r.checks.Load() != before+1 || r.conns.ValidatedAt(local).IsZero() { t.Fatalf("the resumed attempt made %d real requests; validated %v", r.checks.Load()-before, r.conns.ValidatedAt(local)) } } // Astra round 2: a restart after the attempt's time is up, with its // binding saved, goes through the durable sign-out: the binding, the home // and the token go; the end records the attempt's local id, never an // empty one while the home survives; a recorded cancel ends it cancelled. func TestTokenExpiredRecoveryCleansUp(t *testing.T) { for _, cancelled := range []bool{false, true} { t.Run(map[bool]string{false: "expired", true: "cancelled"}[cancelled], func(t *testing.T) { r := newTokenRig(t) id := "cn_x_" + map[bool]string{false: "e", true: "c"}[cancelled] home := r.stopAtBound(id, fakeclaude.Token("late@example.com")) local := filepath.Base(home) if cancelled { if _, err := r.state.db.Exec("UPDATE connect_attempts SET cancelled=1 WHERE id=?", id); err != nil { t.Fatal(err) } } r.limit = time.Nanosecond r.connector() want := map[bool]string{false: "timed_out", true: "cancelled"}[cancelled] var end wire.ConnectionReport r.waitFor(func() bool { rs := r.reports(id) if len(rs) == 0 { return false } end = rs[len(rs)-1] return end.State != wire.ConnConnecting }, "the attempt's end") if end.State != wire.ConnError || end.Reason != want { t.Fatalf("end %+v", end) } var recorded string _ = r.state.db.QueryRow("SELECT local_id FROM connect_attempts WHERE id=?", id).Scan(&recorded) if recorded == "" { t.Fatal("the attempt ended with no local id while its home survived") } r.waitFor(func() bool { _, err := os.Lstat(home) var owed int _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&owed) _, bound := r.binding(local) return os.IsNotExist(err) && owed == 0 && !bound }, "the expired token's binding and home deleted, nothing owed") }) } }