package thin import ( "bytes" "context" "errors" "io/fs" "log/slog" "net/url" "os" "path/filepath" "strconv" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" "golang.org/x/sys/unix" ) // Claude with no terminal (signin.go): the runner's own `claude // setup-token` (the fake, steered from SetupSteerFile beside it) in a // pseudo-terminal, the link it prints on the card, the code sealed and // typed into it, the token it prints kept and checked. // steer writes the fake setup-token's steering words. func (r *tokenRig) steer(words ...string) { r.t.Helper() if err := os.WriteFile(filepath.Join(r.dir, "bin", fakeclaude.SetupSteerFile), []byte(strings.Join(words, "\n")), 0600); err != nil { r.t.Fatal(err) } } // crashable starts a connector that can be stopped at a delivery // boundary, for the durable state each boundary leaves: at stage (or at // once, by crash) every later boundary stops too and its context ends, // so its CLI is stopped and nothing it does after reaches the state. It // is not a process death; that is TestHeadlessSignInRunnerKilled // (SIGKILL to a real runner process, its namespace recovered). type crashable struct { *Connector cancel context.CancelFunc dead atomic.Bool } func (r *tokenRig) crashable(stage string) *crashable { r.t.Helper() ctx, cancel := context.WithCancel(r.ctx) keys := r.keys limit := time.Hour if r.limit > 0 { limit = r.limit } k := &crashable{cancel: cancel} k.Connector = &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))} k.spawn = func(f func()) { f() } k.terminal = r.execTerminal k.fault = func(at string) error { if at == stage { k.dead.Store(true) } if k.dead.Load() { return errStopped } return nil } if err := k.Start(ctx); err != nil { r.t.Fatal(err) } return k } // crash stops the process: the boundaries stop, the context ends (the // CLI is killed), and its attempts have returned. func (k *crashable) crash(r *tokenRig) { r.t.Helper() k.dead.Store(true) k.cancel() r.waitFor(func() bool { k.mu.Lock() defer k.mu.Unlock() return len(k.attempts) == 0 }, "the stopped process's attempts to return") } // signIn starts a sign-in attempt and waits for its card's link. func (r *tokenRig) signIn(c *Connector, id string) (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.KindSubscription}); err != nil { r.t.Fatal(err) } p := r.prompt(id, 1) 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 p.URL, home } // prompt waits for the card asking for attempt's code. func (r *tokenRig) prompt(id string, attempt int64) wire.ConnectPrompt { r.t.Helper() var got wire.ConnectPrompt r.waitFor(func() bool { for _, v := range r.reports(id) { if v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == wire.PromptAuthorize && v.Prompt.Attempt == attempt && v.Prompt.URL != "" { got = *v.Prompt return true } } return false }, "the sign-in card for attempt "+strconv.FormatInt(attempt, 10)) if _, ok := connect.AuthorizeURL(got.URL); !ok { r.t.Fatalf("card link %q", got.URL) } return got } // codeFor is the code Anthropic's page shows for email after the sign-in // that link started. func codeFor(link, email string) string { u, _ := url.Parse(link) return fakeclaude.SetupCode(email, u.Query().Get("state")) } // sealedCode is a code's box, as the page seals it. func (r *tokenRig) sealedCode(id, code string, attempt int64, change func(*wire.SealedPayload)) wire.SecretCommand { r.t.Helper() return r.sealed(id, code, func(p *wire.SealedPayload) { p.Endpoint, p.Attempt = wire.EndpointClaudeCode, attempt if change != nil { change(p) } }) } // pids are the fake CLI's runs so far. func (r *tokenRig) pids() []int { raw, _ := os.ReadFile(filepath.Join(r.dir, "bin", fakeclaude.SetupPidFile)) var out []int for _, l := range strings.Fields(string(raw)) { n, _ := strconv.Atoi(l) out = append(out, n) } return out } // gone waits until every run of the CLI has exited. func (r *tokenRig) gone() { r.t.Helper() r.waitFor(func() bool { for _, pid := range r.pids() { // A zombie is reaped by its parent's Wait; kill(0) on one // still succeeds, so read its state. raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat") if err == nil && !bytes.Contains(raw, []byte(") Z ")) { return false } } return true }, "the CLI to have exited") } // nowhere fails if secret is in any file under the rig's directory (the // runner's state database and its WAL, the homes, the fake's records). func (r *tokenRig) nowhere(secret, what string) { r.t.Helper() _ = filepath.WalkDir(r.dir, func(path string, d fs.DirEntry, err error) error { if err != nil || d.IsDir() || filepath.Dir(path) == filepath.Join(r.dir, "bin") && d.Name() == "claude" { return nil } if raw, _ := os.ReadFile(path); bytes.Contains(raw, []byte(secret)) { r.t.Fatalf("the %s is in %s", what, path) } return nil }) if bytes.Contains(r.logs.Bytes(), []byte(secret)) { r.t.Fatalf("the %s is in the runner's log", what) } } // The whole sign-in: the CLI started on a terminal in the attempt's own // home with BROWSER a no-op (else the fake opens nothing and exits), its // link on the card, the code sealed, typed in, the token it printed kept // 0600 and checked by one real request before the connection is healthy. // The CLI's argv is setup-token alone; the code is on no disk and in no // log, the token only in its file. func TestSignInConnect(t *testing.T) { t.Parallel() r := newTokenRig(t) c := r.connector() link, home := r.signIn(c, "cn_s1") if len(r.pids()) != 1 { t.Fatalf("%d runs of the CLI", len(r.pids())) } code := codeFor(link, "s@example.com") if !r.deliver(c, "f-code", r.sealedCode("cn_s1", code, 1, nil)) { t.Fatal(r.errs) } token := fakeclaude.Token("s@example.com") r.healthy("cn_s1", home, token, "s@example.com") if r.checks.Load() != 1 { t.Fatalf("%d real checks", r.checks.Load()) } r.gone() argv, _ := os.ReadFile(filepath.Join(r.dir, "bin", fakeclaude.SetupArgvFile)) if string(argv) != "setup-token\n" { t.Fatalf("argv %q", argv) } r.nowhere(code, "code") r.nowhere(strings.TrimPrefix(code, "fakecode-"), "code") // The token: in its file and nowhere else. tokenFile := filepath.Join(home, provider.TokenFile) _ = filepath.WalkDir(r.dir, func(path string, d fs.DirEntry, err error) error { if err == nil && !d.IsDir() && path != tokenFile { if raw, _ := os.ReadFile(path); bytes.Contains(raw, []byte(token)) { t.Fatalf("the token is in %s", path) } } return nil }) for _, v := range r.reports("cn_s1") { if v.Prompt != nil && (strings.Contains(v.Prompt.URL, code) || v.Prompt.Code != "") { t.Fatalf("report %+v", v) } } } // The check is what makes the connection: a token the provider refuses // ends the attempt provider_refused, nothing kept. func TestSignInTokenRejected(t *testing.T) { t.Parallel() r := newTokenRig(t) c := r.connector() refused := error(provider.ErrLoginRequired) r.refuse.Store(&refused) link, home := r.signIn(c, "cn_s2") r.deliver(c, "f-code", r.sealedCode("cn_s2", codeFor(link, "s2@example.com"), 1, nil)) end := r.ended("cn_s2") if end.State != wire.ConnError || end.Reason != "provider_refused" || r.checks.Load() != 1 { t.Fatalf("end %+v after %d checks", end, r.checks.Load()) } r.waitFor(func() bool { _, err := os.Stat(home); return os.IsNotExist(err) }, "the home to go") if _, ok := r.binding(filepath.Base(home)); ok { t.Fatal("bound") } for _, v := range r.reports("cn_s2") { if v.State == wire.ConnHealthy { t.Fatal("healthy before the check") } } } // Wrong codes while the CLI asks again (as 2.1.312 does, read // statically: after "OAuth error: ..." it waits for Enter, which the // runner presses). A code it cannot read: the same link. A code the // exchange refuses: a new sign-in, a new link, in the same run. The card // says the code was wrong each time; the right code for the latest link // connects. func TestSignInWrongCodeAgain(t *testing.T) { t.Parallel() r := newTokenRig(t) c := r.connector() link, home := r.signIn(c, "cn_w1") r.deliver(c, "f-code-1", r.sealedCode("cn_w1", "notacode-without-a-state", 1, nil)) p := r.prompt("cn_w1", 2) if p.URL != link || !p.WrongCode { t.Fatalf("second card %+v", p) } r.deliver(c, "f-code-2", r.sealedCode("cn_w1", "fakecode-not-the-right-one#x", 2, nil)) p3 := r.prompt("cn_w1", 3) if p3.URL == link || !p3.WrongCode { t.Fatalf("third card %+v", p3) } if len(r.pids()) != 1 { t.Fatal("the CLI was started again") } r.deliver(c, "f-code-3", r.sealedCode("cn_w1", codeFor(p3.URL, "w@example.com"), 3, nil)) r.healthy2("cn_w1", home, fakeclaude.Token("w@example.com"), "w@example.com", 3) } // healthy2 is healthy for an attempt that took seals boxes. func (r *tokenRig) healthy2(id, home, token, email string, seals int) { r.t.Helper() end := r.ended(id) if end.State != wire.ConnHealthy || end.LocalID != filepath.Base(home) || end.Label != email || r.seals(id) != seals { r.t.Fatalf("end %+v, %d seals", end, r.seals(id)) } raw, err := os.ReadFile(filepath.Join(home, provider.TokenFile)) if err != nil || string(raw) != token { r.t.Fatalf("token file: %v", err) } } // A wrong code the CLI exits on: it is started again, and the card says // the code was wrong with the new link. The first link's code does not // work on the new run; the new one's does. func TestSignInWrongCodeRestarts(t *testing.T) { t.Parallel() r := newTokenRig(t) r.steer("exit_on_wrong") c := r.connector() link, home := r.signIn(c, "cn_w2") r.deliver(c, "f-code-1", r.sealedCode("cn_w2", "fakecode-wrong#x", 1, nil)) p := r.prompt("cn_w2", 2) if p.URL == link || !p.WrongCode || len(r.pids()) != 2 { t.Fatalf("second card %+v after %d runs", p, len(r.pids())) } r.deliver(c, "f-code-2", r.sealedCode("cn_w2", codeFor(link, "w2@example.com"), 2, nil)) p3 := r.prompt("cn_w2", 3) if p3.URL == p.URL || !p3.WrongCode { t.Fatalf("third card %+v", p3) } r.deliver(c, "f-code-3", r.sealedCode("cn_w2", codeFor(p3.URL, "w2@example.com"), 3, nil)) r.healthy2("cn_w2", home, fakeclaude.Token("w2@example.com"), "w2@example.com", 3) } // The CLI's own time limit: it exits waiting; it is started again with a // new link (no wrong code said), up to maxLaunches runs, then the // attempt ends timed_out, the home gone. func TestSignInCLIExpires(t *testing.T) { t.Parallel() r := newTokenRig(t) r.steer("expire_ms=300") c := r.connector() link, home := r.signIn(c, "cn_e1") p := r.prompt("cn_e1", 2) if p.URL == link || p.WrongCode { t.Fatalf("second card %+v", p) } end := r.ended("cn_e1") if end.State != wire.ConnError || end.Reason != "timed_out" || len(r.pids()) != maxLaunches { t.Fatalf("end %+v after %d runs", end, len(r.pids())) } if _, err := os.Stat(home); !os.IsNotExist(err) { t.Fatalf("home %v", err) } r.gone() } // The CLI fails before any link: provider_refused, the home gone. func TestSignInCLIFailsToStart(t *testing.T) { t.Parallel() r := newTokenRig(t) r.steer("fail_start") c := r.connector() if err := c.Accept(r.ctx, "f-connect", wire.ConnectCommand{Connection: "cn_f1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil { t.Fatal(err) } if end := r.ended("cn_f1"); end.State != wire.ConnError || end.Reason != "provider_refused" { t.Fatalf("end %+v", end) } if entries, _ := os.ReadDir(r.root); len(entries) != 0 { t.Fatalf("left %v", entries) } } // Cancel, and the attempt's own time limit: the CLI and its group are // killed, the home deleted, the end reported; a code after is acked and // dropped, never typed. func TestSignInCancelAndLimit(t *testing.T) { t.Parallel() r := newTokenRig(t) c := r.connector() link, home := r.signIn(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) } r.gone() if _, err := os.Stat(home); !os.IsNotExist(err) { t.Fatalf("home %v", err) } if !r.deliver(c, "f-late", r.sealedCode("cn_k1", codeFor(link, "k@example.com"), 1, nil)) || r.seals("cn_k1") != 0 { t.Fatal("a late code was not dropped") } r.limit = 1500 * time.Millisecond c = r.connector() _, home = r.signIn(c, "cn_k2") if end := r.ended("cn_k2"); end.State != wire.ConnError || end.Reason != "timed_out" { t.Fatalf("end %+v", end) } r.gone() if _, err := os.Stat(home); !os.IsNotExist(err) { t.Fatalf("home %v", err) } } // A code's box: the resend is acked and nothing else; a box for an // attempt the CLI no longer waits for is dropped and the attempt waits // on; a code bound as a token, an expired box, a token sealed as the // code and a box for another runner are refused, ending the attempt; a // code's box to a token attempt is refused too. (The code bound as a // token would sign in: only its binding refuses it.) func TestSignInCodeReplayAndRefusals(t *testing.T) { t.Parallel() r := newTokenRig(t) c := r.connector() link, home := r.signIn(c, "cn_r1") r.deliver(c, "f-stale", r.sealedCode("cn_r1", codeFor(link, "r@example.com"), 2, nil)) if r.seals("cn_r1") != 0 || len(r.reports("cn_r1")) != 1 { t.Fatal("a stale attempt's box was taken") } cmd := r.sealedCode("cn_r1", codeFor(link, "r@example.com"), 1, nil) r.deliver(c, "f-1", cmd) r.healthy2("cn_r1", home, fakeclaude.Token("r@example.com"), "r@example.com", 1) reports, logged := len(r.reports("cn_r1")), 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 || len(r.reports("cn_r1")) != reports || r.seals("cn_r1") != 1 || len(r.pids()) != 1 { t.Fatal("a replay was handled again") } for i, x := range []struct { name, reason string box func(id, link string) wire.SecretCommand }{ {"a code bound as a token", "provider_refused", func(id, link string) wire.SecretCommand { return r.sealed(id, codeFor(link, "x@example.com"), nil) }}, {"expired", "timed_out", func(id, link string) wire.SecretCommand { return r.sealedCode(id, codeFor(link, "x@example.com"), 1, func(p *wire.SealedPayload) { p.ExpiresAt = time.Now().Add(-time.Second).UTC() }) }}, {"a token as the code", "provider_refused", func(id, link string) wire.SecretCommand { return r.sealedCode(id, fakeclaude.Token("x@example.com"), 1, nil) }}, {"another runner", "provider_refused", func(id, link string) wire.SecretCommand { return r.sealedCode(id, codeFor(link, "x@example.com"), 1, func(p *wire.SealedPayload) { p.RunnerID = "run_other" }) }}, } { t.Run(x.name, func(t *testing.T) { id := "cn_x" + strconv.Itoa(i) link, home := r.signIn(c, id) if !r.deliver(c, "f-"+id, x.box(id, link)) { t.Fatal("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)) } }) } r.gone() home = r.connect(c, "cn_t1") r.deliver(c, "f-t1", r.sealedCode("cn_t1", "fakecode-00#x", 1, func(p *wire.SealedPayload) { p.Attempt = 1 })) if end := r.ended("cn_t1"); end.Reason != "provider_refused" || r.seals("cn_t1") != 0 { t.Fatalf("a token attempt took a code: %+v", end) } if _, err := os.Stat(home); !os.IsNotExist(err) { t.Fatal(err) } } // A stop at each boundary of a code's delivery and its token's keeping // (crashable; the real kill is TestHeadlessSignInRunnerKilled). // Before the token is committed the CLI died with the process: the // restart ends the attempt runner_offline and deletes its home (with any // staged or renamed token file), and the resent box is acked and // dropped. Once committed, the restart carries the attempt on as a token // attempt to healthy. The code is never on disk. func TestSignInSurvivesCrashes(t *testing.T) { t.Parallel() for _, stage := range []string{"code_opened", "code_committed", "code_typed", "staged", "transaction", "committed"} { t.Run(stage, func(t *testing.T) { r := newTokenRig(t) first := r.crashable(stage) id := "cn_c_" + stage link, home := r.signIn(first.Connector, id) code := codeFor(link, "c@example.com") cmd := r.sealedCode(id, code, 1, nil) acked := r.deliver(first.Connector, "f-code", cmd) if acked == (stage == "code_opened" || stage == "code_committed") { t.Fatalf("acked %v through a stop at %s", acked, stage) } if stage != "code_opened" && stage != "code_committed" { r.waitFor(first.dead.Load, "the stop") } first.crash(r) r.gone() second := r.connector() if !r.deliver(second, "f-code", cmd) { t.Fatal(r.errs) } token := fakeclaude.Token("c@example.com") if stage == "committed" { r.healthy2(id, home, token, "c@example.com", 1) return } if end := r.ended(id); end.State != wire.ConnError || end.Reason != "runner_offline" { t.Fatalf("end %+v", end) } if _, err := os.Stat(home); !os.IsNotExist(err) { t.Fatalf("home %v", err) } if want := map[bool]int{true: 0, false: 1}[stage == "code_opened"]; r.seals(id) != want { t.Fatalf("%d seals", r.seals(id)) } r.nowhere(code, "code") r.nowhere(token, "token") }) } } // The CLI killed mid-sign-in by its own crash (not the runner's): it is // started again with a new link, and nothing is left of the first run. func TestSignInCLIDies(t *testing.T) { t.Parallel() r := newTokenRig(t) c := r.connector() link, _ := r.signIn(c, "cn_d1") pids := r.pids() if err := unix.Kill(pids[0], unix.SIGKILL); err != nil { t.Fatal(err) } p := r.prompt("cn_d1", 2) if p.URL == link || p.WrongCode || len(r.pids()) != 2 { t.Fatalf("card %+v", p) } if err := c.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_d1", Person: connPerson}); err != nil { t.Fatal(err) } r.ended("cn_d1") r.gone() if len(r.errs) != 0 && !errors.Is(r.errs[0], errStopped) { t.Fatal(r.errs) } } // A connect frame that still says same_machine (from an instance before // the loopback sign-in went) is the sign-in by a link: the runner has no // other way to sign Claude in. func TestSignInIgnoresSameMachine(t *testing.T) { t.Parallel() r := newTokenRig(t) c := r.connector() if err := c.Accept(r.ctx, "f-connect", wire.ConnectCommand{Connection: "cn_m1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription, SameMachine: true}); err != nil { t.Fatal(err) } link := r.prompt("cn_m1", 1).URL if !r.deliver(c, "f-code", r.sealedCode("cn_m1", codeFor(link, "m@example.com"), 1, nil)) { t.Fatal(r.errs) } if end := r.ended("cn_m1"); end.State != wire.ConnHealthy { t.Fatalf("end %+v", end) } } // A start after a crash proves a sign-in's namespace gone before it // removes the attempt's home: while it cannot (a namespace survived and // would not die), the home stays and the attempt runs on, unreported; // once it can, the attempt ends runner_offline and the home goes. func TestSignInRecoveryProvesNamespaceGone(t *testing.T) { t.Parallel() r := newTokenRig(t) first := r.crashable("never") _, home := r.signIn(first.Connector, "cn_g1") first.crash(r) if _, err := r.state.db.Exec("UPDATE connect_attempts SET namespace='ns-of-cn_g1' WHERE id='cn_g1'"); err != nil { t.Fatal(err) } start := func(gone func(context.Context, string) error) { keys := r.keys c := &Connector{Runner: r.cfg, State: r.state, Conns: r.conns, Root: r.root, Owners: []string{connPerson}, Seal: &keys, RunnerID: tokenRunner, Limit: time.Hour, Logger: slog.New(slog.NewTextHandler(&r.logs, nil))} c.spawn, c.terminal, c.gone = func(f func()) { f() }, r.execTerminal, gone if err := c.Start(r.ctx); err != nil { t.Fatal(err) } } var asked []string start(func(_ context.Context, id string) error { asked = append(asked, id); return errors.New("survived") }) var state string _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id='cn_g1'").Scan(&state) if _, err := os.Stat(home); err != nil || state != "running" || len(asked) != 1 || asked[0] != "ns-of-cn_g1" { t.Fatalf("home %v, state %s, asked %v", err, state, asked) } for _, v := range r.reports("cn_g1") { if v.State != wire.ConnConnecting { t.Fatalf("reported %+v", v) } } start(func(context.Context, string) error { return nil }) if end := r.ended("cn_g1"); end.Reason != "runner_offline" { t.Fatalf("end %+v", end) } if _, err := os.Stat(home); !os.IsNotExist(err) { t.Fatalf("home %v", err) } }