| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "errors" |
| 7 | "io/fs" |
| 8 | "log/slog" |
| 9 | "net/url" |
| 10 | "os" |
| 11 | "path/filepath" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "sync/atomic" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/fakeclaude" |
| 19 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 20 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 21 | "amadan.net/oficina/equipo/internal/wire" |
| 22 | "golang.org/x/sys/unix" |
| 23 | ) |
| 24 | |
| 25 | // Claude with no terminal (signin.go): the runner's own `claude |
| 26 | // setup-token` (the fake, steered from SetupSteerFile beside it) in a |
| 27 | // pseudo-terminal, the link it prints on the card, the code sealed and |
| 28 | // typed into it, the token it prints kept and checked. |
| 29 | |
| 30 | // steer writes the fake setup-token's steering words. |
| 31 | func (r *tokenRig) steer(words ...string) { |
| 32 | r.t.Helper() |
| 33 | if err := os.WriteFile(filepath.Join(r.dir, "bin", fakeclaude.SetupSteerFile), []byte(strings.Join(words, "\n")), 0600); err != nil { |
| 34 | r.t.Fatal(err) |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // crashable starts a connector that can be stopped at a delivery |
| 39 | // boundary, for the durable state each boundary leaves: at stage (or at |
| 40 | // once, by crash) every later boundary stops too and its context ends, |
| 41 | // so its CLI is stopped and nothing it does after reaches the state. It |
| 42 | // is not a process death; that is TestHeadlessSignInRunnerKilled |
| 43 | // (SIGKILL to a real runner process, its namespace recovered). |
| 44 | type crashable struct { |
| 45 | *Connector |
| 46 | cancel context.CancelFunc |
| 47 | dead atomic.Bool |
| 48 | } |
| 49 | |
| 50 | func (r *tokenRig) crashable(stage string) *crashable { |
| 51 | r.t.Helper() |
| 52 | ctx, cancel := context.WithCancel(r.ctx) |
| 53 | keys := r.keys |
| 54 | limit := time.Hour |
| 55 | if r.limit > 0 { |
| 56 | limit = r.limit |
| 57 | } |
| 58 | k := &crashable{cancel: cancel} |
| 59 | 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))} |
| 60 | k.spawn = func(f func()) { f() } |
| 61 | k.terminal = r.execTerminal |
| 62 | k.fault = func(at string) error { |
| 63 | if at == stage { |
| 64 | k.dead.Store(true) |
| 65 | } |
| 66 | if k.dead.Load() { |
| 67 | return errStopped |
| 68 | } |
| 69 | return nil |
| 70 | } |
| 71 | if err := k.Start(ctx); err != nil { |
| 72 | r.t.Fatal(err) |
| 73 | } |
| 74 | return k |
| 75 | } |
| 76 | |
| 77 | // crash stops the process: the boundaries stop, the context ends (the |
| 78 | // CLI is killed), and its attempts have returned. |
| 79 | func (k *crashable) crash(r *tokenRig) { |
| 80 | r.t.Helper() |
| 81 | k.dead.Store(true) |
| 82 | k.cancel() |
| 83 | r.waitFor(func() bool { |
| 84 | k.mu.Lock() |
| 85 | defer k.mu.Unlock() |
| 86 | return len(k.attempts) == 0 |
| 87 | }, "the stopped process's attempts to return") |
| 88 | } |
| 89 | |
| 90 | // signIn starts a sign-in attempt and waits for its card's link. |
| 91 | func (r *tokenRig) signIn(c *Connector, id string) (string, string) { |
| 92 | r.t.Helper() |
| 93 | if err := c.Accept(r.ctx, "f-connect-"+id, wire.ConnectCommand{Connection: id, Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil { |
| 94 | r.t.Fatal(err) |
| 95 | } |
| 96 | p := r.prompt(id, 1) |
| 97 | var home string |
| 98 | _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home) |
| 99 | if home == "" || filepath.Dir(home) != r.root { |
| 100 | r.t.Fatalf("attempt home %q", home) |
| 101 | } |
| 102 | return p.URL, home |
| 103 | } |
| 104 | |
| 105 | // prompt waits for the card asking for attempt's code. |
| 106 | func (r *tokenRig) prompt(id string, attempt int64) wire.ConnectPrompt { |
| 107 | r.t.Helper() |
| 108 | var got wire.ConnectPrompt |
| 109 | r.waitFor(func() bool { |
| 110 | for _, v := range r.reports(id) { |
| 111 | if v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == wire.PromptAuthorize && v.Prompt.Attempt == attempt && v.Prompt.URL != "" { |
| 112 | got = *v.Prompt |
| 113 | return true |
| 114 | } |
| 115 | } |
| 116 | return false |
| 117 | }, "the sign-in card for attempt "+strconv.FormatInt(attempt, 10)) |
| 118 | if _, ok := connect.AuthorizeURL(got.URL); !ok { |
| 119 | r.t.Fatalf("card link %q", got.URL) |
| 120 | } |
| 121 | return got |
| 122 | } |
| 123 | |
| 124 | // codeFor is the code Anthropic's page shows for email after the sign-in |
| 125 | // that link started. |
| 126 | func codeFor(link, email string) string { |
| 127 | u, _ := url.Parse(link) |
| 128 | return fakeclaude.SetupCode(email, u.Query().Get("state")) |
| 129 | } |
| 130 | |
| 131 | // sealedCode is a code's box, as the page seals it. |
| 132 | func (r *tokenRig) sealedCode(id, code string, attempt int64, change func(*wire.SealedPayload)) wire.SecretCommand { |
| 133 | r.t.Helper() |
| 134 | return r.sealed(id, code, func(p *wire.SealedPayload) { |
| 135 | p.Endpoint, p.Attempt = wire.EndpointClaudeCode, attempt |
| 136 | if change != nil { |
| 137 | change(p) |
| 138 | } |
| 139 | }) |
| 140 | } |
| 141 | |
| 142 | // pids are the fake CLI's runs so far. |
| 143 | func (r *tokenRig) pids() []int { |
| 144 | raw, _ := os.ReadFile(filepath.Join(r.dir, "bin", fakeclaude.SetupPidFile)) |
| 145 | var out []int |
| 146 | for _, l := range strings.Fields(string(raw)) { |
| 147 | n, _ := strconv.Atoi(l) |
| 148 | out = append(out, n) |
| 149 | } |
| 150 | return out |
| 151 | } |
| 152 | |
| 153 | // gone waits until every run of the CLI has exited. |
| 154 | func (r *tokenRig) gone() { |
| 155 | r.t.Helper() |
| 156 | r.waitFor(func() bool { |
| 157 | for _, pid := range r.pids() { |
| 158 | // A zombie is reaped by its parent's Wait; kill(0) on one |
| 159 | // still succeeds, so read its state. |
| 160 | raw, err := os.ReadFile("/proc/" + strconv.Itoa(pid) + "/stat") |
| 161 | if err == nil && !bytes.Contains(raw, []byte(") Z ")) { |
| 162 | return false |
| 163 | } |
| 164 | } |
| 165 | return true |
| 166 | }, "the CLI to have exited") |
| 167 | } |
| 168 | |
| 169 | // nowhere fails if secret is in any file under the rig's directory (the |
| 170 | // runner's state database and its WAL, the homes, the fake's records). |
| 171 | func (r *tokenRig) nowhere(secret, what string) { |
| 172 | r.t.Helper() |
| 173 | _ = filepath.WalkDir(r.dir, func(path string, d fs.DirEntry, err error) error { |
| 174 | if err != nil || d.IsDir() || filepath.Dir(path) == filepath.Join(r.dir, "bin") && d.Name() == "claude" { |
| 175 | return nil |
| 176 | } |
| 177 | if raw, _ := os.ReadFile(path); bytes.Contains(raw, []byte(secret)) { |
| 178 | r.t.Fatalf("the %s is in %s", what, path) |
| 179 | } |
| 180 | return nil |
| 181 | }) |
| 182 | if bytes.Contains(r.logs.Bytes(), []byte(secret)) { |
| 183 | r.t.Fatalf("the %s is in the runner's log", what) |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | // The whole sign-in: the CLI started on a terminal in the attempt's own |
| 188 | // home with BROWSER a no-op (else the fake opens nothing and exits), its |
| 189 | // link on the card, the code sealed, typed in, the token it printed kept |
| 190 | // 0600 and checked by one real request before the connection is healthy. |
| 191 | // The CLI's argv is setup-token alone; the code is on no disk and in no |
| 192 | // log, the token only in its file. |
| 193 | func TestSignInConnect(t *testing.T) { |
| 194 | t.Parallel() |
| 195 | r := newTokenRig(t) |
| 196 | c := r.connector() |
| 197 | link, home := r.signIn(c, "cn_s1") |
| 198 | if len(r.pids()) != 1 { |
| 199 | t.Fatalf("%d runs of the CLI", len(r.pids())) |
| 200 | } |
| 201 | code := codeFor(link, "s@example.com") |
| 202 | if !r.deliver(c, "f-code", r.sealedCode("cn_s1", code, 1, nil)) { |
| 203 | t.Fatal(r.errs) |
| 204 | } |
| 205 | token := fakeclaude.Token("s@example.com") |
| 206 | r.healthy("cn_s1", home, token, "s@example.com") |
| 207 | if r.checks.Load() != 1 { |
| 208 | t.Fatalf("%d real checks", r.checks.Load()) |
| 209 | } |
| 210 | r.gone() |
| 211 | argv, _ := os.ReadFile(filepath.Join(r.dir, "bin", fakeclaude.SetupArgvFile)) |
| 212 | if string(argv) != "setup-token\n" { |
| 213 | t.Fatalf("argv %q", argv) |
| 214 | } |
| 215 | r.nowhere(code, "code") |
| 216 | r.nowhere(strings.TrimPrefix(code, "fakecode-"), "code") |
| 217 | // The token: in its file and nowhere else. |
| 218 | tokenFile := filepath.Join(home, provider.TokenFile) |
| 219 | _ = filepath.WalkDir(r.dir, func(path string, d fs.DirEntry, err error) error { |
| 220 | if err == nil && !d.IsDir() && path != tokenFile { |
| 221 | if raw, _ := os.ReadFile(path); bytes.Contains(raw, []byte(token)) { |
| 222 | t.Fatalf("the token is in %s", path) |
| 223 | } |
| 224 | } |
| 225 | return nil |
| 226 | }) |
| 227 | for _, v := range r.reports("cn_s1") { |
| 228 | if v.Prompt != nil && (strings.Contains(v.Prompt.URL, code) || v.Prompt.Code != "") { |
| 229 | t.Fatalf("report %+v", v) |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // The check is what makes the connection: a token the provider refuses |
| 235 | // ends the attempt provider_refused, nothing kept. |
| 236 | func TestSignInTokenRejected(t *testing.T) { |
| 237 | t.Parallel() |
| 238 | r := newTokenRig(t) |
| 239 | c := r.connector() |
| 240 | refused := error(provider.ErrLoginRequired) |
| 241 | r.refuse.Store(&refused) |
| 242 | link, home := r.signIn(c, "cn_s2") |
| 243 | r.deliver(c, "f-code", r.sealedCode("cn_s2", codeFor(link, "s2@example.com"), 1, nil)) |
| 244 | end := r.ended("cn_s2") |
| 245 | if end.State != wire.ConnError || end.Reason != "provider_refused" || r.checks.Load() != 1 { |
| 246 | t.Fatalf("end %+v after %d checks", end, r.checks.Load()) |
| 247 | } |
| 248 | r.waitFor(func() bool { _, err := os.Stat(home); return os.IsNotExist(err) }, "the home to go") |
| 249 | if _, ok := r.binding(filepath.Base(home)); ok { |
| 250 | t.Fatal("bound") |
| 251 | } |
| 252 | for _, v := range r.reports("cn_s2") { |
| 253 | if v.State == wire.ConnHealthy { |
| 254 | t.Fatal("healthy before the check") |
| 255 | } |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | // Wrong codes while the CLI asks again (as 2.1.312 does, read |
| 260 | // statically: after "OAuth error: ..." it waits for Enter, which the |
| 261 | // runner presses). A code it cannot read: the same link. A code the |
| 262 | // exchange refuses: a new sign-in, a new link, in the same run. The card |
| 263 | // says the code was wrong each time; the right code for the latest link |
| 264 | // connects. |
| 265 | func TestSignInWrongCodeAgain(t *testing.T) { |
| 266 | t.Parallel() |
| 267 | r := newTokenRig(t) |
| 268 | c := r.connector() |
| 269 | link, home := r.signIn(c, "cn_w1") |
| 270 | r.deliver(c, "f-code-1", r.sealedCode("cn_w1", "notacode-without-a-state", 1, nil)) |
| 271 | p := r.prompt("cn_w1", 2) |
| 272 | if p.URL != link || !p.WrongCode { |
| 273 | t.Fatalf("second card %+v", p) |
| 274 | } |
| 275 | r.deliver(c, "f-code-2", r.sealedCode("cn_w1", "fakecode-not-the-right-one#x", 2, nil)) |
| 276 | p3 := r.prompt("cn_w1", 3) |
| 277 | if p3.URL == link || !p3.WrongCode { |
| 278 | t.Fatalf("third card %+v", p3) |
| 279 | } |
| 280 | if len(r.pids()) != 1 { |
| 281 | t.Fatal("the CLI was started again") |
| 282 | } |
| 283 | r.deliver(c, "f-code-3", r.sealedCode("cn_w1", codeFor(p3.URL, "w@example.com"), 3, nil)) |
| 284 | r.healthy2("cn_w1", home, fakeclaude.Token("w@example.com"), "w@example.com", 3) |
| 285 | } |
| 286 | |
| 287 | // healthy2 is healthy for an attempt that took seals boxes. |
| 288 | func (r *tokenRig) healthy2(id, home, token, email string, seals int) { |
| 289 | r.t.Helper() |
| 290 | end := r.ended(id) |
| 291 | if end.State != wire.ConnHealthy || end.LocalID != filepath.Base(home) || end.Label != email || r.seals(id) != seals { |
| 292 | r.t.Fatalf("end %+v, %d seals", end, r.seals(id)) |
| 293 | } |
| 294 | raw, err := os.ReadFile(filepath.Join(home, provider.TokenFile)) |
| 295 | if err != nil || string(raw) != token { |
| 296 | r.t.Fatalf("token file: %v", err) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | // A wrong code the CLI exits on: it is started again, and the card says |
| 301 | // the code was wrong with the new link. The first link's code does not |
| 302 | // work on the new run; the new one's does. |
| 303 | func TestSignInWrongCodeRestarts(t *testing.T) { |
| 304 | t.Parallel() |
| 305 | r := newTokenRig(t) |
| 306 | r.steer("exit_on_wrong") |
| 307 | c := r.connector() |
| 308 | link, home := r.signIn(c, "cn_w2") |
| 309 | r.deliver(c, "f-code-1", r.sealedCode("cn_w2", "fakecode-wrong#x", 1, nil)) |
| 310 | p := r.prompt("cn_w2", 2) |
| 311 | if p.URL == link || !p.WrongCode || len(r.pids()) != 2 { |
| 312 | t.Fatalf("second card %+v after %d runs", p, len(r.pids())) |
| 313 | } |
| 314 | r.deliver(c, "f-code-2", r.sealedCode("cn_w2", codeFor(link, "w2@example.com"), 2, nil)) |
| 315 | p3 := r.prompt("cn_w2", 3) |
| 316 | if p3.URL == p.URL || !p3.WrongCode { |
| 317 | t.Fatalf("third card %+v", p3) |
| 318 | } |
| 319 | r.deliver(c, "f-code-3", r.sealedCode("cn_w2", codeFor(p3.URL, "w2@example.com"), 3, nil)) |
| 320 | r.healthy2("cn_w2", home, fakeclaude.Token("w2@example.com"), "w2@example.com", 3) |
| 321 | } |
| 322 | |
| 323 | // The CLI's own time limit: it exits waiting; it is started again with a |
| 324 | // new link (no wrong code said), up to maxLaunches runs, then the |
| 325 | // attempt ends timed_out, the home gone. |
| 326 | func TestSignInCLIExpires(t *testing.T) { |
| 327 | t.Parallel() |
| 328 | r := newTokenRig(t) |
| 329 | r.steer("expire_ms=300") |
| 330 | c := r.connector() |
| 331 | link, home := r.signIn(c, "cn_e1") |
| 332 | p := r.prompt("cn_e1", 2) |
| 333 | if p.URL == link || p.WrongCode { |
| 334 | t.Fatalf("second card %+v", p) |
| 335 | } |
| 336 | end := r.ended("cn_e1") |
| 337 | if end.State != wire.ConnError || end.Reason != "timed_out" || len(r.pids()) != maxLaunches { |
| 338 | t.Fatalf("end %+v after %d runs", end, len(r.pids())) |
| 339 | } |
| 340 | if _, err := os.Stat(home); !os.IsNotExist(err) { |
| 341 | t.Fatalf("home %v", err) |
| 342 | } |
| 343 | r.gone() |
| 344 | } |
| 345 | |
| 346 | // The CLI fails before any link: provider_refused, the home gone. |
| 347 | func TestSignInCLIFailsToStart(t *testing.T) { |
| 348 | t.Parallel() |
| 349 | r := newTokenRig(t) |
| 350 | r.steer("fail_start") |
| 351 | c := r.connector() |
| 352 | if err := c.Accept(r.ctx, "f-connect", wire.ConnectCommand{Connection: "cn_f1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindSubscription}); err != nil { |
| 353 | t.Fatal(err) |
| 354 | } |
| 355 | if end := r.ended("cn_f1"); end.State != wire.ConnError || end.Reason != "provider_refused" { |
| 356 | t.Fatalf("end %+v", end) |
| 357 | } |
| 358 | if entries, _ := os.ReadDir(r.root); len(entries) != 0 { |
| 359 | t.Fatalf("left %v", entries) |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | // Cancel, and the attempt's own time limit: the CLI and its group are |
| 364 | // killed, the home deleted, the end reported; a code after is acked and |
| 365 | // dropped, never typed. |
| 366 | func TestSignInCancelAndLimit(t *testing.T) { |
| 367 | t.Parallel() |
| 368 | r := newTokenRig(t) |
| 369 | c := r.connector() |
| 370 | link, home := r.signIn(c, "cn_k1") |
| 371 | if err := c.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_k1", Person: connPerson}); err != nil { |
| 372 | t.Fatal(err) |
| 373 | } |
| 374 | if end := r.ended("cn_k1"); end.State != wire.ConnError || end.Reason != "cancelled" { |
| 375 | t.Fatalf("end %+v", end) |
| 376 | } |
| 377 | r.gone() |
| 378 | if _, err := os.Stat(home); !os.IsNotExist(err) { |
| 379 | t.Fatalf("home %v", err) |
| 380 | } |
| 381 | if !r.deliver(c, "f-late", r.sealedCode("cn_k1", codeFor(link, "k@example.com"), 1, nil)) || r.seals("cn_k1") != 0 { |
| 382 | t.Fatal("a late code was not dropped") |
| 383 | } |
| 384 | |
| 385 | r.limit = 1500 * time.Millisecond |
| 386 | c = r.connector() |
| 387 | _, home = r.signIn(c, "cn_k2") |
| 388 | if end := r.ended("cn_k2"); end.State != wire.ConnError || end.Reason != "timed_out" { |
| 389 | t.Fatalf("end %+v", end) |
| 390 | } |
| 391 | r.gone() |
| 392 | if _, err := os.Stat(home); !os.IsNotExist(err) { |
| 393 | t.Fatalf("home %v", err) |
| 394 | } |
| 395 | } |
| 396 | |
| 397 | // A code's box: the resend is acked and nothing else; a box for an |
| 398 | // attempt the CLI no longer waits for is dropped and the attempt waits |
| 399 | // on; a code bound as a token, an expired box, a token sealed as the |
| 400 | // code and a box for another runner are refused, ending the attempt; a |
| 401 | // code's box to a token attempt is refused too. (The code bound as a |
| 402 | // token would sign in: only its binding refuses it.) |
| 403 | func TestSignInCodeReplayAndRefusals(t *testing.T) { |
| 404 | t.Parallel() |
| 405 | r := newTokenRig(t) |
| 406 | c := r.connector() |
| 407 | link, home := r.signIn(c, "cn_r1") |
| 408 | r.deliver(c, "f-stale", r.sealedCode("cn_r1", codeFor(link, "r@example.com"), 2, nil)) |
| 409 | if r.seals("cn_r1") != 0 || len(r.reports("cn_r1")) != 1 { |
| 410 | t.Fatal("a stale attempt's box was taken") |
| 411 | } |
| 412 | cmd := r.sealedCode("cn_r1", codeFor(link, "r@example.com"), 1, nil) |
| 413 | r.deliver(c, "f-1", cmd) |
| 414 | r.healthy2("cn_r1", home, fakeclaude.Token("r@example.com"), "r@example.com", 1) |
| 415 | reports, logged := len(r.reports("cn_r1")), r.logs.Len() |
| 416 | for _, frame := range []string{"f-1", "f-1-again"} { |
| 417 | if !r.deliver(c, frame, cmd) { |
| 418 | t.Fatal(r.errs) |
| 419 | } |
| 420 | } |
| 421 | if r.logs.Len() != logged || len(r.reports("cn_r1")) != reports || r.seals("cn_r1") != 1 || len(r.pids()) != 1 { |
| 422 | t.Fatal("a replay was handled again") |
| 423 | } |
| 424 | |
| 425 | for i, x := range []struct { |
| 426 | name, reason string |
| 427 | box func(id, link string) wire.SecretCommand |
| 428 | }{ |
| 429 | {"a code bound as a token", "provider_refused", func(id, link string) wire.SecretCommand { |
| 430 | return r.sealed(id, codeFor(link, "x@example.com"), nil) |
| 431 | }}, |
| 432 | {"expired", "timed_out", func(id, link string) wire.SecretCommand { |
| 433 | return r.sealedCode(id, codeFor(link, "x@example.com"), 1, func(p *wire.SealedPayload) { p.ExpiresAt = time.Now().Add(-time.Second).UTC() }) |
| 434 | }}, |
| 435 | {"a token as the code", "provider_refused", func(id, link string) wire.SecretCommand { |
| 436 | return r.sealedCode(id, fakeclaude.Token("x@example.com"), 1, nil) |
| 437 | }}, |
| 438 | {"another runner", "provider_refused", func(id, link string) wire.SecretCommand { |
| 439 | return r.sealedCode(id, codeFor(link, "x@example.com"), 1, func(p *wire.SealedPayload) { p.RunnerID = "run_other" }) |
| 440 | }}, |
| 441 | } { |
| 442 | t.Run(x.name, func(t *testing.T) { |
| 443 | id := "cn_x" + strconv.Itoa(i) |
| 444 | link, home := r.signIn(c, id) |
| 445 | if !r.deliver(c, "f-"+id, x.box(id, link)) { |
| 446 | t.Fatal("not acked") |
| 447 | } |
| 448 | if end := r.ended(id); end.State != wire.ConnError || end.Reason != x.reason { |
| 449 | t.Fatalf("end %+v", end) |
| 450 | } |
| 451 | if _, err := os.Stat(home); !os.IsNotExist(err) || r.seals(id) != 0 { |
| 452 | t.Fatalf("home %v, %d seals", err, r.seals(id)) |
| 453 | } |
| 454 | }) |
| 455 | } |
| 456 | r.gone() |
| 457 | home = r.connect(c, "cn_t1") |
| 458 | r.deliver(c, "f-t1", r.sealedCode("cn_t1", "fakecode-00#x", 1, func(p *wire.SealedPayload) { p.Attempt = 1 })) |
| 459 | if end := r.ended("cn_t1"); end.Reason != "provider_refused" || r.seals("cn_t1") != 0 { |
| 460 | t.Fatalf("a token attempt took a code: %+v", end) |
| 461 | } |
| 462 | if _, err := os.Stat(home); !os.IsNotExist(err) { |
| 463 | t.Fatal(err) |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | // A stop at each boundary of a code's delivery and its token's keeping |
| 468 | // (crashable; the real kill is TestHeadlessSignInRunnerKilled). |
| 469 | // Before the token is committed the CLI died with the process: the |
| 470 | // restart ends the attempt runner_offline and deletes its home (with any |
| 471 | // staged or renamed token file), and the resent box is acked and |
| 472 | // dropped. Once committed, the restart carries the attempt on as a token |
| 473 | // attempt to healthy. The code is never on disk. |
| 474 | func TestSignInSurvivesCrashes(t *testing.T) { |
| 475 | t.Parallel() |
| 476 | for _, stage := range []string{"code_opened", "code_committed", "code_typed", "staged", "transaction", "committed"} { |
| 477 | t.Run(stage, func(t *testing.T) { |
| 478 | r := newTokenRig(t) |
| 479 | first := r.crashable(stage) |
| 480 | id := "cn_c_" + stage |
| 481 | link, home := r.signIn(first.Connector, id) |
| 482 | code := codeFor(link, "c@example.com") |
| 483 | cmd := r.sealedCode(id, code, 1, nil) |
| 484 | acked := r.deliver(first.Connector, "f-code", cmd) |
| 485 | if acked == (stage == "code_opened" || stage == "code_committed") { |
| 486 | t.Fatalf("acked %v through a stop at %s", acked, stage) |
| 487 | } |
| 488 | if stage != "code_opened" && stage != "code_committed" { |
| 489 | r.waitFor(first.dead.Load, "the stop") |
| 490 | } |
| 491 | first.crash(r) |
| 492 | r.gone() |
| 493 | second := r.connector() |
| 494 | if !r.deliver(second, "f-code", cmd) { |
| 495 | t.Fatal(r.errs) |
| 496 | } |
| 497 | token := fakeclaude.Token("c@example.com") |
| 498 | if stage == "committed" { |
| 499 | r.healthy2(id, home, token, "c@example.com", 1) |
| 500 | return |
| 501 | } |
| 502 | if end := r.ended(id); end.State != wire.ConnError || end.Reason != "runner_offline" { |
| 503 | t.Fatalf("end %+v", end) |
| 504 | } |
| 505 | if _, err := os.Stat(home); !os.IsNotExist(err) { |
| 506 | t.Fatalf("home %v", err) |
| 507 | } |
| 508 | if want := map[bool]int{true: 0, false: 1}[stage == "code_opened"]; r.seals(id) != want { |
| 509 | t.Fatalf("%d seals", r.seals(id)) |
| 510 | } |
| 511 | r.nowhere(code, "code") |
| 512 | r.nowhere(token, "token") |
| 513 | }) |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | // The CLI killed mid-sign-in by its own crash (not the runner's): it is |
| 518 | // started again with a new link, and nothing is left of the first run. |
| 519 | func TestSignInCLIDies(t *testing.T) { |
| 520 | t.Parallel() |
| 521 | r := newTokenRig(t) |
| 522 | c := r.connector() |
| 523 | link, _ := r.signIn(c, "cn_d1") |
| 524 | pids := r.pids() |
| 525 | if err := unix.Kill(pids[0], unix.SIGKILL); err != nil { |
| 526 | t.Fatal(err) |
| 527 | } |
| 528 | p := r.prompt("cn_d1", 2) |
| 529 | if p.URL == link || p.WrongCode || len(r.pids()) != 2 { |
| 530 | t.Fatalf("card %+v", p) |
| 531 | } |
| 532 | if err := c.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_d1", Person: connPerson}); err != nil { |
| 533 | t.Fatal(err) |
| 534 | } |
| 535 | r.ended("cn_d1") |
| 536 | r.gone() |
| 537 | if len(r.errs) != 0 && !errors.Is(r.errs[0], errStopped) { |
| 538 | t.Fatal(r.errs) |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | // A connect frame that still says same_machine (from an instance before |
| 543 | // the loopback sign-in went) is the sign-in by a link: the runner has no |
| 544 | // other way to sign Claude in. |
| 545 | func TestSignInIgnoresSameMachine(t *testing.T) { |
| 546 | t.Parallel() |
| 547 | r := newTokenRig(t) |
| 548 | c := r.connector() |
| 549 | 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 { |
| 550 | t.Fatal(err) |
| 551 | } |
| 552 | link := r.prompt("cn_m1", 1).URL |
| 553 | if !r.deliver(c, "f-code", r.sealedCode("cn_m1", codeFor(link, "m@example.com"), 1, nil)) { |
| 554 | t.Fatal(r.errs) |
| 555 | } |
| 556 | if end := r.ended("cn_m1"); end.State != wire.ConnHealthy { |
| 557 | t.Fatalf("end %+v", end) |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | // A start after a crash proves a sign-in's namespace gone before it |
| 562 | // removes the attempt's home: while it cannot (a namespace survived and |
| 563 | // would not die), the home stays and the attempt runs on, unreported; |
| 564 | // once it can, the attempt ends runner_offline and the home goes. |
| 565 | func TestSignInRecoveryProvesNamespaceGone(t *testing.T) { |
| 566 | t.Parallel() |
| 567 | r := newTokenRig(t) |
| 568 | first := r.crashable("never") |
| 569 | _, home := r.signIn(first.Connector, "cn_g1") |
| 570 | first.crash(r) |
| 571 | if _, err := r.state.db.Exec("UPDATE connect_attempts SET namespace='ns-of-cn_g1' WHERE id='cn_g1'"); err != nil { |
| 572 | t.Fatal(err) |
| 573 | } |
| 574 | start := func(gone func(context.Context, string) error) { |
| 575 | keys := r.keys |
| 576 | 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))} |
| 577 | c.spawn, c.terminal, c.gone = func(f func()) { f() }, r.execTerminal, gone |
| 578 | if err := c.Start(r.ctx); err != nil { |
| 579 | t.Fatal(err) |
| 580 | } |
| 581 | } |
| 582 | var asked []string |
| 583 | start(func(_ context.Context, id string) error { asked = append(asked, id); return errors.New("survived") }) |
| 584 | var state string |
| 585 | _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id='cn_g1'").Scan(&state) |
| 586 | if _, err := os.Stat(home); err != nil || state != "running" || len(asked) != 1 || asked[0] != "ns-of-cn_g1" { |
| 587 | t.Fatalf("home %v, state %s, asked %v", err, state, asked) |
| 588 | } |
| 589 | for _, v := range r.reports("cn_g1") { |
| 590 | if v.State != wire.ConnConnecting { |
| 591 | t.Fatalf("reported %+v", v) |
| 592 | } |
| 593 | } |
| 594 | start(func(context.Context, string) error { return nil }) |
| 595 | if end := r.ended("cn_g1"); end.Reason != "runner_offline" { |
| 596 | t.Fatalf("end %+v", end) |
| 597 | } |
| 598 | if _, err := os.Stat(home); !os.IsNotExist(err) { |
| 599 | t.Fatalf("home %v", err) |
| 600 | } |
| 601 | } |
| 602 | |