package headless import ( "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "encoding/json" "math" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runner/thin" "amadan.net/oficina/equipo/internal/runnerproto" "amadan.net/oficina/equipo/internal/sealbox" "amadan.net/oficina/equipo/internal/thintest" "amadan.net/oficina/equipo/internal/wire" ) // addToken gives the owner a token connection as the runner makes one // from a delivered secret: a home with the token file and the identity, // no CLI login, bound as kind token. It returns the token. func (r *localRunner) addToken(t *testing.T, id, email string) string { t.Helper() home := private(t, filepath.Join(r.root, "accounts", id)) token := fakeclaude.Token(email) if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(token), 0600); err != nil { t.Fatal(err) } identity := map[string]string{"account_id": email, "home_id": rand.Text(), "provider_version": fakeclaude.Version} writeJSON(t, filepath.Join(home, "equipo-identity.json"), identity) bs := append(r.bindings(t), map[string]any{"id": id, "local_id": id, "label": id, "person_id": thintest.Owner, "provider": "claude", "family": "claude", "model": "claude-opus-5-5", "account_id": email, "provider_home": home, "kind": "token", "expected_identity": identity}) writeJSON(t, r.cfg.AccountBindingsPath, bs) // As the connect check would: a real request answered, recorded on the // runner, so the token is a connection. st, err := thin.OpenState(context.Background(), r.cfg.StateDir) if err != nil { t.Fatal(err) } (&thin.Conns{Runner: r.cfg, State: st}).Validated(id) st.Close() return token } // T1: a turn and an Engineering step on a token connection. The fake CLI // runs only with the token in CLAUDE_CODE_OAUTH_TOKEN (it refuses a turn // without it, and exits on a token in argv), and says so in its reply. // The runner's hello carries its seal key, the one its enrolment key // gives; nothing the runner sent the instance carries the token. func TestHeadlessTokenConnection(t *testing.T) { env, inst, r := localEnv(t) _, key, _ := ed25519.GenerateKey(rand.Reader) if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil { t.Fatal(err) } keys, _ := sealbox.FromEd25519(key) token := r.addToken(t, "claude-7", "tok@example.com") r.only(t, "claude-7") r.start(t) s := open(t, env) s.keep() sent := s.send(t, "Hello on a token.") m := replyOf(t, s, sent.Turn.ID) if !strings.Contains(m.Text, "(signed in by token)") || s.conv.Turns[sent.Turn.ID].Connection != "claude-7" { t.Fatalf("turn on the token connection: %q", m.Text) } text := "tool:record_task:oficina/sample|Fix the README typo|teh\ntool:start_task:$task|Fix it. edit:README.md|teh panes|the panes" sent = s.send(t, text) id := s.taskOf(t, sent.Turn.ID) step := s.step(t, id, 5*time.Minute, wire.StepDone, wire.StepFailed) if step.State != wire.StepDone || !step.Pushed || step.Account != "claude-7" || !strings.Contains(step.Summary, "(signed in by token)") { t.Fatalf("step on the token connection: %+v", step) } conns, err := env.Client.Connections(s.ctx) if err != nil { t.Fatal(err) } for _, c := range conns.Items { if c.LocalID == "claude-7" && (c.Kind != wire.KindToken || c.State != wire.ConnHealthy) { t.Fatalf("connection %+v", c) } } var hello string if err = inst.DB.Writer().QueryRow("SELECT hello FROM runner_sessions").Scan(&hello); err != nil { t.Fatal(err) } var h wire.Hello if err = json.Unmarshal([]byte(hello), &h); err != nil || h.SealKey != keys.PublicString() { t.Fatalf("hello seal key %q, want %q", h.SealKey, keys.PublicString()) } // Everything the instance stored, every table: no token. db := inst.DB.Writer() tables, err := db.Query("SELECT name FROM sqlite_master WHERE type='table'") if err != nil { t.Fatal(err) } var names []string for tables.Next() { var n string _ = tables.Scan(&n) names = append(names, n) } tables.Close() for _, n := range names { rows, err := db.Query(`SELECT * FROM "` + n + `"`) if err != nil { t.Fatal(err) } cols, _ := rows.Columns() for rows.Next() { vals := make([]any, len(cols)) ptrs := make([]any, len(cols)) for i := range vals { ptrs[i] = &vals[i] } _ = rows.Scan(ptrs...) for _, v := range vals { var s string switch x := v.(type) { case string: s = x case []byte: s = string(x) } if strings.Contains(s, token) { rows.Close() t.Fatalf("the token reached the instance's %s", n) } } } rows.Close() } if page := inst.Get(t, "/tasks/"+id); strings.Contains(page, token) { t.Fatal("the token is on the task page") } } // T2, end to end: the person adds Claude by token through the API as the // page does. The box is sealed to the seal key the instance publishes for // the runner, the runner opens it, the CLI's status probe passes, the row // is healthy with the token's expiry, and the next turn runs on it with // the token in CLAUDE_CODE_OAUTH_TOKEN. The token is nowhere on the // instance: its database file and WAL, its logs, its API and pages. func TestHeadlessTokenPasteEndToEnd(t *testing.T) { env, inst, r := localEnv(t) _, key, _ := ed25519.GenerateKey(rand.Reader) if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil { t.Fatal(err) } r.only(t) r.start(t) s := open(t, env) s.keep() c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude, Kind: wire.KindToken}) if err != nil { t.Fatal(err) } s.wait(t, "token card", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Connections[c.ID] return v.Prompt != nil && v.Prompt.Kind == wire.PromptToken }) snap, err := env.Client.Snapshot(s.ctx) if err != nil || snap.Runner.SealKey == "" { t.Fatalf("no seal key published: %v", err) } token := fakeclaude.Token("paste@example.com") sealed, err := sealbox.Seal(snap.Runner.SealKey, wire.SealedPayload{Secret: token, RunnerID: snap.Runner.ID, ConnectionID: c.ID, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().Add(wire.SealedTTL).UTC().Truncate(time.Second)}) if err != nil { t.Fatal(err) } if _, err = env.Client.Secret(s.ctx, c.ID, sealed); err != nil { v, _ := env.Client.Connection(s.ctx, c.ID) t.Fatalf("%v: connection %+v", err, v) } var got wire.Connection s.wait(t, "token healthy", time.Minute, func(cv *thintest.Conversation) bool { got = cv.Connections[c.ID] return got.State == wire.ConnHealthy }) if got.ExpiresAt == nil || !got.ExpiresEstimated || time.Until(*got.ExpiresAt) < 360*24*time.Hour || got.LocalID == "" { t.Fatalf("healthy token connection %+v", got) } // Healthy only after a real request through the contained launch; // its usage is the person's, recorded like any other. until(t, "the check's usage", func() bool { var n int err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'check' AND connection = ? AND outcome = ? AND person = ?", got.LocalID, wire.OutcomeReplied, thintest.Owner).Scan(&n) return err == nil && n == 1 }) // The same box again is refused by the instance or answered with // nothing by the runner: the connection stays as it is. _, _ = env.Client.Secret(s.ctx, c.ID, sealed) sent := s.send(t, "Hello on the pasted token.") m := replyOf(t, s, sent.Turn.ID) if !strings.Contains(m.Text, "(signed in by token)") || s.conv.Turns[sent.Turn.ID].Connection != got.LocalID { t.Fatalf("turn on the pasted token: %q", m.Text) } // Nothing on the instance holds the token: the database file and its // WAL as bytes, the logs, the API and the page. for _, f := range []string{inst.Path, inst.Path + "-wal"} { raw, err := os.ReadFile(f) if err != nil && !os.IsNotExist(err) { t.Fatal(err) } if strings.Contains(string(raw), token) { t.Fatalf("the token is in %s", filepath.Base(f)) } } if strings.Contains(inst.Logs(), token) { t.Fatal("the token is in the instance's logs") } if page := inst.Get(t, "/conversation/connections"); strings.Contains(page, token) || !strings.Contains(page, "Expires about") { t.Fatal("the token is on the page, or its expiry is not") } list, _ := env.Client.Connections(s.ctx) raw, _ := json.Marshal(list) if strings.Contains(string(raw), token) { t.Fatal("the token is in the API") } // Signed out: the home and the token file go. if _, err = env.Client.SignOut(s.ctx, c.ID); err != nil { t.Fatal(err) } s.wait(t, "signed out", time.Minute, func(cv *thintest.Conversation) bool { return cv.Connections[c.ID].State == wire.ConnSignedOut }) if _, err := os.Stat(filepath.Join(r.root, "accounts", got.LocalID)); !os.IsNotExist(err) { t.Fatalf("the token's home stayed: %v", err) } } // A bad token pasted end to end. The CLI's status says signed in for any // token, so only the check's real request, through the contained launch, // finds it out: "This token was rejected", never healthy, the home and // the binding gone, and the refused request's usage recorded. The link // stays up: the instance takes every frame the runner sent. func TestHeadlessTokenRejected(t *testing.T) { env, inst, r := localEnv(t) _, key, _ := ed25519.GenerateKey(rand.Reader) if err := runnerproto.JournalCredentials(filepath.Join(r.cfg.StateDir, "machine-key.json"), base64.RawURLEncoding.EncodeToString(key)); err != nil { t.Fatal(err) } r.only(t) homes := func() string { entries, _ := os.ReadDir(filepath.Join(r.root, "accounts")) var names []string for _, e := range entries { names = append(names, e.Name()) } return strings.Join(names, ",") } before := homes() r.start(t) s := open(t, env) s.keep() c, err := env.Client.Connect(s.ctx, wire.Connect{Provider: wire.ProviderClaude, Kind: wire.KindToken}) if err != nil { t.Fatal(err) } s.wait(t, "token card", time.Minute, func(cv *thintest.Conversation) bool { v := cv.Connections[c.ID] return v.Prompt != nil && v.Prompt.Kind == wire.PromptToken }) snap, err := env.Client.Snapshot(s.ctx) if err != nil { t.Fatal(err) } sealed, err := sealbox.Seal(snap.Runner.SealKey, wire.SealedPayload{Secret: "sk-ant-oat01-revoked-by-the-provider", RunnerID: snap.Runner.ID, ConnectionID: c.ID, Provider: wire.ProviderClaude, Endpoint: wire.EndpointAnthropic, Attempt: 1, ExpiresAt: time.Now().Add(wire.SealedTTL).UTC().Truncate(time.Second)}) if err != nil { t.Fatal(err) } if _, err = env.Client.Secret(s.ctx, c.ID, sealed); err != nil { t.Fatal(err) } var end wire.Connection s.wait(t, "the attempt's end", time.Minute, func(cv *thintest.Conversation) bool { end = cv.Connections[c.ID] return end.State != wire.ConnConnecting }) if end.State != wire.ConnError || end.Reason != "provider_refused" || end.LocalID != "" { t.Fatalf("a bad token ended %+v", end) } if page := inst.Get(t, "/conversation/connections"); !strings.Contains(page, "This token was rejected. Run claude setup-token again.") { t.Fatal("the row does not say the token was rejected") } until(t, "the home and binding gone", func() bool { return homes() == before && len(r.bindings(t)) == 0 }) until(t, "the refused check's usage", func() bool { var n int err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role = 'check' AND outcome = ?", wire.OutcomeFailed).Scan(&n) return err == nil && n == 1 }) } // A token connection's check reads the provider's rate limits as a turn // does: a check that reports windows leaves the connection with that // headroom on the runner, and one refused on quota leaves it limited // until the reset the provider gave, on the runner and on the row. No // turn runs on either. func TestHeadlessTokenCheckHeadroom(t *testing.T) { env, inst, r := localEnv(t) r.addToken(t, "claude-7", "tok@example.com") r.addToken(t, "claude-8", "spent-tok@example.com") r.only(t, "claude-7", "claude-8") r.start(t) s := open(t, env) s.keep() ids := map[string]string{} s.wait(t, "both rows", time.Minute, func(cv *thintest.Conversation) bool { for _, c := range cv.Connections { ids[c.LocalID] = c.ID } return ids["claude-7"] != "" && ids["claude-8"] != "" }) for _, local := range []string{"claude-7", "claude-8"} { if err := env.Client.CheckConnection(s.ctx, ids[local]); err != nil { t.Fatal(err) } } var spent wire.Connection s.wait(t, "the refused check limits its row", 2*time.Minute, func(cv *thintest.Conversation) bool { spent = cv.Connections[ids["claude-8"]] return spent.State == wire.ConnLimited }) if spent.Headroom == nil || spent.Headroom.ResetsAt == nil || time.Until(*spent.Headroom.ResetsAt) < 40*time.Hour { t.Fatalf("the limited row has no reported reset: %+v", spent.Headroom) } until(t, "both checks' usage", func() bool { var n int err := inst.DB.Writer().QueryRow("SELECT count(DISTINCT connection) FROM chat_usage WHERE role = 'check'").Scan(&n) return err == nil && n == 2 }) r.stop(t) st, err := thin.OpenState(context.Background(), r.cfg.StateDir) if err != nil { t.Fatal(err) } defer st.Close() held := map[string]wire.HeldConnection{} for _, h := range (&thin.Conns{Runner: r.cfg, State: st}).Held() { held[h.LocalID] = h } windows := func(h *wire.Headroom) map[string]float64 { out := map[string]float64{} if h != nil { for _, w := range h.Windows { out[w.Name] = math.Round(w.UsedPercent) } } return out } if got := windows(held["claude-7"].Headroom); held["claude-7"].State != wire.ConnHealthy || len(got) != 2 || got["five_hour"] != 12 || got["seven_day"] != 25 { t.Fatalf("the check's windows were not kept: %+v %v", held["claude-7"], got) } if h := held["claude-8"]; h.State != wire.ConnLimited || windows(h.Headroom)["seven_day"] != 100 { t.Fatalf("the refused check did not limit the connection: %+v", h) } var turns int if err := inst.DB.Writer().QueryRow("SELECT count(*) FROM chat_usage WHERE role <> 'check'").Scan(&turns); err != nil || turns != 0 { t.Fatalf("a turn ran: %d %v", turns, err) } } // until polls cond (it reads files and rows, which send no events). func until(t *testing.T, what string, cond func() bool) { t.Helper() deadline := time.Now().Add(time.Minute) for !cond() { if time.Now().After(deadline) { t.Fatalf("timed out waiting for %s", what) } time.Sleep(50 * time.Millisecond) } }