Files
CLIProxyAPI/internal/runtime/executor/antigravity_executor_auth.go

2047 lines
77 KiB
Go

package executor
import (
"bytes"
"context"
"crypto/sha256"
"crypto/subtle"
"crypto/tls"
"encoding/hex"
"errors"
"fmt"
"io"
"mime"
"net/http"
"net/url"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/MoeForge/moego/json"
"github.com/MoeForge/moego/ojson"
"github.com/router-for-me/CLIProxyAPI/v8/internal/auth/antigravity"
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
"github.com/router-for-me/CLIProxyAPI/v8/internal/home"
"github.com/router-for-me/CLIProxyAPI/v8/internal/logging"
"github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps"
sdkAuth "github.com/router-for-me/CLIProxyAPI/v8/sdk/auth"
cliproxyauth "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/httptransport"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/proxyutil"
log "github.com/sirupsen/logrus"
"golang.org/x/sync/singleflight"
)
const (
antigravityCredentialAcquisitionTimeout = 30 * time.Second
antigravityAICodeCacheCapacity = 8192
// antigravityAICodeScopeCooldownDuration matches antigravity.AICodeScopeMissingCooldown (1h).
antigravityAICodeScopeCooldownDuration = time.Hour
antigravityAICodeLocationBlockTTL = time.Hour
antigravityOAuthTokenMaxResponseBytes = 1 << 20
antigravityAICodeMaxExpiresInSeconds = antigravity.AICodeTokenMaxTTLSeconds
antigravity401MaxErrorBodyBytes = 4096
antigravityMaxErrorBodyBytes = 1 << 20
)
var (
errAICodeScopeMissing = errors.New("antigravity: credential missing auth/aicode scope")
errAICodeLocationNotEligible = errors.New("antigravity: aicode location not eligible")
errAntigravity401UnchangedToken = errors.New("antigravity: 401 refresh returned unchanged access token")
antigravityInitialBaseTransport = antigravityBaseTransport
antigravityNow = time.Now
// antigravityHomeAICodeTokenFetcher overrides the Home RESP aicode-token
// lookup in tests. When nil, the executor queries home.Current().GetAntigravityAICodeTokenWithForceRefresh
// whenever an enabled Home client is active.
antigravityHomeAICodeTokenFetcher func(ctx context.Context, authIndex, grantScope, observedAccessTokenSHA256 string) (string, int, error)
// antigravityHomeAICodeForceRefreshFetcher optionally overrides force-refresh
// Home RESP aicode-token lookups in tests (receiving rejectedAICodeTokenSHA256).
antigravityHomeAICodeForceRefreshFetcher func(ctx context.Context, authIndex, grantScope, observedAccessTokenSHA256, rejectedAICodeTokenSHA256 string) (string, int, error)
// antigravityAICodeFlightRegisteredHook is a test-only callback invoked right
// after a caller has synchronously registered onto aicodeRefreshGroup via DoChan.
antigravityAICodeFlightRegisteredHook func(cacheKey string)
aicodeTokenCacheMu sync.Mutex
aicodeAccessTokenCache = helps.NewBoundedLRU[string, antigravityAICodeTokenEntry](antigravityAICodeCacheCapacity)
aicodeLocationBlockedMu sync.Mutex
aicodeLocationBlockedSeq atomic.Uint64
aicodeLocationBlockedCache = helps.NewBoundedLRU[string, antigravityAICodeLocationBlockEntry](antigravityAICodeCacheCapacity)
aicodeLazyProjectIDCache = helps.NewBoundedLRU[string, antigravityLazyProjectEntry](antigravityAICodeCacheCapacity)
aicodeRefreshGroup atomic.Pointer[singleflight.Group]
aicodeProjectDiscoveryGroup atomic.Pointer[singleflight.Group]
)
type antigravityAICodeLocationBlockEntry struct {
detectedLocation string
blockedUntil time.Time
generation uint64
}
func init() {
aicodeRefreshGroup.Store(&singleflight.Group{})
aicodeProjectDiscoveryGroup.Store(&singleflight.Group{})
helps.RegisterAntigravityAICodeScopeEvictionHook(func(key string) {
deleteAICodeCachedToken(key)
})
}
type antigravityAICodeTokenEntry struct {
accessToken string
expiresAt time.Time
}
type antigravityLazyProjectEntry struct {
projectID string
paidTierID string
}
type antigravityAICodeFlightResult struct {
token string
mintedFresh bool
forced bool
rejectedTokenSHA256 string
rejectedFresh bool
}
func resetAntigravityAICodeCaches() {
aicodeTokenCacheMu.Lock()
aicodeAccessTokenCache.Purge()
aicodeTokenCacheMu.Unlock()
helps.ResetAntigravityAICodeScopeCooldown()
aicodeLocationBlockedMu.Lock()
aicodeLocationBlockedCache.Purge()
aicodeLocationBlockedMu.Unlock()
aicodeLazyProjectIDCache.Purge()
aicodeRefreshGroup.Store(&singleflight.Group{})
aicodeProjectDiscoveryGroup.Store(&singleflight.Group{})
}
func getFreshAICodeCachedToken(cacheKey, rejectedToken string, now time.Time) (string, bool) {
aicodeTokenCacheMu.Lock()
defer aicodeTokenCacheMu.Unlock()
entry, ok := aicodeAccessTokenCache.Get(cacheKey)
if !ok || entry.accessToken == "" {
return "", false
}
if rejectedToken != "" && subtle.ConstantTimeCompare([]byte(entry.accessToken), []byte(rejectedToken)) == 1 {
// Atomic compare-and-delete: evict ONLY if the cached entry still holds
// the rejected token so a concurrently minted newer token is never deleted.
aicodeAccessTokenCache.Delete(cacheKey)
return "", false
}
if entry.expiresAt.After(now.Add(antigravityRequestTokenSafetyWindow)) {
return entry.accessToken, true
}
return "", false
}
func setAICodeCachedToken(cacheKey, token string, expiresAt time.Time) {
aicodeTokenCacheMu.Lock()
aicodeAccessTokenCache.Set(cacheKey, antigravityAICodeTokenEntry{
accessToken: token,
expiresAt: expiresAt,
})
aicodeTokenCacheMu.Unlock()
}
func deleteAICodeCachedToken(cacheKey string) {
aicodeTokenCacheMu.Lock()
aicodeAccessTokenCache.Delete(cacheKey)
aicodeTokenCacheMu.Unlock()
}
// invalidateAICodeAccessToken evicts auth's cached downscoped auth/aicode
// access token without issuing any /token exchange. When failedToken is
// non-empty, it performs an atomic constant-time compare-and-delete so a
// concurrently minted fresher token is never clobbered. When failedToken is
// empty, it unconditionally removes the cached entry for auth's active key.
func (e *AntigravityExecutor) invalidateAICodeAccessToken(auth *cliproxyauth.Auth, failedToken string) {
if auth == nil {
return
}
cacheKey := antigravityAICodeCacheKey(auth)
if cacheKey == "" {
return
}
failedToken = strings.TrimSpace(failedToken)
if failedToken == "" {
deleteAICodeCachedToken(cacheKey)
return
}
aicodeTokenCacheMu.Lock()
defer aicodeTokenCacheMu.Unlock()
entry, ok := aicodeAccessTokenCache.Get(cacheKey)
if !ok || entry.accessToken == "" {
return
}
if subtle.ConstantTimeCompare([]byte(entry.accessToken), []byte(failedToken)) == 1 {
aicodeAccessTokenCache.Delete(cacheKey)
}
}
// evictRejectedAICodeAccessToken atomically removes rejectedToken from
// aicodeAccessTokenCache if it is still the cached entry for auth, without
// issuing any /token exchange.
func (e *AntigravityExecutor) evictRejectedAICodeAccessToken(auth *cliproxyauth.Auth, rejectedToken string) {
rejectedToken = strings.TrimSpace(rejectedToken)
if rejectedToken == "" {
return
}
e.invalidateAICodeAccessToken(auth, rejectedToken)
}
func sha256HexTokenFingerprint(token string) string {
token = strings.TrimSpace(token)
if token == "" {
return ""
}
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
func antigravityAICodeCacheKey(auth *cliproxyauth.Auth) string {
return helps.AntigravityAICodeCacheKey(auth, antigravityHomeGrantScope(auth))
}
func isAICodeInsufficientScopeError(statusCode int, body []byte) bool {
return helps.IsAICodeInsufficientScopeError(statusCode, body)
}
func (e *AntigravityExecutor) isInAICodeScopeCooldownKey(cacheKey string, now time.Time) bool {
if cacheKey == "" {
return false
}
if now.IsZero() {
now = antigravityNow()
}
return helps.IsAntigravityAICodeScopeCooldown(cacheKey, now)
}
func (e *AntigravityExecutor) isInAICodeScopeCooldown(auth *cliproxyauth.Auth, now time.Time) bool {
return e.isInAICodeScopeCooldownKey(antigravityAICodeCacheKey(auth), now)
}
func (e *AntigravityExecutor) warnSignOutMissingAICodeScopeWithFlags(auth *cliproxyauth.Auth, cacheKey string, flags map[string]bool, now time.Time) {
if e == nil || auth == nil || cacheKey == "" || len(flags) == 0 {
return
}
if now.IsZero() {
now = antigravityNow()
}
helps.WarnSignOutMissingAICodeScopeIfEnabled(antigravityAuthID(auth), cacheKey, flags, now, antigravityAICodeScopeCooldownDuration)
}
func (e *AntigravityExecutor) warnSignOutMissingAICodeScopeIfEnabled(ctx context.Context, auth *cliproxyauth.Auth, cacheKey string, flags map[string]bool, now time.Time) {
if e == nil || auth == nil || cacheKey == "" {
return
}
effectiveFlags := flags
if effectiveFlags == nil && ctx != nil {
effectiveFlags = e.resolveAntigravityAICodeSnapshotSelection(ctx, auth).AICodeExperimentFlags
}
e.warnSignOutMissingAICodeScopeWithFlags(auth, cacheKey, effectiveFlags, now)
}
func (e *AntigravityExecutor) markAICodeScopeMissingKey(cacheKey string, now time.Time) {
e.markAICodeScopeMissingWithContext(nil, nil, cacheKey, nil, now)
}
func (e *AntigravityExecutor) markAICodeScopeMissingWithContext(ctx context.Context, auth *cliproxyauth.Auth, cacheKey string, flags map[string]bool, now time.Time) {
if cacheKey == "" {
return
}
if now.IsZero() {
now = antigravityNow()
}
helps.MarkAntigravityAICodeScopeMissing(cacheKey, now, antigravityAICodeScopeCooldownDuration)
if auth != nil {
e.warnSignOutMissingAICodeScopeIfEnabled(ctx, auth, cacheKey, flags, now)
}
}
func (e *AntigravityExecutor) markAICodeScopeMissing(auth *cliproxyauth.Auth, now time.Time) {
e.markAICodeScopeMissingWithContext(nil, auth, antigravityAICodeCacheKey(auth), nil, now)
}
func (e *AntigravityExecutor) isAICodeLocationBlockedKey(cacheKey string) bool {
if cacheKey == "" {
return false
}
aicodeLocationBlockedMu.Lock()
defer aicodeLocationBlockedMu.Unlock()
entry, ok := aicodeLocationBlockedCache.Get(cacheKey)
if !ok {
return false
}
if antigravityNow().Before(entry.blockedUntil) {
return true
}
aicodeLocationBlockedCache.Delete(cacheKey)
return false
}
func (e *AntigravityExecutor) isAICodeLocationBlocked(auth *cliproxyauth.Auth) bool {
return e.isAICodeLocationBlockedKey(antigravityAICodeCacheKey(auth))
}
func (e *AntigravityExecutor) aicodeLocationBlockedGenerationKey(cacheKey string) uint64 {
if cacheKey == "" {
return 0
}
aicodeLocationBlockedMu.Lock()
defer aicodeLocationBlockedMu.Unlock()
entry, ok := aicodeLocationBlockedCache.Get(cacheKey)
if !ok {
return 0
}
return entry.generation
}
func (e *AntigravityExecutor) aicodeLocationBlockedGeneration(auth *cliproxyauth.Auth) uint64 {
return e.aicodeLocationBlockedGenerationKey(antigravityAICodeCacheKey(auth))
}
func (e *AntigravityExecutor) markAICodeLocationBlockedKey(cacheKey, detectedLocation string) {
if cacheKey == "" {
return
}
aicodeLocationBlockedMu.Lock()
defer aicodeLocationBlockedMu.Unlock()
gen := aicodeLocationBlockedSeq.Add(1)
aicodeLocationBlockedCache.Set(cacheKey, antigravityAICodeLocationBlockEntry{
detectedLocation: strings.TrimSpace(detectedLocation),
blockedUntil: antigravityNow().Add(antigravityAICodeLocationBlockTTL),
generation: gen,
})
}
func (e *AntigravityExecutor) markAICodeLocationBlocked(auth *cliproxyauth.Auth, detectedLocation string) {
e.markAICodeLocationBlockedKey(antigravityAICodeCacheKey(auth), detectedLocation)
}
func (e *AntigravityExecutor) clearAICodeLocationBlockedKey(cacheKey string) {
if cacheKey == "" {
return
}
aicodeLocationBlockedMu.Lock()
defer aicodeLocationBlockedMu.Unlock()
aicodeLocationBlockedCache.Delete(cacheKey)
}
func (e *AntigravityExecutor) clearAICodeLocationBlocked(auth *cliproxyauth.Auth) {
e.clearAICodeLocationBlockedKey(antigravityAICodeCacheKey(auth))
}
// clearAICodeLocationBlockedIfGeneration clears the location-block entry only
// if no newer LOCATION_NOT_ELIGIBLE mark was recorded after expectedGen was
// captured before the request started.
func (e *AntigravityExecutor) clearAICodeLocationBlockedKeyIfGeneration(cacheKey string, expectedGen uint64) {
if cacheKey == "" {
return
}
aicodeLocationBlockedMu.Lock()
defer aicodeLocationBlockedMu.Unlock()
entry, ok := aicodeLocationBlockedCache.Get(cacheKey)
if !ok || entry.generation != expectedGen {
return
}
aicodeLocationBlockedCache.Delete(cacheKey)
}
func (e *AntigravityExecutor) clearAICodeLocationBlockedIfGeneration(auth *cliproxyauth.Auth, expectedGen uint64) {
e.clearAICodeLocationBlockedKeyIfGeneration(antigravityAICodeCacheKey(auth), expectedGen)
}
// An upstream refusal does not authorize replay on a broader endpoint. The
// existing local route selection still applies before any upstream request.
func (e *AntigravityExecutor) shouldFallbackAICodeToV1Internal(auth *cliproxyauth.Auth, wireHTTPStatus, rpcStatusCode int, body []byte) (string, bool) {
return e.shouldFallbackAICodeToV1InternalWithFlags(nil, auth, nil, wireHTTPStatus, rpcStatusCode, body)
}
func (e *AntigravityExecutor) shouldFallbackAICodeToV1InternalWithFlags(_ context.Context, _ *cliproxyauth.Auth, _ map[string]bool, _, _ int, _ []byte) (string, bool) {
return "", false
}
func (e *AntigravityExecutor) resolveHomeAICodeTokenFetcher() func(ctx context.Context, authIndex, grantScope, observedAccessTokenSHA256, rejectedAICodeTokenSHA256 string) (string, int, error) {
if antigravityHomeAICodeForceRefreshFetcher != nil {
return antigravityHomeAICodeForceRefreshFetcher
}
if antigravityHomeAICodeTokenFetcher != nil {
base := antigravityHomeAICodeTokenFetcher
return func(ctx context.Context, authIndex, grantScope, observedAccessTokenSHA256, _ string) (string, int, error) {
return base(ctx, authIndex, grantScope, observedAccessTokenSHA256)
}
}
client := home.Current()
if client == nil || !client.Enabled() {
return nil
}
return client.GetAntigravityAICodeTokenWithForceRefresh
}
func antigravityAuthIndex(auth *cliproxyauth.Auth) string {
if auth == nil {
return ""
}
if idx := strings.TrimSpace(auth.Index); idx != "" {
return idx
}
return strings.TrimSpace(auth.Clone().EnsureIndex())
}
// antigravityHomeGrantScope returns the Home-stamped signature grant identity
// when auth carries a valid grant binding. Unstamped sanitized credentials fall
// back to observedAccessTokenSHA256 verification instead of sending a locally
// synthesized grant that cannot match Home's full refresh-token grant.
func antigravityHomeGrantScope(auth *cliproxyauth.Auth) string {
if !antigravityHasValidSignatureGrant(auth) {
return ""
}
return strings.TrimSpace(metaStringValue(auth.Metadata, antigravitySignatureGrantScopeMetadataKey))
}
func (e *AntigravityExecutor) ensureAICodeAccessToken(ctx context.Context, auth *cliproxyauth.Auth) (string, error) {
return e.ensureAICodeAccessTokenWithFlags(ctx, auth, nil)
}
func (e *AntigravityExecutor) ensureAICodeAccessTokenWithFlags(ctx context.Context, auth *cliproxyauth.Auth, flags map[string]bool) (string, error) {
return e.ensureAICodeAccessTokenWithRejectedAndFlags(ctx, auth, "", flags)
}
func (e *AntigravityExecutor) ensureAICodeAccessTokenWithRejected(ctx context.Context, auth *cliproxyauth.Auth, rejectedToken string) (string, error) {
return e.ensureAICodeAccessTokenWithRejectedAndFlags(ctx, auth, rejectedToken, nil)
}
func (e *AntigravityExecutor) ensureAICodeAccessTokenWithRejectedAndFlags(ctx context.Context, auth *cliproxyauth.Auth, rejectedToken string, flags map[string]bool) (string, error) {
if auth == nil {
return "", statusErr{code: http.StatusUnauthorized, msg: "missing auth", credentialScoped: true}
}
rejectedToken = strings.TrimSpace(rejectedToken)
// Compute and validate the active credential binding BEFORE checking
// cooldown or token caches so unbound or non-mintable credentials never hit
// warm cache entries and cache/singleflight keys always incorporate the
// exact verified binding.
refreshToken := strings.TrimSpace(metaStringValue(auth.Metadata, "refresh_token"))
if refreshToken != "" && auth.RequiresSignIn && auth.RejectedRefreshToken == refreshToken {
return "", statusErr{code: http.StatusUnauthorized, msg: "antigravity: OAuth sign-in required", terminalUnauthorized: true}
}
var homeFetcher func(ctx context.Context, authIndex, grantScope, observedAccessTokenSHA256, rejectedAICodeTokenSHA256 string) (string, int, error)
var authIndex, grantScope, observedAccessTokenSHA256 string
if refreshToken == "" {
homeFetcher = e.resolveHomeAICodeTokenFetcher()
if homeFetcher != nil {
authIndex = antigravityAuthIndex(auth)
grantScope = antigravityHomeGrantScope(auth)
observedAccessTokenSHA256 = strings.TrimSpace(cliproxyauth.AccessTokenSHA256(auth))
}
if homeFetcher == nil || authIndex == "" {
return "", errAICodeScopeMissing
}
if grantScope == "" && observedAccessTokenSHA256 == "" {
return "", statusErr{
code: http.StatusUnauthorized,
msg: "antigravity home aicode-token missing credential binding",
credentialScoped: true,
}
}
}
cacheKey := helps.AntigravityAICodeCacheKey(auth, grantScope)
if cacheKey == "" {
return "", statusErr{
code: http.StatusUnauthorized,
msg: "antigravity aicode-token missing credential binding",
credentialScoped: true,
}
}
callerCtx := ctx
if ctx == nil {
ctx = context.Background()
}
rejectedTokenSHA256 := sha256HexTokenFingerprint(rejectedToken)
for attempt := 0; attempt < 2; attempt++ {
now := antigravityNow()
if e.isInAICodeScopeCooldownKey(cacheKey, now) {
e.warnSignOutMissingAICodeScopeIfEnabled(callerCtx, auth, cacheKey, flags, now)
return "", errAICodeScopeMissing
}
if cached, ok := getFreshAICodeCachedToken(cacheKey, rejectedToken, now); ok {
return cached, nil
}
// Normal mint and 401 force-refresh share the exact same singleflight key
// (cacheKey) so concurrent callers coalesce onto one /token exchange and
// atomic compare-and-delete never evicts a freshly minted newer token.
flightCh := aicodeRefreshGroup.Load().DoChan(cacheKey, func() (any, error) {
flightNow := antigravityNow()
exchangeGuard, cooldownActive := helps.BeginAntigravityAICodeTokenExchange(cacheKey, flightNow)
if cooldownActive {
e.warnSignOutMissingAICodeScopeIfEnabled(callerCtx, auth, cacheKey, flags, flightNow)
return nil, errAICodeScopeMissing
}
defer exchangeGuard.Finish()
if cached, ok := getFreshAICodeCachedToken(cacheKey, rejectedToken, flightNow); ok {
return antigravityAICodeFlightResult{
token: cached,
mintedFresh: false,
forced: rejectedToken != "",
rejectedTokenSHA256: rejectedTokenSHA256,
}, nil
}
refreshCtx, cancelRefresh := context.WithTimeout(detachedAntigravityCredentialContext(ctx), antigravityCredentialAcquisitionTimeout)
defer cancelRefresh()
var token string
var expiresIn int64
reqStart := antigravityNow()
if refreshToken != "" {
tokenResp, errExchange := e.exchangeAICodeAccessToken(refreshCtx, auth, refreshToken, flags)
if errExchange != nil {
return nil, errExchange
}
if !tokenResp.requestedAt.IsZero() {
reqStart = tokenResp.requestedAt
}
token = strings.TrimSpace(tokenResp.AccessToken)
expiresIn = tokenResp.ExpiresIn
} else {
homeToken, homeExpiresIn, errHome := homeFetcher(refreshCtx, authIndex, grantScope, observedAccessTokenSHA256, rejectedTokenSHA256)
if errHome != nil {
if errors.Is(errHome, home.ErrAntigravityAICodeScopeInsufficient) {
e.markAICodeScopeMissingWithContext(refreshCtx, auth, cacheKey, flags, antigravityNow())
return nil, errAICodeScopeMissing
}
if errors.Is(errHome, home.ErrDisabled) {
return nil, errAICodeScopeMissing
}
if errors.Is(errHome, home.ErrAuthNotFound) {
return nil, statusErr{
code: http.StatusUnauthorized,
msg: "antigravity home aicode-token credential mismatch or not found",
credentialScoped: true,
}
}
return nil, errHome
}
token = strings.TrimSpace(homeToken)
expiresIn = int64(homeExpiresIn)
}
if token == "" || expiresIn <= 0 {
e.markAICodeScopeMissingWithContext(refreshCtx, auth, cacheKey, flags, antigravityNow())
return nil, errAICodeScopeMissing
}
rejectedFresh := rejectedToken != "" && subtle.ConstantTimeCompare([]byte(token), []byte(rejectedToken)) == 1
expiresAt := antigravity.AICodeTokenExpiresAt(reqStart, expiresIn)
commitNow := antigravityNow()
if !expiresAt.After(commitNow) {
return nil, statusErr{code: http.StatusBadGateway, msg: "antigravity aicode token expired before use", credentialScoped: true}
}
var commitFn func()
if cacheKey != "" && expiresAt.After(commitNow.Add(antigravityRequestTokenSafetyWindow)) && !rejectedFresh {
commitFn = func() {
setAICodeCachedToken(cacheKey, token, expiresAt)
}
}
// Atomically verify under the shared cooldown lock that no concurrent
// scope cooldown was activated while this exchange was in flight.
if !helps.CommitAntigravityAICodeTokenIfUnchanged(exchangeGuard, commitNow, commitFn) {
return nil, errAICodeScopeMissing
}
return antigravityAICodeFlightResult{
token: token,
mintedFresh: true,
forced: rejectedToken != "",
rejectedTokenSHA256: rejectedTokenSHA256,
rejectedFresh: rejectedFresh,
}, nil
})
if hook := antigravityAICodeFlightRegisteredHook; hook != nil {
hook(cacheKey)
}
sfRes := <-flightCh
result, errDo, shared := sfRes.Val, sfRes.Err, sfRes.Shared
if errDo != nil {
if !errors.Is(errDo, errAICodeScopeMissing) && !errors.Is(errDo, errAntigravity401UnchangedToken) {
cliproxyexecutor.MarkUpstreamAttempt(ctx)
}
return "", errDo
}
flightRes, ok := result.(antigravityAICodeFlightResult)
if !ok || strings.TrimSpace(flightRes.token) == "" {
return "", fmt.Errorf("antigravity aicode token mint failed: invalid single-flight result")
}
if flightRes.rejectedFresh {
// A forced refresh minted a token identical to an upstream-rejected
// bearer. Never return that known-rejected token to any waiter
// (including normal callers joining the flight) and do not fire a
// duplicate /token exchange. Preserve AlternateTokenUnauthorized so
// Manager.MarkResult never penalizes standard v1internal OAuth.
return "", newAntigravityAICodeUnchangedTokenError()
}
if rejectedToken != "" && subtle.ConstantTimeCompare([]byte(flightRes.token), []byte(rejectedToken)) == 1 {
// Only retry once when we joined a non-forced or cached-hit flight
// (or a forced flight targeting a different rejected token). Two
// concurrent 401 callers sharing a fresh forced mint for the same
// rejected token must not trigger a duplicate /token request.
alreadyForcedForRejected := flightRes.mintedFresh && flightRes.forced && flightRes.rejectedTokenSHA256 == rejectedTokenSHA256
if shared && attempt == 0 && !alreadyForcedForRejected {
continue
}
return "", newAntigravityAICodeUnchangedTokenError()
}
return flightRes.token, nil
}
return "", newAntigravityAICodeUnchangedTokenError()
}
func newAntigravityAICodeUnchangedTokenError() error {
return statusErr{
code: http.StatusUnauthorized,
msg: errAntigravity401UnchangedToken.Error(),
cause: errAntigravity401UnchangedToken,
unauthorizedRefreshAttempted: true,
alternateTokenUnauthorized: true,
}
}
func (e *AntigravityExecutor) exchangeAICodeAccessToken(ctx context.Context, auth *cliproxyauth.Auth, refreshToken string, flagSets ...map[string]bool) (*antigravityTokenRefreshData, error) {
var flags map[string]bool
if len(flagSets) > 0 {
flags = flagSets[0]
}
form := url.Values{}
form.Set("grant_type", "refresh_token")
form.Set("refresh_token", refreshToken)
form.Set("client_id", antigravityClientID)
form.Set("client_secret", antigravityClientSecret)
form.Set("scope", antigravity.AICodeScope)
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodPost, antigravity.TokenEndpoint, strings.NewReader(form.Encode()))
if errReq != nil {
return nil, errReq
}
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
httpClient, cleanup := newAntigravityAICodeOAuthHTTPClient(ctx, e.cfg, auth)
defer cleanup()
reqStart := antigravityNow()
httpResp, errDo := helps.WithAntigravityHTTPClientTrace(httpClient, auth, "aicode_oauth_refresh").Do(httpReq)
if errDo != nil {
return nil, errDo
}
defer func() {
if errClose := httpResp.Body.Close(); errClose != nil {
log.Errorf("antigravity executor: close aicode token response body error: %v", errClose)
}
}()
bodyBytes, errRead := io.ReadAll(io.LimitReader(httpResp.Body, antigravity.AICodeTokenMaxResponseBytes+1))
if errRead != nil {
return nil, errRead
}
if len(bodyBytes) > antigravity.AICodeTokenMaxResponseBytes {
return nil, statusErr{code: http.StatusBadGateway, msg: "antigravity aicode token response exceeded size limit", credentialScoped: true}
}
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
if antigravity.ParseTerminalOAuthGrantError(httpResp.StatusCode, bodyBytes) != "" {
return nil, newAntigravityOAuthStatusErr(httpResp.StatusCode, httpResp.Header, bodyBytes, "")
}
if isAICodeInsufficientScopeError(httpResp.StatusCode, bodyBytes) {
e.markAICodeScopeMissingWithContext(ctx, auth, antigravityAICodeCacheKey(auth), flags, antigravityNow())
return nil, errAICodeScopeMissing
}
fallbackMsg := fmt.Sprintf("antigravity aicode token exchange failed with status %d", httpResp.StatusCode)
return nil, newAntigravityOAuthStatusErr(httpResp.StatusCode, httpResp.Header, bodyBytes, fallbackMsg)
}
if rpcErr, hasRPC := antigravity.ParseGoogleInBandRPCError(bodyBytes); hasRPC {
mappedCode := antigravity.MapGoogleRPCErrorToHTTPCode(rpcErr.Code, rpcErr.Status, rpcErr.IsScopeInsufficient)
if rpcErr.IsScopeInsufficientForHTTPStatus(mappedCode) {
e.markAICodeScopeMissingWithContext(ctx, auth, antigravityAICodeCacheKey(auth), flags, antigravityNow())
return nil, errAICodeScopeMissing
}
fallbackMsg := fmt.Sprintf("antigravity aicode token exchange failed with status %d", mappedCode)
return nil, newAntigravityOAuthStatusErr(mappedCode, httpResp.Header, bodyBytes, fallbackMsg)
}
token, expiresIn, errGrant := antigravity.ParseAICodeTokenGrant(bodyBytes)
if errors.Is(errGrant, antigravity.ErrUnusableAICodeTokenGrant) {
e.markAICodeScopeMissingWithContext(ctx, auth, antigravityAICodeCacheKey(auth), flags, antigravityNow())
return nil, errAICodeScopeMissing
}
if errGrant != nil {
return nil, statusErr{code: http.StatusBadGateway, msg: errGrant.Error(), credentialScoped: true}
}
return &antigravityTokenRefreshData{AccessToken: token, ExpiresIn: expiresIn, requestedAt: reqStart}, nil
}
// newAntigravityAICodeOAuthHTTPClient builds an isolated per-credential HTTP/1.1
// no-ALPN client for downscoped scope=auth/aicode token minting, sharing the
// unified Antigravity OAuth refresh transport.
func newAntigravityAICodeOAuthHTTPClient(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (*http.Client, func()) {
return newAntigravityOAuthHTTPClient(ctx, cfg, auth, 0)
}
// Refresh refreshes the authentication credentials using the refresh token.
func (e *AntigravityExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
expectedGrant := antigravityHomeGrantScope(auth)
expectedAccessTokenSHA256 := strings.TrimSpace(cliproxyauth.AccessTokenSHA256(auth))
if refreshed, handled, errHome := helps.RefreshAuthViaHome(ctx, e.cfg, auth); handled {
if errHome != nil {
return nil, errHome
}
if errContinuity := verifyAntigravityHomeRefreshContinuity(expectedGrant, expectedAccessTokenSHA256, refreshed); errContinuity != nil {
return nil, errContinuity
}
e.invalidateAICodeAccessToken(auth, "")
e.invalidateAICodeAccessToken(refreshed, "")
return refreshed, nil
}
if auth == nil {
return auth, nil
}
updated, errRefresh := e.refreshToken(ctx, auth.Clone(), ctx)
if errRefresh != nil {
return nil, errRefresh
}
return updated, nil
}
func (e *AntigravityExecutor) resolveAntigravityAICodeSnapshotSelection(ctx context.Context, auth *cliproxyauth.Auth) cliproxyauth.AntigravityModelSelection {
var selection cliproxyauth.AntigravityModelSelection
if auth == nil {
return selection
}
meta, ok := cliproxyauth.LookupAntigravityAICodeSnapshot(ctx, auth)
if !ok {
return selection
}
if e != nil && e.cfg != nil && meta.RouteFingerprint != "" {
if expectedFP := cliproxyauth.AntigravitySnapshotRouteFingerprint(auth, e.cfg); expectedFP != "" && meta.RouteFingerprint != expectedFP {
return selection
}
}
selection.AICodeSurfaceConfig = meta.SurfaceConfig
selection.AICodeUserTier = meta.UserTier
selection.AICodeExperimentFlags = meta.ExperimentFlags
selection.AICodeJetskiEnabled = meta.ExperimentFlags[cliproxyauth.AntigravityAICodeFlagUseJetskiEndpoint]
selection.AICodeTrafficMigrationEnabled = meta.ExperimentFlags[cliproxyauth.AntigravityAICodeFlagEnableInferenceTrafficMigration]
selection.AICodePreprodEnabled = meta.ExperimentFlags[cliproxyauth.AntigravityAICodeFlagUsePreprodEndpoint]
selection.AICodeFlagsLoaded = meta.FlagsLoaded
return selection
}
func (e *AntigravityExecutor) ShouldPrepareRequestAuth(auth *cliproxyauth.Auth) bool {
if auth == nil {
return false
}
if antigravityProjectIDFromAuth(auth) != "" {
return false
}
// v1alpha AICode requests do not require legacy project_id discovery; defer
// loadCodeAssist until a request actually executes on or falls back to v1internal.
if e != nil {
selection := e.resolveAntigravityAICodeSnapshotSelection(context.Background(), auth)
if _, wantAICode, usePreprod := resolveAntigravityAICodeTarget(e.cfg, auth, selection); wantAICode &&
antigravityHasAICodeInferenceEntitlement(auth, selection, usePreprod) &&
!e.isInAICodeScopeCooldown(auth, antigravityNow()) &&
!e.isAICodeLocationBlocked(auth) &&
(strings.TrimSpace(metaStringValue(auth.Metadata, "refresh_token")) != "" ||
(e.resolveHomeAICodeTokenFetcher() != nil && antigravityAuthIndex(auth) != "" &&
(antigravityHomeGrantScope(auth) != "" || strings.TrimSpace(cliproxyauth.AccessTokenSHA256(auth)) != ""))) {
return false
}
}
return true
}
func (e *AntigravityExecutor) ShouldPrepareHomePluginRequestAuth(auth *cliproxyauth.Auth) bool {
return e.ShouldPrepareRequestAuth(auth) || (e.cfg != nil && e.cfg.Home.Enabled && antigravityNeedsAccessTokenRefresh(auth))
}
func antigravityNeedsAccessTokenRefresh(auth *cliproxyauth.Auth) bool {
if auth == nil {
return false
}
accessToken := metaStringValue(auth.Metadata, "access_token")
if accessToken == "" {
return true
}
expiry, _ := auth.ExpirationTime()
return !expiry.After(antigravityNow().Add(antigravityRequestTokenSafetyWindow))
}
// detachedAntigravityCredentialContext preserves non-cancellation context
// values (such as transport decorators and injected round trippers) while
// detaching caller cancellation and stripping execution-scoped request proxy
// overrides so credential refresh and credential-wide metadata stay on the
// credential or global proxy.
func detachedAntigravityCredentialContext(ctx context.Context) context.Context {
if ctx == nil {
return context.Background()
}
return cliproxyexecutor.WithoutRequestProxyURL(context.WithoutCancel(ctx))
}
func (e *AntigravityExecutor) PrepareRequestAuth(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
if !e.ShouldPrepareHomePluginRequestAuth(auth) {
return nil, nil
}
updated := auth.Clone()
token, refreshedAuth, refreshedLocal, errToken := e.ensureAccessTokenWithOptions(ctx, updated, false)
if errToken != nil {
return nil, errToken
}
if refreshedAuth != nil {
updated = refreshedAuth
}
if e.cfg != nil && e.cfg.Home.Enabled {
if expiry, known := updated.ExpirationTime(); known && !expiry.After(antigravityNow()) {
return nil, statusErr{code: http.StatusBadGateway, msg: "home returned an expired antigravity access token"}
}
}
if antigravityProjectIDFromAuth(updated) != "" {
e.maybeRefreshAntigravityCreditsHint(ctx, updated, token)
return updated, nil
}
projectID, paidTierID, errProject := e.fetchAntigravityProjectIDWithTier(ctx, updated, token)
if errProject != nil {
var upstreamErr *antigravity.HTTPStatusError
if errors.As(errProject, &upstreamErr) {
cliproxyauth.ReportHomeAuthPreparationFailure(ctx, updated, upstreamErr.StatusCode(), upstreamErr.ResponseBody())
}
if ctx != nil && ctx.Err() != nil && antigravityStatusCodeFromError(errProject) == 0 {
return nil, errProject
}
preparedErr := prepareAntigravityProjectIDError(errProject)
if preparedErr.tosViolation {
closeAntigravityAuthIdleTransports(updated)
e.applyAntigravityTOSState(e.cfg, updated, antigravityResponseBodyFromError(errProject))
} else if preparedErr.code == http.StatusForbidden && cliproxyauth.IsAntigravityValidationRequiredError(preparedErr) {
closeAntigravityAuthIdleTransports(updated)
}
return nil, preparedErr
}
if projectID == "" {
return nil, prepareAntigravityProjectIDError(nil)
}
if updated.Metadata == nil {
updated.Metadata = make(map[string]any)
}
updated.Metadata["project_id"] = projectID
if paidTierID != "" {
updated.Metadata["paid_tier"] = paidTierID
}
if refreshedLocal {
e.queueAntigravityCreditsRefresh(detachedAntigravityCredentialContext(ctx), updated, token, 0)
} else {
e.maybeRefreshAntigravityCreditsHint(ctx, updated, token)
}
return updated, nil
}
func (e *AntigravityExecutor) ensureAccessToken(ctx context.Context, auth *cliproxyauth.Auth) (string, *cliproxyauth.Auth, error) {
token, updated, _, errToken := e.ensureAccessTokenWithOptions(ctx, auth, true)
return token, updated, errToken
}
func (e *AntigravityExecutor) ensureAccessTokenWithOptions(ctx context.Context, auth *cliproxyauth.Auth, discoverProject bool) (string, *cliproxyauth.Auth, bool, error) {
if auth == nil {
return "", nil, false, statusErr{code: http.StatusUnauthorized, msg: "missing auth", credentialScoped: true}
}
if !antigravityNeedsAccessTokenRefresh(auth) {
accessToken := metaStringValue(auth.Metadata, "access_token")
if discoverProject {
e.maybeRefreshAntigravityCreditsHint(ctx, auth, accessToken)
}
return accessToken, nil, false, nil
}
expectedGrant := antigravityHomeGrantScope(auth)
expectedAccessTokenSHA256 := strings.TrimSpace(cliproxyauth.AccessTokenSHA256(auth))
var refreshedLocal bool
var refreshedViaHome bool
updated, errRefresh := cliproxyauth.RefreshExecutionAuth(ctx, auth, func(callCtx context.Context, latest *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
if !antigravityNeedsAccessTokenRefresh(latest) {
if e.cfg != nil && e.cfg.Home.Enabled {
if errContinuity := verifyAntigravityHomeRefreshContinuity(expectedGrant, expectedAccessTokenSHA256, latest); errContinuity != nil {
return nil, errContinuity
}
}
return nil, nil
}
refreshCtx := detachedAntigravityCredentialContext(callCtx)
if refreshed, handled, errHome := helps.RefreshAuthViaHome(refreshCtx, e.cfg, latest); handled {
if errHome != nil {
return nil, errHome
}
if errContinuity := verifyAntigravityHomeRefreshContinuity(expectedGrant, expectedAccessTokenSHA256, refreshed); errContinuity != nil {
return nil, errContinuity
}
token := metaStringValue(refreshed.Metadata, "access_token")
if strings.TrimSpace(token) == "" {
return nil, statusErr{code: http.StatusUnauthorized, msg: "missing access token", credentialScoped: true}
}
refreshedViaHome = true
if discoverProject {
e.maybeRefreshAntigravityCreditsHint(callCtx, refreshed, token)
}
return refreshed, nil
}
refreshed, errToken := e.refreshTokenWithOptions(refreshCtx, latest.Clone(), callCtx, discoverProject)
if errToken != nil {
return nil, errToken
}
refreshedLocal = true
return refreshed, nil
})
if errRefresh != nil {
return "", nil, false, errRefresh
}
if updated == nil {
accessToken := metaStringValue(auth.Metadata, "access_token")
if discoverProject {
e.maybeRefreshAntigravityCreditsHint(ctx, auth, accessToken)
}
return accessToken, nil, false, nil
}
if e.cfg != nil && e.cfg.Home.Enabled {
if errContinuity := verifyAntigravityHomeRefreshContinuity(expectedGrant, expectedAccessTokenSHA256, updated); errContinuity != nil {
return "", nil, false, errContinuity
}
}
token := metaStringValue(updated.Metadata, "access_token")
if strings.TrimSpace(token) == "" {
return "", nil, false, statusErr{code: http.StatusUnauthorized, msg: "missing access token", credentialScoped: true}
}
if discoverProject && !refreshedLocal && !refreshedViaHome {
e.maybeRefreshAntigravityCreditsHint(ctx, updated, token)
}
return token, updated, refreshedLocal, nil
}
func antigravityBearerTokenFromRequest(req *http.Request) string {
if req == nil {
return ""
}
authHeader := strings.TrimSpace(req.Header.Get("Authorization"))
if len(authHeader) >= len("Bearer ") && strings.EqualFold(authHeader[:len("Bearer ")], "Bearer ") {
return strings.TrimSpace(authHeader[len("Bearer "):])
}
return ""
}
// readAntigravityErrorResponseBody drains and closes an upstream error response
// body. Every HTTP 401 response (both initial and final) reads strictly at most
// antigravity401MaxErrorBodyBytes (4096 bytes), and all other non-2xx error
// responses read at most antigravityMaxErrorBodyBytes (1 MiB) so oversized
// bodies cannot exhaust memory. Hitting the active cap conservatively reports
// truncated=true unless resp.ContentLength positively confirms an exact match.
func readAntigravityErrorResponseBody(resp *http.Response) (bodyBytes []byte, truncated bool, errRead error) {
if resp == nil || resp.Body == nil {
return nil, false, nil
}
if resp.StatusCode == http.StatusUnauthorized {
bodyBytes, errRead = io.ReadAll(io.LimitReader(resp.Body, antigravity401MaxErrorBodyBytes))
if len(bodyBytes) == antigravity401MaxErrorBodyBytes &&
resp.ContentLength != antigravity401MaxErrorBodyBytes {
truncated = true
}
} else {
bodyBytes, errRead = io.ReadAll(io.LimitReader(resp.Body, antigravityMaxErrorBodyBytes))
if len(bodyBytes) == antigravityMaxErrorBodyBytes &&
resp.ContentLength != antigravityMaxErrorBodyBytes {
truncated = true
}
}
if errClose := resp.Body.Close(); errClose != nil {
log.Errorf("antigravity executor: close response body error: %v", errClose)
}
return bodyBytes, truncated, errRead
}
func isJSONMediaType(contentType string) bool {
contentType = strings.TrimSpace(contentType)
if contentType == "" {
return false
}
mediaType, _, errParse := mime.ParseMediaType(contentType)
if errParse != nil {
mediaType, _, _ = strings.Cut(contentType, ";")
}
mediaType = strings.ToLower(strings.TrimSpace(mediaType))
return mediaType == "application/json" ||
mediaType == "text/json" ||
strings.HasSuffix(mediaType, "+json")
}
// isAntigravity401UnsafeUnclassified reports whether a 401 error body cannot be
// safely inspected or confirmed as a refreshable auth-token failure (either it
// hit/exceeded the 4096-byte read budget or is malformed JSON).
func isAntigravity401UnsafeUnclassified(contentType string, body []byte, truncated bool) bool {
if truncated {
return true
}
if len(body) == 0 {
return false
}
if isJSONMediaType(contentType) {
return !ojson.ValidBytes(body)
}
trimmed := bytes.TrimSpace(body)
if len(trimmed) == 0 {
return false
}
if trimmed[0] == '{' || trimmed[0] == '[' {
return !ojson.ValidBytes(body)
}
return false
}
func (e *AntigravityExecutor) shouldAttemptAntigravity401RefreshRetry(ctx context.Context, auth *cliproxyauth.Auth, contentType string, body []byte, truncated bool) bool {
if auth == nil || (ctx != nil && ctx.Err() != nil) {
return false
}
if isAntigravity401UnsafeUnclassified(contentType, body, truncated) {
return false
}
// Match Manager's rule semantics: any configured request-scoped error rule
// (stop, stop-and-cooldown, continue, continue-and-cooldown) owns the 401.
if e.matchesAnyRequestScopedErrorRule(ctx, auth, http.StatusUnauthorized, body) {
return false
}
if reason, policyCredTerm, policyReqTerm := parseAntigravityPolicyErrorForStatus(http.StatusUnauthorized, body); (policyCredTerm || policyReqTerm) && reason != "ACCESS_TOKEN_EXPIRED" {
return false
}
return true
}
func annotateAntigravityUnauthorizedError(err error, statusCode int, retried401, usingAICode bool, contentType string, body []byte, bodyTruncated bool) error {
if err == nil || statusCode != http.StatusUnauthorized {
return err
}
var sErr statusErr
if errors.As(err, &sErr) {
if retried401 {
sErr.unauthorizedRefreshAttempted = true
}
if usingAICode {
sErr.alternateTokenUnauthorized = true
}
if isAntigravity401UnsafeUnclassified(contentType, body, bodyTruncated) {
sErr.unclassifiedUnauthorized = true
sErr.credentialScoped = false
}
return sErr
}
return err
}
func transientAntigravity401RefreshError(err error) (error, bool) {
if err == nil {
return nil, false
}
code := antigravityStatusCodeFromError(err)
if code != http.StatusRequestTimeout && code != http.StatusTooManyRequests {
return nil, false
}
return err, true
}
// forceRefreshAntigravityTokenOn401 invalidates the failed access token and
// performs a singleflight force-refresh on the same credential (matching Hub
// 2.36.0 (*oauthTransport).RoundTrip @ 0x142d54bc0) across both v1internal
// and v1alpha (aicode) paths. It commits any rotated refresh_token before
// rejecting identical access tokens via constant-time comparison so callers
// never lose a rotated refresh token and never replay with the rejected bearer.
func (e *AntigravityExecutor) forceRefreshAntigravityTokenOn401(ctx context.Context, auth *cliproxyauth.Auth, usingAICode bool, rejectedToken string) (string, *cliproxyauth.Auth, error) {
if auth == nil {
return "", nil, statusErr{code: http.StatusUnauthorized, msg: "missing auth", credentialScoped: true}
}
rejectedToken = strings.TrimSpace(rejectedToken)
if usingAICode {
tok, errAI := e.ensureAICodeAccessTokenWithRejected(ctx, auth, rejectedToken)
return tok, nil, errAI
}
expectedGrant := antigravityHomeGrantScope(auth)
expectedAccessTokenSHA256 := strings.TrimSpace(cliproxyauth.AccessTokenSHA256(auth))
var reusedAuth *cliproxyauth.Auth
updated, errRefresh := cliproxyauth.RefreshExecutionAuth(ctx, auth, func(callCtx context.Context, latest *cliproxyauth.Auth) (*cliproxyauth.Auth, error) {
latestToken := strings.TrimSpace(metaStringValue(latest.Metadata, "access_token"))
if latestToken != "" && rejectedToken != "" && subtle.ConstantTimeCompare([]byte(latestToken), []byte(rejectedToken)) != 1 && !antigravityNeedsAccessTokenRefresh(latest) {
if e.cfg != nil && e.cfg.Home.Enabled {
if errContinuity := verifyAntigravityHomeRefreshContinuity(expectedGrant, expectedAccessTokenSHA256, latest); errContinuity != nil {
return nil, errContinuity
}
}
reusedAuth = latest.Clone()
return nil, nil
}
refreshCtx := detachedAntigravityCredentialContext(callCtx)
if refreshed, handled, errHome := helps.RefreshAuthViaHome(refreshCtx, e.cfg, latest); handled {
if errHome != nil {
return nil, errHome
}
if errContinuity := verifyAntigravityHomeRefreshContinuity(expectedGrant, expectedAccessTokenSHA256, refreshed); errContinuity != nil {
return nil, errContinuity
}
if strings.TrimSpace(metaStringValue(refreshed.Metadata, "access_token")) == "" {
return nil, statusErr{code: http.StatusUnauthorized, msg: "missing access token", credentialScoped: true}
}
// Return refreshed Auth even if access_token is unchanged so any
// rotated refresh_token/metadata is persisted before rejecting replay.
return refreshed, nil
}
refreshed, errToken := e.refreshTokenWithOptions(refreshCtx, latest.Clone(), callCtx, false)
if errToken != nil {
return nil, errToken
}
if strings.TrimSpace(metaStringValue(refreshed.Metadata, "access_token")) == "" {
return nil, statusErr{code: http.StatusUnauthorized, msg: "missing access token", credentialScoped: true}
}
// Commit any rotated refresh_token before checking access_token equality.
return refreshed, nil
})
if errRefresh != nil {
return "", nil, errRefresh
}
if updated == nil {
updated = reusedAuth
}
if updated == nil {
return "", nil, errAntigravity401UnchangedToken
}
if e.cfg != nil && e.cfg.Home.Enabled {
if errContinuity := verifyAntigravityHomeRefreshContinuity(expectedGrant, expectedAccessTokenSHA256, updated); errContinuity != nil {
return "", nil, errContinuity
}
}
newToken := strings.TrimSpace(metaStringValue(updated.Metadata, "access_token"))
if newToken == "" {
return "", nil, statusErr{code: http.StatusUnauthorized, msg: "missing access token", credentialScoped: true}
}
if rejectedToken != "" && subtle.ConstantTimeCompare([]byte(newToken), []byte(rejectedToken)) == 1 {
return "", updated, errAntigravity401UnchangedToken
}
return newToken, updated, nil
}
func (e *AntigravityExecutor) refreshToken(ctx context.Context, auth *cliproxyauth.Auth, requestCtx context.Context) (*cliproxyauth.Auth, error) {
return e.refreshTokenWithOptions(ctx, auth, requestCtx, true)
}
func antigravityRefreshSingleFlightKey(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, refreshToken string) string {
baseKey := "refresh:" + sha256HexTokenFingerprint(refreshToken)
if auth != nil && auth.RegistrationEpoch != 0 {
baseKey += fmt.Sprintf("|epoch:%d", auth.RegistrationEpoch)
}
proxyURL := strings.TrimSpace(antigravityProxyURL(ctx, cfg, auth))
if proxyURL == "" {
return baseKey + "|proxy:direct"
}
if setting, errParse := proxyutil.Parse(proxyURL); errParse == nil {
switch setting.Mode {
case proxyutil.ModeDirect:
return baseKey + "|proxy:explicit-direct"
case proxyutil.ModeProxy:
if setting.URL != nil {
proxyURL = setting.URL.String()
}
}
}
return baseKey + "|proxy:" + sha256HexTokenFingerprint(proxyURL)
}
func (e *AntigravityExecutor) refreshTokenWithOptions(ctx context.Context, auth *cliproxyauth.Auth, requestCtx context.Context, discoverProject bool) (*cliproxyauth.Auth, error) {
if auth == nil {
return nil, statusErr{code: http.StatusUnauthorized, msg: "missing auth", credentialScoped: true}
}
refreshToken := strings.TrimSpace(metaStringValue(auth.Metadata, "refresh_token"))
if refreshToken == "" {
return auth, statusErr{code: http.StatusUnauthorized, msg: "missing refresh token", credentialScoped: true}
}
if auth.RequiresSignIn && auth.RejectedRefreshToken == refreshToken && !cliproxyauth.IsForceRefreshContext(ctx) {
return auth, statusErr{code: http.StatusUnauthorized, msg: "antigravity: OAuth sign-in required", terminalUnauthorized: true}
}
if ctx == nil {
ctx = context.Background()
}
ctx = cliproxyexecutor.WithoutRequestProxyURL(ctx)
flightKey := antigravityRefreshSingleFlightKey(ctx, e.cfg, auth, refreshToken)
result, errRefresh, _ := antigravityRefreshGroup.Do(flightKey, func() (interface{}, error) {
// A caller may leave, but shared credential acquisition must still be bounded.
refreshCtx, cancelRefresh := context.WithTimeout(context.WithoutCancel(ctx), antigravityCredentialAcquisitionTimeout)
defer cancelRefresh()
return e.refreshTokenSingleFlight(refreshCtx, auth, refreshToken)
})
if errRefresh != nil {
// Any error returned by the shared flight came from the real OAuth HTTP
// call inside the closure (local missing-credential checks return above,
// before the group call). Attribute it as an upstream attempt on THIS
// request's tracker so concurrent callers sharing the flight each record
// the upstream failure on their own tracker, not just the leader's.
cliproxyexecutor.MarkUpstreamAttempt(requestCtx)
return auth, errRefresh
}
tokenResp, ok := result.(*antigravityTokenRefreshData)
if !ok || tokenResp == nil {
return auth, fmt.Errorf("antigravity token refresh failed: invalid single-flight result")
}
accessToken := strings.TrimSpace(tokenResp.AccessToken)
if accessToken == "" {
return auth, statusErr{
code: http.StatusUnauthorized,
msg: "antigravity token refresh returned empty access_token",
credentialScoped: true,
}
}
expiresIn := tokenResp.ExpiresIn
if expiresIn <= 0 {
return auth, statusErr{
code: http.StatusUnauthorized,
msg: "antigravity token refresh returned non-positive expires_in",
credentialScoped: true,
}
}
if expiresIn > antigravityAICodeMaxExpiresInSeconds {
expiresIn = antigravityAICodeMaxExpiresInSeconds
}
rotatedRefreshToken := strings.TrimSpace(tokenResp.RefreshToken)
// Clear any cached downscoped aicode token under both the pre-refresh and
// post-refresh grant keys so a broad OAuth refresh cannot leave a stale
// aicode token cached under an unchanged refresh_token.
e.invalidateAICodeAccessToken(auth, "")
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
grantIdentity := prepareAntigravitySignatureGrantForRefresh(auth)
auth.Metadata["access_token"] = accessToken
if rotatedRefreshToken != "" {
auth.Metadata["refresh_token"] = rotatedRefreshToken
}
finalizeAntigravitySignatureGrantAfterRefresh(auth, grantIdentity)
e.invalidateAICodeAccessToken(auth, "")
auth.Metadata["expires_in"] = expiresIn
mintedAt := tokenResp.requestedAt
if mintedAt.IsZero() {
mintedAt = antigravityNow()
}
auth.Metadata["timestamp"] = mintedAt.UnixMilli()
auth.Metadata["expired"] = mintedAt.Add(time.Duration(expiresIn) * time.Second).Format(time.RFC3339)
auth.Metadata["type"] = antigravityAuthType
if discoverProject && !isAntigravityAuthDisabled(auth) {
if errProject := e.ensureAntigravityProjectID(ctx, auth, accessToken); errProject != nil {
log.Warnf("antigravity executor: ensure project id failed: %v", errProject)
}
e.queueAntigravityCreditsRefresh(ctx, auth, accessToken, 0)
}
return auth, nil
}
func prepareAntigravitySignatureGrantForRefresh(auth *cliproxyauth.Auth) string {
if auth == nil {
return ""
}
grantIdentity := antigravitySignatureGrantIdentity(auth)
if !antigravityHasValidSignatureGrant(auth) {
delete(auth.Metadata, antigravitySignatureGrantScopeMetadataKey)
delete(auth.Metadata, antigravitySignatureGrantHomeBindingMetadataKey)
} else if grantIdentity != "" {
auth.Metadata[antigravitySignatureGrantScopeMetadataKey] = grantIdentity
}
return grantIdentity
}
func finalizeAntigravitySignatureGrantAfterRefresh(auth *cliproxyauth.Auth, grantIdentity string) {
if auth == nil {
return
}
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
binding := antigravitySignatureGrantBinding(auth)
if retained := strings.TrimSpace(metaStringValue(auth.Metadata, antigravitySignatureGrantScopeMetadataKey)); retained != "" {
auth.Metadata[antigravitySignatureGrantBindingMetadataKey] = binding
return
}
if grantIdentity != "" {
auth.Metadata[antigravitySignatureGrantScopeMetadataKey] = grantIdentity
auth.Metadata[antigravitySignatureGrantBindingMetadataKey] = binding
}
}
// verifyAntigravityHomeRefreshContinuity ensures a Home refresh result still
// belongs to the originally dispatched credential identity (matching grant
// identity, or matching non-empty access_token SHA-256 when grant-less) so
// replacing an auth_index with a different account requires re-dispatch rather
// than silently mutating the active credential.
func verifyAntigravityHomeRefreshContinuity(expectedGrant, expectedAccessTokenSHA256 string, refreshed *cliproxyauth.Auth) error {
if refreshed == nil {
return statusErr{
code: http.StatusUnauthorized,
msg: "antigravity home refresh returned empty credential; re-dispatch required",
credentialScoped: true,
}
}
expectedGrant = strings.TrimSpace(expectedGrant)
refreshedGrant := antigravityHomeGrantScope(refreshed)
if expectedGrant != "" {
if refreshedGrant == "" || subtle.ConstantTimeCompare([]byte(refreshedGrant), []byte(expectedGrant)) != 1 {
return statusErr{
code: http.StatusUnauthorized,
msg: "antigravity home refresh grant mismatch; re-dispatch required",
credentialScoped: true,
}
}
return nil
}
if refreshedGrant != "" {
return statusErr{
code: http.StatusUnauthorized,
msg: "antigravity home refresh unexpected grant identity; re-dispatch required",
credentialScoped: true,
}
}
expectedAccessTokenSHA256 = strings.TrimSpace(expectedAccessTokenSHA256)
refreshedAccessTokenSHA256 := strings.TrimSpace(cliproxyauth.AccessTokenSHA256(refreshed))
if expectedAccessTokenSHA256 == "" || refreshedAccessTokenSHA256 == "" ||
subtle.ConstantTimeCompare([]byte(refreshedAccessTokenSHA256), []byte(expectedAccessTokenSHA256)) != 1 {
return statusErr{
code: http.StatusUnauthorized,
msg: "antigravity home refresh access token digest mismatch; re-dispatch required",
credentialScoped: true,
}
}
return nil
}
func (e *AntigravityExecutor) refreshTokenSingleFlight(ctx context.Context, auth *cliproxyauth.Auth, refreshToken string) (*antigravityTokenRefreshData, error) {
form := url.Values{}
form.Set("client_id", antigravityClientID)
form.Set("client_secret", antigravityClientSecret)
form.Set("grant_type", "refresh_token")
form.Set("refresh_token", refreshToken)
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodPost, "https://oauth2.googleapis.com/token", strings.NewReader(form.Encode()))
if errReq != nil {
return nil, errReq
}
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
// Leave User-Agent unset so net/http emits Go-http-client/2.0 on HTTP/2
// and Go-http-client/1.1 on HTTP/1.1, matching the negotiated wire protocol.
httpClient, cleanup := newAntigravityOAuthHTTPClient(ctx, e.cfg, auth, 0)
defer cleanup()
reqStart := antigravityNow()
httpResp, errDo := helps.WithAntigravityHTTPClientTrace(httpClient, auth, "oauth_refresh").Do(httpReq)
if errDo != nil {
return nil, errDo
}
defer func() {
if errClose := httpResp.Body.Close(); errClose != nil {
log.Errorf("antigravity executor: close response body error: %v", errClose)
}
}()
bodyBytes, errRead := io.ReadAll(io.LimitReader(httpResp.Body, antigravityOAuthTokenMaxResponseBytes+1))
if errRead != nil {
return nil, errRead
}
if len(bodyBytes) > antigravityOAuthTokenMaxResponseBytes {
return nil, statusErr{
code: http.StatusBadGateway,
msg: "antigravity token refresh response exceeded size limit",
credentialScoped: true,
}
}
if httpResp.StatusCode < http.StatusOK || httpResp.StatusCode >= http.StatusMultipleChoices {
// Token refresh failures are credential-scoped unless a request-terminal
// policy detail overrides scope; classify raw bounded policy metadata
// before building the strictly allowlisted and redacted public message.
fallbackMsg := fmt.Sprintf("antigravity token refresh failed with status %d", httpResp.StatusCode)
return nil, newAntigravityOAuthStatusErr(httpResp.StatusCode, httpResp.Header, bodyBytes, fallbackMsg)
}
if rpcErr, hasRPC := antigravity.ParseGoogleInBandRPCError(bodyBytes); hasRPC {
mappedCode := antigravity.MapGoogleRPCErrorToHTTPCode(rpcErr.Code, rpcErr.Status, rpcErr.IsScopeInsufficient)
return nil, newAntigravityOAuthStatusErr(mappedCode, httpResp.Header, bodyBytes, "antigravity token refresh returned in-band error")
}
var tokenResp antigravityTokenRefreshData
if errUnmarshal := json.Unmarshal(bodyBytes, &tokenResp); errUnmarshal != nil {
return nil, errUnmarshal
}
tokenResp.AccessToken = strings.TrimSpace(tokenResp.AccessToken)
if tokenResp.AccessToken == "" {
return nil, statusErr{
code: http.StatusBadGateway,
msg: "antigravity token refresh returned empty access_token",
credentialScoped: true,
}
}
if tokenResp.ExpiresIn <= 0 {
return nil, statusErr{
code: http.StatusBadGateway,
msg: "antigravity token refresh returned non-positive expires_in",
credentialScoped: true,
}
}
if tokenResp.ExpiresIn > antigravityAICodeMaxExpiresInSeconds {
tokenResp.ExpiresIn = antigravityAICodeMaxExpiresInSeconds
}
tokenResp.RefreshToken = strings.TrimSpace(tokenResp.RefreshToken)
tokenResp.requestedAt = reqStart
return &tokenResp, nil
}
// newAntigravityOAuthStatusErr extracts internal Antigravity policy
// classification (TOS_VIOLATION + appeal metadata, VALIDATION_REQUIRED,
// AI_POLICY_REQUIRED, and terminal account/billing reasons) from the raw
// bounded OAuth response body BEFORE formatting a strictly allowlisted and
// secret-redacted public statusErr.msg.
func newAntigravityOAuthStatusErr(statusCode int, headers http.Header, body []byte, fallbackMsg string) statusErr {
sErr := statusErr{
code: statusCode,
credentialScoped: true,
}
if statusCode == http.StatusTooManyRequests || statusCode == http.StatusRequestTimeout || statusCode == http.StatusServiceUnavailable {
sErr.retryAfter = antigravity.ParseRetryAfterHeaders(headers, antigravityNow())
if sErr.retryAfter == nil {
sErr.retryAfter, _ = helps.ParseRetryDelay(body)
}
}
if terminal := antigravity.ParseTerminalOAuthGrantError(statusCode, body); terminal != "" {
sErr.code = http.StatusUnauthorized
sErr.cause = terminal
sErr.msg = terminal.Error()
sErr.terminalUnauthorized = true
return sErr
}
if statusCode == http.StatusForbidden {
if violation := parseAntigravityTOSViolationForStatus(statusCode, body); violation != nil {
sErr.tosViolation = true
sErr.credentialScoped = true
sErr.requestStop = true
sErr.tosAppealURL = violation.AppealURL
sErr.tosAppealURLText = violation.AppealURLText
} else if cliproxyauth.IsAntigravityValidationRequiredError(statusErr{code: statusCode, msg: string(body)}) {
sErr.validationRequired = true
sErr.credentialScoped = true
}
}
if !sErr.tosViolation {
if reason, credentialTerminal, requestTerminal := parseAntigravityPolicyErrorForStatus(statusCode, body); reason != "" {
if statusCode == http.StatusUnauthorized && credentialTerminal && !requestTerminal && reason != "ACCESS_TOKEN_EXPIRED" {
sErr.terminalUnauthorized = true
}
if credentialTerminal {
sErr.credentialScoped = true
}
if requestTerminal {
sErr.requestStop = true
if !credentialTerminal {
sErr.requestScoped = true
sErr.credentialScoped = false
}
}
}
}
errMsg := antigravity.FormatOAuthErrorBody(body)
if errMsg == "" {
errMsg = strings.TrimSpace(fallbackMsg)
if errMsg == "" {
if statusText := http.StatusText(statusCode); statusText != "" {
errMsg = statusText
} else {
errMsg = "oauth error"
}
}
}
sErr.msg = errMsg
return sErr
}
// newAntigravityOAuthHTTPClient creates an isolated per-refresh HTTP/1.1
// no-ALPN client for Antigravity OAuth token refresh on oauth2.googleapis.com,
// matching native Antigravity Hub 2.35.2's withCloudCodeOAuthHTTPClient.
// Any resolved *http.Transport is cloned with HTTP/2 disabled, ALPN omitted,
// and MaxIdleConnsPerHost=-1 so distinct credentials never share a TCP/TLS
// connection and one-off refreshes do not retain idle sockets.
func newAntigravityOAuthHTTPClient(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, timeout time.Duration) (clientOut *http.Client, cleanup func()) {
cleanup = func() {}
defer func() { clientOut = httptransport.Decorate(ctx, clientOut) }()
client := helps.NewProxyAwareHTTPClient(httptransport.WithoutDecorator(ctx), cfg, auth, timeout)
var base *http.Transport
if client.Transport != nil {
transport, ok := client.Transport.(*http.Transport)
if !ok {
// A custom non-*http.Transport RoundTripper owns its own protocol behavior.
return client, cleanup
}
base = transport
}
if base == nil {
if antigravityBaseTransport != nil && antigravityBaseTransport != antigravityInitialBaseTransport {
base = antigravityBaseTransport
} else if defaultTransport, okDefault := http.DefaultTransport.(*http.Transport); okDefault && defaultTransport != nil {
base = defaultTransport
} else if http.DefaultTransport != nil && !okDefault {
// Preserve a custom non-*http.Transport installed on http.DefaultTransport.
client.Transport = nil
return client, cleanup
}
}
var owned *http.Transport
if base != nil {
owned = cloneTransportWithHTTP11(base)
} else {
var protocols http.Protocols
protocols.SetHTTP1(true)
owned = &http.Transport{
Protocols: &protocols,
ForceAttemptHTTP2: false,
TLSNextProto: make(map[string]func(authority string, c *tls.Conn) http.RoundTripper),
TLSClientConfig: &tls.Config{NextProtos: nil},
}
}
owned.MaxIdleConnsPerHost = -1
client.Transport = owned
cleanup = owned.CloseIdleConnections
return client, cleanup
}
// newAntigravityProjectDiscoveryHTTPClient clones the credential's HTTP/1.1
// Antigravity transport into an isolated per-discovery client whose cleanup
// closes idle sockets and cancels abandoned in-flight dials (such as a stalled
// SOCKS5 handshake after net/http.Transport.getConn detaches req.Context())
// without disturbing the credential's shared connection pool.
func newAntigravityProjectDiscoveryHTTPClient(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth) (clientOut *http.Client, cleanup func()) {
cleanup = func() {}
defer func() { clientOut = httptransport.Decorate(ctx, clientOut) }()
client := newAntigravityHTTPClient(httptransport.WithoutDecorator(ctx), cfg, auth, 0)
if client == nil {
return &http.Client{}, cleanup
}
transport, ok := client.Transport.(*http.Transport)
if !ok || transport == nil {
return client, cleanup
}
owned := transport.Clone()
owned.MaxIdleConnsPerHost = -1
clone := *client
clone.Transport = owned
cleanup = owned.CloseIdleConnections
return &clone, cleanup
}
func (e *AntigravityExecutor) ensureAntigravityProjectID(ctx context.Context, auth *cliproxyauth.Auth, accessToken string) error {
if isAntigravityAuthDisabled(auth) {
return nil
}
if antigravityProjectIDFromAuth(auth) != "" {
return nil
}
projectID, paidTierID, errFetch := e.fetchAntigravityProjectIDWithTier(ctx, auth, accessToken)
if errFetch != nil {
return errFetch
}
if projectID == "" {
return nil
}
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
auth.Metadata["project_id"] = projectID
if paidTierID != "" {
auth.Metadata["paid_tier"] = paidTierID
}
return nil
}
func (e *AntigravityExecutor) fetchAntigravityProjectID(ctx context.Context, auth *cliproxyauth.Auth, accessToken string) (string, error) {
projectID, _, errFetch := e.fetchAntigravityProjectIDWithTier(ctx, auth, accessToken)
return projectID, errFetch
}
func (e *AntigravityExecutor) fetchAntigravityProjectIDWithTier(ctx context.Context, auth *cliproxyauth.Auth, accessToken string) (string, string, error) {
token := strings.TrimSpace(accessToken)
if token == "" {
token = metaStringValue(auth.Metadata, "access_token")
}
if token == "" {
return "", "", nil
}
if ctx == nil {
ctx = context.Background()
}
// Project discovery is required credential preparation, not a generation request.
// Exclude execution-scoped request proxy overrides while preserving caller cancellation.
acquisitionCtx, cancelAcquisition := context.WithTimeout(cliproxyexecutor.WithoutRequestProxyURL(ctx), antigravityCredentialAcquisitionTimeout)
defer cancelAcquisition()
httpClient, cleanup := newAntigravityProjectDiscoveryHTTPClient(acquisitionCtx, e.cfg, auth)
defer cleanup()
tracedClient := helps.WithAntigravityHTTPClientTrace(httpClient, auth, "project_discovery")
projectID, paidTierID, errFetch := sdkAuth.FetchAntigravityProjectIDWithTier(acquisitionCtx, token, tracedClient)
if errFetch != nil {
cliproxyexecutor.MarkUpstreamAttempt(ctx)
return "", "", errFetch
}
return strings.TrimSpace(projectID), strings.TrimSpace(paidTierID), nil
}
func (e *AntigravityExecutor) projectIDForRequest(ctx context.Context, auth *cliproxyauth.Auth, accessToken string, allowLazyDiscovery bool) (string, error) {
if projectID := antigravityProjectIDFromAuth(auth); projectID != "" {
return projectID, nil
}
if !allowLazyDiscovery || auth == nil || isAntigravityAuthDisabled(auth) {
return "", missingAntigravityProjectIDError(nil)
}
return e.discoverProjectIDForV1Internal(ctx, auth, accessToken)
}
// discoverProjectIDForV1Internal lazily discovers a credential's legacy CCPA
// project_id and resolved paidTier on demand when a v1alpha-configured request
// falls back or routes to v1internal without project_id in metadata. Results
// are cached per credential identity+grant+epoch in a thread-safe LRU so pure
// v1alpha traffic triggers zero loadCodeAssist calls while fallback, multi-leg
// continuations, and subsequent tier resolution succeed end-to-end without
// mutating shared auth metadata.
func (e *AntigravityExecutor) discoverProjectIDForV1Internal(ctx context.Context, auth *cliproxyauth.Auth, accessToken string) (string, error) {
if projectID := antigravityProjectIDFromAuth(auth); projectID != "" {
return projectID, nil
}
cacheKey := antigravityAICodeCacheKey(auth)
if cacheKey != "" {
if cached, ok := aicodeLazyProjectIDCache.Get(cacheKey); ok && strings.TrimSpace(cached.projectID) != "" {
return strings.TrimSpace(cached.projectID), nil
}
}
if ctx != nil {
if errCtx := ctx.Err(); errCtx != nil {
return "", errCtx
}
}
runDiscovery := func(callCtx context.Context) (string, error) {
if cacheKey != "" {
if cached, ok := aicodeLazyProjectIDCache.Get(cacheKey); ok && strings.TrimSpace(cached.projectID) != "" {
return strings.TrimSpace(cached.projectID), nil
}
}
projectID, paidTierID, errProject := e.fetchAntigravityProjectIDWithTier(callCtx, auth, accessToken)
if errProject != nil {
var upstreamErr *antigravity.HTTPStatusError
if errors.As(errProject, &upstreamErr) {
cliproxyauth.ReportHomeAuthPreparationFailure(callCtx, auth, upstreamErr.StatusCode(), upstreamErr.ResponseBody())
}
if callCtx != nil && callCtx.Err() != nil && antigravityStatusCodeFromError(errProject) == 0 {
return "", errProject
}
preparedErr := prepareAntigravityProjectIDError(errProject)
if preparedErr.tosViolation {
closeAntigravityAuthIdleTransports(auth)
e.applyAntigravityTOSState(e.cfg, auth, antigravityResponseBodyFromError(errProject))
} else if preparedErr.code == http.StatusForbidden && cliproxyauth.IsAntigravityValidationRequiredError(preparedErr) {
closeAntigravityAuthIdleTransports(auth)
}
return "", preparedErr
}
if projectID == "" {
return "", prepareAntigravityProjectIDError(nil)
}
if cacheKey != "" {
aicodeLazyProjectIDCache.Set(cacheKey, antigravityLazyProjectEntry{
projectID: projectID,
paidTierID: paidTierID,
})
}
return projectID, nil
}
if cacheKey == "" {
return runDiscovery(ctx)
}
result, errDo, _ := aicodeProjectDiscoveryGroup.Load().Do(cacheKey, func() (any, error) {
return runDiscovery(detachedAntigravityCredentialContext(ctx))
})
if errDo != nil {
return "", errDo
}
projectID, ok := result.(string)
if !ok || strings.TrimSpace(projectID) == "" {
return "", prepareAntigravityProjectIDError(nil)
}
return strings.TrimSpace(projectID), nil
}
func antigravityProjectIDFromAuth(auth *cliproxyauth.Auth) string {
if auth == nil || auth.Metadata == nil {
return ""
}
if pid, ok := auth.Metadata["project_id"].(string); ok {
return strings.TrimSpace(pid)
}
return ""
}
func antigravityCachedLazyPaidTier(auth *cliproxyauth.Auth) string {
cacheKey := antigravityAICodeCacheKey(auth)
if cacheKey == "" {
return ""
}
if cached, ok := aicodeLazyProjectIDCache.Get(cacheKey); ok {
if currentProjectID := antigravityProjectIDFromAuth(auth); currentProjectID != "" && currentProjectID != strings.TrimSpace(cached.projectID) {
return ""
}
return strings.TrimSpace(cached.paidTierID)
}
return ""
}
func isAntigravityVerifiedPaidTier(tier string) bool {
t := strings.TrimSpace(tier)
return t != "" && !strings.EqualFold(t, "free-tier")
}
// resolveAntigravityUserTierWithSelection resolves the verified paid tier for
// AICode entitlement.userTier (Hub 2.36.0 aicodeEntitlement @ 0x142d3bee0).
// It inspects ONLY explicit paid-tier / AICode-license sources and never falls
// back to generic user_tier or current_tier.
func resolveAntigravityUserTierWithSelection(auth *cliproxyauth.Auth, selection cliproxyauth.AntigravityModelSelection) string {
if auth != nil {
if v := strings.TrimSpace(auth.Attributes["aicode_user_tier"]); isAntigravityVerifiedPaidTier(v) {
return v
}
if v := metaStringValue(auth.Metadata, "aicode_user_tier"); isAntigravityVerifiedPaidTier(v) {
return v
}
}
if tier := strings.TrimSpace(selection.AICodeUserTier); isAntigravityVerifiedPaidTier(tier) {
return tier
}
if auth != nil {
if v := metaStringValue(auth.Metadata, "paid_tier"); isAntigravityVerifiedPaidTier(v) {
return v
}
if cachedTier := antigravityCachedLazyPaidTier(auth); isAntigravityVerifiedPaidTier(cachedTier) {
return cachedTier
}
}
if helperTier := helps.AntigravityAICodeUserTierWithSelection(auth, selection); isAntigravityVerifiedPaidTier(helperTier) {
return helperTier
}
return ""
}
// antigravityHasAICodeInferenceEntitlement enforces Hub 2.36.0's paidTier.id
// hard gate before routing consumer inference to aicode v1alpha. Business /
// enterprise auth modes and businessaicode hosts bypass consumer paidTier.
func antigravityHasAICodeInferenceEntitlement(auth *cliproxyauth.Auth, selection cliproxyauth.AntigravityModelSelection, usePreprod bool) bool {
switch strings.ToLower(strings.TrimSpace(helps.AntigravityAuthMode(auth))) {
case "business_licensed_enterprise", "business_agent_platform_paygo":
return true
}
if aicodeBaseURL, _ := resolveAntigravityAICodeBaseURLWithPreprod(auth, usePreprod); helps.IsAntigravityBusinessAICodeHost(aicodeBaseURL) {
return true
}
return isAntigravityVerifiedPaidTier(resolveAntigravityUserTierWithSelection(auth, selection))
}
func missingAntigravityProjectIDError(cause error) statusErr {
msg := "antigravity auth missing project_id"
if cause == nil {
return statusErr{
code: http.StatusServiceUnavailable,
msg: msg,
credentialScoped: true,
}
}
msg = logging.RedactCredentialSecrets(fmt.Sprintf("%s: %v", msg, cause))
if errors.Is(cause, antigravity.ErrProjectIDNotFound) {
return statusErr{
code: http.StatusServiceUnavailable,
msg: msg,
cause: cause,
credentialScoped: true,
}
}
statusCode := antigravityStatusCodeFromError(cause)
if statusCode == 0 {
if isCauseCredentialScoped(cause) {
return statusErr{
code: http.StatusServiceUnavailable,
msg: msg,
cause: cause,
credentialScoped: true,
}
}
if errors.Is(cause, context.Canceled) {
return statusErr{
code: 0,
msg: msg,
cause: cause,
}
}
return statusErr{
code: 0,
msg: msg,
cause: cause,
transientTransport: true,
}
}
sErr := statusErr{
code: statusCode,
msg: msg,
cause: cause,
credentialScoped: isCauseCredentialScoped(cause),
}
type retryAfterProvider interface {
RetryAfter() *time.Duration
}
var rap retryAfterProvider
if errors.As(cause, &rap) && rap != nil {
sErr.retryAfter = rap.RetryAfter()
}
type transientRateLimitMarker interface {
IsTransientRateLimit() bool
}
var trl transientRateLimitMarker
if errors.As(cause, &trl) && trl != nil && trl.IsTransientRateLimit() {
sErr.transientRateLimit = true
}
type streamTruncatedMarker interface {
IsStreamTruncated() bool
}
var stm streamTruncatedMarker
if errors.As(cause, &stm) && stm != nil && stm.IsStreamTruncated() {
sErr.streamTruncated = true
}
responseBody := antigravityResponseBodyFromError(cause)
if statusCode == http.StatusTooManyRequests && sErr.retryAfter == nil && len(responseBody) > 0 {
if retryAfter, parseErr := helps.ParseRetryDelay(responseBody); parseErr == nil && retryAfter != nil {
sErr.retryAfter = retryAfter
}
}
preserveAntigravityCauseTOSMetadata(&sErr, cause, statusCode, responseBody)
if reason, credTerm, reqTerm := parseAntigravityPolicyErrorForStatus(statusCode, responseBody); reason != "" {
if credTerm {
sErr.credentialScoped = true
}
if reqTerm {
sErr.requestStop = true
if !credTerm {
sErr.requestScoped = true
sErr.credentialScoped = false
}
}
}
if !sErr.credentialScoped && !sErr.tosViolation {
type errorCoder interface {
ErrorCode() string
}
var ec errorCoder
if errors.As(cause, &ec) && ec != nil && strings.EqualFold(strings.TrimSpace(ec.ErrorCode()), cliproxyauth.ErrorCodeTransientTransport) {
sErr.transientTransport = true
}
}
return sErr
}
// prepareAntigravityProjectIDError wraps a project-discovery failure during
// PrepareRequestAuth. Upstream HTTP responses keep their status, error chain,
// and TOS classification as credential-scoped failures; genuinely missing
// project_id responses map to a credential-scoped 503 so broken credentials
// enter cooldown instead of halting rotation with HTTP 400; status-less
// transport/timeout failures preserve transient transport classification and
// Unwrap() without cooling healthy credentials.
func prepareAntigravityProjectIDError(cause error) statusErr {
base := missingAntigravityProjectIDError(cause)
if !base.transientTransport && (!base.requestScoped || base.tosViolation) && !errors.Is(cause, context.Canceled) {
base.credentialScoped = true
}
return base
}
func antigravityStatusCodeFromError(err error) int {
if err == nil {
return 0
}
type statusCoder interface {
StatusCode() int
}
var sc statusCoder
if errors.As(err, &sc) && sc != nil {
if code := sc.StatusCode(); code > 0 {
return code
}
}
return 0
}
func isCauseCredentialScoped(cause error) bool {
if cause == nil {
return false
}
type credentialScopedProvider interface {
IsCredentialScoped() bool
}
var csp credentialScopedProvider
if errors.As(cause, &csp) && csp != nil && csp.IsCredentialScoped() {
return true
}
type errorCoder interface {
ErrorCode() string
}
var ec errorCoder
if errors.As(cause, &ec) && ec != nil && strings.EqualFold(strings.TrimSpace(ec.ErrorCode()), cliproxyauth.ErrorCodeCredentialQuota) {
return true
}
return false
}
func preserveAntigravityCauseTOSMetadata(dst *statusErr, cause error, statusCode int, responseBody []byte) {
if dst == nil || cause == nil || statusCode != http.StatusForbidden {
return
}
type tosViolationMarker interface {
IsTerminalTOSViolation() bool
}
var tvm tosViolationMarker
if errors.As(cause, &tvm) && tvm != nil && tvm.IsTerminalTOSViolation() {
dst.tosViolation = true
dst.credentialScoped = true
dst.requestStop = true
}
type errorCoder interface {
ErrorCode() string
}
var ec errorCoder
if errors.As(cause, &ec) && ec != nil && strings.EqualFold(strings.TrimSpace(ec.ErrorCode()), "tos_violation") {
dst.tosViolation = true
dst.credentialScoped = true
dst.requestStop = true
}
type tosMetadataProvider interface {
TOSAppealMetadata() map[string]string
}
var tmp tosMetadataProvider
if errors.As(cause, &tmp) && tmp != nil {
if meta := tmp.TOSAppealMetadata(); len(meta) > 0 {
urlVal := strings.TrimSpace(meta["tos_appeal_url"])
textVal := strings.TrimSpace(meta["tos_appeal_url_text"])
if urlVal != "" || textVal != "" {
dst.tosViolation = true
dst.credentialScoped = true
dst.requestStop = true
dst.tosAppealURL = urlVal
dst.tosAppealURLText = textVal
}
}
}
var authErr *cliproxyauth.Error
if errors.As(cause, &authErr) && authErr != nil {
if strings.EqualFold(strings.TrimSpace(authErr.Code), "tos_violation") {
dst.tosViolation = true
dst.credentialScoped = true
dst.requestStop = true
}
if len(authErr.Metadata) > 0 {
if dst.tosAppealURL == "" {
dst.tosAppealURL = strings.TrimSpace(authErr.Metadata["tos_appeal_url"])
}
if dst.tosAppealURLText == "" {
dst.tosAppealURLText = strings.TrimSpace(authErr.Metadata["tos_appeal_url_text"])
}
}
}
if (!dst.tosViolation || (dst.tosAppealURL == "" && dst.tosAppealURLText == "")) && len(responseBody) > 0 {
if violation := parseAntigravityTOSViolation(responseBody); violation != nil {
dst.tosViolation = true
dst.credentialScoped = true
dst.requestStop = true
if dst.tosAppealURL == "" {
dst.tosAppealURL = violation.AppealURL
}
if dst.tosAppealURLText == "" {
dst.tosAppealURLText = violation.AppealURLText
}
}
}
}
func antigravityResponseBodyFromError(err error) []byte {
if err == nil {
return nil
}
type responseBodyProvider interface {
ResponseBody() []byte
}
var rbp responseBodyProvider
if errors.As(err, &rbp) && rbp != nil {
if body := rbp.ResponseBody(); len(body) > 0 {
return body
}
}
raw := strings.TrimSpace(err.Error())
if raw == "" {
return nil
}
idxArr := strings.IndexByte(raw, '[')
idxObj := strings.IndexByte(raw, '{')
first, second := idxArr, idxObj
if first < 0 || (second >= 0 && second < first) {
first, second = second, first
}
for _, idx := range []int{first, second} {
if idx < 0 {
continue
}
candidate := []byte(strings.TrimSpace(raw[idx:]))
if ojson.ValidBytes(candidate) {
return candidate
}
}
return nil
}
func metaStringValue(metadata map[string]any, key string) string {
if metadata == nil {
return ""
}
if v, ok := metadata[key]; ok {
switch typed := v.(type) {
case string:
return strings.TrimSpace(typed)
case []byte:
return strings.TrimSpace(string(typed))
}
}
return ""
}