fix(antigravity): distinguish expired access from reauthorization

This commit is contained in:
Ming-Sir-69 committed 2026-12-02 22:27:53 +08:00
1 parent 667902572f
commit 272b331868
8 files changed
+195 -21

No files matched your search

@@ -0,0 +1,120 @@
//go:build unit
package service
import (
"context"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
"github.com/stretchr/testify/require"
)
func TestAntigravityUsage_AuthenticationStatus(t *testing.T) {
t.Setenv(antigravityForwardBaseURLEnv, "")
now := time.Now()
expired := now.Add(-time.Minute).Unix()
fresh := now.Add(time.Hour).Format(time.RFC3339)
tests := []struct {
name string
expiresAt any
refreshToken string
accountError string
upstreamCode int
upstreamBody string
wantCode string
wantReauth bool
wantForbidden string
wantCalls int32
force bool
renew bool
}{
{name: "expired with refresh token", expiresAt: expired, refreshToken: "fake-refresh", wantCode: "access_token_expired", upstreamCode: 200, renew: true},
{name: "forced query skips known expired access token", expiresAt: expired, refreshToken: "fake-refresh", wantCode: "access_token_expired", force: true},
{name: "expired without refresh token", expiresAt: expired, wantCode: "access_token_expired", wantReauth: true},
{name: "known refresh rejection", expiresAt: fresh, refreshToken: "fake-refresh", accountError: "Token refresh failed (non-retryable): invalid_grant", wantCode: "unauthenticated", wantReauth: true},
{name: "known verification restriction", expiresAt: expired, refreshToken: "fake-refresh", accountError: "403 VALIDATION_REQUIRED", wantCode: "forbidden", wantForbidden: "validation"},
{name: "401 cannot establish refresh rejection", expiresAt: fresh, refreshToken: "fake-refresh", accountError: "Token refresh failed (non-retryable): invalid_client", upstreamCode: 401, upstreamBody: "UNAUTHENTICATED", wantCode: "unauthenticated", wantCalls: 1},
{name: "401 with unknown expiration", expiresAt: "legacy", refreshToken: "fake-refresh", upstreamCode: 401, upstreamBody: "invalid_grant", wantCode: "unauthenticated", wantCalls: 1},
{name: "verified ban", expiresAt: fresh, refreshToken: "fake-refresh", upstreamCode: 403, upstreamBody: "TOS_VIOLATION", wantCode: "forbidden", wantForbidden: "violation", wantCalls: 1},
{name: "rate limit", expiresAt: fresh, refreshToken: "fake-refresh", upstreamCode: 429, upstreamBody: "RESOURCE_EXHAUSTED", wantCode: "rate_limited", wantCalls: 1},
{name: "valid access token", expiresAt: fresh, refreshToken: "fake-refresh", upstreamCode: 200, wantCalls: 3},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
calls.Add(1)
if tc.upstreamCode == 200 {
body := `{}`
if req.URL.Path == "/v1internal:fetchAvailableModels" {
body = `{"models":{"gemini-3-flash":{"quotaInfo":{"remainingFraction":0.75}}}}`
}
_, _ = w.Write([]byte(body))
return
}
if tc.upstreamCode == 0 {
http.Error(w, "unexpected quota request", http.StatusUnauthorized)
return
}
http.Error(w, tc.upstreamBody, tc.upstreamCode)
}))
t.Cleanup(server.Close)
oldURLs, oldAvailability := antigravity.BaseURLs, antigravity.DefaultURLAvailability
t.Cleanup(func() {
antigravity.BaseURLs, antigravity.DefaultURLAvailability = oldURLs, oldAvailability
})
antigravity.BaseURLs = []string{server.URL, server.URL}
antigravity.DefaultURLAvailability = antigravity.NewURLAvailability(time.Minute)
account := Account{
ID: 7,
Platform: PlatformAntigravity,
Type: AccountTypeOAuth,
Status: StatusActive,
ErrorMessage: tc.accountError,
Credentials: map[string]any{
"access_token": "fake-access",
"refresh_token": tc.refreshToken,
"expires_at": tc.expiresAt,
},
}
if tc.accountError != "" {
account.Status = StatusError
}
repo := &usageErrorAccountRepo{stubOpenAIAccountRepo: stubOpenAIAccountRepo{accounts: []Account{account}}}
svc := &AccountUsageService{
accountRepo: repo,
cache: NewUsageCache(),
antigravityQuotaFetcher: NewAntigravityQuotaFetcher(nil, &config.Config{}),
}
usage, err := svc.GetUsage(context.Background(), account.ID, tc.force)
require.NoError(t, err)
require.Equal(t, tc.wantCode, usage.ErrorCode)
require.Equal(t, tc.wantReauth, usage.NeedsReauth)
require.Equal(t, tc.wantForbidden, usage.ForbiddenType)
require.Equal(t, tc.wantCalls, calls.Load())
require.Zero(t, repo.clearCalls)
if tc.renew {
// Another authorized path saved renewed credentials. The next quota
// read should recover without a manual cache bypass or reauthorization.
repo.accounts[0].Credentials["expires_at"] = fresh
repo.accounts[0].Credentials["access_token"] = "renewed-fake-access"
usage, err := svc.GetUsage(context.Background(), account.ID)
require.NoError(t, err)
require.Empty(t, usage.ErrorCode)
require.False(t, usage.NeedsReauth)
require.Contains(t, usage.AntigravityQuota, "gemini-3-flash")
require.Equal(t, int32(3), calls.Load())
}
})
}
}
@@ -277,9 +277,9 @@ type UsageInfo struct {
// 状态标记(从 ForbiddenType / HTTP 错误码推导)
NeedsVerify bool `json:"needs_verify,omitempty"` // 需要人工验证(forbidden_type=validation)
IsBanned bool `json:"is_banned,omitempty"` // 账号被封(forbidden_type=violation)
NeedsReauth bool `json:"needs_reauth,omitempty"` // token 失效需重新授权(401)
NeedsReauth bool `json:"needs_reauth,omitempty"` // 已确认需要重新授权
// 错误码(机器可读):forbidden / unauthenticated / rate_limited / network_error
// 错误码(机器可读):forbidden / unauthenticated / access_token_expired / rate_limited / network_error
ErrorCode string `json:"error_code,omitempty"`
// 获取 usage 时的错误信息(降级返回,而非 500)
@@ -428,13 +428,9 @@ func (s *AccountUsageService) getUsageForAccount(ctx context.Context, account *A
return usage, err
}
// Antigravity 平台:使用 AntigravityQuotaFetcher 获取额度
if account.Platform == PlatformAntigravity {
usage, err := s.getAntigravityUsage(ctx, account, forceProbe)
if err == nil {
s.tryClearRecoverableAccountError(ctx, account)
}
return usage, err
// Quota responses cannot establish that a refresh credential recovered.
return s.getAntigravityUsage(ctx, account, forceProbe)
}
if account.Platform == PlatformGrok {
@@ -1182,8 +1178,14 @@ func (s *AccountUsageService) cachedAntigravityUsage(accountID int64, force bool
// getAntigravityUsage 获取 Antigravity 账户额度;force 跳过缓存(仍经 singleflight 合并并发请求)。
func (s *AccountUsageService) getAntigravityUsage(ctx context.Context, account *Account, force bool) (*UsageInfo, error) {
now := time.Now()
if account.Type == AccountTypeOAuth {
if usage := antigravityQuotaAuthStatus(account, now); usage != nil {
enrichUsageWithAccountError(usage, account)
return usage, nil
}
}
if s.antigravityQuotaFetcher == nil || !s.antigravityQuotaFetcher.CanFetch(account) {
now := time.Now()
return &UsageInfo{UpdatedAt: &now}, nil
}
@@ -1422,6 +1424,34 @@ func antigravityCacheTTL(info *UsageInfo) time.Duration {
return apiCacheTTL
}
// antigravityQuotaAuthStatus uses local credential state so checking quota never
// sends a known-expired access token or starts a token refresh.
func antigravityQuotaAuthStatus(account *Account, now time.Time) *UsageInfo {
if account.Status == StatusError {
message := strings.ToLower(account.ErrorMessage)
if strings.HasPrefix(message, "token refresh failed (non-retryable):") &&
(strings.Contains(message, "invalid_grant") || strings.Contains(message, "invalid_refresh_token")) {
return &UsageInfo{
UpdatedAt: &now,
ErrorCode: errorCodeUnauthenticated,
Error: "OAuth refresh credential was rejected",
NeedsReauth: true,
}
}
}
expiresAt := account.GetCredentialAsTime("expires_at")
if expiresAt == nil || now.Before(*expiresAt) {
return nil
}
return &UsageInfo{
UpdatedAt: &now,
ErrorCode: errorCodeAccessTokenExpired,
Error: "OAuth access token expired",
NeedsReauth: strings.TrimSpace(account.GetCredential("refresh_token")) == "",
}
}
// buildAntigravityDegradedUsage 从 FetchQuota 错误构建降级 UsageInfo
func buildAntigravityDegradedUsage(err error) *UsageInfo {
now := time.Now()
@@ -1440,8 +1470,8 @@ func buildAntigravityDegradedUsage(err error) *UsageInfo {
case strings.Contains(errStr, "HTTP 401") ||
strings.Contains(errStr, "UNAUTHENTICATED") ||
strings.Contains(errStr, "invalid_grant"):
// This endpoint only checks the access token.
info.ErrorCode = errorCodeUnauthenticated
info.NeedsReauth = true
case strings.Contains(errStr, "HTTP 429"):
info.ErrorCode = errorCodeRateLimited
default:
@@ -1458,7 +1488,7 @@ func buildAntigravityDegradedUsage(err error) *UsageInfo {
//
// 场景 2(降级路径):被封号的账号 OAuth token 失效,FetchAvailableModels 返回 401,
//
// 降级逻辑设置了 needs_reauth,但账号实际是 403 封号/需验证,需覆盖为正确状态。
// 已知的封禁或验证状态优先于额度查询的认证错误。
func enrichUsageWithAccountError(info *UsageInfo, account *Account) {
if info == nil || account == nil || account.Status != StatusError {
return
@@ -21,10 +21,11 @@ const (
forbiddenTypeForbidden = "forbidden"
// 机器可读的错误码
errorCodeForbidden = "forbidden"
errorCodeUnauthenticated = "unauthenticated"
errorCodeRateLimited = "rate_limited"
errorCodeNetworkError = "network_error"
errorCodeForbidden = "forbidden"
errorCodeUnauthenticated = "unauthenticated"
errorCodeAccessTokenExpired = "access_token_expired"
errorCodeRateLimited = "rate_limited"
errorCodeNetworkError = "network_error"
)
// AntigravityQuotaFetcher 从 Antigravity API 获取额度
@@ -292,14 +292,14 @@
</div>
</div>
<!-- Needs reauth (401) -->
<!-- Confirmed reauthorization requirement -->
<div v-else-if="needsReauth" class="space-y-1">
<span class="inline-block rounded px-1.5 py-0.5 text-[10px] font-medium bg-orange-100 text-orange-700 dark:bg-orange-900/40 dark:text-orange-300">
{{ t('admin.accounts.needsReauth') }}
</span>
</div>
<!-- Degraded error (non-403, non-401) -->
<!-- Quota fetch status -->
<div v-else-if="usageInfo?.error" class="space-y-1">
<span class="inline-block rounded px-1.5 py-0.5 text-[10px] font-medium bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300">
{{ usageErrorLabel }}
@@ -1518,12 +1518,14 @@ const isForbidden = computed(() => !!usageInfo.value?.is_forbidden)
const forbiddenType = computed(() => usageInfo.value?.forbidden_type || 'forbidden')
const validationURL = computed(() => usageInfo.value?.validation_url || '')
// 需要重新授权(401)
// 已确认需要重新授权
const needsReauth = computed(() => !!usageInfo.value?.needs_reauth)
// 降级错误标签(rate_limited / network_error)
// 配额查询错误标签
const usageErrorLabel = computed(() => {
const code = usageInfo.value?.error_code
if (code === 'access_token_expired') return t('admin.accounts.accessTokenExpired')
if (code === 'unauthenticated') return t('admin.accounts.usageAuthenticationFailed')
if (code === 'rate_limited') return t('admin.accounts.rateLimited')
return t('admin.accounts.usageError')
})
@@ -128,6 +128,23 @@ describe('AccountUsageCell', () => {
wrapper.unmount()
})
it.each([
['access_token_expired', false, 'accessTokenExpired'],
['unauthenticated', false, 'usageAuthenticationFailed'],
['unauthenticated', true, 'needsReauth'],
])('labels Antigravity usage error %s (reauth %s)', async (errorCode, needsReauth, label) => {
getUsage.mockResolvedValue({ error_code: errorCode, error: 'quota unavailable', needs_reauth: needsReauth })
const wrapper = mount(AccountUsageCell, {
props: { account: makeAccount({ id: 6403 }) },
global: { stubs: { AccountQuotaInfo: true } }
})
await flushPromises()
expect(wrapper.text()).toContain(`admin.accounts.${label}`)
expect(wrapper.text().includes('admin.accounts.needsReauth')).toBe(needsReauth)
wrapper.unmount()
})
it('shows Antigravity local usage and separate account/user costs when the upstream query fails', async () => {
getUsage.mockRejectedValue(new Error('upstream quota unavailable'))
const wrapper = mount(AccountUsageCell, {
@@ -1870,6 +1870,8 @@ export default {
copyLink: 'Copy Link',
linkCopied: 'Link Copied',
needsReauth: 'Re-auth Required',
accessTokenExpired: 'Access Token Expired',
usageAuthenticationFailed: 'Quota Authentication Failed',
rateLimited: 'Rate Limited',
usageError: 'Fetch Error'
},
@@ -647,6 +647,8 @@ export default {
copyLink: '复制链接',
linkCopied: '链接已复制',
needsReauth: '需要重新授权',
accessTokenExpired: '访问令牌已过期',
usageAuthenticationFailed: '额度查询认证失败',
rateLimited: '限流中',
usageError: '获取失败',
testing: '测试中...',
+2 -2
View File
@@ -1561,9 +1561,9 @@ export interface AccountUsageInfo {
// 状态标记(后端自动推导)
needs_verify?: boolean // 需要人工验证(forbidden_type=validation)
is_banned?: boolean // 账号被封(forbidden_type=violation)
needs_reauth?: boolean // token 失效需重新授权(401)
needs_reauth?: boolean // 已确认需要重新授权
// 机器可读错误码:forbidden / unauthenticated / rate_limited / network_error
// 机器可读错误码:forbidden / unauthenticated / access_token_expired / rate_limited / network_error
error_code?: string
error?: string // usage 获取失败时的错误信息