oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package thin
2
3import (
4 "bytes"
5 "context"
6 "crypto/ed25519"
7 "crypto/rand"
8 "encoding/json"
9 "errors"
10 "log/slog"
11 "os"
12 "path/filepath"
13 "strings"
14 "sync"
15 "sync/atomic"
16 "testing"
17 "time"
18
19 "amadan.net/oficina/equipo/internal/fakeclaude"
20 "amadan.net/oficina/equipo/internal/runner"
21 "amadan.net/oficina/equipo/internal/runner/provider"
22 "amadan.net/oficina/equipo/internal/sealbox"
23 "amadan.net/oficina/equipo/internal/wire"
24)
25
26const tokenRunner = "run_token_1"
27
28// lockedBuffer is a log the connector's goroutines write to.
29type lockedBuffer struct {
30 mu sync.Mutex
31 b bytes.Buffer
32}
33
34func (l *lockedBuffer) Write(p []byte) (int, error) {
35 l.mu.Lock()
36 defer l.mu.Unlock()
37 return l.b.Write(p)
38}
39
40func (l *lockedBuffer) Bytes() []byte {
41 l.mu.Lock()
42 defer l.mu.Unlock()
43 return bytes.Clone(l.b.Bytes())
44}
45
46func (l *lockedBuffer) Len() int { return len(l.Bytes()) }
47
48func (l *lockedBuffer) String() string { return string(l.Bytes()) }
49
50// tokenRig is a runner state with no connections, the fake claude for
51// the status probe, a seal key, and connectors over them that a test
52// can stop and start again as the runner process would.
53type tokenRig struct {
54 t *testing.T
55 dir, root string
56 // limit is the next connector's attempt limit (default an hour).
57 limit time.Duration
58 state *State
59 cfg runner.Config
60 conns *Conns
61 keys sealbox.Keys
62 logs lockedBuffer
63 errs []error
64 ctx context.Context
65 // checks counts the real-request checks (verify); refuse makes the
66 // next ones fail for another reason than the token.
67 checks atomic.Int64
68 refuse atomic.Pointer[error]
69}
70
71func newTokenRig(t *testing.T) *tokenRig { return newTokenRigAt(t, t.TempDir()) }
72
73// newTokenRigAt is the rig in dir.
74func newTokenRigAt(t *testing.T, dir string) *tokenRig {
75 r := &tokenRig{t: t, dir: dir, root: filepath.Join(dir, "accounts")}
76 for _, d := range []string{r.root, filepath.Join(dir, "config"), filepath.Join(dir, "state"), filepath.Join(dir, "bin"), filepath.Join(dir, "scratch")} {
77 if err := os.MkdirAll(d, 0700); err != nil {
78 t.Fatal(err)
79 }
80 }
81 self, _ := os.Executable()
82 raw, err := os.ReadFile(self)
83 if err != nil {
84 t.Fatal(err)
85 }
86 claudePath := filepath.Join(dir, "bin", "claude")
87 if err = os.WriteFile(claudePath, raw, 0755); err != nil {
88 t.Fatal(err)
89 }
90 if r.state, err = OpenState(context.Background(), filepath.Join(dir, "state")); err != nil {
91 t.Fatal(err)
92 }
93 t.Cleanup(func() { r.state.Close() })
94 r.cfg = runner.Config{AccountBindingsPath: filepath.Join(dir, "config", "bindings.json"), ClaudePath: claudePath, CodexPath: "/bin/true", ScratchRoot: filepath.Join(dir, "scratch")}
95 r.conns = &Conns{Runner: r.cfg, State: r.state, Verify: r.verify}
96 _, key, _ := ed25519.GenerateKey(rand.Reader)
97 if r.keys, err = sealbox.FromEd25519(key); err != nil {
98 t.Fatal(err)
99 }
100 ctx, cancel := context.WithCancel(context.Background())
101 t.Cleanup(cancel)
102 r.ctx = ctx
103 return r
104}
105
106// verify is the token check as the provider answers a real request: the
107// fake CLI's turn runs only on a token fakeclaude.Token made. (The
108// contained launch itself is TestHeadlessTokenRejected's.)
109func (r *tokenRig) verify(ctx context.Context, b runner.AccountBinding) error {
110 r.checks.Add(1)
111 if err := r.refuse.Load(); err != nil {
112 return *err
113 }
114 raw, err := provider.ReadToken(b.ProviderHome)
115 if err != nil {
116 return err
117 }
118 defer clear(raw)
119 if !fakeclaude.Accepts(string(raw)) {
120 return provider.ErrLoginRequired
121 }
122 return nil
123}
124
125// connector starts a connector, as a runner process does.
126func (r *tokenRig) connector() *Connector {
127 keys := r.keys
128 limit := time.Hour
129 if r.limit > 0 {
130 limit = r.limit
131 }
132 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))}
133 c.spawn = func(f func()) { f() }
134 c.terminal = r.execTerminal
135 if err := c.Start(r.ctx); err != nil {
136 r.t.Fatal(err)
137 }
138 return c
139}
140
141// connect starts a token attempt and waits for its card.
142func (r *tokenRig) connect(c *Connector, id string) string {
143 r.t.Helper()
144 if err := c.Accept(r.ctx, "f-connect-"+id, wire.ConnectCommand{Connection: id, Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}); err != nil {
145 r.t.Fatal(err)
146 }
147 r.waitFor(func() bool {
148 for _, v := range r.reports(id) {
149 if v.State == wire.ConnConnecting && v.Prompt != nil && v.Prompt.Kind == wire.PromptToken && v.Prompt.Code == "claude setup-token" {
150 return true
151 }
152 }
153 return false
154 }, "the token card")
155 var home string
156 _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id=?", id).Scan(&home)
157 if home == "" || filepath.Dir(home) != r.root {
158 r.t.Fatalf("attempt home %q", home)
159 }
160 return home
161}
162
163// sealed is a box for the attempt, as the app seals it.
164func (r *tokenRig) sealed(id, token string, change func(*wire.SealedPayload)) wire.SecretCommand {
165 r.t.Helper()
166 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()}
167 if change != nil {
168 change(&p)
169 }
170 s, err := sealbox.Seal(r.keys.PublicString(), p)
171 if err != nil {
172 r.t.Fatal(err)
173 }
174 return wire.SecretCommand{Connection: id, Person: connPerson, Sealed: s}
175}
176
177// deliver is the link's handling of one secret frame: the handler, and
178// an ack only when it returns nil.
179func (r *tokenRig) deliver(c *Connector, frame string, cmd wire.SecretCommand) bool {
180 err := c.Secret(r.ctx, frame, cmd)
181 if err != nil {
182 r.errs = append(r.errs, err)
183 }
184 return err == nil
185}
186
187func (r *tokenRig) reports(id string) []wire.ConnectionReport {
188 frames, _, err := r.state.Unacked(context.Background(), 0)
189 if err != nil {
190 r.t.Fatal(err)
191 }
192 var out []wire.ConnectionReport
193 for _, f := range frames {
194 var v wire.ConnectionReport
195 if f.Type == wire.FrameConnection && json.Unmarshal(f.Data, &v) == nil && v.Connection == id {
196 out = append(out, v)
197 }
198 }
199 return out
200}
201
202// ended waits for the attempt's final report.
203func (r *tokenRig) ended(id string) wire.ConnectionReport {
204 r.t.Helper()
205 var last wire.ConnectionReport
206 r.waitFor(func() bool {
207 var state string
208 _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id=?", id).Scan(&state)
209 rs := r.reports(id)
210 // done, or removed once the sign-out it owed has run.
211 if state != "done" && state != "removed" || len(rs) == 0 {
212 return false
213 }
214 last = rs[len(rs)-1]
215 return last.State != wire.ConnConnecting
216 }, "the attempt's end")
217 return last
218}
219
220func (r *tokenRig) waitFor(ok func() bool, what string) {
221 r.t.Helper()
222 deadline := time.Now().Add(20 * time.Second)
223 for !ok() {
224 if time.Now().After(deadline) {
225 r.t.Fatalf("no %s", what)
226 }
227 time.Sleep(20 * time.Millisecond)
228 }
229}
230
231func (r *tokenRig) seals(id string) int {
232 var n int
233 if err := r.state.db.QueryRow("SELECT count(*) FROM seen_seals WHERE connection_id=?", id).Scan(&n); err != nil {
234 r.t.Fatal(err)
235 }
236 return n
237}
238
239func (r *tokenRig) binding(local string) (runner.AccountBinding, bool) {
240 return r.conns.Binding(local)
241}
242
243// healthy checks a delivered attempt ended as one token connection.
244func (r *tokenRig) healthy(id, home, token, email string) {
245 r.t.Helper()
246 end := r.ended(id)
247 local := filepath.Base(home)
248 if end.State != wire.ConnHealthy || end.LocalID != local || end.Label != email {
249 r.t.Fatalf("end %+v", end)
250 }
251 b, ok := r.binding(local)
252 if !ok || b.Kind != wire.KindToken || b.Provider != wire.ProviderClaude || b.PersonID != connPerson {
253 r.t.Fatalf("binding %+v %v", b, ok)
254 }
255 raw, err := os.ReadFile(filepath.Join(home, provider.TokenFile))
256 info, serr := os.Stat(filepath.Join(home, provider.TokenFile))
257 if err != nil || serr != nil || string(raw) != token || info.Mode().Perm() != 0600 {
258 r.t.Fatalf("token file: %v %v", err, serr)
259 }
260 if _, err = os.Lstat(filepath.Join(home, provider.TokenStaging)); !os.IsNotExist(err) {
261 r.t.Fatalf("staging file left: %v", err)
262 }
263 healthy := 0
264 for _, v := range r.reports(id) {
265 if v.State == wire.ConnHealthy {
266 healthy++
267 }
268 }
269 if healthy != 1 || r.seals(id) != 1 {
270 r.t.Fatalf("%d healthy reports, %d seen_seals rows", healthy, r.seals(id))
271 }
272 for _, h := range r.conns.Held() {
273 if h.LocalID == local {
274 if h.Kind != wire.KindToken || h.Label != email || h.ExpiresAt == nil || !h.ExpiresEstimated || time.Until(*h.ExpiresAt) < wire.TokenLifetime-time.Hour {
275 r.t.Fatalf("held %+v", h)
276 }
277 return
278 }
279 }
280 r.t.Fatal("not held")
281}
282
283// A pasted token: the card, the box delivered once, the probe, the
284// binding, healthy with the account's email and a year to run.
285func TestTokenConnect(t *testing.T) {
286 r := newTokenRig(t)
287 c := r.connector()
288 home := r.connect(c, "cn_t1")
289 token := fakeclaude.Token("t@example.com")
290 if !r.deliver(c, "f-secret", r.sealed("cn_t1", token, nil)) {
291 t.Fatal(r.errs)
292 }
293 r.healthy("cn_t1", home, token, "t@example.com")
294 // The expiry stays the same across a restart.
295 before := r.conns.Held()[0].ExpiresAt
296 r.conns = &Conns{Runner: r.cfg, State: r.state, Verify: r.verify}
297 r.connector()
298 if after := r.conns.Held()[0].ExpiresAt; after == nil || !after.Equal(*before) {
299 t.Fatalf("expiry moved: %v %v", before, after)
300 }
301}
302
303// A token whose CLI names no account: healthy, no label.
304func TestTokenConnectWithoutEmail(t *testing.T) {
305 r := newTokenRig(t)
306 c := r.connector()
307 home := r.connect(c, "cn_t2")
308 token := fakeclaude.Token("")
309 r.deliver(c, "f-secret", r.sealed("cn_t2", token, nil))
310 r.healthy("cn_t2", home, token, "")
311 if b, _ := r.binding(filepath.Base(home)); b.AccountID != "token:"+filepath.Base(home) {
312 t.Fatalf("account %q", b.AccountID)
313 }
314}
315
316// A token the provider does not accept: the CLI's status says signed in
317// (it says so for any token), so only the real request finds it out.
318// The attempt ends provider_refused (the app's "This token was
319// rejected"), nothing kept, never healthy.
320func TestTokenRejected(t *testing.T) {
321 r := newTokenRig(t)
322 c := r.connector()
323 home := r.connect(c, "cn_t3")
324 r.deliver(c, "f-secret", r.sealed("cn_t3", "sk-ant-oat01-revoked", nil))
325 if end := r.ended("cn_t3"); end.State != wire.ConnError || end.Reason != "provider_refused" || end.LocalID != "" {
326 t.Fatalf("end %+v", end)
327 }
328 if r.checks.Load() != 1 {
329 t.Fatalf("%d checks", r.checks.Load())
330 }
331 for _, v := range r.reports("cn_t3") {
332 if v.State == wire.ConnHealthy {
333 t.Fatal("a rejected token was healthy")
334 }
335 }
336 // The sign-out recorded with the end deletes the home.
337 r.waitFor(func() bool {
338 _, err := os.Lstat(home)
339 var owed int
340 _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&owed)
341 return os.IsNotExist(err) && owed == 0
342 }, "the rejected token's home deleted")
343 if bs, _ := runner.LoadBindings(r.cfg.AccountBindingsPath); len(bs) != 0 || len(r.conns.Held()) != 0 {
344 t.Fatal("a rejected token was bound")
345 }
346}
347
348// A check that cannot finish (no reply, no refusal) proves nothing: the
349// attempt ends in error and nothing is kept.
350func TestTokenCheckUnfinished(t *testing.T) {
351 r := newTokenRig(t)
352 stopped := errCheckFailed
353 r.refuse.Store(&stopped)
354 c := r.connector()
355 home := r.connect(c, "cn_t4")
356 r.deliver(c, "f-secret", r.sealed("cn_t4", fakeclaude.Token("u@example.com"), nil))
357 if end := r.ended("cn_t4"); end.State != wire.ConnError || end.Reason != "provider_refused" || end.LocalID != "" {
358 t.Fatalf("end %+v", end)
359 }
360 // The sign-out recorded with the end deletes the home.
361 r.waitFor(func() bool {
362 _, err := os.Lstat(home)
363 return os.IsNotExist(err)
364 }, "the unchecked token's home deleted")
365 if bs, _ := runner.LoadBindings(r.cfg.AccountBindingsPath); len(bs) != 0 {
366 t.Fatal("an unchecked token stayed bound")
367 }
368}
369
370// The hourly pass never clears a real rejection, and never spends a
371// request: it asks only the CLI's local status, which says signed in for
372// any token. A turn's refusal marks a token connection sign_in_again; a
373// Check again (one small request) that fails for any reason keeps it;
374// one the provider answers clears it, and so does any answered run.
375func TestTokenRejectionSurvivesHourlyCheck(t *testing.T) {
376 r := newTokenRig(t)
377 c := r.connector()
378 home := r.connect(c, "cn_h1")
379 r.deliver(c, "f-secret", r.sealed("cn_h1", fakeclaude.Token(""), nil))
380 r.ended("cn_h1")
381 local := filepath.Base(home)
382 state := func() string {
383 for _, h := range r.conns.Held() {
384 if h.LocalID == local {
385 return h.State
386 }
387 }
388 return "gone"
389 }
390 if state() != wire.ConnHealthy {
391 t.Fatalf("state %s", state())
392 }
393 // The provider revokes the token: a turn is refused.
394 if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte("sk-ant-oat01-revoked-later"), 0600); err != nil {
395 t.Fatal(err)
396 }
397 r.conns.SignInAgain(local)
398 // The hourly pass, with the CLI's own status as the refresh: it says
399 // signed in, spends no request and decides nothing.
400 paths := provider.LoginOptions{ClaudePath: r.cfg.ClaudePath, CodexPath: r.cfg.CodexPath}
401 r.conns.Refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) {
402 return provider.RefreshLogin(ctx, b, paths)
403 }
404 before := r.checks.Load()
405 for i := 0; i < 3; i++ {
406 r.conns.Check(r.ctx)
407 }
408 if state() != wire.ConnSignInAgain || r.checks.Load() != before {
409 t.Fatalf("after the hourly passes: %s, %d real checks", state(), r.checks.Load()-before)
410 }
411 // Check again that does not finish, or with no checker: unchanged.
412 busy := errors.New("the check did not finish")
413 r.refuse.Store(&busy)
414 r.conns.CheckAgain(r.ctx, local)
415 if state() != wire.ConnSignInAgain || r.checks.Load() != before+1 {
416 t.Fatalf("an unfinished check changed the rejection: %s", state())
417 }
418 verify := r.conns.Verify
419 r.conns.Verify = nil
420 r.conns.CheckAgain(r.ctx, local)
421 if state() != wire.ConnSignInAgain {
422 t.Fatalf("without a check: %s", state())
423 }
424 // The provider answers again: Check again clears it.
425 r.conns.Verify = verify
426 r.refuse.Store(nil)
427 if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(fakeclaude.Token("")), 0600); err != nil {
428 t.Fatal(err)
429 }
430 r.conns.CheckAgain(r.ctx, local)
431 if state() != wire.ConnHealthy {
432 t.Fatalf("after an answered check: %s", state())
433 }
434 // Refused again, then a run on it is answered: that clears it too.
435 r.conns.SignInAgain(local)
436 r.conns.Answered(local)
437 if state() != wire.ConnHealthy {
438 t.Fatalf("after an answered run: %s", state())
439 }
440}
441
442// A stop after the binding is saved and before the attempt is marked
443// done. The restarted runner finds its own binding (same home, same
444// attempt): it is not a second connection of the same account. Without
445// a cancel the attempt finishes healthy, once; with a cancel recorded,
446// the sign-out it owes is recorded durably and the home and its token
447// are deleted.
448func TestTokenRecoversSavedBinding(t *testing.T) {
449 for _, cancelled := range []bool{false, true} {
450 t.Run(map[bool]string{false: "kept", true: "cancelled"}[cancelled], func(t *testing.T) {
451 r := newTokenRig(t)
452 first := r.connector()
453 stopped := make(chan struct{})
454 first.fault = func(at string) error {
455 if at == "bound" {
456 close(stopped)
457 return errStopped
458 }
459 return nil
460 }
461 id := "cn_b_" + map[bool]string{false: "kept", true: "cancelled"}[cancelled]
462 home := r.connect(first, id)
463 token := fakeclaude.Token("b@example.com")
464 if !r.deliver(first, "f-secret", r.sealed(id, token, nil)) {
465 t.Fatal(r.errs)
466 }
467 select {
468 case <-stopped:
469 case <-time.After(20 * time.Second):
470 t.Fatal("never reached the saved binding")
471 }
472 local := filepath.Base(home)
473 r.waitFor(func() bool {
474 var state string
475 _ = r.state.db.QueryRow("SELECT state FROM connect_attempts WHERE id=?", id).Scan(&state)
476 _, ok := r.binding(local)
477 return ok && state == "running"
478 }, "the stop between the binding and the attempt's end")
479 if cancelled {
480 if err := first.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: id, Person: connPerson}); err != nil {
481 t.Fatal(err)
482 }
483 }
484 r.connector()
485 for _, v := range r.reports(id) {
486 if v.Reason == "already_connected" {
487 t.Fatalf("its own binding called a second connection: %+v", v)
488 }
489 }
490 if !cancelled {
491 r.healthy(id, home, token, "b@example.com")
492 return
493 }
494 if end := r.ended(id); end.State != wire.ConnError || end.Reason != "cancelled" || end.LocalID != "" {
495 t.Fatalf("end %+v", end)
496 }
497 r.waitFor(func() bool {
498 _, err := os.Lstat(home)
499 var owed int
500 _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&owed)
501 return os.IsNotExist(err) && owed == 0
502 }, "the cancelled token's home deleted and nothing owed")
503 if _, ok := r.binding(local); ok || len(r.conns.Held()) != 0 {
504 t.Fatal("the cancelled token stayed bound")
505 }
506 })
507 }
508}
509
510// A stop after the cancelled attempt's end and sign-out are recorded,
511// before the sign-out ran: the next start does it from the record.
512func TestTokenCancelledCleanupIsDurable(t *testing.T) {
513 r := newTokenRig(t)
514 first := r.connector()
515 stopped := make(chan struct{})
516 first.fault = func(at string) error {
517 if at == "bound" {
518 close(stopped)
519 return errStopped
520 }
521 return nil
522 }
523 home := r.connect(first, "cn_d1")
524 r.deliver(first, "f-secret", r.sealed("cn_d1", fakeclaude.Token("d@example.com"), nil))
525 <-stopped
526 r.waitFor(func() bool { _, ok := r.binding(filepath.Base(home)); return ok }, "the binding")
527 if err := first.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_d1", Person: connPerson}); err != nil {
528 t.Fatal(err)
529 }
530 // The second process records the end and the sign-out it owes, and
531 // stops before the sign-out runs.
532 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}
533 second.spawn = func(func()) {}
534 owed := make(chan struct{})
535 second.fault = func(at string) error {
536 if at == "owed" {
537 close(owed)
538 return errStopped
539 }
540 return nil
541 }
542 if err := second.Start(r.ctx); err != nil {
543 t.Fatal(err)
544 }
545 <-owed
546 var n int
547 _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups WHERE connection='cn_d1'").Scan(&n)
548 if _, err := os.Lstat(home); err != nil || n != 1 {
549 t.Fatalf("after the stop: home %v, %d owed", err, n)
550 }
551 r.connector()
552 r.waitFor(func() bool {
553 _, err := os.Lstat(home)
554 var n int
555 _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&n)
556 return os.IsNotExist(err) && n == 0
557 }, "the home deleted from the record")
558}
559
560// Crash at each delivery boundary: the process stops after the staging
561// file is synced, inside the seen_seals transaction, or after the commit
562// and before the ack. The restarted runner recovers and the instance's
563// resend ends with one token file, one seen_seals row, one ack and a
564// healthy connection.
565func TestTokenDeliverySurvivesCrashes(t *testing.T) {
566 for _, stage := range []string{"staged", "transaction", "committed"} {
567 t.Run(stage, func(t *testing.T) {
568 r := newTokenRig(t)
569 first := r.connector()
570 first.fault = func(at string) error {
571 if at == stage {
572 return errStopped
573 }
574 return nil
575 }
576 id := "cn_c_" + stage
577 home := r.connect(first, id)
578 token := fakeclaude.Token("c@example.com")
579 cmd := r.sealed(id, token, nil)
580 if r.deliver(first, "f-secret", cmd) {
581 t.Fatal("acked through a stop")
582 }
583 committed := r.seals(id)
584 if stage == "committed" && committed != 1 || stage != "committed" && committed != 0 {
585 t.Fatalf("%d seen_seals rows after a stop at %s", committed, stage)
586 }
587 // What the stop left: the staged file; the token file renamed
588 // in a transaction that never committed; the committed file.
589 left := map[string]string{"staged": provider.TokenStaging, "transaction": provider.TokenFile, "committed": provider.TokenFile}[stage]
590 if got := tokenFiles(home); len(got) != 1 || got[0] != left {
591 t.Fatalf("after the stop: %v", got)
592 }
593 // The first process is gone (its attempt never wakes again); a
594 // new one starts on the same state. Recovery keeps only a
595 // committed token.
596 second := r.connector()
597 want := []string{}
598 if stage == "committed" {
599 want = []string{provider.TokenFile}
600 }
601 if got := tokenFiles(home); strings.Join(got, ",") != strings.Join(want, ",") {
602 t.Fatalf("after recovery: %v", got)
603 }
604 acks := 0
605 if r.deliver(second, "f-secret", cmd) {
606 acks++
607 }
608 r.healthy(id, home, token, "c@example.com")
609 if acks != 1 {
610 t.Fatalf("%d acks", acks)
611 }
612 entries, _ := os.ReadDir(home)
613 files := 0
614 for _, e := range entries {
615 if e.Name() == provider.TokenFile || e.Name() == provider.TokenStaging {
616 files++
617 }
618 }
619 if files != 1 {
620 t.Fatalf("%d token files", files)
621 }
622 })
623 }
624}
625
626// The same box again is acked and changes nothing; a box for another
627// attempt, an expired box, one sealed for another runner and one whose
628// clear fields were changed are refused, ending the attempt.
629func TestTokenReplayAndRefusals(t *testing.T) {
630 r := newTokenRig(t)
631 c := r.connector()
632 home := r.connect(c, "cn_r1")
633 token := fakeclaude.Token("r@example.com")
634 cmd := r.sealed("cn_r1", token, nil)
635 r.deliver(c, "f-1", cmd)
636 r.healthy("cn_r1", home, token, "r@example.com")
637 before, _ := os.Stat(filepath.Join(home, provider.TokenFile))
638 reports := len(r.reports("cn_r1"))
639 // The resend, and the same box in another frame: acked, nothing else
640 // (not even opened or looked at as a refusal).
641 logged := r.logs.Len()
642 for _, frame := range []string{"f-1", "f-1-again"} {
643 if !r.deliver(c, frame, cmd) {
644 t.Fatal(r.errs)
645 }
646 }
647 if r.logs.Len() != logged {
648 t.Fatalf("a delivered pair was handled again: %s", r.logs.String()[logged:])
649 }
650 // A later attempt's box for a connection already made: dropped.
651 r.deliver(c, "f-2", r.sealed("cn_r1", fakeclaude.Token("x@example.com"), func(p *wire.SealedPayload) { p.Attempt = 2 }))
652 after, _ := os.Stat(filepath.Join(home, provider.TokenFile))
653 if !os.SameFile(before, after) || !after.ModTime().Equal(before.ModTime()) || len(r.reports("cn_r1")) != reports || r.seals("cn_r1") != 1 {
654 t.Fatal("a replay changed the connection")
655 }
656
657 refusals := []struct {
658 name, reason string
659 box func(id string) wire.SecretCommand
660 }{
661 {"another attempt's box", "provider_refused", func(id string) wire.SecretCommand {
662 other := r.sealed("cn_other", token, nil)
663 other.Connection = id
664 return other
665 }},
666 {"clear fields changed", "provider_refused", func(id string) wire.SecretCommand {
667 s := r.sealed(id, token, nil)
668 s.Sealed.Attempt = 7
669 return s
670 }},
671 {"expired", "timed_out", func(id string) wire.SecretCommand {
672 return r.sealed(id, token, func(p *wire.SealedPayload) { p.ExpiresAt = time.Now().Add(-time.Second).UTC() })
673 }},
674 {"another runner's key", "provider_refused", func(id string) wire.SecretCommand {
675 _, key, _ := ed25519.GenerateKey(rand.Reader)
676 k, _ := sealbox.FromEd25519(key)
677 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()})
678 return wire.SecretCommand{Connection: id, Person: connPerson, Sealed: s}
679 }},
680 {"another runner's id", "provider_refused", func(id string) wire.SecretCommand {
681 return r.sealed(id, token, func(p *wire.SealedPayload) { p.RunnerID = "run_other" })
682 }},
683 {"another endpoint", "provider_refused", func(id string) wire.SecretCommand {
684 return r.sealed(id, token, func(p *wire.SealedPayload) { p.Endpoint = "https://api.example.com:443" })
685 }},
686 {"another person", "provider_refused", func(id string) wire.SecretCommand {
687 s := r.sealed(id, token, nil)
688 s.Person = "q@example.com"
689 return s
690 }},
691 }
692 for i, x := range refusals {
693 t.Run(x.name, func(t *testing.T) {
694 id := "cn_x" + string(rune('a'+i))
695 home := r.connect(c, id)
696 if !r.deliver(c, "f-x-"+id, x.box(id)) {
697 t.Fatal("a refused box was not acked")
698 }
699 if end := r.ended(id); end.State != wire.ConnError || end.Reason != x.reason {
700 t.Fatalf("end %+v", end)
701 }
702 if _, err := os.Stat(home); !os.IsNotExist(err) || r.seals(id) != 0 {
703 t.Fatalf("home %v, %d seals", err, r.seals(id))
704 }
705 })
706 }
707}
708
709// A cancel before the box arrives: the attempt ends cancelled and the
710// late box is acked and dropped, nothing written.
711func TestTokenCancelBeforeSecret(t *testing.T) {
712 r := newTokenRig(t)
713 c := r.connector()
714 home := r.connect(c, "cn_k1")
715 if err := c.Cancel(r.ctx, "f-cancel", wire.CancelConnectCommand{Connection: "cn_k1", Person: connPerson}); err != nil {
716 t.Fatal(err)
717 }
718 if end := r.ended("cn_k1"); end.State != wire.ConnError || end.Reason != "cancelled" {
719 t.Fatalf("end %+v", end)
720 }
721 if !r.deliver(c, "f-secret", r.sealed("cn_k1", fakeclaude.Token("k@example.com"), nil)) {
722 t.Fatal(r.errs)
723 }
724 if _, err := os.Stat(home); !os.IsNotExist(err) || r.seals("cn_k1") != 0 {
725 t.Fatalf("home %v after a cancel", err)
726 }
727}
728
729// Sign-out deletes the home with its token, the binding and the expiry.
730func TestTokenSignOut(t *testing.T) {
731 r := newTokenRig(t)
732 c := r.connector()
733 home := r.connect(c, "cn_s1")
734 token := fakeclaude.Token("s@example.com")
735 r.deliver(c, "f-secret", r.sealed("cn_s1", token, nil))
736 r.healthy("cn_s1", home, token, "s@example.com")
737 local := filepath.Base(home)
738 if err := c.Disconnect(r.ctx, "f-out", wire.DisconnectCommand{Connection: "cn_s1", Person: connPerson, LocalID: local}); err != nil {
739 t.Fatal(err)
740 }
741 if _, err := os.Stat(home); !os.IsNotExist(err) {
742 t.Fatal("the home stayed")
743 }
744 if _, ok := r.binding(local); ok {
745 t.Fatal("still bound")
746 }
747 var n int
748 _ = r.state.db.QueryRow("SELECT count(*) FROM conn_expiry WHERE id=?", local).Scan(&n)
749 if n != 0 || len(r.conns.Held()) != 0 {
750 t.Fatal("the expiry stayed")
751 }
752 signedOut := false
753 for _, v := range r.reports("cn_s1") {
754 signedOut = signedOut || v.State == wire.ConnSignedOut
755 }
756 if !signedOut {
757 t.Fatal("no signed_out report")
758 }
759}
760
761// The canary: whatever happens to a token, nothing the runner sends the
762// instance, logs, returns as an error or reports in hello carries it.
763func TestTokenNeverLeaves(t *testing.T) {
764 r := newTokenRig(t)
765 c := r.connector()
766 good := fakeclaude.Token("canary@example.com")
767 bad := "sk-ant-oat01-canary-rejected-91c2"
768 r.connect(c, "cn_g")
769 r.deliver(c, "f-g", r.sealed("cn_g", good, nil))
770 r.ended("cn_g")
771 r.connect(c, "cn_b")
772 r.deliver(c, "f-b", r.sealed("cn_b", bad, nil))
773 r.ended("cn_b")
774 r.connect(c, "cn_e")
775 r.deliver(c, "f-e", r.sealed("cn_e", good, func(p *wire.SealedPayload) { p.ExpiresAt = time.Now().Add(-time.Minute).UTC() }))
776 r.ended("cn_e")
777 r.connect(c, "cn_w")
778 r.deliver(c, "f-w", r.sealed("cn_w", good, func(p *wire.SealedPayload) { p.Endpoint = "https://api.example.com:443" }))
779 r.ended("cn_w")
780 // A stop mid-delivery returns an error the link logs.
781 c.fault = func(string) error { return errStopped }
782 r.connect(c, "cn_f")
783 r.deliver(c, "f-f", r.sealed("cn_f", good, nil))
784 c.fault = nil
785
786 frames, _, err := r.state.Unacked(context.Background(), 0)
787 if err != nil {
788 t.Fatal(err)
789 }
790 var sent bytes.Buffer
791 for _, f := range frames {
792 sent.Write(f.Data)
793 }
794 held, _ := json.Marshal(r.conns.Held())
795 sent.Write(held)
796 sent.Write(r.logs.Bytes())
797 for _, e := range r.errs {
798 sent.WriteString(e.Error())
799 }
800 var rows bytes.Buffer
801 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"} {
802 rs, err := r.state.db.Query(q)
803 if err != nil {
804 t.Fatal(err)
805 }
806 for rs.Next() {
807 var v string
808 _ = rs.Scan(&v)
809 rows.WriteString(v)
810 }
811 rs.Close()
812 }
813 for _, tok := range []string{good, bad} {
814 for name, b := range map[string][]byte{"sent, logged, held or returned": sent.Bytes(), "runner state": rows.Bytes()} {
815 if bytes.Contains(b, []byte(tok)) || strings.Contains(string(b), strings.TrimPrefix(tok, "sk-ant-oat01-")) {
816 t.Fatalf("a token is in what the runner %s", name)
817 }
818 }
819 }
820 if len(r.errs) != 1 || !errors.Is(r.errs[0], errStopped) {
821 t.Fatalf("errors %v", r.errs)
822 }
823}
824
825// tokenFiles are the token's files in a home, by name.
826func tokenFiles(home string) []string {
827 got := []string{}
828 for _, name := range []string{provider.TokenStaging, provider.TokenFile} {
829 if _, err := os.Lstat(filepath.Join(home, name)); err == nil {
830 got = append(got, name)
831 }
832 }
833 return got
834}
835
836// The secret frame read right after the connect frame, before the
837// attempt's card went out: the attempt is ready for it.
838func TestTokenSecretRightAfterConnect(t *testing.T) {
839 r := newTokenRig(t)
840 c := r.connector()
841 if err := c.Accept(r.ctx, "f-connect", wire.ConnectCommand{Connection: "cn_q1", Person: connPerson, Provider: wire.ProviderClaude, Kind: wire.KindToken}); err != nil {
842 t.Fatal(err)
843 }
844 token := fakeclaude.Token("q@example.com")
845 if !r.deliver(c, "f-secret", r.sealed("cn_q1", token, nil)) {
846 t.Fatal(r.errs)
847 }
848 var home string
849 _ = r.state.db.QueryRow("SELECT home FROM connect_attempts WHERE id='cn_q1'").Scan(&home)
850 r.healthy("cn_q1", home, token, "q@example.com")
851}
852
853// stopAtBound runs a token attempt to its saved binding and stops the
854// runner there (before the real check and the attempt's end).
855func (r *tokenRig) stopAtBound(id, token string) string {
856 r.t.Helper()
857 first := r.connector()
858 stopped := make(chan struct{})
859 first.fault = func(at string) error {
860 if at == "bound" {
861 close(stopped)
862 return errStopped
863 }
864 return nil
865 }
866 home := r.connect(first, id)
867 if !r.deliver(first, "f-secret-"+id, r.sealed(id, token, nil)) {
868 r.t.Fatal(r.errs)
869 }
870 select {
871 case <-stopped:
872 case <-time.After(20 * time.Second):
873 r.t.Fatal("never reached the saved binding")
874 }
875 r.waitFor(func() bool {
876 _, ok := r.binding(filepath.Base(home))
877 return ok
878 }, "the saved binding")
879 return home
880}
881
882// Astra round 2: the hourly pass between the saved binding and the real
883// check never makes the token a connection (its CLI status says signed in
884// for any token), and the resumed attempt still makes the real request.
885func TestTokenHourlyPassBeforeTheCheck(t *testing.T) {
886 r := newTokenRig(t)
887 token := fakeclaude.Token("race@example.com")
888 home := r.stopAtBound("cn_race", token)
889 local := filepath.Base(home)
890 paths := provider.LoginOptions{ClaudePath: r.cfg.ClaudePath, CodexPath: r.cfg.CodexPath}
891 r.conns.Refresh = func(ctx context.Context, b provider.Binding) (provider.Identity, error) {
892 return provider.RefreshLogin(ctx, b, paths)
893 }
894 before := r.checks.Load()
895 r.conns.Check(r.ctx)
896 if len(r.conns.Held()) != 0 || !r.conns.ValidatedAt(local).IsZero() {
897 t.Fatalf("the CLI's status made the token a connection: %+v", r.conns.Held())
898 }
899 if _, _, err := r.conns.Choose(r.ctx, connPerson, "coordinator", "", nil); err == nil {
900 t.Fatal("an unvalidated token was chosen")
901 }
902 r.connector()
903 r.healthy("cn_race", home, token, "race@example.com")
904 if r.checks.Load() != before+1 || r.conns.ValidatedAt(local).IsZero() {
905 t.Fatalf("the resumed attempt made %d real requests; validated %v", r.checks.Load()-before, r.conns.ValidatedAt(local))
906 }
907}
908
909// Astra round 2: a restart after the attempt's time is up, with its
910// binding saved, goes through the durable sign-out: the binding, the home
911// and the token go; the end records the attempt's local id, never an
912// empty one while the home survives; a recorded cancel ends it cancelled.
913func TestTokenExpiredRecoveryCleansUp(t *testing.T) {
914 for _, cancelled := range []bool{false, true} {
915 t.Run(map[bool]string{false: "expired", true: "cancelled"}[cancelled], func(t *testing.T) {
916 r := newTokenRig(t)
917 id := "cn_x_" + map[bool]string{false: "e", true: "c"}[cancelled]
918 home := r.stopAtBound(id, fakeclaude.Token("late@example.com"))
919 local := filepath.Base(home)
920 if cancelled {
921 if _, err := r.state.db.Exec("UPDATE connect_attempts SET cancelled=1 WHERE id=?", id); err != nil {
922 t.Fatal(err)
923 }
924 }
925 r.limit = time.Nanosecond
926 r.connector()
927 want := map[bool]string{false: "timed_out", true: "cancelled"}[cancelled]
928 var end wire.ConnectionReport
929 r.waitFor(func() bool {
930 rs := r.reports(id)
931 if len(rs) == 0 {
932 return false
933 }
934 end = rs[len(rs)-1]
935 return end.State != wire.ConnConnecting
936 }, "the attempt's end")
937 if end.State != wire.ConnError || end.Reason != want {
938 t.Fatalf("end %+v", end)
939 }
940 var recorded string
941 _ = r.state.db.QueryRow("SELECT local_id FROM connect_attempts WHERE id=?", id).Scan(&recorded)
942 if recorded == "" {
943 t.Fatal("the attempt ended with no local id while its home survived")
944 }
945 r.waitFor(func() bool {
946 _, err := os.Lstat(home)
947 var owed int
948 _ = r.state.db.QueryRow("SELECT count(*) FROM connect_cleanups").Scan(&owed)
949 _, bound := r.binding(local)
950 return os.IsNotExist(err) && owed == 0 && !bound
951 }, "the expired token's binding and home deleted, nothing owed")
952 })
953 }
954}
955