package thin import ( "bytes" "context" "encoding/json" "fmt" "log/slog" "net/http" "net/http/httptest" "net/netip" "os" "path/filepath" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/runner/connect" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/wire" ) func TestClaudeUsageRefresh(t *testing.T) { for _, status := range []int{200, 401, 403, 404, 500} { t.Run(fmt.Sprint(status), func(t *testing.T) { r := newConnectorRig(t) r.cfg.ScratchRoot = filepath.Join(t.TempDir(), "scratch") r.conns.Runner = r.cfg b, _ := r.conns.Binding("codex-1") b.Provider, b.Family, b.Kind = "claude", "claude", wire.KindSubscription raw, _ := json.Marshal([]any{b}) if err := os.WriteFile(r.bindings, raw, 0600); err != nil { t.Fatal(err) } identity, _ := json.Marshal(b.ExpectedIdentity) for name, body := range map[string][]byte{provider.IdentityFile: identity, ".claude.json": []byte(`{"oauthAccount":{"emailAddress":"a@example.com"}}`)} { if err := os.WriteFile(filepath.Join(r.home, name), body, 0600); err != nil { t.Fatal(err) } } token := "fixture-usage-bearer-private" putToken := func() { t.Helper() if err := os.WriteFile(filepath.Join(r.home, ".credentials.json"), []byte(`{"claudeAiOauth":{"accessToken":"`+token+`"}}`), 0600); err != nil { t.Fatal(err) } } putToken() reads := 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { reads++ if req.Method != "GET" || req.URL.Path != "/api/oauth/usage" || req.URL.RawQuery != "" || req.Header.Get("Authorization") != "Bearer "+token || req.Header.Get("User-Agent") != "equipo-runner/test" || req.Header.Get("anthropic-beta") != "oauth-2025-04-20" { t.Error("unexpected usage request") } w.WriteHeader(status) if status == 200 { fmt.Fprint(w, `{"five_hour":{"utilization":12.5,"resets_at":"2026-11-14T14:00:00Z"},"seven_day":{"utilization":2,"resets_at":"2026-11-20T12:00:00Z"},"secret":"body-private"}`) } else { fmt.Fprint(w, token+" body-private") } })) defer srv.Close() at := time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC) reader := &ProfileReader{Origin: srv.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), Version: "test"} var logs bytes.Buffer setup := func() { r.conns.ClaudeUsage = reader r.conns.ClaudeStatus = func(context.Context, provider.Binding) (provider.Identity, string, error) { return provider.Identity{AccountID: b.AccountID, ProviderVersion: b.ExpectedIdentity.ProviderVersion}, "max", nil } r.conns.now = func() time.Time { return at } r.conns.Logger = slog.New(slog.NewTextHandler(&logs, nil)) } setup() r.conns.Check(context.Background()) if reads != 1 { t.Fatalf("hourly check made %d reads", reads) } held := r.conns.Held()[0] if held.State != wire.ConnHealthy { t.Fatalf("usage endpoint changed login health: %s", held.State) } if held.Plan != "max" { t.Fatalf("plan %q", held.Plan) } if status == 200 { h := held.Headroom if h == nil || len(h.Windows) != 2 || h.Windows[0].UsedPercent != 12.5 || h.Windows[1].UsedPercent != 2 || h.CheckedAt == nil || !h.CheckedAt.Equal(at) || !h.Fetched || h.Unavailable { t.Fatalf("reading %+v", h) } if h.Windows[0].Minutes != 300 || h.Windows[1].Minutes != 10080 || h.Windows[0].ResetsAt.Format(time.RFC3339) != "2026-11-14T14:00:00Z" { t.Fatal("windows changed") } } else if status != 500 && status != 401 && (held.Headroom == nil || !held.Headroom.Unavailable || held.Headroom.CheckedAt != nil) { t.Fatalf("refusal %+v", held.Headroom) } else if (status == 500 || status == 401) && held.Headroom != nil { t.Fatalf("%d invented a reading or a refusal", status) } // A restart and Check again both respect a refused endpoint's backoff. r.conns = &Conns{Runner: r.cfg, State: r.state} setup() at = at.Add(time.Hour) r.conns.CheckAgain(context.Background(), b.ID) denied := status == 403 || status == 404 want := 2 if denied { want = 1 } if reads != want { t.Fatalf("Check again reads %d, want %d", reads, want) } token = "fixture-replaced-private" putToken() r.conns.Check(context.Background()) want++ if reads != want { t.Fatal("token change did not retry") } at = at.Add(7 * 24 * time.Hour) r.conns.Check(context.Background()) want++ if reads != want { t.Fatal("week did not retry") } if strings.Contains(logs.String(), "private") { t.Fatalf("secret leaked in logs") } }) } } func TestClaudeUsageSkipsSetupToken(t *testing.T) { r := newProfileRig(t) r.conns.Runner.ScratchRoot = filepath.Join(t.TempDir(), "scratch") if err := r.state.recordProfile(context.Background(), r.b.ID, profileMark(r.token), "", time.Now()); err != nil { t.Fatal(err) } checks := 0 r.conns.Refresh = func(context.Context, provider.Binding) (provider.Identity, error) { checks++ return r.b.ExpectedIdentity, nil } r.conns.ClaudeStatus = func(context.Context, provider.Binding) (provider.Identity, string, error) { t.Error("setup token treated as login") return provider.Identity{}, "", nil } srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("setup-token usage requested") })) defer srv.Close() r.conns.ClaudeUsage = &ProfileReader{Origin: srv.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} r.conns.Check(context.Background()) if checks != 1 { t.Fatal("local status did not run") } } func TestClaudeUsageKeepsLastReading(t *testing.T) { r := newConnectorRig(t) at := time.Now().UTC() r.conns.now = func() time.Time { return at } status := 200 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(status) fmt.Fprint(w, `{"seven_day":{"utilization":86,"resets_at":null}}`) })) defer srv.Close() r.conns.ClaudeUsage = &ProfileReader{Origin: srv.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} if err := r.conns.load(context.Background()); err != nil { t.Fatal(err) } r.conns.readClaudeUsage(context.Background(), "codex-1", []byte("fixture")) original := r.conns.Held()[0].Headroom.CheckedAt for _, code := range []int{500, 403} { status = code at = at.Add(time.Hour) r.conns.readClaudeUsage(context.Background(), "codex-1", []byte("fixture")) h := r.conns.Held()[0].Headroom if h.CheckedAt == nil || !h.CheckedAt.Equal(*original) || len(h.Windows) != 1 || h.Windows[0].UsedPercent != 86 || h.Unavailable != (code == 403) { t.Fatalf("last reading lost: %+v", h) } } // Turn readings use their own source and preserve the unavailable notice. l := claudeUsage([]byte(`{"seven_day":{"utilization":90}}`)) l.Headroom.Fetched = false r.conns.Observe("codex-1", *l, "") h := r.conns.Held()[0].Headroom if h.Fetched || !h.Unavailable { t.Fatalf("turn source %+v", h) } status = 200 at = at.Add(7 * 24 * time.Hour) r.conns.readClaudeUsage(context.Background(), "codex-1", []byte("fixture")) if h := r.conns.Held()[0].Headroom; !h.Fetched || h.Unavailable || !h.CheckedAt.Equal(at) { t.Fatalf("recovery %+v", h) } } func TestClaudeUsageUnknownIsNotZero(t *testing.T) { for _, raw := range []string{`{}`, `null`, `{"five_hour":null}`, `{"five_hour":{"utilization":null}}`, `{"five_hour":{"utilization":-1}}`, `{"five_hour":{"utilization":1,"resets_at":"invalid"}}`, `{"five_hour":{"utilization":"secret"}}`} { if claudeUsage([]byte(raw)) != nil { t.Fatalf("invalid reading accepted: %s", raw) } } if l := claudeUsage([]byte(`{"five_hour":{"utilization":0,"resets_at":null},"extra_usage":{"is_enabled":false}}`)); l == nil || len(l.Headroom.Windows) != 1 || l.Headroom.Windows[0].UsedPercent != 0 { t.Fatal("reported zero lost") } } func TestHandshakeHelloWithholdsUsageRefresh(t *testing.T) { hello := func() wire.Hello { return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Versions: map[string]string{"runner": "test", "claude": "2.1.312"}, Connections: []wire.HeldConnection{{LocalID: "cl", Headroom: &wire.Headroom{Fetched: true, Unavailable: true}}}} } for _, protocol := range []int{19, 20} { inst := newFakeInstance(t) link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) c := <-inst.conns _, raw := read(t, c, wire.FrameHello) if strings.Contains(string(raw), "fetched") || strings.Contains(string(raw), "unavailable") { t.Fatal("initial hello leaked fields") } welcome, _ := json.Marshal(wire.Frame{ID: "welcome", Type: wire.FrameWelcome, Data: json.RawMessage(fmt.Sprintf(`{"generation":3,"runner_id":"RUNNER1","protocol":%d,"role":"primary"}`, protocol))}) write(t, c, welcome) read(t, c, wire.FrameSync) if protocol == 19 { link.HelloSoon() } _, raw = read(t, c, wire.FrameHello) for _, field := range []string{"fetched", "unavailable"} { if strings.Contains(string(raw), field) != (protocol == 20) { t.Fatalf("%d: %s", protocol, raw) } } } } func TestClaudeUsageSafeTransport(t *testing.T) { target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("redirect followed") })) defer target.Close() body := "" src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if body == "" { http.Redirect(w, r, target.URL, http.StatusFound) } else { fmt.Fprint(w, body) } })) defer src.Close() p := &ProfileReader{Origin: src.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} if status, l := p.readUsage(context.Background(), []byte("fixture-private")); status != 302 || l != nil { t.Fatal("redirect returned reading") } body = `{"five_hour":{"utilization":1},"padding":"` + strings.Repeat("x", maxProfileBytes) + `"}` if status, l := p.readUsage(context.Background(), []byte("fixture-private")); status != 200 || l != nil { t.Fatal("oversized response accepted") } // Without the test client a release refuses every other origin. p.HTTP = nil if status, l := p.readUsage(context.Background(), []byte("fixture-private")); status != 0 || l != nil { t.Fatal("release accepted another origin") } }