From ebe0e82e63b3abb8df967b299722331fd61d6a93 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Wed, 18 Nov 2026 11:58:52 -0600 Subject: [PATCH 1/3] Identify the rejected Grok credential source Grok quota checks can use credentials from the Grok CLI, Pi, or Hermes. Naming the selected source prevents a rejection from directing the user to sign in again in the wrong application. Change-Id: If95ca676b8e39e468e5c713fde99ae5aa0ffeba6 --- internal/quotas/creds.go | 12 ++++++------ internal/quotas/creds_test.go | 2 +- internal/quotas/fetch_test.go | 27 +++++++++++++++++++++++++++ internal/quotas/grok.go | 19 ++++++++++++++----- 4 files changed, 48 insertions(+), 12 deletions(-) diff --git a/internal/quotas/creds.go b/internal/quotas/creds.go index e3f3f46..5d2b531 100644 --- a/internal/quotas/creds.go +++ b/internal/quotas/creds.go @@ -126,20 +126,20 @@ func (s Source) MiniMaxToken() (string, error) { } // XAIToken is a SuperGrok or X Premium sign-in, never an xAI API key. -func (s Source) XAIToken() (string, error) { +func (s Source) XAIToken() (string, string, error) { if token := s.grokCLIToken(); token != "" { - return token, nil + return token, "Grok CLI", nil } if token := s.piToken("xai", "oauth", "access"); token != "" { - return token, nil + return token, "Pi", nil } if token := s.providerToken("xai-oauth"); token != "" { - return token, nil + return token, "Hermes", nil } if token := s.poolToken("xai-oauth"); token != "" { - return token, nil + return token, "Hermes", nil } - return "", MissingError{Text: "Sign in to Grok with the Grok CLI, Pi, or Hermes to read its plan."} + return "", "", MissingError{Text: "Sign in to Grok with the Grok CLI, Pi, or Hermes to read its plan."} } func (s Source) authDocuments() []map[string]any { diff --git a/internal/quotas/creds_test.go b/internal/quotas/creds_test.go index 4553b32..f05843c 100644 --- a/internal/quotas/creds_test.go +++ b/internal/quotas/creds_test.go @@ -52,7 +52,7 @@ func TestXAITokenUsesClientSignInsInOrder(t *testing.T) { require.NoError(t, os.WriteFile(path, []byte(body), 0o600)) } source := Source{UserHome: func() string { return home }, Env: func(string) string { return "" }} - token, err := source.XAIToken() + token, _, err := source.XAIToken() if tc.want == "" { var missing MissingError require.ErrorAs(t, err, &missing) diff --git a/internal/quotas/fetch_test.go b/internal/quotas/fetch_test.go index fad37d7..ed38cf4 100644 --- a/internal/quotas/fetch_test.go +++ b/internal/quotas/fetch_test.go @@ -133,6 +133,33 @@ func TestZAIRefusesAKeyWithoutACodingPlan(t *testing.T) { assert.Equal(t, "This key has no GLM Coding Plan: subscribe at z.ai/subscribe.", said.Error()) } +func TestGrokNamesRejectedCredentialSource(t *testing.T) { + t.Parallel() + cases := []struct { + name string + path string + body string + }{ + {"Grok CLI", ".grok/auth.json", `{"https://auth.x.ai::client":{"auth_mode":"oidc","key":"token"}}`}, + {"Pi", ".pi/agent/auth.json", `{"xai":{"type":"oauth","access":"token"}}`}, + {"Hermes", ".hermes/auth.json", `{"providers":{"xai-oauth":{"tokens":{"access_token":"token"}}}}`}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + home := t.TempDir() + path := filepath.Join(home, tc.path) + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700)) + require.NoError(t, os.WriteFile(path, []byte(tc.body), 0o600)) + source := Source{UserHome: func() string { return home }, Env: func(string) string { return "" }} + client := stubClient(t, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusUnauthorized) }) + _, err := fetchGrok(t.Context(), source, client) + require.Error(t, err) + assert.Contains(t, err.Error(), "401") + assert.Contains(t, err.Error(), tc.name) + }) + } +} + func TestGrokNamesATeamAccount(t *testing.T) { t.Parallel() client := stubClient(t, func(w http.ResponseWriter, _ *http.Request) { diff --git a/internal/quotas/grok.go b/internal/quotas/grok.go index 9af30d4..fbd06e1 100644 --- a/internal/quotas/grok.go +++ b/internal/quotas/grok.go @@ -16,7 +16,7 @@ const ( ) func fetchGrok(ctx context.Context, source Source, client *http.Client) (Report, error) { - token, err := source.XAIToken() + token, credentialSource, err := source.XAIToken() if err != nil { return Report{}, err } @@ -26,10 +26,7 @@ func fetchGrok(ctx context.Context, source Source, client *http.Client) (Report, } decoded, err := getJSON(ctx, client, grokBilling, headers, readWait) if err != nil { - if status, ok := errors.AsType[StatusError](err); ok && teamAccount(status) { - return Report{}, SaidError{Text: "Grok keeps no personal quota for a team account."} - } - return Report{}, err + return Report{}, grokError(err, credentialSource) } body, ok := asObject(decoded) if !ok { @@ -62,6 +59,18 @@ func fetchGrok(ctx context.Context, source Source, client *http.Client) (Report, return Report{Name: grokPlanName(ctx, client, headers), Limits: limits, Notes: notes}, nil } +func grokError(err error, credentialSource string) error { + if status, ok := errors.AsType[StatusError](err); ok { + if teamAccount(status) { + return SaidError{Text: "Grok keeps no personal quota for a team account."} + } + if status.Status == http.StatusUnauthorized || forbidden(status.Status) { + return SaidError{Text: fmt.Sprintf("It refused the %s sign-in (%d): sign in again in %s.", credentialSource, status.Status, credentialSource)} + } + } + return err +} + func grokPlanName(ctx context.Context, client *http.Client, headers map[string]string) string { decoded, err := getJSON(ctx, client, grokSettings, headers, 5*time.Second) if err != nil { From fb45c970ce3233d3b980403d4587f93ccd181a82 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Wed, 18 Nov 2026 12:09:45 -0600 Subject: [PATCH 2/3] Refactor: Carry credential sources through quota lookups Keep the source alongside each selected credential so quota failures can point to the right place without changing lookup precedence. Change-Id: I5899d1e378e7bbf793f806ca426562e67143528d --- internal/quotas/anthropic.go | 2 +- internal/quotas/copilot.go | 2 +- internal/quotas/creds.go | 76 +++++++++++++++++------------------ internal/quotas/creds_test.go | 12 +++--- internal/quotas/deepseek.go | 2 +- internal/quotas/minimax.go | 2 +- internal/quotas/ollama.go | 2 +- internal/quotas/opencode.go | 2 +- internal/quotas/zai.go | 2 +- 9 files changed, 51 insertions(+), 51 deletions(-) diff --git a/internal/quotas/anthropic.go b/internal/quotas/anthropic.go index 23cb072..256289d 100644 --- a/internal/quotas/anthropic.go +++ b/internal/quotas/anthropic.go @@ -16,7 +16,7 @@ const ( ) func fetchAnthropic(ctx context.Context, source Source, client *http.Client) (Report, error) { - token, err := source.AnthropicPlanToken() + token, _, err := source.AnthropicPlanToken() if err != nil { return Report{}, err } diff --git a/internal/quotas/copilot.go b/internal/quotas/copilot.go index e9f648d..5d01880 100644 --- a/internal/quotas/copilot.go +++ b/internal/quotas/copilot.go @@ -14,7 +14,7 @@ const ( ) func fetchCopilot(ctx context.Context, source Source, client *http.Client) (Report, error) { - token, err := source.CopilotToken(ctx) + token, _, err := source.CopilotToken(ctx) if err != nil { return Report{}, err } diff --git a/internal/quotas/creds.go b/internal/quotas/creds.go index 5d2b531..89e2304 100644 --- a/internal/quotas/creds.go +++ b/internal/quotas/creds.go @@ -26,49 +26,49 @@ type Source struct { } // APIKey reads provider keys, including Pi keys for Ollama Cloud and OpenCode Go. -func (s Source) APIKey(provider string, vars []string, what string) (string, error) { +func (s Source) APIKey(provider string, vars []string, what string) (string, string, error) { switch provider { case "ollama-cloud", "opencode-go": for _, key := range vars { if value := strings.TrimSpace(s.env(key)); value != "" { - return value, nil + return value, key + " environment variable", nil } } if token := s.piToken(provider, "api_key", "key"); token != "" { - return token, nil + return token, "Pi", nil } } dotenv := s.dotEnv() for _, key := range vars { - if value := preferDotEnv(dotenv, key, s.env(key)); value != "" { - return value, nil + if value, location := preferDotEnv(dotenv, key, s.env(key)); value != "" { + return value, location, nil } } if token := s.poolToken(provider); token != "" { - return token, nil + return token, "Hermes", nil } - return "", MissingError{Text: fmt.Sprintf("Add a %s key in Hermes to read its plan.", what)} + return "", "", MissingError{Text: fmt.Sprintf("Add a %s key in Hermes to read its plan.", what)} } // AnthropicPlanToken is Claude's plan sign-in. A Console API key has no plan. -func (s Source) AnthropicPlanToken() (string, error) { +func (s Source) AnthropicPlanToken() (string, string, error) { dotenv := s.dotEnv() - if token := firstSecret(dotenv, s.env, "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"); token != "" { - return requirePlanToken(token) + if token, location := firstSecret(dotenv, s.env, "ANTHROPIC_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN"); token != "" { + return requirePlanToken(token, location) } - if token := preferDotEnv(dotenv, "ANTHROPIC_API_KEY", s.env("ANTHROPIC_API_KEY")); token != "" { - return requirePlanToken(token) + if token, location := preferDotEnv(dotenv, "ANTHROPIC_API_KEY", s.env("ANTHROPIC_API_KEY")); token != "" { + return requirePlanToken(token, location) } if token := s.poolToken("anthropic"); claudeOAuth(token) { - return token, nil + return token, "Hermes", nil } if token := s.claudeCodeToken(); claudeOAuth(token) { - return token, nil + return token, "Claude Code", nil } if token := s.hermesOAuthToken(); claudeOAuth(token) { - return token, nil + return token, "Hermes", nil } - return "", MissingError{Text: "Sign in to Claude in Hermes to read its plan."} + return "", "", MissingError{Text: "Sign in to Claude in Hermes to read its plan."} } // Command finds a service CLI from an override, PATH, or mise's shims. @@ -86,43 +86,43 @@ func (s Source) Command(overrideEnv, name, missing string) (string, error) { } // CopilotToken is the GitHub token behind Copilot's premium requests. -func (s Source) CopilotToken(ctx context.Context) (string, error) { +func (s Source) CopilotToken(ctx context.Context) (string, string, error) { for _, key := range []string{"GITHUB_TOKEN", "GH_TOKEN"} { if value := strings.TrimSpace(s.env(key)); value != "" { - return value, nil + return value, key + " environment variable", nil } } if token := s.piToken("github-copilot", "oauth", "access"); token != "" { - return token, nil + return token, "Pi", nil } gh, err := s.look("gh") if err != nil || blank(gh) { gh = s.shim("gh") } if gh == "" { - return "", MissingError{Text: "Sign in with the GitHub CLI (`gh auth login`) to read Copilot's plan."} + return "", "", MissingError{Text: "Sign in with the GitHub CLI (`gh auth login`) to read Copilot's plan."} } output, err := s.run(ctx, gh, "auth", "token") token := strings.TrimSpace(string(output)) if err != nil || blank(token) { - return "", MissingError{Text: "Sign in with the GitHub CLI (`gh auth login`) to read Copilot's plan."} + return "", "", MissingError{Text: "Sign in with the GitHub CLI (`gh auth login`) to read Copilot's plan."} } - return token, nil + return token, "GitHub CLI", nil } // MiniMaxToken is a Coding Plan key, or the OAuth access token for that plan. -func (s Source) MiniMaxToken() (string, error) { - token, err := s.APIKey("minimax", []string{"MINIMAX_API_KEY"}, "MiniMax") +func (s Source) MiniMaxToken() (string, string, error) { + token, location, err := s.APIKey("minimax", []string{"MINIMAX_API_KEY"}, "MiniMax") if err == nil { - return token, nil + return token, location, nil } if oauth := s.providerToken("minimax-oauth"); oauth != "" { - return oauth, nil + return oauth, "Hermes", nil } if oauth := s.poolToken("minimax-oauth"); oauth != "" { - return oauth, nil + return oauth, "Hermes", nil } - return "", err + return "", "", err } // XAIToken is a SuperGrok or X Premium sign-in, never an xAI API key. @@ -317,31 +317,31 @@ func (s Source) userHome() string { return home } -func preferDotEnv(dotenv map[string]string, key, environ string) string { +func preferDotEnv(dotenv map[string]string, key, environ string) (string, string) { raw := strings.TrimSpace(dotenv[key]) if strings.HasPrefix(raw, "op://") { raw = "" } if raw != "" { - return raw + return raw, "Hermes .env (" + key + ")" } - return strings.TrimSpace(environ) + return strings.TrimSpace(environ), key + " environment variable" } -func firstSecret(dotenv map[string]string, env func(string) string, keys ...string) string { +func firstSecret(dotenv map[string]string, env func(string) string, keys ...string) (string, string) { for _, key := range keys { - if value := preferDotEnv(dotenv, key, env(key)); value != "" { - return value + if value, location := preferDotEnv(dotenv, key, env(key)); value != "" { + return value, location } } - return "" + return "", "" } -func requirePlanToken(token string) (string, error) { +func requirePlanToken(token, location string) (string, string, error) { if claudeOAuth(token) { - return token, nil + return token, location, nil } - return "", MissingError{Text: "Claude's plan is only reported for a Claude sign-in, not a Console API key."} + return "", "", MissingError{Text: "Claude's plan is only reported for a Claude sign-in, not a Console API key."} } func claudeOAuth(token string) bool { diff --git a/internal/quotas/creds_test.go b/internal/quotas/creds_test.go index f05843c..181f9a0 100644 --- a/internal/quotas/creds_test.go +++ b/internal/quotas/creds_test.go @@ -102,7 +102,7 @@ func TestPiAPIKeysPrecedeHermesButNotEnvironment(t *testing.T) { } return nil, os.ErrNotExist } - key, err := source.APIKey(provider.id, []string{provider.envKey}, provider.id) + key, _, err := source.APIKey(provider.id, []string{provider.envKey}, provider.id) require.NoError(t, err) assert.Equal(t, tc.want, key) }) @@ -139,7 +139,7 @@ func TestCopilotUsesPiBeforeGitHubCLI(t *testing.T) { assert.Equal(t, "gh-token", tc.want, "GitHub CLI should only run as a fallback") return []byte("gh-token\n"), nil } - token, err := source.CopilotToken(t.Context()) + token, _, err := source.CopilotToken(t.Context()) require.NoError(t, err) assert.Equal(t, tc.want, token) }) @@ -152,7 +152,7 @@ func TestDotEnvBeatsAStaleEnvironmentKey(t *testing.T) { t.Setenv("DEEPSEEK_API_KEY", "from-env") require.NoError(t, os.WriteFile(filepath.Join(home, ".env"), []byte("DEEPSEEK_API_KEY=from-dotenv\n"), 0o600)) - key, err := (Source{}).APIKey("deepseek", []string{"DEEPSEEK_API_KEY"}, "DeepSeek") + key, _, err := (Source{}).APIKey("deepseek", []string{"DEEPSEEK_API_KEY"}, "DeepSeek") require.NoError(t, err) assert.Equal(t, "from-dotenv", key) } @@ -165,7 +165,7 @@ func TestPoolSuppliesAKeyTheEnvironmentDoesNot(t *testing.T) { t.Setenv("Z_AI_API_KEY", "") require.NoError(t, os.WriteFile(filepath.Join(home, "auth.json"), []byte(`{"credential_pool":{"zai":[{"access_token":"pool-zai"}]}}`), 0o600)) - key, err := (Source{}).APIKey("zai", []string{"GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"}, "Z.ai") + key, _, err := (Source{}).APIKey("zai", []string{"GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"}, "Z.ai") require.NoError(t, err) assert.Equal(t, "pool-zai", key) } @@ -176,7 +176,7 @@ func TestConsoleAPIKeyIsNotAClaudePlan(t *testing.T) { t.Setenv("CLAUDE_CODE_OAUTH_TOKEN", "") t.Setenv("ANTHROPIC_API_KEY", "sk-ant-api-test") - _, err := (Source{}).AnthropicPlanToken() + _, _, err := (Source{}).AnthropicPlanToken() var missing MissingError require.ErrorAs(t, err, &missing) assert.Contains(t, missing.Error(), "Console API key") @@ -192,7 +192,7 @@ func TestClaudeCodeFileSuppliesAPlanToken(t *testing.T) { require.NoError(t, os.MkdirAll(filepath.Join(home, ".claude"), 0o700)) require.NoError(t, os.WriteFile(filepath.Join(home, ".claude", ".credentials.json"), []byte(`{"claudeAiOauth":{"accessToken":"sk-ant-oat-file"}}`), 0o600)) - token, err := (Source{UserHome: func() string { return home }}).AnthropicPlanToken() + token, _, err := (Source{UserHome: func() string { return home }}).AnthropicPlanToken() require.NoError(t, err) assert.Equal(t, "sk-ant-oat-file", token) } diff --git a/internal/quotas/deepseek.go b/internal/quotas/deepseek.go index 72a0411..6da0b02 100644 --- a/internal/quotas/deepseek.go +++ b/internal/quotas/deepseek.go @@ -12,7 +12,7 @@ const ( ) func fetchDeepSeek(ctx context.Context, source Source, client *http.Client) (Report, error) { - key, err := source.APIKey(deepSeekID, []string{"DEEPSEEK_API_KEY"}, "DeepSeek") + key, _, err := source.APIKey(deepSeekID, []string{"DEEPSEEK_API_KEY"}, "DeepSeek") if err != nil { return Report{}, err } diff --git a/internal/quotas/minimax.go b/internal/quotas/minimax.go index 9c98057..5e5e513 100644 --- a/internal/quotas/minimax.go +++ b/internal/quotas/minimax.go @@ -13,7 +13,7 @@ const ( ) func fetchMiniMax(ctx context.Context, source Source, client *http.Client) (Report, error) { - token, err := source.MiniMaxToken() + token, _, err := source.MiniMaxToken() if err != nil { return Report{}, err } diff --git a/internal/quotas/ollama.go b/internal/quotas/ollama.go index 3ddfc83..3f9a266 100644 --- a/internal/quotas/ollama.go +++ b/internal/quotas/ollama.go @@ -13,7 +13,7 @@ const ( ) func fetchOllama(ctx context.Context, source Source, client *http.Client) (Report, error) { - key, err := source.APIKey("ollama-cloud", []string{"OLLAMA_API_KEY"}, "Ollama Cloud") + key, _, err := source.APIKey("ollama-cloud", []string{"OLLAMA_API_KEY"}, "Ollama Cloud") if err != nil { return Report{}, err } diff --git a/internal/quotas/opencode.go b/internal/quotas/opencode.go index 5e850bf..ac8ddbf 100644 --- a/internal/quotas/opencode.go +++ b/internal/quotas/opencode.go @@ -14,7 +14,7 @@ const ( ) func fetchOpenCode(ctx context.Context, source Source, client *http.Client) (Report, error) { - key, err := source.APIKey(openCodeID, []string{"OPENCODE_GO_API_KEY"}, "OpenCode Go") + key, _, err := source.APIKey(openCodeID, []string{"OPENCODE_GO_API_KEY"}, "OpenCode Go") if err != nil { return Report{}, err } diff --git a/internal/quotas/zai.go b/internal/quotas/zai.go index c52e79d..f1c25b7 100644 --- a/internal/quotas/zai.go +++ b/internal/quotas/zai.go @@ -16,7 +16,7 @@ const ( ) func fetchZAI(ctx context.Context, source Source, client *http.Client) (Report, error) { - key, err := source.APIKey(zaiID, []string{"GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"}, "Z.ai") + key, _, err := source.APIKey(zaiID, []string{"GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"}, "Z.ai") if err != nil { return Report{}, err } From 7373d40b16e72a182dddf756c189f0d8da066bd6 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Wed, 18 Nov 2026 12:13:32 -0600 Subject: [PATCH 3/3] Name the credential source in quota rejection errors Point users to the credential they need to check instead of assuming it came from Hermes. Apply the same guidance to MiniMax's body-level auth rejection, without printing the credential itself. Change-Id: Ic3da607cc03d44fbd318509682cf94d6d196a991 --- internal/quotas/anthropic.go | 4 ++-- internal/quotas/copilot.go | 4 ++-- internal/quotas/deepseek.go | 4 ++-- internal/quotas/fetch_test.go | 37 +++++++++++++++++++++++++++++++++++ internal/quotas/grok.go | 17 ++++++---------- internal/quotas/http.go | 21 +++++++++++++------- internal/quotas/minimax.go | 10 +++++----- internal/quotas/ollama.go | 4 ++-- internal/quotas/opencode.go | 4 ++-- internal/quotas/zai.go | 6 +++--- 10 files changed, 75 insertions(+), 36 deletions(-) diff --git a/internal/quotas/anthropic.go b/internal/quotas/anthropic.go index 256289d..1faab72 100644 --- a/internal/quotas/anthropic.go +++ b/internal/quotas/anthropic.go @@ -16,14 +16,14 @@ const ( ) func fetchAnthropic(ctx context.Context, source Source, client *http.Client) (Report, error) { - token, _, err := source.AnthropicPlanToken() + token, credentialSource, err := source.AnthropicPlanToken() if err != nil { return Report{}, err } decoded, err := getJSON(ctx, client, anthropicURL, map[string]string{ "Authorization": "Bearer " + token, "anthropic-beta": "oauth-2025-04-20", - }, readWait) + }, readWait, credentialSource) if err != nil { return Report{}, err } diff --git a/internal/quotas/copilot.go b/internal/quotas/copilot.go index 5d01880..79c1f87 100644 --- a/internal/quotas/copilot.go +++ b/internal/quotas/copilot.go @@ -14,14 +14,14 @@ const ( ) func fetchCopilot(ctx context.Context, source Source, client *http.Client) (Report, error) { - token, _, err := source.CopilotToken(ctx) + token, credentialSource, err := source.CopilotToken(ctx) if err != nil { return Report{}, err } decoded, err := getJSON(ctx, client, copilotURL, map[string]string{ "Authorization": "token " + token, "X-GitHub-Api-Version": "2025-04-01", - }, readWait) + }, readWait, credentialSource) if err != nil { return Report{}, err } diff --git a/internal/quotas/deepseek.go b/internal/quotas/deepseek.go index 6da0b02..5dd3a8d 100644 --- a/internal/quotas/deepseek.go +++ b/internal/quotas/deepseek.go @@ -12,11 +12,11 @@ const ( ) func fetchDeepSeek(ctx context.Context, source Source, client *http.Client) (Report, error) { - key, _, err := source.APIKey(deepSeekID, []string{"DEEPSEEK_API_KEY"}, "DeepSeek") + key, credentialSource, err := source.APIKey(deepSeekID, []string{"DEEPSEEK_API_KEY"}, "DeepSeek") if err != nil { return Report{}, err } - decoded, err := getJSON(ctx, client, deepSeekURL, bearer(key), readWait) + decoded, err := getJSON(ctx, client, deepSeekURL, bearer(key), readWait, credentialSource) if err != nil { return Report{}, err } diff --git a/internal/quotas/fetch_test.go b/internal/quotas/fetch_test.go index ed38cf4..997d27b 100644 --- a/internal/quotas/fetch_test.go +++ b/internal/quotas/fetch_test.go @@ -133,6 +133,43 @@ func TestZAIRefusesAKeyWithoutACodingPlan(t *testing.T) { assert.Equal(t, "This key has no GLM Coding Plan: subscribe at z.ai/subscribe.", said.Error()) } +func TestQuotaRefusalsNameCredentialSource(t *testing.T) { + t.Parallel() + tests := []struct { + name string + fetch func(context.Context, Source, *http.Client) (Report, error) + source Source + status int + body string + want string + }{ + {"DeepSeek environment", fetchDeepSeek, envSource(map[string]string{"DEEPSEEK_API_KEY": "test-key"}), http.StatusUnauthorized, "", "DEEPSEEK_API_KEY environment variable"}, + {"MiniMax body refusal", fetchMiniMax, envSource(map[string]string{"MINIMAX_API_KEY": "test-key"}), http.StatusOK, `{"base_resp":{"status_code":1004}}`, "MINIMAX_API_KEY environment variable"}, + {"Copilot Pi sign-in", fetchCopilot, Source{ + UserHome: func() string { return "/test-home" }, + Env: func(string) string { return "" }, + ReadFile: func(path string) ([]byte, error) { + if path == "/test-home/.pi/agent/auth.json" { + return []byte(`{"github-copilot":{"type":"oauth","access":"test-key"}}`), nil + } + return nil, os.ErrNotExist + }, + }, http.StatusForbidden, "", "Pi"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + client := stubClient(t, func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.body)) + }) + _, err := tc.fetch(t.Context(), tc.source, client) + require.Error(t, err) + assert.Contains(t, err.Error(), tc.want) + assert.NotContains(t, err.Error(), "test-key") + }) + } +} + func TestGrokNamesRejectedCredentialSource(t *testing.T) { t.Parallel() cases := []struct { diff --git a/internal/quotas/grok.go b/internal/quotas/grok.go index fbd06e1..b50b08f 100644 --- a/internal/quotas/grok.go +++ b/internal/quotas/grok.go @@ -24,9 +24,9 @@ func fetchGrok(ctx context.Context, source Source, client *http.Client) (Report, "Authorization": "Bearer " + token, "x-xai-token-auth": "xai-grok-cli", // #nosec G101 -- client name the Grok CLI sends, not a secret } - decoded, err := getJSON(ctx, client, grokBilling, headers, readWait) + decoded, err := getJSON(ctx, client, grokBilling, headers, readWait, credentialSource) if err != nil { - return Report{}, grokError(err, credentialSource) + return Report{}, grokError(err) } body, ok := asObject(decoded) if !ok { @@ -59,20 +59,15 @@ func fetchGrok(ctx context.Context, source Source, client *http.Client) (Report, return Report{Name: grokPlanName(ctx, client, headers), Limits: limits, Notes: notes}, nil } -func grokError(err error, credentialSource string) error { - if status, ok := errors.AsType[StatusError](err); ok { - if teamAccount(status) { - return SaidError{Text: "Grok keeps no personal quota for a team account."} - } - if status.Status == http.StatusUnauthorized || forbidden(status.Status) { - return SaidError{Text: fmt.Sprintf("It refused the %s sign-in (%d): sign in again in %s.", credentialSource, status.Status, credentialSource)} - } +func grokError(err error) error { + if status, ok := errors.AsType[StatusError](err); ok && teamAccount(status) { + return SaidError{Text: "Grok keeps no personal quota for a team account."} } return err } func grokPlanName(ctx context.Context, client *http.Client, headers map[string]string) string { - decoded, err := getJSON(ctx, client, grokSettings, headers, 5*time.Second) + decoded, err := getJSON(ctx, client, grokSettings, headers, 5*time.Second, "") if err != nil { return grokName } diff --git a/internal/quotas/http.go b/internal/quotas/http.go index 571a7d3..1d21dfa 100644 --- a/internal/quotas/http.go +++ b/internal/quotas/http.go @@ -28,7 +28,7 @@ func NewHTTPClient() *http.Client { } } -func getJSON(ctx context.Context, client *http.Client, endpoint string, headers map[string]string, wait time.Duration) (any, error) { +func getJSON(ctx context.Context, client *http.Client, endpoint string, headers map[string]string, wait time.Duration, credentialSource string) (any, error) { if client == nil { client = NewHTTPClient() } @@ -55,7 +55,7 @@ func getJSON(ctx context.Context, client *http.Client, endpoint string, headers defer func() { _ = response.Body.Close() }() if response.StatusCode >= 300 { - return nil, StatusError{Status: response.StatusCode, Text: answered(response.StatusCode)} + return nil, StatusError{Status: response.StatusCode, Text: answered(response.StatusCode, credentialSource)} } body, err := io.ReadAll(io.LimitReader(response.Body, readLimit+1)) if err != nil { @@ -85,14 +85,21 @@ func requestFailure(ctx context.Context, err error, wait time.Duration) error { return SaidError{Text: "It could not be reached: try again later."} } -func answered(status int) string { - if status == http.StatusUnauthorized || forbidden(status) { - return fmt.Sprintf("It refused the sign-in (%d): sign in again in Hermes.", status) +func answered(status int, credentialSource string) string { + switch status { + case http.StatusUnauthorized, http.StatusForbidden: + return credentialRejected(fmt.Sprint(status), credentialSource) + default: + return fmt.Sprintf("It answered %d.", status) } - return fmt.Sprintf("It answered %d.", status) } -func forbidden(status int) bool { return status == http.StatusForbidden } +func credentialRejected(code, credentialSource string) string { + if credentialSource == "" { + return fmt.Sprintf("It refused the credential (%s): check or replace it.", code) + } + return fmt.Sprintf("It refused the credential from %s (%s): check or replace that credential.", credentialSource, code) +} func readFailure(err error) string { if errors.Is(err, context.DeadlineExceeded) { diff --git a/internal/quotas/minimax.go b/internal/quotas/minimax.go index 5e5e513..7974ab8 100644 --- a/internal/quotas/minimax.go +++ b/internal/quotas/minimax.go @@ -13,11 +13,11 @@ const ( ) func fetchMiniMax(ctx context.Context, source Source, client *http.Client) (Report, error) { - token, _, err := source.MiniMaxToken() + token, credentialSource, err := source.MiniMaxToken() if err != nil { return Report{}, err } - decoded, err := getJSON(ctx, client, miniMaxURL, bearer(token), readWait) + decoded, err := getJSON(ctx, client, miniMaxURL, bearer(token), readWait, credentialSource) if err != nil { return Report{}, err } @@ -25,21 +25,21 @@ func fetchMiniMax(ctx context.Context, source Source, client *http.Client) (Repo if !ok { return Report{}, SaidError{Text: "It answered with something that is not a report."} } - if err := miniMaxRefusal(body); err != nil { + if err := miniMaxRefusal(body, credentialSource); err != nil { return Report{}, err } limits, notes := miniMaxCollect(body) return Report{Name: miniMaxName, Limits: limits, Notes: notes}, nil } -func miniMaxRefusal(body map[string]any) error { +func miniMaxRefusal(body map[string]any, credentialSource string) error { base, _ := asObject(body["base_resp"]) code, codeOK := asNumber(base["status_code"]) if codeOK && !refusedCode(code) { return nil } if code == 1004 { - return SaidError{Text: "It refused the key: sign in again in Hermes."} + return SaidError{Text: credentialRejected("code 1004", credentialSource)} } shown := "unknown" if codeOK { diff --git a/internal/quotas/ollama.go b/internal/quotas/ollama.go index 3f9a266..616e38e 100644 --- a/internal/quotas/ollama.go +++ b/internal/quotas/ollama.go @@ -13,11 +13,11 @@ const ( ) func fetchOllama(ctx context.Context, source Source, client *http.Client) (Report, error) { - key, _, err := source.APIKey("ollama-cloud", []string{"OLLAMA_API_KEY"}, "Ollama Cloud") + key, credentialSource, err := source.APIKey("ollama-cloud", []string{"OLLAMA_API_KEY"}, "Ollama Cloud") if err != nil { return Report{}, err } - decoded, err := getJSON(ctx, client, ollamaURL, bearer(key), readWait) + decoded, err := getJSON(ctx, client, ollamaURL, bearer(key), readWait, credentialSource) if err != nil { return Report{}, err } diff --git a/internal/quotas/opencode.go b/internal/quotas/opencode.go index ac8ddbf..433cb1d 100644 --- a/internal/quotas/opencode.go +++ b/internal/quotas/opencode.go @@ -14,11 +14,11 @@ const ( ) func fetchOpenCode(ctx context.Context, source Source, client *http.Client) (Report, error) { - key, _, err := source.APIKey(openCodeID, []string{"OPENCODE_GO_API_KEY"}, "OpenCode Go") + key, credentialSource, err := source.APIKey(openCodeID, []string{"OPENCODE_GO_API_KEY"}, "OpenCode Go") if err != nil { return Report{}, err } - decoded, err := getJSON(ctx, client, openCodeURL, bearer(key), readWait) + decoded, err := getJSON(ctx, client, openCodeURL, bearer(key), readWait, credentialSource) if err != nil { return Report{}, err } diff --git a/internal/quotas/zai.go b/internal/quotas/zai.go index f1c25b7..8408615 100644 --- a/internal/quotas/zai.go +++ b/internal/quotas/zai.go @@ -16,12 +16,12 @@ const ( ) func fetchZAI(ctx context.Context, source Source, client *http.Client) (Report, error) { - key, _, err := source.APIKey(zaiID, []string{"GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"}, "Z.ai") + key, credentialSource, err := source.APIKey(zaiID, []string{"GLM_API_KEY", "ZAI_API_KEY", "Z_AI_API_KEY"}, "Z.ai") if err != nil { return Report{}, err } headers := bearer(key) - decoded, err := getJSON(ctx, client, zaiURL, headers, readWait) + decoded, err := getJSON(ctx, client, zaiURL, headers, readWait, credentialSource) if err != nil { return Report{}, err } @@ -169,7 +169,7 @@ func zaiWindow(unit, count any) string { } func zaiPlanName(ctx context.Context, client *http.Client, headers map[string]string) string { - decoded, err := getJSON(ctx, client, zaiPlan, headers, 5*time.Second) + decoded, err := getJSON(ctx, client, zaiPlan, headers, 5*time.Second, "") if err != nil { return "" }