| 1 | package thin |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "net/http" |
| 10 | "net/http/httptest" |
| 11 | "net/netip" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "strings" |
| 15 | "testing" |
| 16 | "time" |
| 17 | |
| 18 | "amadan.net/oficina/equipo/internal/runner/connect" |
| 19 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 20 | "amadan.net/oficina/equipo/internal/wire" |
| 21 | ) |
| 22 | |
| 23 | func TestClaudeUsageRefresh(t *testing.T) { |
| 24 | for _, status := range []int{200, 401, 403, 404, 500} { |
| 25 | t.Run(fmt.Sprint(status), func(t *testing.T) { |
| 26 | r := newConnectorRig(t) |
| 27 | r.cfg.ScratchRoot = filepath.Join(t.TempDir(), "scratch") |
| 28 | r.conns.Runner = r.cfg |
| 29 | b, _ := r.conns.Binding("codex-1") |
| 30 | b.Provider, b.Family, b.Kind = "claude", "claude", wire.KindSubscription |
| 31 | raw, _ := json.Marshal([]any{b}) |
| 32 | if err := os.WriteFile(r.bindings, raw, 0600); err != nil { |
| 33 | t.Fatal(err) |
| 34 | } |
| 35 | identity, _ := json.Marshal(b.ExpectedIdentity) |
| 36 | for name, body := range map[string][]byte{provider.IdentityFile: identity, ".claude.json": []byte(`{"oauthAccount":{"emailAddress":"a@example.com"}}`)} { |
| 37 | if err := os.WriteFile(filepath.Join(r.home, name), body, 0600); err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | } |
| 41 | token := "fixture-usage-bearer-private" |
| 42 | putToken := func() { |
| 43 | t.Helper() |
| 44 | if err := os.WriteFile(filepath.Join(r.home, ".credentials.json"), []byte(`{"claudeAiOauth":{"accessToken":"`+token+`"}}`), 0600); err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | } |
| 48 | putToken() |
| 49 | reads := 0 |
| 50 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 51 | reads++ |
| 52 | 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" { |
| 53 | t.Error("unexpected usage request") |
| 54 | } |
| 55 | w.WriteHeader(status) |
| 56 | if status == 200 { |
| 57 | 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"}`) |
| 58 | } else { |
| 59 | fmt.Fprint(w, token+" body-private") |
| 60 | } |
| 61 | })) |
| 62 | defer srv.Close() |
| 63 | at := time.Date(2026, 11, 13, 12, 0, 0, 0, time.UTC) |
| 64 | reader := &ProfileReader{Origin: srv.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil), Version: "test"} |
| 65 | var logs bytes.Buffer |
| 66 | setup := func() { |
| 67 | r.conns.ClaudeUsage = reader |
| 68 | r.conns.ClaudeStatus = func(context.Context, provider.Binding) (provider.Identity, string, error) { |
| 69 | return provider.Identity{AccountID: b.AccountID, ProviderVersion: b.ExpectedIdentity.ProviderVersion}, "max", nil |
| 70 | } |
| 71 | r.conns.now = func() time.Time { return at } |
| 72 | r.conns.Logger = slog.New(slog.NewTextHandler(&logs, nil)) |
| 73 | } |
| 74 | setup() |
| 75 | r.conns.Check(context.Background()) |
| 76 | if reads != 1 { |
| 77 | t.Fatalf("hourly check made %d reads", reads) |
| 78 | } |
| 79 | held := r.conns.Held()[0] |
| 80 | if held.State != wire.ConnHealthy { |
| 81 | t.Fatalf("usage endpoint changed login health: %s", held.State) |
| 82 | } |
| 83 | if held.Plan != "max" { |
| 84 | t.Fatalf("plan %q", held.Plan) |
| 85 | } |
| 86 | if status == 200 { |
| 87 | h := held.Headroom |
| 88 | 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 { |
| 89 | t.Fatalf("reading %+v", h) |
| 90 | } |
| 91 | if h.Windows[0].Minutes != 300 || h.Windows[1].Minutes != 10080 || h.Windows[0].ResetsAt.Format(time.RFC3339) != "2026-11-14T14:00:00Z" { |
| 92 | t.Fatal("windows changed") |
| 93 | } |
| 94 | } else if status != 500 && status != 401 && (held.Headroom == nil || !held.Headroom.Unavailable || held.Headroom.CheckedAt != nil) { |
| 95 | t.Fatalf("refusal %+v", held.Headroom) |
| 96 | } else if (status == 500 || status == 401) && held.Headroom != nil { |
| 97 | t.Fatalf("%d invented a reading or a refusal", status) |
| 98 | } |
| 99 | // A restart and Check again both respect a refused endpoint's backoff. |
| 100 | r.conns = &Conns{Runner: r.cfg, State: r.state} |
| 101 | setup() |
| 102 | at = at.Add(time.Hour) |
| 103 | r.conns.CheckAgain(context.Background(), b.ID) |
| 104 | denied := status == 403 || status == 404 |
| 105 | want := 2 |
| 106 | if denied { |
| 107 | want = 1 |
| 108 | } |
| 109 | if reads != want { |
| 110 | t.Fatalf("Check again reads %d, want %d", reads, want) |
| 111 | } |
| 112 | token = "fixture-replaced-private" |
| 113 | putToken() |
| 114 | r.conns.Check(context.Background()) |
| 115 | want++ |
| 116 | if reads != want { |
| 117 | t.Fatal("token change did not retry") |
| 118 | } |
| 119 | at = at.Add(7 * 24 * time.Hour) |
| 120 | r.conns.Check(context.Background()) |
| 121 | want++ |
| 122 | if reads != want { |
| 123 | t.Fatal("week did not retry") |
| 124 | } |
| 125 | if strings.Contains(logs.String(), "private") { |
| 126 | t.Fatalf("secret leaked in logs") |
| 127 | } |
| 128 | }) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | func TestClaudeUsageSkipsSetupToken(t *testing.T) { |
| 133 | r := newProfileRig(t) |
| 134 | r.conns.Runner.ScratchRoot = filepath.Join(t.TempDir(), "scratch") |
| 135 | if err := r.state.recordProfile(context.Background(), r.b.ID, profileMark(r.token), "", time.Now()); err != nil { |
| 136 | t.Fatal(err) |
| 137 | } |
| 138 | checks := 0 |
| 139 | r.conns.Refresh = func(context.Context, provider.Binding) (provider.Identity, error) { |
| 140 | checks++ |
| 141 | return r.b.ExpectedIdentity, nil |
| 142 | } |
| 143 | r.conns.ClaudeStatus = func(context.Context, provider.Binding) (provider.Identity, string, error) { |
| 144 | t.Error("setup token treated as login") |
| 145 | return provider.Identity{}, "", nil |
| 146 | } |
| 147 | srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("setup-token usage requested") })) |
| 148 | defer srv.Close() |
| 149 | r.conns.ClaudeUsage = &ProfileReader{Origin: srv.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} |
| 150 | r.conns.Check(context.Background()) |
| 151 | if checks != 1 { |
| 152 | t.Fatal("local status did not run") |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | func TestClaudeUsageKeepsLastReading(t *testing.T) { |
| 157 | r := newConnectorRig(t) |
| 158 | at := time.Now().UTC() |
| 159 | r.conns.now = func() time.Time { return at } |
| 160 | status := 200 |
| 161 | srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 162 | w.WriteHeader(status) |
| 163 | fmt.Fprint(w, `{"seven_day":{"utilization":86,"resets_at":null}}`) |
| 164 | })) |
| 165 | defer srv.Close() |
| 166 | r.conns.ClaudeUsage = &ProfileReader{Origin: srv.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} |
| 167 | if err := r.conns.load(context.Background()); err != nil { |
| 168 | t.Fatal(err) |
| 169 | } |
| 170 | r.conns.readClaudeUsage(context.Background(), "codex-1", []byte("fixture")) |
| 171 | original := r.conns.Held()[0].Headroom.CheckedAt |
| 172 | for _, code := range []int{500, 403} { |
| 173 | status = code |
| 174 | at = at.Add(time.Hour) |
| 175 | r.conns.readClaudeUsage(context.Background(), "codex-1", []byte("fixture")) |
| 176 | h := r.conns.Held()[0].Headroom |
| 177 | if h.CheckedAt == nil || !h.CheckedAt.Equal(*original) || len(h.Windows) != 1 || h.Windows[0].UsedPercent != 86 || h.Unavailable != (code == 403) { |
| 178 | t.Fatalf("last reading lost: %+v", h) |
| 179 | } |
| 180 | } |
| 181 | // Turn readings use their own source and preserve the unavailable notice. |
| 182 | l := claudeUsage([]byte(`{"seven_day":{"utilization":90}}`)) |
| 183 | l.Headroom.Fetched = false |
| 184 | r.conns.Observe("codex-1", *l, "") |
| 185 | h := r.conns.Held()[0].Headroom |
| 186 | if h.Fetched || !h.Unavailable { |
| 187 | t.Fatalf("turn source %+v", h) |
| 188 | } |
| 189 | status = 200 |
| 190 | at = at.Add(7 * 24 * time.Hour) |
| 191 | r.conns.readClaudeUsage(context.Background(), "codex-1", []byte("fixture")) |
| 192 | if h := r.conns.Held()[0].Headroom; !h.Fetched || h.Unavailable || !h.CheckedAt.Equal(at) { |
| 193 | t.Fatalf("recovery %+v", h) |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | func TestClaudeUsageUnknownIsNotZero(t *testing.T) { |
| 198 | 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"}}`} { |
| 199 | if claudeUsage([]byte(raw)) != nil { |
| 200 | t.Fatalf("invalid reading accepted: %s", raw) |
| 201 | } |
| 202 | } |
| 203 | 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 { |
| 204 | t.Fatal("reported zero lost") |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | func TestHandshakeHelloWithholdsUsageRefresh(t *testing.T) { |
| 209 | hello := func() wire.Hello { |
| 210 | 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}}}} |
| 211 | } |
| 212 | for _, protocol := range []int{19, 20} { |
| 213 | inst := newFakeInstance(t) |
| 214 | link, _, _, _ := startLinkWith(t, inst.url, &stubCoordinator{}, hello) |
| 215 | c := <-inst.conns |
| 216 | _, raw := read(t, c, wire.FrameHello) |
| 217 | if strings.Contains(string(raw), "fetched") || strings.Contains(string(raw), "unavailable") { |
| 218 | t.Fatal("initial hello leaked fields") |
| 219 | } |
| 220 | 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))}) |
| 221 | write(t, c, welcome) |
| 222 | read(t, c, wire.FrameSync) |
| 223 | if protocol == 19 { |
| 224 | link.HelloSoon() |
| 225 | } |
| 226 | _, raw = read(t, c, wire.FrameHello) |
| 227 | for _, field := range []string{"fetched", "unavailable"} { |
| 228 | if strings.Contains(string(raw), field) != (protocol == 20) { |
| 229 | t.Fatalf("%d: %s", protocol, raw) |
| 230 | } |
| 231 | } |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | func TestClaudeUsageSafeTransport(t *testing.T) { |
| 236 | target := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("redirect followed") })) |
| 237 | defer target.Close() |
| 238 | body := "" |
| 239 | src := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 240 | if body == "" { |
| 241 | http.Redirect(w, r, target.URL, http.StatusFound) |
| 242 | } else { |
| 243 | fmt.Fprint(w, body) |
| 244 | } |
| 245 | })) |
| 246 | defer src.Close() |
| 247 | p := &ProfileReader{Origin: src.URL, HTTP: connect.SafeClient(nil, func(a netip.Addr) bool { return a.IsLoopback() }, nil)} |
| 248 | if status, l := p.readUsage(context.Background(), []byte("fixture-private")); status != 302 || l != nil { |
| 249 | t.Fatal("redirect returned reading") |
| 250 | } |
| 251 | body = `{"five_hour":{"utilization":1},"padding":"` + strings.Repeat("x", maxProfileBytes) + `"}` |
| 252 | if status, l := p.readUsage(context.Background(), []byte("fixture-private")); status != 200 || l != nil { |
| 253 | t.Fatal("oversized response accepted") |
| 254 | } |
| 255 | // Without the test client a release refuses every other origin. |
| 256 | p.HTTP = nil |
| 257 | if status, l := p.readUsage(context.Background(), []byte("fixture-private")); status != 0 || l != nil { |
| 258 | t.Fatal("release accepted another origin") |
| 259 | } |
| 260 | } |
| 261 | |