diff --git a/README.md b/README.md index e9b4b0b3..19c212a8 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,17 @@ The frontend runs at `http://127.0.0.1:5173` by default and proxies API requests After the administrator has been created, change its password and remove `bootstrapAdmin` from the configuration. Keep `credentialEncryptionKey` permanently: changing it makes existing encrypted credentials unreadable. +### Migrating accounts from the Python version + +The **Grok Web SSO tokens** used by the Python version can be migrated, but its database or original pool JSON cannot be imported directly. Export **TXT (one token per line)** from the Python v2 admin page, or extract the raw SSO tokens from the old storage. Then open `/accounts` in the Go version, select **Grok Web**, and use **Connect account → Quick import SSO** or **Import account files**. + +The Go Web importer accepts: + +- TXT: one raw token per line; `sso=` and `sso=; ...` are also accepted +- JSON: `{"provider":"grok_web","accounts":[{"sso_token":"...","name":"optional","tier":"auto|basic|super|heavy"}]}` + +Python pool assignments, tags, status, quota, usage, cooldown, proxy, and Cloudflare metadata are not migrated. TXT imports use tier `auto` and resync upstream state. The Python version did not contain Grok Build OAuth credentials, so its pools cannot be imported under the **Grok Build** tab. Each import is limited to 1,000 files, 30 MiB total, and 10,000 accounts; wait for identity, quota, and model-capability synchronization after importing. + ## Models and routing Public model names are unqualified by default. Internally, `Build/`, `Web/`, and `Console/` are used as stable route IDs. Qualified names remain available for explicitly selecting a source, but they are not shown as ordinary model names. diff --git a/README.zh-CN.md b/README.zh-CN.md index 171c8565..88d19d37 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -212,6 +212,17 @@ pnpm dev 管理员创建成功后,建议修改密码并从配置中删除 `bootstrapAdmin`。`credentialEncryptionKey` 必须长期保留,更换后已有凭据将无法解密。 +### 从 Python 版迁移账号 + +可以迁移 Python 版使用的 **Grok Web SSO Token**,但不能直接导入旧数据库或原始号池 JSON。请先从 Python v2 管理页导出 **TXT(每行一个 Token)**,或自行从旧存储中提取裸 SSO Token;然后在 Go 版 `/accounts` 的 **Grok Web** 页签选择“连接账号”→“快速导入 SSO”或“导入账号文件”。 + +Go 版 Web 导入支持以下格式: + +- TXT:每行一个裸 Token,也接受 `sso=` 或 `sso=; ...` +- JSON:`{"provider":"grok_web","accounts":[{"sso_token":"...","name":"可选","tier":"auto|basic|super|heavy"}]}` + +Python 版的 pool、标签、状态、额度、使用统计、冷却、代理/Cloudflare 配置等元数据不会迁移;TXT 导入时等级按 `auto` 重新同步。Python 版不含 Grok Build OAuth 凭据,因此不能将其号池导入 Go 版的 **Grok Build** 页签。单次最多 1,000 个文件、总计 30 MiB / 10,000 个账号;导入后请等待身份、额度和模型能力同步完成。 + ## 模型与路由 公开模型名默认不带来源前缀。内部使用 `Build/`、`Web/`、`Console/` 作为稳定路由 ID;带前缀名称仍可用于显式指定来源,但不会作为普通模型名展示。 diff --git a/backend/internal/application/gateway/failure.go b/backend/internal/application/gateway/failure.go index ea00004a..e19a32a3 100644 --- a/backend/internal/application/gateway/failure.go +++ b/backend/internal/application/gateway/failure.go @@ -104,6 +104,9 @@ func newHTTPUpstreamFailure(status int, body []byte, accountID uint64, accountNa failure.PublicMessage = "上游账号额度不足" failure.AccountScoped = true failure.QuotaExhausted = true + // spending-limit is account-scoped, but its paid/free recovery kind depends on + // the selected account's billing snapshot and must be decided by the selector. + failure.FreeQuotaExhausted = isFreeQuotaExhaustion(metadataText) case http.StatusForbidden: failure.Code = "upstream_forbidden" failure.PublicMessage = "上游拒绝了该请求" diff --git a/backend/internal/application/gateway/failure_test.go b/backend/internal/application/gateway/failure_test.go index 959d3f40..1ab68c2e 100644 --- a/backend/internal/application/gateway/failure_test.go +++ b/backend/internal/application/gateway/failure_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" "github.com/chenyme/grok2api/backend/internal/infra/provider" ) @@ -49,21 +50,45 @@ func TestHTTPUpstreamFailureClassifiesBuildForbiddenBodies(t *testing.T) { } } +func TestHTTPUpstreamFailureLeavesPaymentRecoveryKindToBilling(t *testing.T) { + failure := newHTTPUpstreamFailure(http.StatusPaymentRequired, []byte(`{ + "code":"personal-team-blocked:spending-limit", + "error":"You have run out of credits" + }`), 42, "build") + if !failure.AccountScoped || !failure.QuotaExhausted || failure.FreeQuotaExhausted || failure.UpstreamCode != "personal-team-blocked:spending-limit" { + t.Fatalf("failure = %#v", failure) + } +} + func TestRetryableResponseHonorsUpstreamRetryVeto(t *testing.T) { response := &provider.Response{ StatusCode: http.StatusInternalServerError, Header: http.Header{"X-Should-Retry": {"false"}}, Body: io.NopCloser(strings.NewReader(`{"error":"invalid request history"}`)), } - if isRetryableResponse(response) { + if isRetryableResponse(response, accountdomain.ProviderBuild) { t.Fatal("x-should-retry:false 必须禁止换账号重试") } response.Header.Set("X-Should-Retry", "true") - if !isRetryableResponse(response) { + if !isRetryableResponse(response, accountdomain.ProviderBuild) { t.Fatal("x-should-retry:true 不应覆盖现有状态码重试策略") } response.Header.Set("X-Should-Retry", "unknown") - if !isRetryableResponse(response) { + if !isRetryableResponse(response, accountdomain.ProviderBuild) { t.Fatal("未知 x-should-retry 值应按未提供处理") } } + +func TestPaymentRequiredAlwaysRetriesDespiteUpstreamVeto(t *testing.T) { + response := &provider.Response{ + StatusCode: http.StatusPaymentRequired, + Header: http.Header{"X-Should-Retry": {"false"}}, + Body: io.NopCloser(strings.NewReader(`{"code":"personal-team-blocked:spending-limit","error":"You have run out of credits"}`)), + } + if !isRetryableResponse(response, accountdomain.ProviderBuild) { + t.Fatal("402 spending-limit must force account rotation even when X-Should-Retry is false") + } + if isRetryableResponse(response, accountdomain.ProviderWeb) { + t.Fatal("non-Build 402 must continue honoring X-Should-Retry:false") + } +} diff --git a/backend/internal/application/gateway/selector.go b/backend/internal/application/gateway/selector.go index c973d0de..bd8b70e3 100644 --- a/backend/internal/application/gateway/selector.go +++ b/backend/internal/application/gateway/selector.go @@ -33,6 +33,19 @@ const maxConcurrencySnapshots = 256 const modelAccessDeniedCooldown = 5 * time.Minute +const defaultFreeQuotaRecoveryPause = 24 * time.Hour + +// paymentRequiredRecoveryPause is only the final fallback for a 402 account +// without an upstream reset, Retry-After, or parseable billing period. +const paymentRequiredRecoveryPause = 20 * time.Hour + +type quotaRecoveryHints struct { + Billing *account.Billing + QuotaMode string + RetryAfter time.Duration + Fallback time.Duration +} + type candidateSnapshot struct { values []account.RoutingCandidate expiresAt time.Time @@ -493,9 +506,16 @@ func (s *Selector) markSuccess(ctx context.Context, credential account.Credentia } } -func (s *Selector) MarkFreeQuotaExhausted(ctx context.Context, credential account.Credential, used, limit int64) { +func (s *Selector) MarkFreeQuotaExhausted(ctx context.Context, credential account.Credential, used, limit int64, hints quotaRecoveryHints) { now := time.Now().UTC() - nextProbeAt := now.Add(24 * time.Hour) + if hints.Fallback <= 0 { + hints.Fallback = defaultFreeQuotaRecoveryPause + } + nextProbeAt := s.resolveQuotaRecoveryAt(ctx, credential.ID, now, hints) + s.markFreeQuotaExhaustedAt(ctx, credential, used, limit, now, nextProbeAt) +} + +func (s *Selector) markFreeQuotaExhaustedAt(ctx context.Context, credential account.Credential, used, limit int64, now, nextProbeAt time.Time) { _ = s.accounts.SaveQuotaRecovery(ctx, account.QuotaRecovery{ AccountID: credential.ID, Kind: account.QuotaRecoveryKindFree, Status: account.QuotaRecoveryStatusExhausted, ConfirmedUsed: used, ConfirmedLimit: limit, ExhaustedAt: &now, @@ -508,11 +528,11 @@ func (s *Selector) MarkFreeQuotaExhausted(ctx context.Context, credential accoun func (s *Selector) MarkModelQuotaExhausted(ctx context.Context, credential account.Credential, upstreamModel string, retryAfter time.Duration) { upstreamModel = strings.TrimSpace(upstreamModel) if upstreamModel == "" { - s.MarkFreeQuotaExhausted(ctx, credential, 0, 0) + s.MarkFreeQuotaExhausted(ctx, credential, 0, 0, quotaRecoveryHints{}) return } if retryAfter <= 0 { - retryAfter = 24 * time.Hour + retryAfter = defaultFreeQuotaRecoveryPause } until := time.Now().UTC().Add(retryAfter) _ = s.accounts.UpsertModelQuotaBlock(ctx, account.ModelQuotaBlock{ @@ -540,23 +560,51 @@ func (s *Selector) MarkModelAccessDenied(ctx context.Context, credential account s.invalidateCandidates(credential.Provider) } -// MarkPaidQuotaExhausted 使用已知真实账期将付费账号移出号池,到期后才允许 Billing 探测。 -func (s *Selector) MarkPaidQuotaExhausted(ctx context.Context, credential account.Credential, billing *account.Billing) bool { - if billing == nil || !billing.IsPaid() { - return false - } - periodEnd, ok := billing.PeriodEnd() - if !ok { - return false - } +// MarkPaymentQuotaExhausted 将 402/spending-limit 账号移出号池。付费账号按真实账期 +// 进行 Billing 探测;Free/Unknown 依次采用上游 ResetAt、Retry-After、账期时间和 20h fallback。 +func (s *Selector) MarkPaymentQuotaExhausted(ctx context.Context, credential account.Credential, hints quotaRecoveryHints) { now := time.Now().UTC() - _ = s.accounts.SaveQuotaRecovery(ctx, account.QuotaRecovery{ - AccountID: credential.ID, Kind: account.QuotaRecoveryKindPaid, Status: account.QuotaRecoveryStatusExhausted, - ExhaustedAt: &now, NextProbeAt: &periodEnd, LastConfirmedAt: &now, UpdatedAt: now, - }) - _ = s.sticky.DeleteByAccount(ctx, credential.ID) - s.invalidateCandidates(credential.Provider) - return true + if hints.Billing != nil && hints.Billing.IsPaid() { + if periodEnd, ok := hints.Billing.PeriodEnd(); ok && periodEnd.After(now) { + _ = s.accounts.SaveQuotaRecovery(ctx, account.QuotaRecovery{ + AccountID: credential.ID, Kind: account.QuotaRecoveryKindPaid, Status: account.QuotaRecoveryStatusExhausted, + ExhaustedAt: &now, NextProbeAt: &periodEnd, LastConfirmedAt: &now, UpdatedAt: now, + }) + _ = s.sticky.DeleteByAccount(ctx, credential.ID) + s.invalidateCandidates(credential.Provider) + return + } + } + hints.Fallback = paymentRequiredRecoveryPause + s.MarkFreeQuotaExhausted(ctx, credential, 0, 0, hints) +} + +func (s *Selector) resolveQuotaRecoveryAt(ctx context.Context, accountID uint64, now time.Time, hints quotaRecoveryHints) time.Time { + if mode := strings.TrimSpace(hints.QuotaMode); mode != "" { + if windows, err := s.accounts.GetQuotaWindows(ctx, []uint64{accountID}); err == nil { + var resetAt time.Time + for _, window := range windows[accountID] { + if window.Mode != mode || window.ResetAt == nil || !window.ResetAt.After(now) { + continue + } + if resetAt.IsZero() || window.ResetAt.Before(resetAt) { + resetAt = window.ResetAt.UTC() + } + } + if !resetAt.IsZero() { + return resetAt + } + } + } + if hints.RetryAfter > 0 { + return now.Add(hints.RetryAfter) + } + if hints.Billing != nil { + if periodEnd, ok := hints.Billing.PeriodEnd(); ok && periodEnd.After(now) { + return periodEnd + } + } + return now.Add(hints.Fallback) } // MarkQuotaStateChanged 在 Billing 探测改变持久化额度状态后立即失效候选快照。 diff --git a/backend/internal/application/gateway/selector_test.go b/backend/internal/application/gateway/selector_test.go index 25f33a24..c68710c9 100644 --- a/backend/internal/application/gateway/selector_test.go +++ b/backend/internal/application/gateway/selector_test.go @@ -145,6 +145,84 @@ func TestSelectorSkipsQuotaProbeBeforeDue(t *testing.T) { } } +func TestSelectorQuotaRecoveryUsesBestKnownReset(t *testing.T) { + ctx := context.Background() + database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "quota-recovery.db")) + if err != nil { + t.Fatal(err) + } + defer database.Close() + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + accounts := relational.NewAccountRepository(database) + value, _, err := accounts.UpsertByIdentity(ctx, account.Credential{ + Provider: account.ProviderBuild, Name: "build", SourceKey: "build", EncryptedAccessToken: "encrypted", + Enabled: true, AuthStatus: account.AuthStatusActive, MaxConcurrent: 1, + }) + if err != nil { + t.Fatal(err) + } + now := time.Now().UTC() + resetAt := now.Add(4 * time.Hour).Truncate(time.Second) + if err := accounts.SaveQuotaWindows(ctx, value.ID, account.WebTierAuto, now, []account.QuotaWindow{{ + AccountID: value.ID, Mode: "fast", Remaining: 0, Total: 20, ResetAt: &resetAt, Source: account.QuotaSourceUpstream, + }}); err != nil { + t.Fatal(err) + } + selector := NewSelector(accounts, memory.NewConcurrencyLimiter(), memory.NewStickyStore(), nil, time.Hour, time.Second, time.Minute) + + paidPeriodEnd := now.Add(7 * time.Hour).Truncate(time.Second) + selector.MarkPaymentQuotaExhausted(ctx, value, quotaRecoveryHints{Billing: &account.Billing{ + AccountID: value.ID, PlanCode: "super", MonthlyLimit: 100, BillingPeriodEnd: paidPeriodEnd.Format(time.RFC3339), + }, QuotaMode: "fast", RetryAfter: time.Hour}) + recovery := requireQuotaRecovery(t, ctx, accounts, value.ID) + if recovery.Kind != account.QuotaRecoveryKindPaid || recovery.NextProbeAt == nil || !recovery.NextProbeAt.Equal(paidPeriodEnd) { + t.Fatalf("paid recovery = %#v", recovery) + } + + selector.MarkPaymentQuotaExhausted(ctx, value, quotaRecoveryHints{QuotaMode: "fast", RetryAfter: time.Hour}) + recovery = requireQuotaRecovery(t, ctx, accounts, value.ID) + if recovery.Kind != account.QuotaRecoveryKindFree || recovery.NextProbeAt == nil || !recovery.NextProbeAt.Equal(resetAt) { + t.Fatalf("upstream reset recovery = %#v", recovery) + } + + retryStarted := time.Now().UTC() + selector.MarkPaymentQuotaExhausted(ctx, value, quotaRecoveryHints{QuotaMode: "missing", RetryAfter: 90 * time.Minute}) + recovery = requireQuotaRecovery(t, ctx, accounts, value.ID) + assertRecoveryDelay(t, recovery, retryStarted, 90*time.Minute) + + fallbackStarted := time.Now().UTC() + selector.MarkPaymentQuotaExhausted(ctx, value, quotaRecoveryHints{QuotaMode: "missing"}) + recovery = requireQuotaRecovery(t, ctx, accounts, value.ID) + assertRecoveryDelay(t, recovery, fallbackStarted, paymentRequiredRecoveryPause) + + freeStarted := time.Now().UTC() + selector.MarkFreeQuotaExhausted(ctx, value, 100, 100, quotaRecoveryHints{QuotaMode: "missing"}) + recovery = requireQuotaRecovery(t, ctx, accounts, value.ID) + assertRecoveryDelay(t, recovery, freeStarted, defaultFreeQuotaRecoveryPause) +} + +func requireQuotaRecovery(t *testing.T, ctx context.Context, accounts repository.AccountRepository, accountID uint64) account.QuotaRecovery { + t.Helper() + recovery, err := accounts.GetQuotaRecovery(ctx, accountID) + if err != nil { + t.Fatal(err) + } + return recovery +} + +func assertRecoveryDelay(t *testing.T, recovery account.QuotaRecovery, started time.Time, delay time.Duration) { + t.Helper() + if recovery.NextProbeAt == nil { + t.Fatalf("recovery has no next probe: %#v", recovery) + } + want := started.Add(delay) + if recovery.NextProbeAt.Before(want.Add(-time.Second)) || recovery.NextProbeAt.After(want.Add(2*time.Second)) { + t.Fatalf("next probe = %s, want around %s", recovery.NextProbeAt, want) + } +} + func TestSelectorUsesPaidWeeklyPoolAsWebQuotaGate(t *testing.T) { ctx := context.Background() database, err := relational.OpenSQLite(ctx, filepath.Join(t.TempDir(), "weekly-web.db")) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 5cf7bb4d..13fe388f 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -655,7 +655,7 @@ attemptLoop: } egressForbidden := s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden finalEgressForbidden := egressForbidden && (attempt > 0 || attempt+1 >= attempts) - if isRetryableResponse(response) && !finalEgressForbidden { + if isRetryableResponse(response, route.Provider) && !finalEgressForbidden { retryAfter := parseRetryAfter(response.Header.Get("Retry-After"), time.Now().UTC()) body, _ := readRetryableBody(response.Body) if egressForbidden { @@ -715,16 +715,23 @@ attemptLoop: s.selector.MarkQuotaStateChanged(credential.Provider) failureHandled = reconcileErr == nil && exhausted } else if used, limit, exhausted := parseFreeQuotaExhaustion(body); exhausted { - s.selector.MarkFreeQuotaExhausted(ctx, credential, used, limit) + s.selector.MarkFreeQuotaExhausted(ctx, credential, used, limit, quotaRecoveryHints{ + Billing: lease.Billing, QuotaMode: lease.QuotaMode, RetryAfter: retryAfter, + }) failureHandled = true } else if lastFailure.ModelQuotaExhausted { s.selector.MarkModelQuotaExhausted(ctx, credential, route.UpstreamModel, retryAfter) failureHandled = true } else if lastFailure.FreeQuotaExhausted { - s.selector.MarkFreeQuotaExhausted(ctx, credential, 0, 0) + s.selector.MarkFreeQuotaExhausted(ctx, credential, 0, 0, quotaRecoveryHints{ + Billing: lease.Billing, QuotaMode: lease.QuotaMode, RetryAfter: retryAfter, + }) failureHandled = true } else if lastFailure.QuotaExhausted { - failureHandled = s.selector.MarkPaidQuotaExhausted(ctx, credential, lease.Billing) + s.selector.MarkPaymentQuotaExhausted(ctx, credential, quotaRecoveryHints{ + Billing: lease.Billing, QuotaMode: lease.QuotaMode, RetryAfter: retryAfter, + }) + failureHandled = true } if s.providers.SupportsCredentialRefresh(credential.Provider) && lastFailure.PermanentAccountDenial { if credential.Provider == accountdomain.ProviderBuild { @@ -799,8 +806,9 @@ attemptLoop: record.ContextOutputTokens = usage.ContextOutputTokens record.DurationMS = time.Since(startedAt).Milliseconds() record.ErrorCode = errorCode - if response.StatusCode < 200 || response.StatusCode >= 300 || errorCode != "" { - record.Attempts = failureAttempts.snapshot() + attempts := failureAttempts.snapshot() + if response.StatusCode < 200 || response.StatusCode >= 300 || errorCode != "" || len(attempts) > 0 { + record.Attempts = attempts } record.CreatedAt = now applyAuditEgress(&record, egressTrace, route.Provider) @@ -1142,13 +1150,24 @@ func isRetryable(status int) bool { return status == 402 || status == 403 || status == 429 || status >= 500 } -func isRetryableResponse(response *provider.Response) bool { +func isRetryableResponse(response *provider.Response, upstreamProvider accountdomain.Provider) bool { if response == nil || !isRetryable(response.StatusCode) { return false } + // Account-scoped payment failures must always rotate accounts. + // Upstream X-Should-Retry:false is only honored for non-account errors (e.g. 5xx history). + if forcesAccountFailover(response.StatusCode, upstreamProvider) { + return true + } return !strings.EqualFold(strings.TrimSpace(response.Header.Get("X-Should-Retry")), "false") } +// forcesAccountFailover scopes the Build billing-wall override to the Provider +// whose 402 contract is known. Other Providers continue honoring X-Should-Retry. +func forcesAccountFailover(status int, upstreamProvider accountdomain.Provider) bool { + return upstreamProvider == accountdomain.ProviderBuild && status == http.StatusPaymentRequired +} + func parseRetryAfter(value string, now time.Time) time.Duration { value = strings.TrimSpace(value) if seconds, err := strconv.Atoi(value); err == nil && seconds > 0 { diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index c9d4bc2a..5db024db 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -115,7 +115,11 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { t.Fatal(err) } - adapter := &failoverAdapter{firstID: first.ID} + adapter := &failoverAdapter{ + firstID: first.ID, failureStatus: http.StatusPaymentRequired, + failureBody: `{"code":"personal-team-blocked:spending-limit","error":"You have run out of credits"}`, + failureHeader: http.Header{"X-Should-Retry": {"false"}}, + } registry := provider.NewRegistry(adapter) cipher := testCipher(t) sticky := memory.NewStickyStore() @@ -159,11 +163,11 @@ func TestGatewayFailsOverBeforeReturningBody(t *testing.T) { t.Fatalf("observed account = %#v, err = %v", observedAccount, err) } logs, total, err := auditRepo.List(ctx, 0, 10) - if err != nil || total != 1 || logs[0].AccountID == nil || *logs[0].AccountID != second.ID || logs[0].ClientKeyName != "test-key" || logs[0].ModelPublicID != "grok-test" || logs[0].ModelUpstreamModel != "Build/grok-test" || logs[0].AccountName != "second" || logs[0].CachedInputTokens != 80 || logs[0].AttemptCount != 0 { + if err != nil || total != 1 || logs[0].AccountID == nil || *logs[0].AccountID != second.ID || logs[0].ClientKeyName != "test-key" || logs[0].ModelPublicID != "grok-test" || logs[0].ModelUpstreamModel != "Build/grok-test" || logs[0].AccountName != "second" || logs[0].CachedInputTokens != 80 || logs[0].StatusCode != http.StatusOK || logs[0].AttemptCount != 1 { t.Fatalf("audit = %#v, %d, %v", logs, total, err) } detail, err := auditRepo.Get(ctx, logs[0].ID) - if err != nil || len(detail.Attempts) != 0 { + if err != nil || len(detail.Attempts) != 1 || detail.Attempts[0].UpstreamStatusCode == nil || *detail.Attempts[0].UpstreamStatusCode != http.StatusPaymentRequired || !strings.Contains(string(detail.Attempts[0].ResponseBody), "personal-team-blocked:spending-limit") { t.Fatalf("audit detail = %#v, err = %v", detail, err) } ownership, err := responseRepo.Get(ctx, "resp-test", clientKey.ID, time.Now().UTC()) @@ -1387,6 +1391,9 @@ func runQuotaRefreshWorkers(t *testing.T, service *accountapp.Service) { type failoverAdapter struct { mu sync.Mutex firstID uint64 + failureStatus int + failureBody string + failureHeader http.Header attempts []uint64 lastMethod string lastPath string @@ -1753,12 +1760,21 @@ func (a *failoverAdapter) ForwardResponse(_ context.Context, request provider.Re resourceStatus := a.resourceStatus a.mu.Unlock() status, body := http.StatusOK, "ok" + header := make(http.Header) if request.Method != http.MethodPost && resourceStatus != 0 { status, body = resourceStatus, "missing" } else if request.Credential.ID == a.firstID { - status, body = http.StatusTooManyRequests, "limited" + status = a.failureStatus + if status == 0 { + status = http.StatusTooManyRequests + } + body = a.failureBody + if body == "" { + body = "limited" + } + header = a.failureHeader.Clone() } - return &provider.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil + return &provider.Response{StatusCode: status, Header: header, Body: io.NopCloser(strings.NewReader(body))}, nil } func (a *failoverAdapter) setResourceStatus(status int) { diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index d154bed2..52a031e3 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1483,8 +1483,12 @@ func writeGatewayError(c *gin.Context, err error) { status, code = http.StatusBadRequest, "invalid_request" message = err.Error() case errors.As(err, &upstreamFailure): - if isUpstreamCredentialStatus(upstreamFailure.HTTPStatus) { + if isSanitizedUpstreamAvailabilityFailure(upstreamFailure) { + // Gateway mid-tier behavior: never expose upstream upgrade/billing prompts to clients. code = upstreamFailure.ClientCredentialErrorCode() + if upstreamFailure.QuotaExhausted || upstreamFailure.FreeQuotaExhausted || upstreamFailure.HTTPStatus == http.StatusPaymentRequired { + code = "upstream_unavailable" + } status, message = http.StatusServiceUnavailable, credentialErrorMessage(code) } else { status, code, message = upstreamFailure.HTTPStatus, upstreamFailure.Code, upstreamFailure.PublicMessage @@ -1518,8 +1522,11 @@ func writeGatewayAnthropicError(c *gin.Context, err error) { status, errorType = http.StatusBadRequest, "invalid_request_error" message = err.Error() case errors.As(err, &upstreamFailure): - if isUpstreamCredentialStatus(upstreamFailure.HTTPStatus) { + if isSanitizedUpstreamAvailabilityFailure(upstreamFailure) { clientCode = upstreamFailure.ClientCredentialErrorCode() + if upstreamFailure.QuotaExhausted || upstreamFailure.FreeQuotaExhausted || upstreamFailure.HTTPStatus == http.StatusPaymentRequired { + clientCode = "upstream_unavailable" + } status, errorType, message = http.StatusServiceUnavailable, "overloaded_error", credentialErrorMessage(clientCode) } else { status, message = upstreamFailure.HTTPStatus, upstreamFailure.PublicMessage @@ -1545,7 +1552,12 @@ func writeGatewayAnthropicError(c *gin.Context, err error) { } func isUpstreamCredentialStatus(status int) bool { - return status == http.StatusUnauthorized || status == http.StatusForbidden + // Include 402 so official "add credits / upgrade SuperGrok" bodies never reach clients (Grok CLI, etc.). + return status == http.StatusUnauthorized || status == http.StatusForbidden || status == http.StatusPaymentRequired +} + +func isSanitizedUpstreamAvailabilityFailure(failure *gateway.UpstreamFailure) bool { + return failure != nil && (isUpstreamCredentialStatus(failure.HTTPStatus) || failure.QuotaExhausted || failure.FreeQuotaExhausted) } func selectionErrorResponse(c *gin.Context, failure *gateway.SelectionUnavailableError) (int, string, string) { diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 6c9772d2..b9fd1190 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -179,6 +179,19 @@ func TestGatewayErrorHidesUpstreamCredentialStatus(t *testing.T) { t.Fatalf("Anthropic status=%d body=%s", anthropicRecorder.Code, anthropicRecorder.Body.String()) } + quotaRouter := gin.New() + quotaRouter.GET("/", func(c *gin.Context) { + writeGatewayAnthropicError(c, &gateway.UpstreamFailure{ + HTTPStatus: http.StatusTooManyRequests, Code: "upstream_rate_limited", PublicMessage: "official upgrade prompt", + QuotaExhausted: true, + }) + }) + quotaRecorder := httptest.NewRecorder() + quotaRouter.ServeHTTP(quotaRecorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if quotaRecorder.Code != http.StatusServiceUnavailable || !strings.Contains(quotaRecorder.Body.String(), `"type":"overloaded_error"`) || strings.Contains(quotaRecorder.Body.String(), "upgrade") { + t.Fatalf("Anthropic quota status=%d body=%s", quotaRecorder.Code, quotaRecorder.Body.String()) + } + credentialRouter := gin.New() credentialRouter.GET("/", func(c *gin.Context) { writeGatewayAnthropicError(c, &gateway.UpstreamFailure{