| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "database/sql" |
| 7 | "log/slog" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "net/netip" |
| 11 | "net/url" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "slices" |
| 15 | "strings" |
| 16 | "sync" |
| 17 | "testing" |
| 18 | "time" |
| 19 | |
| 20 | "amadan.net/oficina/equipo/internal/fakeclaude" |
| 21 | "amadan.net/oficina/equipo/internal/runner" |
| 22 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 23 | "amadan.net/oficina/equipo/internal/runner/egress" |
| 24 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 25 | "amadan.net/oficina/equipo/internal/wire" |
| 26 | ) |
| 27 | |
| 28 | // fakeProfile is Claude's profile endpoint as the pinned CLI reads it: a |
| 29 | // GET with the token as a bearer, from a runner that names itself |
| 30 | // (ProfileAgent/<version>). It answers status, with the account's email |
| 31 | // on a 200; it counts the reads by token and fails the test on any other |
| 32 | // request. With token "" it takes any bearer. |
| 33 | type fakeProfile struct { |
| 34 | t *testing.T |
| 35 | srv *httptest.Server |
| 36 | mu sync.Mutex |
| 37 | status int |
| 38 | email string |
| 39 | token string |
| 40 | reads int |
| 41 | agents []string |
| 42 | seen map[string]int |
| 43 | } |
| 44 | |
| 45 | func newFakeProfile(t *testing.T, token string) *fakeProfile { |
| 46 | f := &fakeProfile{t: t, status: http.StatusOK, token: token, seen: map[string]int{}} |
| 47 | f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 48 | f.mu.Lock() |
| 49 | defer f.mu.Unlock() |
| 50 | f.reads++ |
| 51 | bearer, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") |
| 52 | f.seen[bearer]++ |
| 53 | f.agents = append(f.agents, r.Header.Get("User-Agent")) |
| 54 | 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") { |
| 55 | t.Errorf("not the CLI's profile read: %s %s", r.Method, r.URL) |
| 56 | w.WriteHeader(http.StatusTeapot) |
| 57 | return |
| 58 | } |
| 59 | w.Header().Set("Content-Type", "application/json") |
| 60 | w.WriteHeader(f.status) |
| 61 | if f.status == http.StatusOK { |
| 62 | _, _ = w.Write([]byte(`{"account":{"uuid":"acc-1","email":"` + f.email + `","display_name":"A"},"organization":{"uuid":"org-1","organization_type":"claude_max"}}`)) |
| 63 | return |
| 64 | } |
| 65 | _, _ = w.Write([]byte(`{"type":"error","error":{"type":"permission_error","message":"secret detail ` + bearer + `"}}`)) |
| 66 | })) |
| 67 | t.Cleanup(f.srv.Close) |
| 68 | return f |
| 69 | } |
| 70 | |
| 71 | func (f *fakeProfile) answer(status int, email string) { |
| 72 | f.mu.Lock() |
| 73 | f.status, f.email = status, email |
| 74 | f.mu.Unlock() |
| 75 | } |
| 76 | |
| 77 | func (f *fakeProfile) count() int { |
| 78 | f.mu.Lock() |
| 79 | defer f.mu.Unlock() |
| 80 | return f.reads |
| 81 | } |
| 82 | |
| 83 | // readsOf counts the reads made with token. |
| 84 | func (f *fakeProfile) readsOf(token string) int { |
| 85 | f.mu.Lock() |
| 86 | defer f.mu.Unlock() |
| 87 | return f.seen[token] |
| 88 | } |
| 89 | |
| 90 | // reader is the runner's profile reader pointed at the fake through the |
| 91 | // seam an API key's requests use (connect.SafeClient), loopback allowed. |
| 92 | func (f *fakeProfile) reader(clock *time.Time) *ProfileReader { |
| 93 | 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 }} |
| 94 | } |
| 95 | |
| 96 | // profileRig is a runner state holding one validated token connection |
| 97 | // whose CLI named no account, its token, a fake profile endpoint, and |
| 98 | // the check's options with a log. |
| 99 | type profileRig struct { |
| 100 | t *testing.T |
| 101 | state *State |
| 102 | conns *Conns |
| 103 | b runner.AccountBinding |
| 104 | token []byte |
| 105 | fake *fakeProfile |
| 106 | clock time.Time |
| 107 | logs lockedBuffer |
| 108 | o ClaudeOptions |
| 109 | dir string |
| 110 | } |
| 111 | |
| 112 | func newProfileRig(t *testing.T) *profileRig { |
| 113 | dir := t.TempDir() |
| 114 | r := &profileRig{t: t, dir: dir, clock: time.Date(2026, 11, 12, 9, 0, 0, 0, time.UTC)} |
| 115 | for _, d := range []string{"config", "state", "accounts/claude-3"} { |
| 116 | if err := os.MkdirAll(filepath.Join(dir, d), 0700); err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | } |
| 120 | var err error |
| 121 | if r.state, err = OpenState(context.Background(), filepath.Join(dir, "state")); err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | t.Cleanup(func() { r.state.Close() }) |
| 125 | cfg := runner.Config{AccountBindingsPath: filepath.Join(dir, "config", "bindings.json")} |
| 126 | home := filepath.Join(dir, "accounts", "claude-3") |
| 127 | if err = saveToken(context.Background(), cfg.AccountBindingsPath, connPerson, "claude-3", home, provider.Identity{AccountID: provider.TokenAccountID("claude-3"), ProviderVersion: provider.LoginVersion("claude")}); err != nil { |
| 128 | t.Fatal(err) |
| 129 | } |
| 130 | r.conns = &Conns{Runner: cfg, State: r.state} |
| 131 | r.conns.Validated("claude-3") |
| 132 | var ok bool |
| 133 | if r.b, ok = r.conns.Binding("claude-3"); !ok || tokenLabel(r.b.AccountID) != "" { |
| 134 | t.Fatalf("binding %+v", r.b) |
| 135 | } |
| 136 | r.token = []byte(fakeclaude.Token("")) |
| 137 | if err = os.WriteFile(filepath.Join(home, provider.TokenFile), r.token, 0600); err != nil { |
| 138 | t.Fatal(err) |
| 139 | } |
| 140 | r.fake = newFakeProfile(t, string(r.token)) |
| 141 | r.o = ClaudeOptions{State: r.state, Profile: r.fake.reader(&r.clock), Logger: slog.New(slog.NewTextHandler(&r.logs, nil))} |
| 142 | return r |
| 143 | } |
| 144 | |
| 145 | // check is the profile read a token check makes once the provider |
| 146 | // answered it, with the token from its lease. |
| 147 | func (r *profileRig) check() bool { |
| 148 | return r.o.readProfile(context.Background(), r.b, bytes.Clone(r.token)) |
| 149 | } |
| 150 | |
| 151 | // label is the connection's label in hello. |
| 152 | func (r *profileRig) label() string { |
| 153 | r.t.Helper() |
| 154 | for _, h := range r.conns.Held() { |
| 155 | if h.LocalID == r.b.ID { |
| 156 | return h.Label |
| 157 | } |
| 158 | } |
| 159 | r.t.Fatal("not held") |
| 160 | return "" |
| 161 | } |
| 162 | |
| 163 | // unavailable reports what thin.db says of the connection's profile: |
| 164 | // recorded at all, and not available for this sign-in. |
| 165 | func (r *profileRig) unavailable() (recorded, unavailable bool) { |
| 166 | var u int |
| 167 | err := r.state.db.QueryRow("SELECT unavailable FROM conn_profile WHERE id=?", r.b.ID).Scan(&u) |
| 168 | if err == sql.ErrNoRows { |
| 169 | return false, false |
| 170 | } |
| 171 | if err != nil { |
| 172 | r.t.Fatal(err) |
| 173 | } |
| 174 | return true, u == 1 |
| 175 | } |
| 176 | |
| 177 | // The profile names the account: the email is the provider's, the |
| 178 | // connection's label in hello (which the instance shows plainly and |
| 179 | // asks no email for), and is not asked for again on the next check. |
| 180 | func TestTokenProfileNamesAccount(t *testing.T) { |
| 181 | r := newProfileRig(t) |
| 182 | r.fake.answer(http.StatusOK, "acct@example.com") |
| 183 | if r.label() != "" { |
| 184 | t.Fatal("labelled before the read") |
| 185 | } |
| 186 | if !r.check() || r.fake.count() != 1 { |
| 187 | t.Fatalf("the check did not read the profile: %d reads", r.fake.count()) |
| 188 | } |
| 189 | if got := r.label(); got != "acct@example.com" { |
| 190 | t.Fatalf("label %q", got) |
| 191 | } |
| 192 | if rec, un := r.unavailable(); !rec || un { |
| 193 | t.Fatalf("recorded %v, unavailable %v", rec, un) |
| 194 | } |
| 195 | // The next check: nothing due. |
| 196 | r.clock = r.clock.Add(time.Hour) |
| 197 | if r.check() || r.fake.count() != 1 { |
| 198 | t.Fatalf("read again on the next check: %d", r.fake.count()) |
| 199 | } |
| 200 | // A week on, asked again; the same answer changes nothing. |
| 201 | r.clock = r.clock.Add(ProfileRetry) |
| 202 | if r.check() || r.fake.count() != 2 || r.label() != "acct@example.com" { |
| 203 | t.Fatalf("a week on: %d reads, %q", r.fake.count(), r.label()) |
| 204 | } |
| 205 | // Signed out: forgotten with the connection. |
| 206 | r.conns.Forget(r.b.ID) |
| 207 | if rec, _ := r.unavailable(); rec { |
| 208 | t.Fatal("the profile outlived the connection") |
| 209 | } |
| 210 | if !strings.Contains(r.logs.String(), "status=200 email=true outcome=found") { |
| 211 | t.Fatalf("log %s", r.logs.String()) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | // 401, 403, 404: the profile is not available for this sign-in. Nothing |
| 216 | // is named (the instance keeps asking for the email); the next check does |
| 217 | // not ask; a week later, or another token, does. |
| 218 | func TestTokenProfileNotAvailable(t *testing.T) { |
| 219 | for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound} { |
| 220 | t.Run(http.StatusText(status), func(t *testing.T) { |
| 221 | r := newProfileRig(t) |
| 222 | r.fake.answer(status, "") |
| 223 | if r.check() || r.fake.count() != 1 || r.label() != "" { |
| 224 | t.Fatalf("%d reads, label %q", r.fake.count(), r.label()) |
| 225 | } |
| 226 | if rec, un := r.unavailable(); !rec || !un { |
| 227 | t.Fatalf("recorded %v, unavailable %v", rec, un) |
| 228 | } |
| 229 | r.clock = r.clock.Add(ProfileRetry - time.Minute) |
| 230 | if r.check(); r.fake.count() != 1 { |
| 231 | t.Fatal("asked again on the next check") |
| 232 | } |
| 233 | // A week on, the profile answers now. |
| 234 | r.clock = r.clock.Add(time.Minute) |
| 235 | r.fake.answer(http.StatusOK, "later@example.com") |
| 236 | if !r.check() || r.fake.count() != 2 || r.label() != "later@example.com" { |
| 237 | t.Fatalf("a week on: %d reads, %q", r.fake.count(), r.label()) |
| 238 | } |
| 239 | // Unavailable again, then another token on the connection. |
| 240 | r.clock = r.clock.Add(ProfileRetry) |
| 241 | r.fake.answer(status, "") |
| 242 | if !r.check() || r.label() != "" || r.fake.count() != 3 { |
| 243 | t.Fatalf("unavailable again: %d reads, %q", r.fake.count(), r.label()) |
| 244 | } |
| 245 | r.token = []byte(fakeclaude.Token("") + "-2") |
| 246 | r.fake.mu.Lock() |
| 247 | r.fake.token = string(r.token) |
| 248 | r.fake.mu.Unlock() |
| 249 | if r.check(); r.fake.count() != 4 { |
| 250 | t.Fatal("another token was not asked about") |
| 251 | } |
| 252 | }) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | // Anything else (a 500, a 200 the CLI could not read, no answer at all) |
| 257 | // records nothing new: the next check asks again. |
| 258 | func TestTokenProfileFailureRetries(t *testing.T) { |
| 259 | r := newProfileRig(t) |
| 260 | r.fake.answer(http.StatusInternalServerError, "") |
| 261 | if r.check() || r.fake.count() != 1 || r.label() != "" { |
| 262 | t.Fatalf("%d reads, %q", r.fake.count(), r.label()) |
| 263 | } |
| 264 | if rec, _ := r.unavailable(); rec { |
| 265 | t.Fatal("a 500 was recorded") |
| 266 | } |
| 267 | r.fake.answer(http.StatusOK, "not an email") |
| 268 | if r.check() || r.fake.count() != 2 { |
| 269 | t.Fatal("not asked again on the next check") |
| 270 | } |
| 271 | if rec, _ := r.unavailable(); rec { |
| 272 | t.Fatal("an unreadable answer was recorded") |
| 273 | } |
| 274 | // Recorded as found, then a failure: the email stands. |
| 275 | r.fake.answer(http.StatusOK, "acct@example.com") |
| 276 | if !r.check() || r.label() != "acct@example.com" { |
| 277 | t.Fatal("not found") |
| 278 | } |
| 279 | r.clock = r.clock.Add(ProfileRetry) |
| 280 | r.fake.answer(http.StatusBadGateway, "") |
| 281 | if r.check() || r.label() != "acct@example.com" { |
| 282 | t.Fatal("a failure changed the label") |
| 283 | } |
| 284 | // No answer at all. |
| 285 | r.fake.srv.Close() |
| 286 | if r.check() || r.label() != "acct@example.com" { |
| 287 | t.Fatal("no answer changed the label") |
| 288 | } |
| 289 | if !strings.Contains(r.logs.String(), "status=0 email=false outcome=failed") { |
| 290 | t.Fatalf("log %s", r.logs.String()) |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | // No read where none can help: an account `auth status` named, a check |
| 295 | // with no reader, no token. |
| 296 | func TestTokenProfileSkipped(t *testing.T) { |
| 297 | r := newProfileRig(t) |
| 298 | named := r.b |
| 299 | named.AccountID = "cli@example.com" |
| 300 | if r.o.readProfile(context.Background(), named, r.token) { |
| 301 | t.Fatal("changed a named account") |
| 302 | } |
| 303 | none := r.o |
| 304 | none.Profile = nil |
| 305 | none.readProfile(context.Background(), r.b, r.token) |
| 306 | r.o.readProfile(context.Background(), r.b, nil) |
| 307 | if r.fake.count() != 0 { |
| 308 | t.Fatalf("%d reads", r.fake.count()) |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | // The release reads api.anthropic.com, the Claude route's one host, on |
| 313 | // 443: the read adds no egress. |
| 314 | func TestTokenProfileHostIsClaudes(t *testing.T) { |
| 315 | u, err := url.Parse(AnthropicProfile().Origin) |
| 316 | if err != nil || u.Scheme != "https" || u.Port() != "" || u.Path != "" { |
| 317 | t.Fatalf("origin %q", AnthropicProfile().Origin) |
| 318 | } |
| 319 | hosts := egress.Routes()[egress.Route{Harness: "claude", Provider: "claude"}] |
| 320 | if !slices.Equal(hosts, []string{u.Hostname()}) || wire.EndpointAnthropic != "https://"+u.Hostname()+":443" { |
| 321 | t.Fatalf("Claude route %v, profile host %q", hosts, u.Hostname()) |
| 322 | } |
| 323 | if o := OptionsFromEnv(func(string) string { return "" }); o.Claude.Profile == nil || o.Claude.Profile.Origin != ProfileOrigin || o.Claude.Profile.HTTP != nil { |
| 324 | t.Fatal("a release runner reads no profile, or not through the safe client") |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | // Nothing of the read is logged or reported but its status and whether |
| 329 | // it named an email: not the token, not the header, not the email, not |
| 330 | // the answer. The check's report (its usage frame) and thin.db hold no |
| 331 | // token either. Every outcome is run. |
| 332 | func TestTokenProfileLogsNoSecret(t *testing.T) { |
| 333 | r := newProfileRig(t) |
| 334 | const email = "hidden.account@example.com" |
| 335 | for _, a := range []struct { |
| 336 | status int |
| 337 | email string |
| 338 | }{{http.StatusOK, email}, {http.StatusForbidden, ""}, {http.StatusInternalServerError, ""}} { |
| 339 | r.clock = r.clock.Add(ProfileRetry) |
| 340 | r.fake.answer(a.status, a.email) |
| 341 | r.check() |
| 342 | } |
| 343 | if r.fake.count() != 3 { |
| 344 | t.Fatalf("%d reads", r.fake.count()) |
| 345 | } |
| 346 | 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 { |
| 347 | t.Fatal(err) |
| 348 | } |
| 349 | var reported []string |
| 350 | rows, err := r.state.db.Query("SELECT body FROM outbox") |
| 351 | if err != nil { |
| 352 | t.Fatal(err) |
| 353 | } |
| 354 | for rows.Next() { |
| 355 | var body string |
| 356 | _ = rows.Scan(&body) |
| 357 | reported = append(reported, body) |
| 358 | } |
| 359 | rows.Close() |
| 360 | if len(reported) == 0 { |
| 361 | t.Fatal("no check report") |
| 362 | } |
| 363 | logs := r.logs.String() |
| 364 | if !strings.Contains(logs, "token profile") || !strings.Contains(logs, "status=403") { |
| 365 | t.Fatalf("the reads were not logged: %s", logs) |
| 366 | } |
| 367 | for name, text := range map[string]string{"log": logs, "check report": strings.Join(reported, "\n")} { |
| 368 | for _, secret := range []string{string(r.token), "Bearer", email, "hidden.account", "permission_error"} { |
| 369 | if strings.Contains(text, secret) { |
| 370 | t.Errorf("the %s holds %q", name, secret) |
| 371 | } |
| 372 | } |
| 373 | } |
| 374 | r.state.Close() |
| 375 | for _, f := range []string{"thin.db", "thin.db-wal"} { |
| 376 | raw, err := os.ReadFile(filepath.Join(r.dir, "state", f)) |
| 377 | if err != nil && !os.IsNotExist(err) { |
| 378 | t.Fatal(err) |
| 379 | } |
| 380 | if bytes.Contains(raw, r.token) { |
| 381 | t.Errorf("%s holds the token", f) |
| 382 | } |
| 383 | } |
| 384 | } |
| 385 | |
| 386 | // At connect: the check that makes the connection reads the profile, and |
| 387 | // the healthy report and hello carry the account it named. |
| 388 | func TestTokenConnectProfileNamesAccount(t *testing.T) { |
| 389 | r := newTokenRig(t) |
| 390 | token := fakeclaude.Token("") |
| 391 | fake := newFakeProfile(t, token) |
| 392 | fake.answer(http.StatusOK, "linked@example.com") |
| 393 | clock := time.Now() |
| 394 | o := ClaudeOptions{State: r.state, Profile: fake.reader(&clock)} |
| 395 | // The check as CheckToken makes it: the provider answers, then the |
| 396 | // profile is read with the lease's token. |
| 397 | r.conns.Verify = func(ctx context.Context, b runner.AccountBinding) error { |
| 398 | if err := r.verify(ctx, b); err != nil { |
| 399 | return err |
| 400 | } |
| 401 | raw, err := provider.ReadToken(b.ProviderHome) |
| 402 | if err != nil { |
| 403 | return err |
| 404 | } |
| 405 | defer clear(raw) |
| 406 | o.readProfile(ctx, b, raw) |
| 407 | return nil |
| 408 | } |
| 409 | c := r.connector() |
| 410 | home := r.connect(c, "cn_p1") |
| 411 | if !r.deliver(c, "f-secret", r.sealed("cn_p1", token, nil)) { |
| 412 | t.Fatal(r.errs) |
| 413 | } |
| 414 | r.healthy("cn_p1", home, token, "linked@example.com") |
| 415 | if fake.count() != 1 { |
| 416 | t.Fatalf("%d reads", fake.count()) |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | // The read names the runner, not the Claude CLI: ProfileAgent/<version> |
| 421 | // from the build, or "unknown" for a version that is not a plain token. |
| 422 | func TestTokenProfileUserAgent(t *testing.T) { |
| 423 | r := newProfileRig(t) |
| 424 | r.fake.answer(http.StatusOK, "acct@example.com") |
| 425 | r.check() |
| 426 | r.fake.mu.Lock() |
| 427 | agents := slices.Clone(r.fake.agents) |
| 428 | r.fake.mu.Unlock() |
| 429 | if !slices.Equal(agents, []string{ProfileAgent + "/v9.8.7-test"}) { |
| 430 | t.Fatalf("user agents %q", agents) |
| 431 | } |
| 432 | 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"} { |
| 433 | if got := (&ProfileReader{Version: v}).userAgent(); got != want { |
| 434 | t.Errorf("version %q: %q", v, want) |
| 435 | } |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | // addToken gives the rig another token connection: its home with the |
| 440 | // token file, the binding (account named by the CLI when cli is not |
| 441 | // ""), validated when validated is. |
| 442 | func (r *profileRig) addToken(id, token, cli string, validated bool) runner.AccountBinding { |
| 443 | r.t.Helper() |
| 444 | home := filepath.Join(r.dir, "accounts", id) |
| 445 | if err := os.MkdirAll(home, 0700); err != nil { |
| 446 | r.t.Fatal(err) |
| 447 | } |
| 448 | if err := os.WriteFile(filepath.Join(home, provider.TokenFile), []byte(token), 0600); err != nil { |
| 449 | r.t.Fatal(err) |
| 450 | } |
| 451 | account := cli |
| 452 | if account == "" { |
| 453 | account = provider.TokenAccountID(id) |
| 454 | } |
| 455 | if err := saveToken(context.Background(), r.conns.Runner.AccountBindingsPath, connPerson, id, home, provider.Identity{AccountID: account, ProviderVersion: provider.LoginVersion("claude")}); err != nil { |
| 456 | r.t.Fatal(err) |
| 457 | } |
| 458 | if validated { |
| 459 | r.conns.Validated(id) |
| 460 | } |
| 461 | b, ok := r.conns.Binding(id) |
| 462 | if !ok { |
| 463 | r.t.Fatal("not bound") |
| 464 | } |
| 465 | return b |
| 466 | } |
| 467 | |
| 468 | // start is a runner start's profile pass on a fresh view of the |
| 469 | // connections, as Run makes it; it counts the labels it changed. |
| 470 | func (r *profileRig) start() int { |
| 471 | r.conns = &Conns{Runner: r.conns.Runner, State: r.state} |
| 472 | named := 0 |
| 473 | r.o.readProfilesAtStart(context.Background(), r.conns, func() { named++ }) |
| 474 | return named |
| 475 | } |
| 476 | |
| 477 | // At start, each existing token connection with no email and no recent |
| 478 | // not-available record is read once: exactly one GET for the bare one, |
| 479 | // none for one recently not available, one the profile named, one the |
| 480 | // CLI named, or one never validated. A restart within the retry |
| 481 | // interval reads the not-available one no more; after it, once. |
| 482 | func TestTokenProfileAtStart(t *testing.T) { |
| 483 | r := newProfileRig(t) |
| 484 | r.fake.token = "" |
| 485 | bare := r.b |
| 486 | bareToken := string(r.token) |
| 487 | 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"} |
| 488 | unavailable := r.addToken("claude-4", tokens["claude-4"], "", true) |
| 489 | if err := r.state.recordProfile(context.Background(), unavailable.ID, profileMark([]byte(tokens["claude-4"])), "", r.clock.Add(-time.Hour)); err != nil { |
| 490 | t.Fatal(err) |
| 491 | } |
| 492 | named := r.addToken("claude-5", tokens["claude-5"], "", true) |
| 493 | 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 { |
| 494 | t.Fatal(err) |
| 495 | } |
| 496 | r.addToken("claude-6", tokens["claude-6"], "cli@example.com", true) |
| 497 | r.addToken("claude-7", tokens["claude-7"], "", false) |
| 498 | |
| 499 | r.fake.answer(http.StatusOK, "bare@example.com") |
| 500 | if got := r.start(); got != 1 || r.fake.count() != 1 || r.fake.readsOf(bareToken) != 1 { |
| 501 | t.Fatalf("start: %d named, %d reads (%d of the bare one)", got, r.fake.count(), r.fake.readsOf(bareToken)) |
| 502 | } |
| 503 | if r.label() != "bare@example.com" { |
| 504 | t.Fatalf("bare label %q", r.label()) |
| 505 | } |
| 506 | for _, id := range []string{"claude-4", "claude-5", "claude-6", "claude-7"} { |
| 507 | if n := r.fake.readsOf(tokens[id]); n != 0 { |
| 508 | t.Errorf("%s read %d times at start", id, n) |
| 509 | } |
| 510 | } |
| 511 | // Restarted: nothing is due. |
| 512 | r.clock = r.clock.Add(24 * time.Hour) |
| 513 | if r.start(); r.fake.count() != 1 { |
| 514 | t.Fatalf("a restart read again: %d", r.fake.count()) |
| 515 | } |
| 516 | // The bare one turns out not available; restarts within the interval |
| 517 | // leave it, the first after it reads it once. |
| 518 | r.b = bare |
| 519 | r.clock = r.clock.Add(ProfileRetry) |
| 520 | r.fake.answer(http.StatusForbidden, "") |
| 521 | r.check() |
| 522 | if r.fake.readsOf(bareToken) != 2 || r.label() != "" { |
| 523 | t.Fatal("not recorded unavailable") |
| 524 | } |
| 525 | r.clock = r.clock.Add(ProfileRetry - time.Hour) |
| 526 | r.start() |
| 527 | if r.fake.readsOf(bareToken) != 2 { |
| 528 | t.Fatal("a restart within the interval read a not-available one") |
| 529 | } |
| 530 | r.clock = r.clock.Add(time.Hour) |
| 531 | r.start() |
| 532 | if r.fake.readsOf(bareToken) != 3 { |
| 533 | t.Fatal("not read once after the interval") |
| 534 | } |
| 535 | for _, id := range []string{"claude-5", "claude-6", "claude-7"} { |
| 536 | if n := r.fake.readsOf(tokens[id]); n != 0 { |
| 537 | t.Errorf("%s read %d times", id, n) |
| 538 | } |
| 539 | } |
| 540 | if !strings.Contains(r.logs.String(), "status=403 email=false outcome=unavailable") { |
| 541 | t.Fatalf("log %s", r.logs.String()) |
| 542 | } |
| 543 | } |
| 544 | |