mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-11-29 21:33:01 +08:00
fix(antigravity): skip model capability probes for unauthenticated credentials
- Gate Antigravity capability probing, refresh scheduling, queue admission, and post-slot execution on credential authentication eligibility instead of disabled status alone. - Suppress repeated 401 probes for unknown-expiry access tokens under terminally rejected refresh grants using a route-independent credential and token key, and notify auth change watchers on terminal refresh failures. - Add race-safe regression tests covering unauthenticated probe skipping, valid-token preservation during temporary quota errors, slot-wait expiry re-checks, terminal refresh probe cancellation, and credential recovery. Closes: #7817
This commit is contained in:
@@ -29,7 +29,7 @@ type antigravityHintPersistRequest struct {
|
||||
// one worker per account. Repeated updates replace a single queued successor,
|
||||
// rather than accumulating singleflight followers while an upstream is stalled.
|
||||
func (s *Service) queueAntigravityModelRefresh(ctx context.Context, auth *coreauth.Auth, provider string) {
|
||||
if s == nil || auth == nil || auth.ID == "" || isAntigravityAuthDisabled(auth) || s.antigravityHomeEnabled() {
|
||||
if s == nil || auth == nil || auth.ID == "" || shouldSkipAntigravityModelProbe(auth, antigravityNowFunc()) || s.antigravityHomeEnabled() {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
@@ -216,7 +216,7 @@ func (s *Service) antigravityAccountProbeCurrent(probe *antigravityAccountProbe)
|
||||
}
|
||||
}
|
||||
token, _ := current.Metadata["access_token"].(string)
|
||||
return !current.Disabled && current.Status != coreauth.StatusDisabled &&
|
||||
return !shouldSkipAntigravityModelProbe(current, antigravityNowFunc()) &&
|
||||
antigravityAuthModelSettingsEqual(current, probe.auth) &&
|
||||
s.antigravityCapabilityKey(current) == probe.routeKey && strings.TrimSpace(token) == probe.token
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
|
||||
cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/sdk/config"
|
||||
)
|
||||
|
||||
@@ -91,3 +92,90 @@ func TestAntigravityDeletedAccountCannotStartQueuedProbe(t *testing.T) {
|
||||
t.Fatal("removed account started a late queued probe")
|
||||
}
|
||||
}
|
||||
|
||||
type failingAntigravityRefreshExecutor struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *failingAntigravityRefreshExecutor) Identifier() string { return "antigravity" }
|
||||
|
||||
func (e *failingAntigravityRefreshExecutor) Refresh(context.Context, *coreauth.Auth) (*coreauth.Auth, error) {
|
||||
return nil, e.err
|
||||
}
|
||||
|
||||
func (e *failingAntigravityRefreshExecutor) Execute(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
|
||||
return cliproxyexecutor.Response{}, nil
|
||||
}
|
||||
|
||||
func (e *failingAntigravityRefreshExecutor) ExecuteStream(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (e *failingAntigravityRefreshExecutor) CountTokens(context.Context, *coreauth.Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) {
|
||||
return cliproxyexecutor.Response{}, nil
|
||||
}
|
||||
|
||||
func (e *failingAntigravityRefreshExecutor) HttpRequest(context.Context, *coreauth.Auth, *http.Request) (*http.Response, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestAntigravityTerminalRefreshFailureCancelsAndBlocksProbe(t *testing.T) {
|
||||
resetAntigravityCapabilityCache()
|
||||
t.Cleanup(resetAntigravityCapabilityCache)
|
||||
|
||||
// Keep the probe clock before the access token expiry so the probe connects,
|
||||
// while ForceRefreshAuth sees an expired access token at wall-clock time.Now().
|
||||
wallNow := time.Now().UTC()
|
||||
antigravityNowFunc = func() time.Time { return wallNow.Add(-2 * time.Hour) }
|
||||
t.Cleanup(func() { antigravityNowFunc = time.Now })
|
||||
|
||||
started, cancelled := make(chan struct{}), make(chan struct{})
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.(http.Flusher).Flush()
|
||||
close(started)
|
||||
<-r.Context().Done()
|
||||
close(cancelled)
|
||||
}))
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
manager.RegisterExecutor(&failingAntigravityRefreshExecutor{
|
||||
err: &coreauth.Error{
|
||||
Code: "token_revoked",
|
||||
Message: "token_revoked",
|
||||
HTTPStatus: http.StatusUnauthorized,
|
||||
},
|
||||
})
|
||||
svc := &Service{cfg: &config.Config{}, coreManager: manager}
|
||||
t.Cleanup(func() { cancel(); svc.WaitAntigravityProbes(); server.Close() })
|
||||
|
||||
auth := antigravityTestAuth("terminal-refresh-cancel", server.URL)
|
||||
auth.Metadata["refresh_token"] = "dead-rt"
|
||||
auth.Metadata["expired"] = wallNow.Add(-time.Hour).Format(time.RFC3339)
|
||||
registered, errRegister := manager.Register(ctx, auth)
|
||||
if errRegister != nil {
|
||||
t.Fatal(errRegister)
|
||||
}
|
||||
t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(registered.ID) })
|
||||
|
||||
svc.registerModelsForAuth(ctx, registered)
|
||||
<-started
|
||||
|
||||
if _, errRefresh := manager.ForceRefreshAuth(ctx, registered.ID); errRefresh == nil {
|
||||
t.Fatal("expected terminal refresh failure, got nil")
|
||||
}
|
||||
select {
|
||||
case <-cancelled:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("connected probe was not canceled after terminal refresh failure")
|
||||
}
|
||||
svc.WaitAntigravityProbes()
|
||||
|
||||
// Late queued probe using the old snapshot must also be rejected at admission.
|
||||
key := svc.antigravityCapabilityKey(registered)
|
||||
probeCtx, finish, active := svc.beginAntigravityAccountProbe(ctx, registered, key, "flight", "token-terminal-refresh-cancel")
|
||||
defer finish()
|
||||
if active || probeCtx.Err() == nil {
|
||||
t.Fatal("terminally unauthenticated account started a late queued probe")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,14 @@ type antigravityFailureState struct {
|
||||
failures uint8
|
||||
lastFailure time.Time
|
||||
nextRetry time.Time
|
||||
terminal bool
|
||||
authID string
|
||||
}
|
||||
|
||||
type antigravityTerminalFailureRef struct {
|
||||
key string
|
||||
authID string
|
||||
lastFailure time.Time
|
||||
}
|
||||
|
||||
func nextAntigravityFailure(previous antigravityFailureState, now time.Time, randomInt64N func(int64) int64) antigravityFailureState {
|
||||
@@ -102,6 +110,104 @@ func isAntigravityAuthDisabled(auth *coreauth.Auth) bool {
|
||||
return auth != nil && (auth.Disabled || auth.Status == coreauth.StatusDisabled)
|
||||
}
|
||||
|
||||
func isAntigravityRefreshTerminallyRejected(auth *coreauth.Auth) bool {
|
||||
if auth == nil {
|
||||
return false
|
||||
}
|
||||
refreshToken := ""
|
||||
if auth.Metadata != nil {
|
||||
refreshToken, _ = auth.Metadata["refresh_token"].(string)
|
||||
refreshToken = strings.TrimSpace(refreshToken)
|
||||
if refreshToken == "" {
|
||||
refreshToken, _ = auth.Metadata["refreshToken"].(string)
|
||||
refreshToken = strings.TrimSpace(refreshToken)
|
||||
}
|
||||
}
|
||||
rejected := strings.TrimSpace(auth.RejectedRefreshToken)
|
||||
if rejected != "" {
|
||||
return refreshToken == "" || refreshToken == rejected
|
||||
}
|
||||
return auth.RequiresSignIn
|
||||
}
|
||||
|
||||
// antigravityTerminalAuthFailureKey scopes confirmed terminal 401 suppression to
|
||||
// the credential identity, registration epoch, and access_token only, independent
|
||||
// of route attributes such as User-Agent or proxy URL.
|
||||
func antigravityTerminalAuthFailureKey(auth *coreauth.Auth, accessToken string) string {
|
||||
if auth == nil {
|
||||
return ""
|
||||
}
|
||||
accessToken = strings.TrimSpace(accessToken)
|
||||
if accessToken == "" {
|
||||
return ""
|
||||
}
|
||||
tokenHash := fmt.Sprintf("%x", sha256.Sum256([]byte(accessToken)))
|
||||
identity := auth.ID
|
||||
if identity == "" {
|
||||
identity = tokenHash
|
||||
}
|
||||
return fmt.Sprintf("terminal:%q/%d/%s", identity, auth.RegistrationEpoch, tokenHash)
|
||||
}
|
||||
|
||||
func isAntigravityTokenTerminallySuppressed(auth *coreauth.Auth) bool {
|
||||
if !isAntigravityRefreshTerminallyRejected(auth) || auth.Metadata == nil {
|
||||
return false
|
||||
}
|
||||
token, _ := auth.Metadata["access_token"].(string)
|
||||
terminalKey := antigravityTerminalAuthFailureKey(auth, token)
|
||||
if terminalKey == "" {
|
||||
return false
|
||||
}
|
||||
antigravityCapabilityMu.RLock()
|
||||
suppressed := antigravityAuthFailureCache[terminalKey].terminal
|
||||
antigravityCapabilityMu.RUnlock()
|
||||
return suppressed
|
||||
}
|
||||
|
||||
func shouldSkipAntigravityModelProbe(auth *coreauth.Auth, now time.Time) bool {
|
||||
if auth == nil || isAntigravityAuthDisabled(auth) {
|
||||
return true
|
||||
}
|
||||
if coreauth.HasUnauthorizedAuthFailure(auth) {
|
||||
return true
|
||||
}
|
||||
if now.IsZero() {
|
||||
now = antigravityNowFunc()
|
||||
}
|
||||
if !auth.HasValidAccessToken(now) {
|
||||
return true
|
||||
}
|
||||
return isAntigravityTokenTerminallySuppressed(auth)
|
||||
}
|
||||
|
||||
func (s *Service) pruneStaleAntigravityTerminalFailures(candidates []antigravityTerminalFailureRef) {
|
||||
if s == nil || s.coreManager == nil || len(candidates) == 0 {
|
||||
return
|
||||
}
|
||||
var stale []antigravityTerminalFailureRef
|
||||
for _, cand := range candidates {
|
||||
currentAuth, exists := s.coreManager.GetByID(cand.authID)
|
||||
if !exists || currentAuth == nil || isAntigravityAuthDisabled(currentAuth) || !isAntigravityRefreshTerminallyRejected(currentAuth) {
|
||||
stale = append(stale, cand)
|
||||
continue
|
||||
}
|
||||
currentToken, _ := currentAuth.Metadata["access_token"].(string)
|
||||
if antigravityTerminalAuthFailureKey(currentAuth, currentToken) != cand.key {
|
||||
stale = append(stale, cand)
|
||||
}
|
||||
}
|
||||
if len(stale) == 0 {
|
||||
return
|
||||
}
|
||||
antigravityCapabilityMu.Lock()
|
||||
for _, cand := range stale {
|
||||
if entry, ok := antigravityAuthFailureCache[cand.key]; ok && entry.terminal && entry.lastFailure.Equal(cand.lastFailure) {
|
||||
delete(antigravityAuthFailureCache, cand.key)
|
||||
}
|
||||
}
|
||||
antigravityCapabilityMu.Unlock()
|
||||
}
|
||||
|
||||
func antigravityTokenFailureKey(cacheKey, accessToken string) string {
|
||||
return cacheKey + fmt.Sprintf("/%x", sha256.Sum256([]byte(accessToken)))
|
||||
}
|
||||
@@ -335,7 +441,7 @@ func (s *Service) fetchAntigravityModelCapabilityHintsForAuth(ctx context.Contex
|
||||
// Return the key captured with the HTTP User-Agent so publication cannot label a
|
||||
// result with a version resolved before or after the actual probe snapshot.
|
||||
func (s *Service) fetchAntigravityModelCapabilityHints(ctx context.Context, auth *coreauth.Auth) (string, antigravityModelCapabilityHints) {
|
||||
if auth == nil || auth.Metadata == nil || isAntigravityAuthDisabled(auth) || s.antigravityHomeEnabled() {
|
||||
if auth == nil || auth.Metadata == nil || shouldSkipAntigravityModelProbe(auth, antigravityNowFunc()) || s.antigravityHomeEnabled() {
|
||||
return "", antigravityModelCapabilityHints{}
|
||||
}
|
||||
if ctx == nil {
|
||||
@@ -405,12 +511,45 @@ func (s *Service) fetchAntigravityModelCapabilityHints(ctx context.Context, auth
|
||||
return hints, nil
|
||||
}
|
||||
defer func() { <-antigravityProbeSlots }()
|
||||
// Re-check current credential eligibility after waiting for a probe slot,
|
||||
// since token expiry passes without emitting an auth-change notification.
|
||||
probeAuth := auth
|
||||
if s.coreManager != nil && auth.ID != "" {
|
||||
currentAuth, exists := s.coreManager.GetByID(auth.ID)
|
||||
if !exists || currentAuth == nil || currentAuth.RegistrationEpoch != auth.RegistrationEpoch {
|
||||
return s.cachedAntigravityHintsForKey(auth, baseURLs[0], routeFingerprint, cacheKey), nil
|
||||
}
|
||||
currentToken, _ := currentAuth.Metadata["access_token"].(string)
|
||||
if strings.TrimSpace(currentToken) != accessToken {
|
||||
return s.cachedAntigravityHintsForKey(auth, baseURLs[0], routeFingerprint, cacheKey), nil
|
||||
}
|
||||
probeAuth = currentAuth
|
||||
}
|
||||
if ctx.Err() != nil || shouldSkipAntigravityModelProbe(probeAuth, antigravityNowFunc()) {
|
||||
return s.cachedAntigravityHintsForKey(auth, baseURLs[0], routeFingerprint, cacheKey), nil
|
||||
}
|
||||
hints, status := s.probeAntigravityModelCapabilityHints(ctx, auth, baseURLs, proxyURL, accessToken, userAgent)
|
||||
terminalFailureKey := antigravityTerminalAuthFailureKey(probeAuth, accessToken)
|
||||
terminalAuthError := false
|
||||
terminalAuthID := probeAuth.ID
|
||||
if status == antigravityProbeStatusAuthError {
|
||||
latestAuth := probeAuth
|
||||
if s.coreManager != nil && auth.ID != "" {
|
||||
if currentAuth, exists := s.coreManager.GetByID(auth.ID); exists && currentAuth != nil && currentAuth.RegistrationEpoch == auth.RegistrationEpoch {
|
||||
latestAuth = currentAuth
|
||||
}
|
||||
}
|
||||
terminalAuthError = isAntigravityRefreshTerminallyRejected(latestAuth)
|
||||
terminalAuthID = latestAuth.ID
|
||||
terminalFailureKey = antigravityTerminalAuthFailureKey(latestAuth, accessToken)
|
||||
}
|
||||
var staleTerminalCandidates []antigravityTerminalFailureRef
|
||||
antigravityCapabilityMu.Lock()
|
||||
defer antigravityCapabilityMu.Unlock()
|
||||
current := antigravityCapabilityCache[cacheKey]
|
||||
if ctx.Err() != nil || current.probeRevision != revision {
|
||||
return current.hints.clone(), nil
|
||||
retained := current.hints.clone()
|
||||
antigravityCapabilityMu.Unlock()
|
||||
return retained, nil
|
||||
}
|
||||
now := antigravityNowFunc()
|
||||
for key, other := range antigravityCapabilityCache {
|
||||
@@ -419,6 +558,16 @@ func (s *Service) fetchAntigravityModelCapabilityHints(ctx context.Context, auth
|
||||
}
|
||||
}
|
||||
for key, failure := range antigravityAuthFailureCache {
|
||||
if failure.terminal {
|
||||
if s.coreManager != nil && failure.authID != "" && now.Sub(failure.lastFailure) > 2*antigravityCapabilityCacheTTL {
|
||||
staleTerminalCandidates = append(staleTerminalCandidates, antigravityTerminalFailureRef{
|
||||
key: key,
|
||||
authID: failure.authID,
|
||||
lastFailure: failure.lastFailure,
|
||||
})
|
||||
}
|
||||
continue
|
||||
}
|
||||
if now.Sub(failure.lastFailure) > 2*antigravityCapabilityCacheTTL {
|
||||
delete(antigravityAuthFailureCache, key)
|
||||
}
|
||||
@@ -433,6 +582,11 @@ func (s *Service) fetchAntigravityModelCapabilityHints(ctx context.Context, auth
|
||||
antigravityCapabilityCache[cacheKey] = current
|
||||
delete(antigravityAuthFailureCache, flightKey)
|
||||
delete(antigravityAuthFailureCache, cacheKey)
|
||||
if terminalFailureKey != "" {
|
||||
delete(antigravityAuthFailureCache, terminalFailureKey)
|
||||
}
|
||||
antigravityCapabilityMu.Unlock()
|
||||
s.pruneStaleAntigravityTerminalFailures(staleTerminalCandidates)
|
||||
return hints, nil
|
||||
}
|
||||
switch status {
|
||||
@@ -440,8 +594,20 @@ func (s *Service) fetchAntigravityModelCapabilityHints(ctx context.Context, auth
|
||||
// 403 forbidden failures persist across routine access_token rotation via cacheKey.
|
||||
antigravityAuthFailureCache[cacheKey] = nextAntigravityForbiddenFailure(antigravityAuthFailureCache[cacheKey], now, rand.Int64N)
|
||||
case antigravityProbeStatusAuthError:
|
||||
// 401 unauthorized failures back off longer for the same token while retrying immediately on token refresh.
|
||||
antigravityAuthFailureCache[flightKey] = nextAntigravityAuthErrorFailure(antigravityAuthFailureCache[flightKey], now, rand.Int64N)
|
||||
if terminalAuthError && terminalFailureKey != "" {
|
||||
// Refresh grant is terminally rejected and upstream confirmed this access_token
|
||||
// is unauthorized; suppress further probes for this credential+token independent of route metadata.
|
||||
delete(antigravityAuthFailureCache, flightKey)
|
||||
antigravityAuthFailureCache[terminalFailureKey] = antigravityFailureState{
|
||||
failures: antigravityFailureMaxCount,
|
||||
lastFailure: now,
|
||||
terminal: true,
|
||||
authID: terminalAuthID,
|
||||
}
|
||||
} else {
|
||||
// 401 unauthorized failures back off longer for the same token while retrying immediately on token refresh.
|
||||
antigravityAuthFailureCache[flightKey] = nextAntigravityAuthErrorFailure(antigravityAuthFailureCache[flightKey], now, rand.Int64N)
|
||||
}
|
||||
default:
|
||||
// Missing models (including legacy capability-only responses) and transient errors
|
||||
// are not a successful catalog. Preserve last success and increase the jittered backoff.
|
||||
@@ -451,6 +617,8 @@ func (s *Service) fetchAntigravityModelCapabilityHints(ctx context.Context, auth
|
||||
if status == antigravityProbeStatusSuccess && len(hints.WebSearchModelIDs) > 0 {
|
||||
retained.WebSearchModelIDs = hints.WebSearchModelIDs
|
||||
}
|
||||
antigravityCapabilityMu.Unlock()
|
||||
s.pruneStaleAntigravityTerminalFailures(staleTerminalCandidates)
|
||||
return retained, nil
|
||||
})
|
||||
select {
|
||||
@@ -727,7 +895,7 @@ func (s *Service) refreshAntigravityModels(ctx context.Context) {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
if auth == nil || isAntigravityAuthDisabled(auth) || !strings.EqualFold(auth.Provider, "antigravity") {
|
||||
if auth == nil || shouldSkipAntigravityModelProbe(auth, antigravityNowFunc()) || !strings.EqualFold(auth.Provider, "antigravity") {
|
||||
continue
|
||||
}
|
||||
snapshot := auth.Clone()
|
||||
@@ -762,7 +930,7 @@ func (s *Service) nextAntigravityModelRefreshDelay() time.Duration {
|
||||
return antigravityRefreshScanInterval
|
||||
}
|
||||
for _, auth := range s.coreManager.List() {
|
||||
if auth == nil || isAntigravityAuthDisabled(auth) || !strings.EqualFold(auth.Provider, "antigravity") {
|
||||
if auth == nil || shouldSkipAntigravityModelProbe(auth, now) || !strings.EqualFold(auth.Provider, "antigravity") {
|
||||
continue
|
||||
}
|
||||
key := s.antigravityCapabilityKey(auth)
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
package cliproxy
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"testing/synctest"
|
||||
"time"
|
||||
|
||||
coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
|
||||
@@ -500,3 +504,432 @@ func TestAntigravityDisabledAuthSkipsModelCapabilityProbe(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityUnauthenticatedAuthSkipsModelCapabilityProbe(t *testing.T) {
|
||||
now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
mutate func(*coreauth.Auth)
|
||||
}{
|
||||
{
|
||||
name: "RequiresSignInStatusErrorExpiredToken",
|
||||
mutate: func(a *coreauth.Auth) {
|
||||
a.Status = coreauth.StatusError
|
||||
a.Unavailable = true
|
||||
a.RequiresSignIn = true
|
||||
a.RejectedRefreshToken = "dead-rt"
|
||||
a.Metadata["refresh_token"] = "dead-rt"
|
||||
a.Metadata["expired"] = now.Add(-time.Hour).Format(time.RFC3339)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "TerminalUnauthorizedFailure",
|
||||
mutate: func(a *coreauth.Auth) {
|
||||
a.Status = coreauth.StatusError
|
||||
a.Unavailable = true
|
||||
a.LastError = &coreauth.Error{
|
||||
Code: "unauthorized",
|
||||
Message: "unauthorized (refresh token invalid)",
|
||||
HTTPStatus: http.StatusUnauthorized,
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "RejectedAccessToken",
|
||||
mutate: func(a *coreauth.Auth) {
|
||||
a.Status = coreauth.StatusActive
|
||||
a.RejectedAccessToken = a.Metadata["access_token"].(string)
|
||||
a.Metadata["expired"] = now.Add(time.Hour).Format(time.RFC3339)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "ExpiredAccessTokenWhileRetryingRefresh",
|
||||
mutate: func(a *coreauth.Auth) {
|
||||
a.Status = coreauth.StatusError
|
||||
a.Unavailable = true
|
||||
a.NextRefreshAfter = now.Add(30 * time.Minute)
|
||||
a.Metadata["expired"] = now.Add(-time.Minute).Format(time.RFC3339)
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resetAntigravityCapabilityCache()
|
||||
t.Cleanup(resetAntigravityCapabilityCache)
|
||||
antigravityNowFunc = func() time.Time { return now }
|
||||
t.Cleanup(func() { antigravityNowFunc = time.Now })
|
||||
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
if r.Header.Get("Authorization") == "Bearer recovered-token" {
|
||||
_, _ = w.Write([]byte(`{"models":{"gemini-3.1-flash-lite":{}}}`))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
svc := &Service{cfg: &config.Config{}, coreManager: manager}
|
||||
auth := antigravityTestAuth("unauth-"+tc.name, server.URL)
|
||||
auth.Metadata[antigravityPersistedHintsMetaKey] = buildPersistedAntigravityCapabilityHintsValue(
|
||||
"project-unauth-"+tc.name, server.URL,
|
||||
antigravityModelCapabilityHints{ModelIDs: map[string]struct{}{"gemini-3.1-flash-lite": {}}},
|
||||
)
|
||||
tc.mutate(auth)
|
||||
registered, errRegister := manager.Register(t.Context(), auth)
|
||||
if errRegister != nil {
|
||||
t.Fatal(errRegister)
|
||||
}
|
||||
t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(registered.ID) })
|
||||
|
||||
wake := svc.antigravityModelRefreshWake()
|
||||
select {
|
||||
case <-wake:
|
||||
default:
|
||||
}
|
||||
|
||||
// Without any pre-seeded backoff, direct fetch, queue, and refresh must all skip network probes.
|
||||
gotKey, gotHints := svc.fetchAntigravityModelCapabilityHints(t.Context(), registered)
|
||||
if gotKey != "" || gotHints.ModelIDs != nil {
|
||||
t.Fatalf("unauthenticated auth did not short-circuit fetch: key=%q hints=%v", gotKey, gotHints)
|
||||
}
|
||||
svc.queueAntigravityModelRefresh(t.Context(), registered, "antigravity")
|
||||
svc.WaitAntigravityProbes()
|
||||
select {
|
||||
case <-wake:
|
||||
t.Fatal("unauthenticated auth fetch/queue triggered refresh wakeup")
|
||||
default:
|
||||
}
|
||||
svc.refreshAntigravityModels(t.Context())
|
||||
svc.WaitAntigravityProbes()
|
||||
if calls.Load() != 0 {
|
||||
t.Fatalf("unauthenticated auth issued %d network probes, want 0", calls.Load())
|
||||
}
|
||||
|
||||
// Pre-seed a short retry deadline so nextAntigravityModelRefreshDelay would shorten if it failed to skip.
|
||||
cacheKey := svc.antigravityCapabilityKey(registered)
|
||||
token, _ := registered.Metadata["access_token"].(string)
|
||||
failureKey := antigravityTokenFailureKey(cacheKey, token)
|
||||
antigravityCapabilityMu.Lock()
|
||||
antigravityAuthFailureCache[failureKey] = antigravityFailureState{
|
||||
failures: 1,
|
||||
lastFailure: now,
|
||||
nextRetry: now.Add(10 * time.Second),
|
||||
}
|
||||
antigravityCapabilityMu.Unlock()
|
||||
if delay := svc.nextAntigravityModelRefreshDelay(); delay != antigravityRefreshScanInterval {
|
||||
t.Fatalf("nextAntigravityModelRefreshDelay=%s want %s (unauthenticated auth must be skipped)", delay, antigravityRefreshScanInterval)
|
||||
}
|
||||
|
||||
// Persisted capability hints remain readable for non-disabled credentials.
|
||||
if cached := svc.cachedAntigravityHints(registered); len(cached.ModelIDs) != 1 {
|
||||
t.Fatalf("cachedAntigravityHints=%v, want persisted fallback preserved", cached.ModelIDs)
|
||||
}
|
||||
|
||||
// Once credentials recover with a valid fresh token, probing resumes cleanly.
|
||||
recovered := registered.Clone()
|
||||
recovered.Status = coreauth.StatusActive
|
||||
recovered.Unavailable = false
|
||||
recovered.RequiresSignIn = false
|
||||
recovered.RejectedRefreshToken = ""
|
||||
recovered.RejectedAccessToken = ""
|
||||
recovered.LastError = nil
|
||||
recovered.NextRefreshAfter = time.Time{}
|
||||
recovered.Metadata["access_token"] = "recovered-token"
|
||||
recovered.Metadata["refresh_token"] = "fresh-rt"
|
||||
recovered.Metadata["expired"] = now.Add(time.Hour).Format(time.RFC3339)
|
||||
if _, errUpdate := manager.Update(t.Context(), recovered); errUpdate != nil {
|
||||
t.Fatal(errUpdate)
|
||||
}
|
||||
svc.refreshAntigravityModels(t.Context())
|
||||
svc.WaitAntigravityProbes()
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("recovered auth issued %d probes, want 1", calls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityProbeStillRunsForValidTokenStates(t *testing.T) {
|
||||
now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
mutate func(*coreauth.Auth)
|
||||
}{
|
||||
{
|
||||
name: "RequiresSignInWithValidUnexpiredAccessToken",
|
||||
mutate: func(a *coreauth.Auth) {
|
||||
a.Status = coreauth.StatusActive
|
||||
a.Unavailable = false
|
||||
a.RequiresSignIn = true
|
||||
a.RejectedRefreshToken = "dead-rt"
|
||||
a.Metadata["refresh_token"] = "dead-rt"
|
||||
a.Metadata["expired"] = now.Add(time.Hour).Format(time.RFC3339)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "TemporaryQuotaStatusErrorWithValidAccessToken",
|
||||
mutate: func(a *coreauth.Auth) {
|
||||
a.Status = coreauth.StatusError
|
||||
a.Unavailable = true
|
||||
a.NextRetryAfter = now.Add(10 * time.Minute)
|
||||
a.Quota = coreauth.QuotaState{
|
||||
Exceeded: true,
|
||||
NextRecoverAt: now.Add(10 * time.Minute),
|
||||
}
|
||||
a.Metadata["expired"] = now.Add(time.Hour).Format(time.RFC3339)
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "RequiresSignInWithValidAccessTokenAndTemporaryQuotaStatusError",
|
||||
mutate: func(a *coreauth.Auth) {
|
||||
a.Status = coreauth.StatusError
|
||||
a.Unavailable = true
|
||||
a.RequiresSignIn = true
|
||||
a.RejectedRefreshToken = "dead-rt"
|
||||
a.Metadata["refresh_token"] = "dead-rt"
|
||||
a.NextRetryAfter = now.Add(10 * time.Minute)
|
||||
a.LastError = &coreauth.Error{
|
||||
Code: "rate_limit_exceeded",
|
||||
Message: "quota exceeded",
|
||||
HTTPStatus: http.StatusTooManyRequests,
|
||||
}
|
||||
a.Quota = coreauth.QuotaState{
|
||||
Exceeded: true,
|
||||
NextRecoverAt: now.Add(10 * time.Minute),
|
||||
}
|
||||
a.Metadata["expired"] = now.Add(time.Hour).Format(time.RFC3339)
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resetAntigravityCapabilityCache()
|
||||
t.Cleanup(resetAntigravityCapabilityCache)
|
||||
antigravityNowFunc = func() time.Time { return now }
|
||||
t.Cleanup(func() { antigravityNowFunc = time.Now })
|
||||
|
||||
var calls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
_, _ = w.Write([]byte(`{"models":{"gemini-3.1-flash-lite":{}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
svc := &Service{cfg: &config.Config{}, coreManager: manager}
|
||||
auth := antigravityTestAuth("valid-"+tc.name, server.URL)
|
||||
tc.mutate(auth)
|
||||
registered, errRegister := manager.Register(t.Context(), auth)
|
||||
if errRegister != nil {
|
||||
t.Fatal(errRegister)
|
||||
}
|
||||
t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(registered.ID) })
|
||||
|
||||
svc.refreshAntigravityModels(t.Context())
|
||||
svc.WaitAntigravityProbes()
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("valid-token auth issued %d probes, want 1", calls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityTerminalRefreshUnknownExpirySuppressesAfter401(t *testing.T) {
|
||||
resetAntigravityCapabilityCache()
|
||||
t.Cleanup(resetAntigravityCapabilityCache)
|
||||
|
||||
var clockMu sync.Mutex
|
||||
now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
|
||||
userAgent := "antigravity/hub/2.34.0 (aidev_client; os_type=darwin; arch=arm64)"
|
||||
antigravityNowFunc = func() time.Time {
|
||||
clockMu.Lock()
|
||||
defer clockMu.Unlock()
|
||||
return now
|
||||
}
|
||||
t.Cleanup(func() { antigravityNowFunc = time.Now })
|
||||
prevUserAgent := antigravityModelUserAgent
|
||||
antigravityModelUserAgent = func() string {
|
||||
clockMu.Lock()
|
||||
defer clockMu.Unlock()
|
||||
return userAgent
|
||||
}
|
||||
t.Cleanup(func() { antigravityModelUserAgent = prevUserAgent })
|
||||
advance := func(d time.Duration) {
|
||||
clockMu.Lock()
|
||||
now = now.Add(d)
|
||||
clockMu.Unlock()
|
||||
}
|
||||
|
||||
var deadCalls, healthyCalls atomic.Int32
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Header.Get("Authorization") {
|
||||
case "Bearer token-dead-no-exp":
|
||||
deadCalls.Add(1)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
case "Bearer token-healthy-sibling":
|
||||
healthyCalls.Add(1)
|
||||
_, _ = w.Write([]byte(`{"models":{"gemini-3.1-flash-lite":{}}}`))
|
||||
case "Bearer recovered-no-exp-token":
|
||||
deadCalls.Add(1)
|
||||
_, _ = w.Write([]byte(`{"models":{"gemini-3.1-flash-lite":{}}}`))
|
||||
default:
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
svc := &Service{cfg: &config.Config{}, coreManager: manager}
|
||||
|
||||
dead := antigravityTestAuth("dead-no-exp", server.URL)
|
||||
dead.Status = coreauth.StatusActive
|
||||
dead.RequiresSignIn = true
|
||||
dead.RejectedRefreshToken = "dead-rt"
|
||||
dead.Metadata["refresh_token"] = "dead-rt"
|
||||
registeredDead, errRegister := manager.Register(t.Context(), dead)
|
||||
if errRegister != nil {
|
||||
t.Fatal(errRegister)
|
||||
}
|
||||
t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(registeredDead.ID) })
|
||||
|
||||
healthy := antigravityTestAuth("healthy-sibling", server.URL)
|
||||
healthy.Status = coreauth.StatusActive
|
||||
registeredHealthy, errRegisterHealthy := manager.Register(t.Context(), healthy)
|
||||
if errRegisterHealthy != nil {
|
||||
t.Fatal(errRegisterHealthy)
|
||||
}
|
||||
t.Cleanup(func() { GlobalModelRegistry().UnregisterClient(registeredHealthy.ID) })
|
||||
|
||||
// First probe discovers the unknown-expiry access_token is rejected with 401.
|
||||
svc.refreshAntigravityModels(t.Context())
|
||||
svc.WaitAntigravityProbes()
|
||||
if deadCalls.Load() != 1 || healthyCalls.Load() != 1 {
|
||||
t.Fatalf("initial probes dead=%d healthy=%d, want 1 and 1", deadCalls.Load(), healthyCalls.Load())
|
||||
}
|
||||
|
||||
// Advancing past max 401 retry cap and beyond cache eviction horizon must not re-probe the dead token,
|
||||
// even while healthy siblings run probes and trigger cache cleanup.
|
||||
advance(antigravityCapabilityRetryMax + time.Minute)
|
||||
svc.refreshAntigravityModels(t.Context())
|
||||
svc.WaitAntigravityProbes()
|
||||
if deadCalls.Load() != 1 {
|
||||
t.Fatalf("dead unknown-expiry auth retried after max backoff: calls=%d want 1", deadCalls.Load())
|
||||
}
|
||||
|
||||
advance(3 * antigravityCapabilityCacheTTL)
|
||||
svc.refreshAntigravityModels(t.Context())
|
||||
svc.WaitAntigravityProbes()
|
||||
if deadCalls.Load() != 1 {
|
||||
t.Fatalf("dead unknown-expiry auth retried after eviction window: calls=%d want 1", deadCalls.Load())
|
||||
}
|
||||
if healthyCalls.Load() != 2 {
|
||||
t.Fatalf("healthy sibling calls=%d want 2", healthyCalls.Load())
|
||||
}
|
||||
if delay := svc.nextAntigravityModelRefreshDelay(); delay != antigravityRefreshScanInterval {
|
||||
t.Fatalf("nextAntigravityModelRefreshDelay=%s want %s", delay, antigravityRefreshScanInterval)
|
||||
}
|
||||
|
||||
// Updating client User-Agent (or proxy) must not bypass terminal suppression for the same credential+token.
|
||||
clockMu.Lock()
|
||||
userAgent = "antigravity/hub/2.35.0 (aidev_client; os_type=darwin; arch=arm64)"
|
||||
clockMu.Unlock()
|
||||
svc.refreshAntigravityModels(t.Context())
|
||||
svc.WaitAntigravityProbes()
|
||||
if deadCalls.Load() != 1 {
|
||||
t.Fatalf("dead unknown-expiry auth retried after User-Agent change: calls=%d want 1", deadCalls.Load())
|
||||
}
|
||||
if healthyCalls.Load() != 3 {
|
||||
t.Fatalf("healthy sibling calls after User-Agent change=%d want 3", healthyCalls.Load())
|
||||
}
|
||||
|
||||
// Replacing credentials clears terminal suppression and resumes probing cleanly.
|
||||
recovered := registeredDead.Clone()
|
||||
recovered.RequiresSignIn = false
|
||||
recovered.RejectedRefreshToken = ""
|
||||
recovered.Metadata["access_token"] = "recovered-no-exp-token"
|
||||
recovered.Metadata["refresh_token"] = "fresh-rt"
|
||||
if _, errUpdate := manager.Update(t.Context(), recovered); errUpdate != nil {
|
||||
t.Fatal(errUpdate)
|
||||
}
|
||||
svc.refreshAntigravityModels(t.Context())
|
||||
svc.WaitAntigravityProbes()
|
||||
if deadCalls.Load() != 2 {
|
||||
t.Fatalf("recovered auth calls=%d want 2", deadCalls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityProbeSkipsWhenTokenExpiresWaitingForSlot(t *testing.T) {
|
||||
synctest.Test(t, func(t *testing.T) {
|
||||
resetAntigravityCapabilityCache()
|
||||
defer resetAntigravityCapabilityCache()
|
||||
|
||||
slots := antigravityProbeSlots
|
||||
antigravityProbeSlots = make(chan struct{}, cap(slots))
|
||||
defer func() { antigravityProbeSlots = slots }()
|
||||
for range cap(antigravityProbeSlots) {
|
||||
antigravityProbeSlots <- struct{}{}
|
||||
}
|
||||
|
||||
var clockMu sync.Mutex
|
||||
now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
|
||||
antigravityNowFunc = func() time.Time {
|
||||
clockMu.Lock()
|
||||
defer clockMu.Unlock()
|
||||
return now
|
||||
}
|
||||
defer func() { antigravityNowFunc = time.Now }()
|
||||
|
||||
var calls atomic.Int32
|
||||
transport := http.DefaultTransport
|
||||
http.DefaultTransport = antigravityReviewTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls.Add(1)
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusUnauthorized,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader("")),
|
||||
Request: r,
|
||||
}, nil
|
||||
})
|
||||
defer func() { http.DefaultTransport = transport }()
|
||||
|
||||
manager := coreauth.NewManager(nil, nil, nil)
|
||||
svc := &Service{cfg: &config.Config{}, coreManager: manager}
|
||||
auth := antigravityTestAuth("slot-expiry", "https://slot-expiry.invalid")
|
||||
auth.Metadata["expired"] = now.Add(5 * time.Minute).Format(time.RFC3339)
|
||||
registered, errRegister := manager.Register(t.Context(), auth)
|
||||
if errRegister != nil {
|
||||
t.Fatal(errRegister)
|
||||
}
|
||||
defer GlobalModelRegistry().UnregisterClient(registered.ID)
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
svc.fetchAntigravityModelCapabilityHints(t.Context(), registered)
|
||||
}()
|
||||
// Wait until the probe goroutine has passed pre-slot checks and is blocked acquiring a slot.
|
||||
synctest.Wait()
|
||||
|
||||
// Advance clock past token expiry without emitting any auth-change notification.
|
||||
clockMu.Lock()
|
||||
now = now.Add(10 * time.Minute)
|
||||
clockMu.Unlock()
|
||||
|
||||
for range cap(antigravityProbeSlots) {
|
||||
<-antigravityProbeSlots
|
||||
}
|
||||
<-done
|
||||
synctest.Wait()
|
||||
|
||||
if calls.Load() != 0 {
|
||||
t.Fatalf("token expired while waiting for probe slot still issued %d HTTP requests, want 0", calls.Load())
|
||||
}
|
||||
antigravityCapabilityMu.RLock()
|
||||
failureCount := len(antigravityAuthFailureCache)
|
||||
antigravityCapabilityMu.RUnlock()
|
||||
if failureCount != 0 {
|
||||
t.Fatalf("expected 0 failure cache entries, got %d", failureCount)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1287,6 +1287,7 @@ func (m *Manager) markRejectedAccessToken(id, failedAccessToken string) {
|
||||
current.Generation++
|
||||
current.UpdatedAt = time.Now()
|
||||
m.auths[id] = current
|
||||
m.notifyAuthChangeLocked(id)
|
||||
if m.scheduler != nil {
|
||||
m.scheduler.upsertAuth(current.Clone())
|
||||
}
|
||||
@@ -1463,6 +1464,7 @@ func (m *Manager) refreshAuthForRequestAtVersion(ctx context.Context, id, failed
|
||||
}
|
||||
}
|
||||
m.auths[id] = current
|
||||
m.notifyAuthChangeLocked(id)
|
||||
if m.scheduler != nil {
|
||||
m.scheduler.upsertAuth(current.Clone())
|
||||
}
|
||||
@@ -1579,6 +1581,7 @@ func (m *Manager) refreshAuthForRequestAtVersion(ctx context.Context, id, failed
|
||||
current.StatusMessage = "unauthorized (refresh token invalid)"
|
||||
}
|
||||
m.auths[id] = current
|
||||
m.notifyAuthChangeLocked(id)
|
||||
if m.scheduler != nil {
|
||||
m.scheduler.upsertAuth(current.Clone())
|
||||
}
|
||||
@@ -1738,6 +1741,9 @@ func (m *Manager) refreshAuthForRequestAtVersion(ctx context.Context, id, failed
|
||||
}
|
||||
}
|
||||
m.auths[id] = current
|
||||
if shouldUnschedule || hasUnauthorizedAuthFailure(current) {
|
||||
m.notifyAuthChangeLocked(id)
|
||||
}
|
||||
if m.scheduler != nil {
|
||||
m.scheduler.upsertAuth(current.Clone())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user