package thin import ( "bytes" "context" "database/sql" "log/slog" "net/http" "net/http/httptest" "net/netip" "net/url" "os" "path/filepath" "slices" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/fakeclaude" "amadan.net/oficina/equipo/internal/runner" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/egress" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" ) // fakeProfile is Claude's profile endpoint as the pinned CLI reads it: a // GET with the token as a bearer, from a runner that names itself // (ProfileAgent/). It answers status, with the account's email // on a 200; it counts the reads by token and fails the test on any other // request. With token "" it takes any bearer. type fakeProfile struct { t *testing.T srv *httptest.Server mu sync.Mutex status int email string token string reads int agents []string seen map[string]int } func newFakeProfile(t *testing.T, token string) *fakeProfile { f := &fakeProfile{t: t, status: http.StatusOK, token: token, seen: map[string]int{}} f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() f.reads++ bearer, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") f.seen[bearer]++ f.agents = append(f.agents, r.Header.Get("User-Agent")) if r.Method != http.MethodGet || r.URL.Path != "/api/oauth/profile" || r.URL.RawQuery != "" || bearer == "" || f.token != "" && bearer != f.token || r.Header.Get("anthropic-beta") != "" || r.Header.Get("Cache-Control") != "no-cache" || !strings.HasPrefix(r.Header.Get("User-Agent"), ProfileAgent+"/") || strings.Contains(r.Header.Get("User-Agent"), "claude-cli") { t.Errorf("not the CLI's profile read: %s %s", r.Method, r.URL) w.WriteHeader(http.StatusTeapot) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(f.status) if f.status == http.StatusOK { _, _ = w.Write([]byte(`{"account":{"uuid":"acc-1","email":"` + f.email + `","display_name":"A"},"organization":{"uuid":"org-1","organization_type":"claude_max"}}`)) return } _, _ = w.Write([]byte(`{"type":"error","error":{"type":"permission_error","message":"secret detail ` + bearer + `"}}`)) })) t.Cleanup(f.srv.Close) return f } func (f *fakeProfile) answer(status int, email string) { f.mu.Lock() f.status, f.email = status, email f.mu.Unlock() } func (f *fakeProfile) count() int { f.mu.Lock() defer f.mu.Unlock() return f.reads } // readsOf counts the reads made with token. func (f *fakeProfile) readsOf(token string) int { f.mu.Lock() defer f.mu.Unlock() return f.seen[token] } // reader is the runner's profile reader pointed at the fake through the // seam an API key's requests use (connect.SafeClient), loopback allowed. func (f *fakeProfile) reader(clock *time.Time) *ProfileReader { return &ProfileReader{Origin: f.srv.URL, Version: "v9.8.7-test", HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), now: func() time.Time { return *clock }} } // profileRig is a runner state holding one validated token connection // whose CLI named no account, its token, a fake profile endpoint, and // the check's options with a log. type profileRig struct { t *testing.T state *State conns *Conns b runner.AccountBinding token []byte fake *fakeProfile clock time.Time logs lockedBuffer o ClaudeOptions dir string } func newProfileRig(t *testing.T) *profileRig { dir := t.TempDir() r := &profileRig{t: t, dir: dir, clock: time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)} for _, d := range []string{"config", "state", "accounts/claude-3"} { if err := os.MkdirAll(filepath.Join(dir, d), 0700); err != nil { t.Fatal(err) } } var err error if r.state, err = OpenState(context.Background(), filepath.Join(dir, "state")); err != nil { t.Fatal(err) } t.Cleanup(func() { r.state.Close() }) cfg := runner.Config{AccountBindingsPath: filepath.Join(dir, "config", "bindings.json")} home := filepath.Join(dir, "accounts", "claude-3") if err = saveToken(context.Background(), cfg.AccountBindingsPath, connPerson, "claude-3", home, provider.Identity{AccountID: provider.TokenAccountID("claude-3"), ProviderVersion: provider.LoginVersion("claude")}); err != nil { t.Fatal(err) } r.conns = &Conns{Runner: cfg, State: r.state} r.conns.Validated("claude-3") var ok bool if r.b, ok = r.conns.Binding("claude-3"); !ok || tokenLabel(r.b.AccountID) != "" { t.Fatalf("binding %+v", r.b) } r.token = []byte(fakeclaude.Token("")) if err = os.WriteFile(filepath.Join(home, provider.TokenFile), r.token, 0600); err != nil { t.Fatal(err) } r.fake = newFakeProfile(t, string(r.token)) r.o = ClaudeOptions{State: r.state, Profile: r.fake.reader(&r.clock), Logger: slog.New(slog.NewTextHandler(&r.logs, nil))} return r } // check is the profile read a token check makes once the provider // answered it, with the token from its lease. func (r *profileRig) check() bool { return r.o.readProfile(context.Background(), r.b, bytes.Clone(r.token)) } // label is the connection's label in hello. func (r *profileRig) label() string { r.t.Helper() for _, h := range r.conns.Held() { if h.LocalID == r.b.ID { return h.Label } } r.t.Fatal("not held") return "" } // unavailable reports what thin.db says of the connection's profile: // recorded at all, and not available for this sign-in. func (r *profileRig) unavailable() (recorded, unavailable bool) { var u int err := r.state.db.QueryRow("SELECT unavailable FROM conn_profile WHERE id=?", r.b.ID).Scan(&u) if err == sql.ErrNoRows { return false, false } if err != nil { r.t.Fatal(err) } return true, u == 1 } // The profile names the account: the email is the provider's, the // connection's label in hello (which the instance shows plainly and // asks no email for), and is not asked for again on the next check. func TestTokenProfileNamesAccount(t *testing.T) { r := newProfileRig(t) r.fake.answer(http.StatusOK, "acct@example.com") if r.label() != "" { t.Fatal("labelled before the read") } if !r.check() || r.fake.count() != 1 { t.Fatalf("the check did not read the profile: %d reads", r.fake.count()) } if got := r.label(); got != "acct@example.com" { t.Fatalf("label %q", got) } if rec, un := r.unavailable(); !rec || un { t.Fatalf("recorded %v, unavailable %v", rec, un) } // The next check: nothing due. r.clock = r.clock.Add(time.Hour) if r.check() || r.fake.count() != 1 { t.Fatalf("read again on the next check: %d", r.fake.count()) } // A week on, asked again; the same answer changes nothing. r.clock = r.clock.Add(ProfileRetry) if r.check() || r.fake.count() != 2 || r.label() != "acct@example.com" { t.Fatalf("a week on: %d reads, %q", r.fake.count(), r.label()) } // Signed out: forgotten with the connection. r.conns.Forget(r.b.ID) if rec, _ := r.unavailable(); rec { t.Fatal("the profile outlived the connection") } if !strings.Contains(r.logs.String(), "status=200 email=true outcome=found") { t.Fatalf("log %s", r.logs.String()) } } // 401, 403, 404: the profile is not available for this sign-in. Nothing // is named (the instance keeps asking for the email); the next check does // not ask; a week later, or another token, does. func TestTokenProfileNotAvailable(t *testing.T) { for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound} { t.Run(http.StatusText(status), func(t *testing.T) { r := newProfileRig(t) r.fake.answer(status, "") if r.check() || r.fake.count() != 1 || r.label() != "" { t.Fatalf("%d reads, label %q", r.fake.count(), r.label()) } if rec, un := r.unavailable(); !rec || !un { t.Fatalf("recorded %v, unavailable %v", rec, un) } r.clock = r.clock.Add(ProfileRetry - time.Minute) if r.check(); r.fake.count() != 1 { t.Fatal("asked again on the next check") } // A week on, the profile answers now. r.clock = r.clock.Add(time.Minute) r.fake.answer(http.StatusOK, "later@example.com") if !r.check() || r.fake.count() != 2 || r.label() != "later@example.com" { t.Fatalf("a week on: %d reads, %q", r.fake.count(), r.label()) } // Unavailable again, then another token on the connection. r.clock = r.clock.Add(ProfileRetry) r.fake.answer(status, "") if !r.check() || r.label() != "" || r.fake.count() != 3 { t.Fatalf("unavailable again: %d reads, %q", r.fake.count(), r.label()) } r.token = []byte(fakeclaude.Token("") + "-2") r.fake.mu.Lock() r.fake.token = string(r.token) r.fake.mu.Unlock() if r.check(); r.fake.count() != 4 { t.Fatal("another token was not asked about") } }) } } // Anything else (a 500, a 200 the CLI could not read, no answer at all) // records nothing new: the next check asks again. func TestTokenProfileFailureRetries(t *testing.T) { r := newProfileRig(t) r.fake.answer(http.StatusInternalServerError, "") if r.check() || r.fake.count() != 1 || r.label() != "" { t.Fatalf("%d reads, %q", r.fake.count(), r.label()) } if rec, _ := r.unavailable(); rec { t.Fatal("a 500 was recorded") } r.fake.answer(http.StatusOK, "not an email") if r.check() || r.fake.count() != 2 { t.Fatal("not asked again on the next check") } if rec, _ := r.unavailable(); rec { t.Fatal("an unreadable answer was recorded") } // Recorded as found, then a failure: the email stands. r.fake.answer(http.StatusOK, "acct@example.com") if !r.check() || r.label() != "acct@example.com" { t.Fatal("not found") } r.clock = r.clock.Add(ProfileRetry) r.fake.answer(http.StatusBadGateway, "") if r.check() || r.label() != "acct@example.com" { t.Fatal("a failure changed the label") } // No answer at all. r.fake.srv.Close() if r.check() || r.label() != "acct@example.com" { t.Fatal("no answer changed the label") } if !strings.Contains(r.logs.String(), "status=0 email=false outcome=failed") { t.Fatalf("log %s", r.logs.String()) } } // No read where none can help: an account `auth status` named, a check // with no reader, no token. func TestTokenProfileSkipped(t *testing.T) { r := newProfileRig(t) named := r.b named.AccountID = "cli@example.com" if r.o.readProfile(context.Background(), named, r.token) { t.Fatal("changed a named account") } none := r.o none.Profile = nil none.readProfile(context.Background(), r.b, r.token) r.o.readProfile(context.Background(), r.b, nil) if r.fake.count() != 0 { t.Fatalf("%d reads", r.fake.count()) } } // The release reads api.anthropic.com, the Claude route's one host, on // 443: the read adds no egress. func TestTokenProfileHostIsClaudes(t *testing.T) { u, err := url.Parse(AnthropicProfile().Origin) if err != nil || u.Scheme != "https" || u.Port() != "" || u.Path != "" { t.Fatalf("origin %q", AnthropicProfile().Origin) } hosts := egress.Routes()[egress.Route{Harness: "claude", Provider: "claude"}] if !slices.Equal(hosts, []string{u.Hostname()}) || wire.EndpointAnthropic != "https://"+u.Hostname()+":443" { t.Fatalf("Claude route %v, profile host %q", hosts, u.Hostname()) } if o := OptionsFromEnv(func(string) string { return "" }); o.Claude.Profile == nil || o.Claude.Profile.Origin != ProfileOrigin || o.Claude.Profile.HTTP != nil { t.Fatal("a release runner reads no profile, or not through the safe client") } } // Nothing of the read is logged or reported but its status and whether // it named an email: not the token, not the header, not the email, not // the answer. The check's report (its usage frame) and thin.db hold no // token either. Every outcome is run. func TestTokenProfileLogsNoSecret(t *testing.T) { r := newProfileRig(t) const email = "hidden.account@example.com" for _, a := range []struct { status int email string }{{http.StatusOK, email}, {http.StatusForbidden, ""}, {http.StatusInternalServerError, ""}} { r.clock = r.clock.Add(ProfileRetry) r.fake.answer(a.status, a.email) r.check() } if r.fake.count() != 3 { t.Fatalf("%d reads", r.fake.count()) } if err := r.state.ReportCheck(context.Background(), []wire.Usage{{Connection: r.b.ID, Provider: "claude", Model: "claude-opus-5-5", Attempt: 1, Outcome: wire.OutcomeReplied}}); err != nil { t.Fatal(err) } var reported []string rows, err := r.state.db.Query("SELECT body FROM outbox") if err != nil { t.Fatal(err) } for rows.Next() { var body string _ = rows.Scan(&body) reported = append(reported, body) } rows.Close() if len(reported) == 0 { t.Fatal("no check report") } logs := r.logs.String() if !strings.Contains(logs, "token profile") || !strings.Contains(logs, "status=403") { t.Fatalf("the reads were not logged: %s", logs) } for name, text := range map[string]string{"log": logs, "check report": strings.Join(reported, "\n")} { for _, secret := range []string{string(r.token), "Bearer", email, "hidden.account", "permission_error"} { if strings.Contains(text, secret) { t.Errorf("the %s holds %q", name, secret) } } } r.state.Close() for _, f := range []string{"thin.db", "thin.db-wal"} { raw, err := os.ReadFile(filepath.Join(r.dir, "state", f)) if err != nil && !os.IsNotExist(err) { t.Fatal(err) } if bytes.Contains(raw, r.token) { t.Errorf("%s holds the token", f) } } } // At connect: the check that makes the connection reads the profile, and // the healthy report and hello carry the account it named. func TestTokenConnectProfileNamesAccount(t *testing.T) { r := newTokenRig(t) token := fakeclaude.Token("") fake := newFakeProfile(t, token) fake.answer(http.StatusOK, "linked@example.com") clock := time.Now() o := ClaudeOptions{State: r.state, Profile: fake.reader(&clock)} // The check as CheckToken makes it: the provider answers, then the // profile is read with the lease's token. r.conns.Verify = func(ctx context.Context, b runner.AccountBinding) error { if err := r.verify(ctx, b); err != nil { return err } raw, err := provider.ReadToken(b.ProviderHome) if err != nil { return err } defer clear(raw) o.readProfile(ctx, b, raw) return nil } c := r.connector() home := r.connect(c, "cn_p1") if !r.deliver(c, "f-secret", r.sealed("cn_p1", token, nil)) { t.Fatal(r.errs) } r.healthy("cn_p1", home, token, "linked@example.com") if fake.count() != 1 { t.Fatalf("%d reads", fake.count()) } } // The read names the runner, not the Claude CLI: ProfileAgent/ // from the build, or "unknown" for a version that is not a plain token. func TestTokenProfileUserAgent(t *testing.T) { r := newProfileRig(t) r.fake.answer(http.StatusOK, "acct@example.com") r.check() r.fake.mu.Lock() agents := slices.Clone(r.fake.agents) r.fake.mu.Unlock() if !slices.Equal(agents, []string{ProfileAgent + "/v9.8.7-test"}) { t.Fatalf("user agents %q", agents) } for v, want := range map[string]string{"v0.40.1": ProfileAgent + "/v0.40.1", "": ProfileAgent + "/unknown", "v1 (x)": ProfileAgent + "/unknown", "v1\r\nX: y": ProfileAgent + "/unknown"} { if got := (&ProfileReader{Version: v}).userAgent(); got != want { t.Errorf("version %q: %q", v, want) } } } // addToken gives the rig another token connection: its home with the // token file, the binding (account named by the CLI when cli is not // ""), validated when validated is. func (r *profileRig) addToken(id, token, cli string, validated bool) runner.AccountBinding { r.t.Helper() home := filepath.Join(r.dir, "accounts", id) if err := os.MkdirAll(home, 0700); err != nil { r.t.Fatal(err) } if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(token), 0600); err != nil { r.t.Fatal(err) } account := cli if account == "" { account = provider.TokenAccountID(id) } if err := saveToken(context.Background(), r.conns.Runner.AccountBindingsPath, connPerson, id, home, provider.Identity{AccountID: account, ProviderVersion: provider.LoginVersion("claude")}); err != nil { r.t.Fatal(err) } if validated { r.conns.Validated(id) } b, ok := r.conns.Binding(id) if !ok { r.t.Fatal("not bound") } return b } // start is a runner start's profile pass on a fresh view of the // connections, as Run makes it; it counts the labels it changed. func (r *profileRig) start() int { r.conns = &Conns{Runner: r.conns.Runner, State: r.state} named := 0 r.o.readProfilesAtStart(context.Background(), r.conns, func() { named++ }) return named } // At start, each existing token connection with no email and no recent // not-available record is read once: exactly one GET for the bare one, // none for one recently not available, one the profile named, one the // CLI named, or one never validated. A restart within the retry // interval reads the not-available one no more; after it, once. func TestTokenProfileAtStart(t *testing.T) { r := newProfileRig(t) r.fake.token = "" bare := r.b bareToken := string(r.token) tokens := map[string]string{"claude-4": "sk-ant-oat01-fake-four-ok", "claude-5": "sk-ant-oat01-fake-five-ok", "claude-6": "sk-ant-oat01-fake-six-ok", "claude-7": "sk-ant-oat01-fake-seven-ok"} unavailable := r.addToken("claude-4", tokens["claude-4"], "", true) if err := r.state.recordProfile(context.Background(), unavailable.ID, profileMark([]byte(tokens["claude-4"])), "", r.clock.Add(-time.Hour)); err != nil { t.Fatal(err) } named := r.addToken("claude-5", tokens["claude-5"], "", true) if err := r.state.recordProfile(context.Background(), named.ID, profileMark([]byte(tokens["claude-5"])), "five@example.com", r.clock.Add(-30*24*time.Hour)); err != nil { t.Fatal(err) } r.addToken("claude-6", tokens["claude-6"], "cli@example.com", true) r.addToken("claude-7", tokens["claude-7"], "", false) r.fake.answer(http.StatusOK, "bare@example.com") if got := r.start(); got != 1 || r.fake.count() != 1 || r.fake.readsOf(bareToken) != 1 { t.Fatalf("start: %d named, %d reads (%d of the bare one)", got, r.fake.count(), r.fake.readsOf(bareToken)) } if r.label() != "bare@example.com" { t.Fatalf("bare label %q", r.label()) } for _, id := range []string{"claude-4", "claude-5", "claude-6", "claude-7"} { if n := r.fake.readsOf(tokens[id]); n != 0 { t.Errorf("%s read %d times at start", id, n) } } // Restarted: nothing is due. r.clock = r.clock.Add(24 * time.Hour) if r.start(); r.fake.count() != 1 { t.Fatalf("a restart read again: %d", r.fake.count()) } // The bare one turns out not available; restarts within the interval // leave it, the first after it reads it once. r.b = bare r.clock = r.clock.Add(ProfileRetry) r.fake.answer(http.StatusForbidden, "") r.check() if r.fake.readsOf(bareToken) != 2 || r.label() != "" { t.Fatal("not recorded unavailable") } r.clock = r.clock.Add(ProfileRetry - time.Hour) r.start() if r.fake.readsOf(bareToken) != 2 { t.Fatal("a restart within the interval read a not-available one") } r.clock = r.clock.Add(time.Hour) r.start() if r.fake.readsOf(bareToken) != 3 { t.Fatal("not read once after the interval") } for _, id := range []string{"claude-5", "claude-6", "claude-7"} { if n := r.fake.readsOf(tokens[id]); n != 0 { t.Errorf("%s read %d times", id, n) } } if !strings.Contains(r.logs.String(), "status=403 email=false outcome=unavailable") { t.Fatalf("log %s", r.logs.String()) } }