From cdbda2f2dc758487e939f684ef231a82ed9dfeac Mon Sep 17 00:00:00 2001 From: Luis Pater Date: Sat, 21 Nov 2026 16:10:40 +0800 Subject: [PATCH] fix(antigravity): persist execution-time token refreshes and preserve refresh context values - Route Antigravity execution-time OAuth refreshes through a Manager refresh coordinator that serializes per-credential refreshes, persists rotated tokens with detached cancellation, updates in-flight MarkResult auth state, and keeps Home-dispatched snapshots isolated from local credentials. - Preserve non-cancellation context values such as httptransport.Decorator and custom round trippers via context.WithoutCancel while stripping execution-scoped RequestProxyURL across OAuth refresh, project discovery, and credits hint refreshes. - Add race-tested regression tests covering single refresh persistence, client cancellation, project discovery failure, safety-window crossing, unsupported attachments, Home isolation, request preparation context preservation, and proxy isolation. Closes: #7749 --- .../executor/antigravity_executor_auth.go | 104 +- .../executor/antigravity_executor_credits.go | 20 +- .../antigravity_refresh_issue7749_test.go | 1739 +++++++++++++++++ sdk/cliproxy/auth/conductor_execution.go | 180 +- sdk/cliproxy/auth/conductor_home.go | 20 +- sdk/cliproxy/auth/conductor_home_execution.go | 16 +- sdk/cliproxy/auth/conductor_stream.go | 23 + sdk/cliproxy/auth/execution_auth_refresh.go | 237 +++ .../auth/execution_auth_refresh_test.go | 364 ++++ 9 files changed, 2645 insertions(+), 58 deletions(-) create mode 100644 internal/runtime/executor/antigravity_refresh_issue7749_test.go create mode 100644 sdk/cliproxy/auth/execution_auth_refresh.go create mode 100644 sdk/cliproxy/auth/execution_auth_refresh_test.go diff --git a/internal/runtime/executor/antigravity_executor_auth.go b/internal/runtime/executor/antigravity_executor_auth.go index 00a420f3b6..236d025971 100644 --- a/internal/runtime/executor/antigravity_executor_auth.go +++ b/internal/runtime/executor/antigravity_executor_auth.go @@ -27,6 +27,8 @@ const antigravityCredentialAcquisitionTimeout = 30 * time.Second var antigravityInitialBaseTransport = antigravityBaseTransport +var antigravityNow = time.Now + // Refresh refreshes the authentication credentials using the refresh token. func (e *AntigravityExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Auth) (*cliproxyauth.Auth, error) { if refreshed, handled, err := helps.RefreshAuthViaHome(ctx, e.cfg, auth); handled { @@ -43,9 +45,36 @@ func (e *AntigravityExecutor) Refresh(ctx context.Context, auth *cliproxyauth.Au } func (e *AntigravityExecutor) ShouldPrepareRequestAuth(auth *cliproxyauth.Auth) bool { + if auth == nil { + return false + } return antigravityProjectIDFromAuth(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 auth == nil || !e.ShouldPrepareRequestAuth(auth) { return nil, nil @@ -83,23 +112,13 @@ func (e *AntigravityExecutor) PrepareRequestAuth(ctx context.Context, auth *clip } updated.Metadata["project_id"] = projectID if refreshedLocal { - e.queueAntigravityCreditsRefresh(detachedRoundTripperContext(ctx), updated, token, 0) + e.queueAntigravityCreditsRefresh(detachedAntigravityCredentialContext(ctx), updated, token, 0) } else { e.maybeRefreshAntigravityCreditsHint(ctx, updated, token) } return updated, nil } -func detachedRoundTripperContext(ctx context.Context) context.Context { - detached := context.Background() - if ctx != nil { - if rt, ok := ctx.Value("cliproxy.roundtripper").(http.RoundTripper); ok && rt != nil { - detached = context.WithValue(detached, "cliproxy.roundtripper", rt) - } - } - return detached -} - 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 @@ -109,34 +128,59 @@ func (e *AntigravityExecutor) ensureAccessTokenWithOptions(ctx context.Context, if auth == nil { return "", nil, false, statusErr{code: http.StatusUnauthorized, msg: "missing auth"} } - accessToken := metaStringValue(auth.Metadata, "access_token") - expiry, _ := auth.ExpirationTime() - if accessToken != "" && expiry.After(time.Now().Add(antigravityRequestTokenSafetyWindow)) { + if !antigravityNeedsAccessTokenRefresh(auth) { + accessToken := metaStringValue(auth.Metadata, "access_token") if discoverProject { e.maybeRefreshAntigravityCreditsHint(ctx, auth, accessToken) } return accessToken, nil, false, nil } - refreshCtx := detachedRoundTripperContext(ctx) - if refreshed, handled, err := helps.RefreshAuthViaHome(refreshCtx, e.cfg, auth); handled { - if err != nil { - return "", nil, false, err + 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) { + return nil, nil } - token := metaStringValue(refreshed.Metadata, "access_token") - if strings.TrimSpace(token) == "" { - return "", nil, false, statusErr{code: http.StatusUnauthorized, msg: "missing access token"} + refreshCtx := detachedAntigravityCredentialContext(callCtx) + if refreshed, handled, errHome := helps.RefreshAuthViaHome(refreshCtx, e.cfg, latest); handled { + if errHome != nil { + return nil, errHome + } + token := metaStringValue(refreshed.Metadata, "access_token") + if strings.TrimSpace(token) == "" { + return nil, statusErr{code: http.StatusUnauthorized, msg: "missing access token"} + } + refreshedViaHome = true + if discoverProject { + e.maybeRefreshAntigravityCreditsHint(callCtx, refreshed, token) + } + return refreshed, nil } - if discoverProject { - e.maybeRefreshAntigravityCreditsHint(ctx, refreshed, token) + refreshed, errToken := e.refreshTokenWithOptions(refreshCtx, latest.Clone(), callCtx, discoverProject) + if errToken != nil { + return nil, errToken } - return token, refreshed, false, nil - } - - updated, errRefresh := e.refreshTokenWithOptions(refreshCtx, auth.Clone(), ctx, discoverProject) + refreshedLocal = true + return refreshed, nil + }) if errRefresh != nil { return "", nil, false, errRefresh } - return metaStringValue(updated.Metadata, "access_token"), updated, true, nil + if updated == nil { + accessToken := metaStringValue(auth.Metadata, "access_token") + if discoverProject { + e.maybeRefreshAntigravityCreditsHint(ctx, auth, accessToken) + } + return accessToken, nil, false, nil + } + token := metaStringValue(updated.Metadata, "access_token") + if strings.TrimSpace(token) == "" { + return "", nil, false, statusErr{code: http.StatusUnauthorized, msg: "missing access token"} + } + if discoverProject && !refreshedLocal && !refreshedViaHome { + e.maybeRefreshAntigravityCreditsHint(ctx, updated, token) + } + return token, updated, refreshedLocal, nil } func (e *AntigravityExecutor) refreshToken(ctx context.Context, auth *cliproxyauth.Auth, requestCtx context.Context) (*cliproxyauth.Auth, error) { @@ -154,6 +198,7 @@ func (e *AntigravityExecutor) refreshTokenWithOptions(ctx context.Context, auth if ctx == nil { ctx = context.Background() } + ctx = cliproxyexecutor.WithoutRequestProxyURL(ctx) refreshToken = strings.TrimSpace(refreshToken) result, errRefresh, _ := antigravityRefreshGroup.Do(refreshToken, func() (interface{}, error) { @@ -345,7 +390,8 @@ func (e *AntigravityExecutor) fetchAntigravityProjectID(ctx context.Context, aut ctx = context.Background() } // Project discovery is required credential preparation, not a generation request. - acquisitionCtx, cancelAcquisition := context.WithTimeout(ctx, antigravityCredentialAcquisitionTimeout) + // Exclude execution-scoped request proxy overrides while preserving caller cancellation. + acquisitionCtx, cancelAcquisition := context.WithTimeout(cliproxyexecutor.WithoutRequestProxyURL(ctx), antigravityCredentialAcquisitionTimeout) defer cancelAcquisition() httpClient := newAntigravityHTTPClient(acquisitionCtx, e.cfg, auth, 0) tracedClient := helps.WithAntigravityHTTPClientTrace(httpClient, auth, "project_discovery") diff --git a/internal/runtime/executor/antigravity_executor_credits.go b/internal/runtime/executor/antigravity_executor_credits.go index 7f3daba0e0..9c6e486fd4 100644 --- a/internal/runtime/executor/antigravity_executor_credits.go +++ b/internal/runtime/executor/antigravity_executor_credits.go @@ -18,6 +18,7 @@ import ( homekv "github.com/router-for-me/CLIProxyAPI/v8/internal/home" "github.com/router-for-me/CLIProxyAPI/v8/internal/runtime/executor/helps" cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" log "github.com/sirupsen/logrus" "golang.org/x/sync/singleflight" ) @@ -500,13 +501,7 @@ func (e *AntigravityExecutor) maybeRefreshAntigravityCreditsHint(ctx context.Con if !written { return } - refreshCtx := context.Background() - if ctx != nil { - if rt, ok := ctx.Value("cliproxy.roundtripper").(http.RoundTripper); ok && rt != nil { - refreshCtx = context.WithValue(refreshCtx, "cliproxy.roundtripper", rt) - } - } - refreshCtx, cancel := context.WithTimeout(refreshCtx, antigravityCreditsHintRefreshTimeout) + refreshCtx, cancel := context.WithTimeout(detachedAntigravityCredentialContext(ctx), antigravityCreditsHintRefreshTimeout) authCopy := auth.Clone() go func(auth *cliproxyauth.Auth, token string) { defer cancel() @@ -572,17 +567,16 @@ func (e *AntigravityExecutor) queueAntigravityCreditsRefresh(ctx context.Context var refreshCtx context.Context var cancelRefresh context.CancelFunc if timeout > 0 { - // Keep the existing independent warm-hint budget and transport selection. - lifecycle = context.Background() - if rt, ok := ctx.Value("cliproxy.roundtripper").(http.RoundTripper); ok && rt != nil { - lifecycle = context.WithValue(lifecycle, "cliproxy.roundtripper", rt) - } + // Keep the existing independent warm-hint budget and transport selection + // while preserving non-cancellation context values and excluding + // execution-scoped request proxy overrides. + lifecycle = detachedAntigravityCredentialContext(ctx) refreshCtx, cancelRefresh = context.WithTimeout(lifecycle, timeout) } else { // Optional post-refresh work still follows the caller's lifecycle, but a // stalled upstream must not leak the goroutine or wedge state.task, so it // runs under the bounded warm-hint budget instead of an unbounded cancel. - refreshCtx, cancelRefresh = context.WithTimeout(lifecycle, antigravityCreditsHintRefreshTimeout) + refreshCtx, cancelRefresh = context.WithTimeout(cliproxyexecutor.WithoutRequestProxyURL(lifecycle), antigravityCreditsHintRefreshTimeout) } task := &antigravityCreditsRefreshTask{ state: state, diff --git a/internal/runtime/executor/antigravity_refresh_issue7749_test.go b/internal/runtime/executor/antigravity_refresh_issue7749_test.go new file mode 100644 index 0000000000..566f3e61d3 --- /dev/null +++ b/internal/runtime/executor/antigravity_refresh_issue7749_test.go @@ -0,0 +1,1739 @@ +package executor + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + translatorcommon "github.com/router-for-me/CLIProxyAPI/v8/internal/translator/common" + cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" + sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/httptransport" + sdktranslator "github.com/router-for-me/CLIProxyAPI/v8/sdk/translator" +) + +type issue7749ContextKey struct{} + +type issue7749MemoryStore struct { + mu sync.Mutex + auths map[string]*cliproxyauth.Auth + saves int +} + +func newIssue7749MemoryStore() *issue7749MemoryStore { + return &issue7749MemoryStore{auths: make(map[string]*cliproxyauth.Auth)} +} + +func (s *issue7749MemoryStore) List(context.Context) ([]*cliproxyauth.Auth, error) { + s.mu.Lock() + defer s.mu.Unlock() + out := make([]*cliproxyauth.Auth, 0, len(s.auths)) + for _, a := range s.auths { + out = append(out, a.Clone()) + } + return out, nil +} + +func (s *issue7749MemoryStore) Save(_ context.Context, auth *cliproxyauth.Auth) (string, error) { + if auth == nil { + return "", nil + } + s.mu.Lock() + defer s.mu.Unlock() + s.auths[auth.ID] = auth.Clone() + s.saves++ + return auth.ID, nil +} + +func (s *issue7749MemoryStore) Delete(_ context.Context, id string) error { + s.mu.Lock() + defer s.mu.Unlock() + delete(s.auths, id) + return nil +} + +func (s *issue7749MemoryStore) get(id string) *cliproxyauth.Auth { + s.mu.Lock() + defer s.mu.Unlock() + if a := s.auths[id]; a != nil { + return a.Clone() + } + return nil +} + +type issue7749ResultHook struct { + cliproxyauth.NoopHook + mu sync.Mutex + results []cliproxyauth.Result +} + +func (h *issue7749ResultHook) OnResult(_ context.Context, result cliproxyauth.Result) { + h.mu.Lock() + h.results = append(h.results, result) + h.mu.Unlock() +} + +func (h *issue7749ResultHook) snapshot() []cliproxyauth.Result { + h.mu.Lock() + defer h.mu.Unlock() + out := make([]cliproxyauth.Result, len(h.results)) + copy(out, h.results) + return out +} + +type issue7749StaticRTProvider struct { + rt http.RoundTripper +} + +func (p issue7749StaticRTProvider) RoundTripperFor(*cliproxyauth.Auth) http.RoundTripper { + return p.rt +} + +func TestIssue7749AntigravityExpiringTokenPersistsOnceAcrossConsecutiveRequests(t *testing.T) { + resetAntigravityRefreshGroupForTest() + t.Cleanup(resetAntigravityRefreshGroupForTest) + resetAntigravityCreditsRetryState() + t.Cleanup(resetAntigravityCreditsRetryState) + + var ( + tokenCalls atomic.Int32 + generateCalls atomic.Int32 + ) + const ( + oldAccessToken = "expiring-access-7749" + newAccessToken = "refreshed-access-7749" + oldRefreshToken = "old-refresh-7749" + newRefreshToken = "rotated-refresh-7749" + geminiModelID = "gemini-3.6-flash" + claudeModelID = "claude-sonnet-4-5" + ) + + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + switch { + case req.URL.String() == "https://oauth2.googleapis.com/token": + tokenCalls.Add(1) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(fmt.Sprintf( + `{"access_token":%q,"refresh_token":%q,"expires_in":3600,"token_type":"Bearer"}`, + newAccessToken, newRefreshToken, + ))), + }, nil + + case strings.HasSuffix(req.URL.Path, ":loadCodeAssist"): + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"tier-7749","availableCredits":[]}}`)), + }, nil + + case strings.Contains(req.URL.Path, "streamGenerateContent"): + generateCalls.Add(1) + if got := req.Header.Get("Authorization"); got != "Bearer "+newAccessToken { + t.Errorf("streamGenerate Authorization = %q, want Bearer %s", got, newAccessToken) + } + sse := "data: " + `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":2,"candidatesTokenCount":1,"totalTokenCount":3}}}` + "\n\n" + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(sse)), + }, nil + + case strings.Contains(req.URL.Path, "generateContent"): + generateCalls.Add(1) + if got := req.Header.Get("Authorization"); got != "Bearer "+newAccessToken { + t.Errorf("generate Authorization = %q, want Bearer %s", got, newAccessToken) + } + body := `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":2,"candidatesTokenCount":1,"totalTokenCount":3}}}` + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + }, nil + + default: + return nil, fmt.Errorf("unexpected HTTP request: %s %s", req.Method, req.URL.String()) + } + }) + + store := newIssue7749MemoryStore() + hook := &issue7749ResultHook{} + exec := NewAntigravityExecutor(&config.Config{}) + manager := cliproxyauth.NewManager(store, nil, hook) + manager.SetRoundTripperProvider(issue7749StaticRTProvider{rt: transport}) + manager.RegisterExecutor(exec) + + authID := "ag-issue-7749-persist-" + uuid.NewString() + initialExpiry := time.Now().UTC().Add(antigravityRequestTokenSafetyWindow - time.Minute) + auth := &cliproxyauth.Auth{ + ID: authID, + FileName: authID + ".json", + Provider: "antigravity", + Status: cliproxyauth.StatusActive, + Metadata: map[string]any{ + "type": "antigravity", + "email": "ag-7749@example.com", + "project_id": "proj-existing-7749", + "access_token": oldAccessToken, + "refresh_token": oldRefreshToken + "-" + uuid.NewString(), + "expired": initialExpiry.Format(time.RFC3339), + }, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + if exec.ShouldPrepareRequestAuth(nil) { + t.Fatal("ShouldPrepareRequestAuth(nil) = true, want false") + } + + registry.GetGlobalRegistry().RegisterClient(authID, "antigravity", []*registry.ModelInfo{ + {ID: geminiModelID}, + {ID: claudeModelID}, + }) + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + payload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`) + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatAntigravity, + } + + // Request 1: non-stream Gemini (Execute). + if _, errExec := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: geminiModelID, + Payload: payload, + }, opts); errExec != nil { + t.Fatalf("Execute #1 (gemini) error = %v", errExec) + } + + // Request 2: non-stream Claude (executeClaudeNonStream). + if _, errExec := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: claudeModelID, + Payload: payload, + }, opts); errExec != nil { + t.Fatalf("Execute #2 (claude) error = %v", errExec) + } + + // Request 3: streaming Gemini (ExecuteStream). + streamOpts := opts + streamOpts.Stream = true + streamRes, errStream := manager.ExecuteStream(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: geminiModelID, + Payload: payload, + }, streamOpts) + if errStream != nil { + t.Fatalf("ExecuteStream #3 error = %v", errStream) + } + for chunk := range streamRes.Chunks { + if chunk.Err != nil { + t.Fatalf("ExecuteStream #3 chunk error = %v", chunk.Err) + } + } + + if got := tokenCalls.Load(); got != 1 { + t.Fatalf("POST https://oauth2.googleapis.com/token calls = %d, want 1 across 3 consecutive requests", got) + } + if got := generateCalls.Load(); got != 3 { + t.Fatalf("generateContent calls = %d, want 3", got) + } + + managed, okManaged := manager.GetByID(authID) + if !okManaged || managed == nil { + t.Fatalf("managed auth %s not found", authID) + } + if got := metaStringValue(managed.Metadata, "access_token"); got != newAccessToken { + t.Fatalf("managed access_token = %q, want %q", got, newAccessToken) + } + if got := metaStringValue(managed.Metadata, "refresh_token"); got != newRefreshToken { + t.Fatalf("managed refresh_token = %q, want rotated %q", got, newRefreshToken) + } + if exp, okExp := managed.ExpirationTime(); !okExp || !exp.After(time.Now().Add(antigravityRequestTokenSafetyWindow)) { + t.Fatalf("managed expiry = %v (ok=%v), want > now+%s", exp, okExp, antigravityRequestTokenSafetyWindow) + } + + persisted := store.get(authID) + if persisted == nil { + t.Fatal("persisted auth not found in store") + } + if got := metaStringValue(persisted.Metadata, "access_token"); got != newAccessToken { + t.Fatalf("persisted access_token = %q, want %q", got, newAccessToken) + } + if got := metaStringValue(persisted.Metadata, "refresh_token"); got != newRefreshToken { + t.Fatalf("persisted refresh_token = %q, want rotated %q", got, newRefreshToken) + } + + results := hook.snapshot() + if len(results) != 3 { + t.Fatalf("recorded MarkResult count = %d, want 3", len(results)) + } + for i, res := range results { + if res.AccessToken != newAccessToken { + t.Fatalf("results[%d].AccessToken = %q, want %q", i, res.AccessToken, newAccessToken) + } + if res.RefreshToken != newRefreshToken { + t.Fatalf("results[%d].RefreshToken = %q, want %q", i, res.RefreshToken, newRefreshToken) + } + } +} + +func TestIssue7749AntigravityFailedRequestRecordsRefreshedAccessTokenInMarkResult(t *testing.T) { + resetAntigravityRefreshGroupForTest() + t.Cleanup(resetAntigravityRefreshGroupForTest) + resetAntigravityCreditsRetryState() + t.Cleanup(resetAntigravityCreditsRetryState) + + const ( + oldAccessToken = "stale-access-7749-fail" + newAccessToken = "fresh-access-7749-fail" + modelID = "gemini-3.6-flash" + ) + + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + switch { + case req.URL.String() == "https://oauth2.googleapis.com/token": + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(fmt.Sprintf( + `{"access_token":%q,"expires_in":3600,"token_type":"Bearer"}`, + newAccessToken, + ))), + }, nil + + case strings.HasSuffix(req.URL.Path, ":loadCodeAssist"): + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"tier-7749","availableCredits":[]}}`)), + }, nil + + case strings.Contains(strings.ToLower(req.URL.Path), "generatecontent"): + return &http.Response{ + StatusCode: http.StatusInternalServerError, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"code":500,"message":"upstream failure"}}`)), + }, nil + + default: + return nil, fmt.Errorf("unexpected HTTP request: %s %s", req.Method, req.URL.String()) + } + }) + + hook := &issue7749ResultHook{} + exec := NewAntigravityExecutor(&config.Config{}) + manager := cliproxyauth.NewManager(newIssue7749MemoryStore(), nil, hook) + manager.SetRoundTripperProvider(issue7749StaticRTProvider{rt: transport}) + manager.RegisterExecutor(exec) + + authID := "ag-issue-7749-fail-" + uuid.NewString() + auth := &cliproxyauth.Auth{ + ID: authID, + FileName: authID + ".json", + Provider: "antigravity", + Status: cliproxyauth.StatusActive, + Metadata: map[string]any{ + "type": "antigravity", + "project_id": "proj-fail-7749", + "access_token": oldAccessToken, + "refresh_token": "refresh-fail-7749-" + uuid.NewString(), + "expired": time.Now().UTC().Add(antigravityRequestTokenSafetyWindow - time.Minute).Format(time.RFC3339), + }, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "antigravity", []*registry.ModelInfo{ + {ID: modelID}, + }) + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + _, errExec := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatAntigravity, + }) + if errExec == nil { + t.Fatal("Execute() error = nil, want upstream 500 failure") + } + + results := hook.snapshot() + if len(results) == 0 { + t.Fatal("expected at least one MarkResult call") + } + last := results[len(results)-1] + if last.AccessToken != newAccessToken { + t.Fatalf("failed Result.AccessToken = %q, want refreshed %q", last.AccessToken, newAccessToken) + } + + // Verify ExecuteStream failure also records the refreshed AccessToken in MarkResult. + streamAuthID := "ag-issue-7749-fail-stream-" + uuid.NewString() + streamAuth := &cliproxyauth.Auth{ + ID: streamAuthID, + FileName: streamAuthID + ".json", + Provider: "antigravity", + Status: cliproxyauth.StatusActive, + Metadata: map[string]any{ + "type": "antigravity", + "email": "ag-7749-fail-stream@example.com", + "project_id": "proj-fail-stream-7749", + "access_token": oldAccessToken, + "refresh_token": "old-refresh-fail-stream-" + uuid.NewString(), + "expired": time.Now().UTC().Add(2 * time.Minute).Format(time.RFC3339), + }, + } + registry.GetGlobalRegistry().RegisterClient(streamAuthID, "antigravity", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(streamAuthID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + registry.GetGlobalRegistry().UnregisterClient(streamAuthID) + }) + streamHook := &issue7749ResultHook{} + streamManager := cliproxyauth.NewManager(newIssue7749MemoryStore(), nil, streamHook) + streamManager.SetRoundTripperProvider(issue7749StaticRTProvider{rt: transport}) + streamManager.RegisterExecutor(exec) + if _, errReg := streamManager.Register(context.Background(), streamAuth); errReg != nil { + t.Fatalf("Register stream auth: %v", errReg) + } + if _, errStream := streamManager.ExecuteStream(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`), + }, cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatAntigravity, + Stream: true, + }); errStream == nil { + t.Fatal("ExecuteStream() error = nil, want upstream 500 failure") + } + streamResults := streamHook.snapshot() + if len(streamResults) == 0 { + t.Fatal("expected at least one MarkResult call for failed ExecuteStream") + } + if lastStream := streamResults[len(streamResults)-1]; lastStream.AccessToken != newAccessToken { + t.Fatalf("failed ExecuteStream Result.AccessToken = %q, want refreshed %q", lastStream.AccessToken, newAccessToken) + } +} + +func TestIssue7749EnsureAccessTokenPreservesContextValuesAndExcludesRequestProxy(t *testing.T) { + resetAntigravityRefreshGroupForTest() + t.Cleanup(resetAntigravityRefreshGroupForTest) + resetAntigravityCreditsRetryState() + t.Cleanup(resetAntigravityCreditsRetryState) + + t.Run("preserves decorator and context values while clearing RequestProxyURL", func(t *testing.T) { + var ( + decoratorCalled atomic.Bool + seenCustomVal atomic.Value + seenReqProxy atomic.Value + ) + baseRT := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + switch { + case req.URL.String() == "https://oauth2.googleapis.com/token": + seenCustomVal.Store(fmt.Sprint(req.Context().Value(issue7749ContextKey{}))) + seenReqProxy.Store(cliproxyexecutor.RequestProxyURL(req.Context())) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"access_token":"tok-ctx-7749","expires_in":3600}`)), + }, nil + case strings.HasSuffix(req.URL.Path, ":loadCodeAssist"): + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"tier","availableCredits":[]}}`)), + }, nil + default: + return nil, fmt.Errorf("unexpected request: %s", req.URL) + } + }) + + ctx := context.Background() + ctx = context.WithValue(ctx, issue7749ContextKey{}, "marker-7749") + ctx = context.WithValue(ctx, "cliproxy.roundtripper", http.RoundTripper(baseRT)) + ctx = cliproxyexecutor.WithRequestProxyURL(ctx, "http://request-proxy.example:8081") + ctx = httptransport.WithDecorator(ctx, func(next http.RoundTripper) http.RoundTripper { + return roundTripperFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.String() == "https://oauth2.googleapis.com/token" { + decoratorCalled.Store(true) + } + return next.RoundTrip(req) + }) + }) + + authID := "ag-ctx-7749-" + uuid.NewString() + auth := &cliproxyauth.Auth{ + ID: authID, + Provider: "antigravity", + Metadata: map[string]any{ + "project_id": "proj-ctx-7749", + "access_token": "expiring", + "refresh_token": "refresh-ctx-7749-" + uuid.NewString(), + "expired": time.Now().UTC().Add(-time.Minute).Format(time.RFC3339), + }, + } + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + }) + + exec := NewAntigravityExecutor(&config.Config{}) + token, updated, errToken := exec.ensureAccessToken(ctx, auth) + if errToken != nil || token != "tok-ctx-7749" || updated == nil { + t.Fatalf("ensureAccessToken() = (%q, %v, %v), want refreshed token", token, updated, errToken) + } + if !decoratorCalled.Load() { + t.Fatal("ensureAccessToken dropped httptransport.Decorator from refresh context") + } + if got, _ := seenCustomVal.Load().(string); got != "marker-7749" { + t.Fatalf("refresh context custom value = %q, want marker-7749", got) + } + if got, _ := seenReqProxy.Load().(string); got != "" { + t.Fatalf("refresh context RequestProxyURL = %q, want empty (credential/global proxy only)", got) + } + }) + + t.Run("routes OAuth refresh through credential proxy rather than RequestProxyURL", func(t *testing.T) { + var requestProxyHits atomic.Int32 + var authProxyHits atomic.Int32 + var globalProxyHits atomic.Int32 + requestProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requestProxyHits.Add(1) + http.Error(w, "request proxy should not be used for OAuth refresh", http.StatusBadGateway) + })) + defer requestProxy.Close() + authProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + authProxyHits.Add(1) + http.Error(w, "auth proxy reached", http.StatusBadGateway) + })) + defer authProxy.Close() + globalProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + globalProxyHits.Add(1) + http.Error(w, "global proxy should not override auth proxy", http.StatusBadGateway) + })) + defer globalProxy.Close() + + ctx := cliproxyexecutor.WithRequestProxyURL(context.Background(), requestProxy.URL) + exec := NewAntigravityExecutor(&config.Config{ + SDKConfig: sdkconfig.SDKConfig{ProxyURL: globalProxy.URL}, + }) + auth := &cliproxyauth.Auth{ + ID: "ag-proxy-iso-7749-" + uuid.NewString(), + Provider: "antigravity", + ProxyURL: authProxy.URL, + Metadata: map[string]any{ + "project_id": "proj-proxy-iso-7749", + "access_token": "expiring", + "refresh_token": "refresh-proxy-iso-7749-" + uuid.NewString(), + "expired": time.Now().UTC().Add(-time.Minute).Format(time.RFC3339), + }, + } + + _, _, _ = exec.ensureAccessToken(ctx, auth) + if requestProxyHits.Load() != 0 { + t.Fatalf("OAuth refresh used RequestProxyURL %d times, want 0", requestProxyHits.Load()) + } + if globalProxyHits.Load() != 0 { + t.Fatalf("OAuth refresh used global proxy %d times, want 0", globalProxyHits.Load()) + } + if authProxyHits.Load() == 0 { + t.Fatal("OAuth refresh did not use auth.ProxyURL") + } + }) +} + +func TestIssue7749CreditsRefreshPreservesContextValuesAndExcludesRequestProxy(t *testing.T) { + resetAntigravityCreditsRetryState() + t.Cleanup(resetAntigravityCreditsRetryState) + + newAuth := func(prefix string) *cliproxyauth.Auth { + return &cliproxyauth.Auth{ + ID: prefix + "-" + uuid.NewString(), + Provider: "antigravity", + Metadata: map[string]any{ + "project_id": "proj-credits-7749", + "access_token": "warm-token-7749", + "expired": time.Now().UTC().Add(time.Hour).Format(time.RFC3339), + }, + } + } + + t.Run("local queue timeout>0", func(t *testing.T) { + var ( + decoratorCalled atomic.Bool + seenCustomVal atomic.Value + seenReqProxy atomic.Value + ) + baseRT := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + seenCustomVal.Store(fmt.Sprint(req.Context().Value(issue7749ContextKey{}))) + seenReqProxy.Store(cliproxyexecutor.RequestProxyURL(req.Context())) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"tier","availableCredits":[]}}`)), + }, nil + }) + ctx := context.WithValue(context.Background(), issue7749ContextKey{}, "credits-local-7749") + ctx = context.WithValue(ctx, "cliproxy.roundtripper", http.RoundTripper(baseRT)) + ctx = cliproxyexecutor.WithRequestProxyURL(ctx, "http://request-proxy.example:8081") + ctx = httptransport.WithDecorator(ctx, func(next http.RoundTripper) http.RoundTripper { + return roundTripperFunc(func(req *http.Request) (*http.Response, error) { + decoratorCalled.Store(true) + return next.RoundTrip(req) + }) + }) + + auth := newAuth("ag-credits-local-7749") + exec := NewAntigravityExecutor(&config.Config{ + QuotaExceeded: config.QuotaExceeded{AntigravityCredits: true}, + }) + exec.maybeRefreshAntigravityCreditsHint(ctx, auth, "warm-token-7749") + + value, ok := antigravityCreditsHintRefreshByID.Load(auth.ID) + if !ok { + t.Fatal("expected credits refresh task state") + } + waitForAntigravityCreditsRefresh(t, value.(*antigravityCreditsHintRefreshState)) + + if !decoratorCalled.Load() { + t.Fatal("queueAntigravityCreditsRefresh(timeout>0) dropped httptransport.Decorator") + } + if got, _ := seenCustomVal.Load().(string); got != "credits-local-7749" { + t.Fatalf("credits context custom value = %q, want credits-local-7749", got) + } + if got, _ := seenReqProxy.Load().(string); got != "" { + t.Fatalf("credits context RequestProxyURL = %q, want empty", got) + } + }) + + t.Run("home kv branch", func(t *testing.T) { + kv := newFakeAntigravityKVClient() + useFakeAntigravityKVClient(t, kv, true, nil) + + done := make(chan struct{}) + var ( + decoratorCalled atomic.Bool + seenCustomVal atomic.Value + seenReqProxy atomic.Value + ) + baseRT := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + seenCustomVal.Store(fmt.Sprint(req.Context().Value(issue7749ContextKey{}))) + seenReqProxy.Store(cliproxyexecutor.RequestProxyURL(req.Context())) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: &closeSignalReadCloser{ + ReadCloser: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"tier","availableCredits":[]}}`)), + closed: done, + }, + }, nil + }) + ctx := context.WithValue(context.Background(), issue7749ContextKey{}, "credits-home-7749") + ctx = context.WithValue(ctx, "cliproxy.roundtripper", http.RoundTripper(baseRT)) + ctx = cliproxyexecutor.WithRequestProxyURL(ctx, "http://request-proxy.example:8081") + ctx = httptransport.WithDecorator(ctx, func(next http.RoundTripper) http.RoundTripper { + return roundTripperFunc(func(req *http.Request) (*http.Response, error) { + decoratorCalled.Store(true) + return next.RoundTrip(req) + }) + }) + + auth := newAuth("ag-credits-home-7749") + exec := NewAntigravityExecutor(&config.Config{ + QuotaExceeded: config.QuotaExceeded{AntigravityCredits: true}, + }) + exec.maybeRefreshAntigravityCreditsHint(ctx, auth, "warm-token-7749") + + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for home kv background credits refresh") + } + + if !decoratorCalled.Load() { + t.Fatal("maybeRefreshAntigravityCreditsHint(home kv) dropped httptransport.Decorator") + } + if got, _ := seenCustomVal.Load().(string); got != "credits-home-7749" { + t.Fatalf("home kv credits context custom value = %q, want credits-home-7749", got) + } + if got, _ := seenReqProxy.Load().(string); got != "" { + t.Fatalf("home kv credits context RequestProxyURL = %q, want empty", got) + } + }) + + t.Run("post-refresh queue timeout==0 excludes RequestProxyURL", func(t *testing.T) { + var ( + decoratorCalled atomic.Bool + seenCustomVal atomic.Value + seenReqProxy atomic.Value + ) + baseRT := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + seenCustomVal.Store(fmt.Sprint(req.Context().Value(issue7749ContextKey{}))) + seenReqProxy.Store(cliproxyexecutor.RequestProxyURL(req.Context())) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"tier","availableCredits":[]}}`)), + }, nil + }) + ctx := context.WithValue(context.Background(), issue7749ContextKey{}, "credits-postrefresh-7749") + ctx = context.WithValue(ctx, "cliproxy.roundtripper", http.RoundTripper(baseRT)) + ctx = cliproxyexecutor.WithRequestProxyURL(ctx, "http://request-proxy.example:8081") + ctx = httptransport.WithDecorator(ctx, func(next http.RoundTripper) http.RoundTripper { + return roundTripperFunc(func(req *http.Request) (*http.Response, error) { + decoratorCalled.Store(true) + return next.RoundTrip(req) + }) + }) + + auth := newAuth("ag-credits-postrefresh-7749") + exec := NewAntigravityExecutor(&config.Config{}) + exec.queueAntigravityCreditsRefresh(ctx, auth, "warm-token-7749", 0) + + value, ok := antigravityCreditsHintRefreshByID.Load(auth.ID) + if !ok { + t.Fatal("expected post-refresh credits task state") + } + waitForAntigravityCreditsRefresh(t, value.(*antigravityCreditsHintRefreshState)) + + if !decoratorCalled.Load() { + t.Fatal("queueAntigravityCreditsRefresh(timeout==0) did not invoke httptransport.Decorator") + } + if got, _ := seenCustomVal.Load().(string); got != "credits-postrefresh-7749" { + t.Fatalf("post-refresh credits context custom value = %q, want credits-postrefresh-7749", got) + } + if got, _ := seenReqProxy.Load().(string); got != "" { + t.Fatalf("post-refresh credits context RequestProxyURL = %q, want empty", got) + } + }) +} + +func TestIssue7749ClientCancelDuringRefreshStillPersistsRotatedToken(t *testing.T) { + cases := []struct { + name string + projectID string + }{ + {name: "existing project_id via Execute", projectID: "proj-cancel-7749"}, + {name: "missing project_id via PrepareRequestAuth", projectID: ""}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + const ( + modelID = "gemini-3.6-flash" + rotatedAccess = "access-rotated-after-cancel-7749" + rotatedRefresh = "refresh-rotated-after-cancel-7749" + discoveredProj = "proj-discovered-after-cancel-7749" + ) + authID := "ag-cancel-7749-" + uuid.NewString() + initialRefresh := "refresh-initial-cancel-7749-" + uuid.NewString() + + oauthStarted := make(chan struct{}) + releaseOAuth := make(chan struct{}) + var ( + oauthCalls atomic.Int32 + upstreamCalls atomic.Int32 + seenAuthHeaders sync.Mutex + authHeaders []string + ) + + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + switch { + case req.URL.String() == "https://oauth2.googleapis.com/token": + call := oauthCalls.Add(1) + if call == 1 { + close(oauthStarted) + <-releaseOAuth + } + body := fmt.Sprintf(`{"access_token":%q,"refresh_token":%q,"expires_in":3600}`, rotatedAccess, rotatedRefresh) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "loadCodeAssist"): + body := fmt.Sprintf(`{"cloudaicompanionProject":%q,"paidTier":{"id":"tier","availableCredits":[]}}`, discoveredProj) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "generateContent"): + upstreamCalls.Add(1) + seenAuthHeaders.Lock() + authHeaders = append(authHeaders, req.Header.Get("Authorization")) + seenAuthHeaders.Unlock() + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]}}]}}`)), + Request: req, + }, nil + default: + return nil, fmt.Errorf("unexpected request: %s", req.URL.String()) + } + }) + + store := newIssue7749MemoryStore() + manager := cliproxyauth.NewManager(store, nil, nil) + manager.SetRoundTripperProvider(issue7749StaticRTProvider{rt: transport}) + exec := NewAntigravityExecutor(&config.Config{}) + manager.RegisterExecutor(exec) + + meta := map[string]any{ + "type": "antigravity", + "email": "ag-cancel-7749@example.com", + "access_token": "expiring-cancel-7749", + "refresh_token": initialRefresh, + "expired": time.Now().UTC().Add(2 * time.Minute).Format(time.RFC3339), + } + if tc.projectID != "" { + meta["project_id"] = tc.projectID + } + auth := &cliproxyauth.Auth{ + ID: authID, + FileName: authID + ".json", + Provider: "antigravity", + Status: cliproxyauth.StatusActive, + Metadata: meta, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "antigravity", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + payload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`) + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatAntigravity} + + reqCtx, cancelReq := context.WithCancel(context.Background()) + errCh := make(chan error, 1) + go func() { + _, errExec := manager.Execute(reqCtx, []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: payload, + }, opts) + errCh <- errExec + }() + + select { + case <-oauthStarted: + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for OAuth refresh to start") + } + + cancelReq() + close(releaseOAuth) + + var errCanceled error + select { + case errCanceled = <-errCh: + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for canceled Execute to return") + } + if !errors.Is(errCanceled, context.Canceled) { + t.Fatalf("canceled Execute error = %v, want context.Canceled", errCanceled) + } + if got := upstreamCalls.Load(); got != 0 { + t.Fatalf("upstream generateContent calls after cancel = %d, want 0", got) + } + + gotAuth, ok := manager.GetByID(authID) + if !ok || gotAuth == nil { + t.Fatalf("manager missing auth %s after canceled refresh", authID) + } + if got := metaStringValue(gotAuth.Metadata, "access_token"); got != rotatedAccess { + t.Fatalf("manager access_token after cancel = %q, want %q", got, rotatedAccess) + } + if got := metaStringValue(gotAuth.Metadata, "refresh_token"); got != rotatedRefresh { + t.Fatalf("manager refresh_token after cancel = %q, want %q", got, rotatedRefresh) + } + savedAuth := store.get(authID) + if savedAuth == nil { + t.Fatal("store did not persist auth after canceled refresh") + } + if got := metaStringValue(savedAuth.Metadata, "refresh_token"); got != rotatedRefresh { + t.Fatalf("store refresh_token after cancel = %q, want %q", got, rotatedRefresh) + } + + // A follow-up request must reuse the persisted refreshed token with zero extra OAuth calls. + if _, errNext := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: payload, + }, opts); errNext != nil { + t.Fatalf("follow-up Execute error = %v", errNext) + } + if got := oauthCalls.Load(); got != 1 { + t.Fatalf("total OAuth calls across canceled + follow-up request = %d, want 1", got) + } + seenAuthHeaders.Lock() + headers := append([]string(nil), authHeaders...) + seenAuthHeaders.Unlock() + if len(headers) != 1 || headers[0] != "Bearer "+rotatedAccess { + t.Fatalf("follow-up Authorization headers = %v, want [Bearer %s]", headers, rotatedAccess) + } + }) + } +} + +func TestIssue7749ProjectDiscoveryFailureStillPersistsRotatedToken(t *testing.T) { + cases := []struct { + name string + failStatusCode int + failBody string + }{ + {name: "loadCodeAssist HTTP 500", failStatusCode: http.StatusInternalServerError, failBody: `{"error":"boom"}`}, + {name: "loadCodeAssist empty project_id", failStatusCode: http.StatusOK, failBody: `{}`}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + const ( + modelID = "gemini-3.6-flash" + rotatedAccess = "access-rotated-projfail-7749" + rotatedRefresh = "refresh-rotated-projfail-7749" + recoveredProj = "proj-recovered-7749" + ) + authID := "ag-projfail-7749-" + uuid.NewString() + initialRefresh := "refresh-initial-projfail-7749-" + uuid.NewString() + + var ( + oauthCalls atomic.Int32 + allowDiscovery atomic.Bool + seenRefreshToken sync.Mutex + refreshTokens []string + ) + + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + switch { + case req.URL.String() == "https://oauth2.googleapis.com/token": + bodyBytes, _ := io.ReadAll(req.Body) + seenRefreshToken.Lock() + refreshTokens = append(refreshTokens, string(bodyBytes)) + seenRefreshToken.Unlock() + call := oauthCalls.Add(1) + if call > 1 { + return &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":"invalid_grant"}`)), + Request: req, + }, nil + } + body := fmt.Sprintf(`{"access_token":%q,"refresh_token":%q,"expires_in":3600}`, rotatedAccess, rotatedRefresh) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "onboardUser"): + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"done":true,"response":{}}`)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "loadCodeAssist"): + if !allowDiscovery.Load() { + return &http.Response{ + StatusCode: tc.failStatusCode, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(tc.failBody)), + Request: req, + }, nil + } + body := fmt.Sprintf(`{"cloudaicompanionProject":%q,"paidTier":{"id":"tier","availableCredits":[]}}`, recoveredProj) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "generateContent"): + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"recovered"}]}}]}}`)), + Request: req, + }, nil + default: + return nil, fmt.Errorf("unexpected request: %s", req.URL.String()) + } + }) + + store := newIssue7749MemoryStore() + manager := cliproxyauth.NewManager(store, nil, nil) + manager.SetRoundTripperProvider(issue7749StaticRTProvider{rt: transport}) + exec := NewAntigravityExecutor(&config.Config{}) + manager.RegisterExecutor(exec) + + auth := &cliproxyauth.Auth{ + ID: authID, + FileName: authID + ".json", + Provider: "antigravity", + Status: cliproxyauth.StatusActive, + Metadata: map[string]any{ + "type": "antigravity", + "email": "ag-projfail-7749@example.com", + "access_token": "expiring-projfail-7749", + "refresh_token": initialRefresh, + "expired": time.Now().UTC().Add(2 * time.Minute).Format(time.RFC3339), + }, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "antigravity", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + payload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`) + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatAntigravity} + + if _, errFirst := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: payload, + }, opts); errFirst == nil { + t.Fatal("first Execute unexpectedly succeeded when project discovery failed") + } + + gotAuth, ok := manager.GetByID(authID) + if !ok || gotAuth == nil { + t.Fatalf("manager missing auth %s after project discovery failure", authID) + } + if got := metaStringValue(gotAuth.Metadata, "access_token"); got != rotatedAccess { + t.Fatalf("manager access_token after project discovery failure = %q, want %q", got, rotatedAccess) + } + if got := metaStringValue(gotAuth.Metadata, "refresh_token"); got != rotatedRefresh { + t.Fatalf("manager refresh_token after project discovery failure = %q, want %q", got, rotatedRefresh) + } + savedAuth := store.get(authID) + if savedAuth == nil { + t.Fatal("store did not persist rotated token after project discovery failure") + } + if got := metaStringValue(savedAuth.Metadata, "refresh_token"); got != rotatedRefresh { + t.Fatalf("store refresh_token after project discovery failure = %q, want %q", got, rotatedRefresh) + } + + // Clear transient cooldown from the failed discovery attempt and verify recovery. + clearIssue7749Cooldown(t, manager, gotAuth, modelID) + + allowDiscovery.Store(true) + if _, errSecond := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: payload, + }, opts); errSecond != nil { + t.Fatalf("recovery Execute error = %v", errSecond) + } + if got := oauthCalls.Load(); got != 1 { + t.Fatalf("OAuth calls across failed discovery + recovery = %d, want 1", got) + } + recoveredAuth, _ := manager.GetByID(authID) + if got := metaStringValue(recoveredAuth.Metadata, "project_id"); got != recoveredProj { + t.Fatalf("recovered project_id = %q, want %q", got, recoveredProj) + } + }) + } +} + +func TestIssue7749TokenCrossingSafetyWindowAfterPrepareStillPersistsAndUpdatesMarkResult(t *testing.T) { + const ( + modelID = "gemini-3.6-flash" + staleAccess = "stale-window-7749" + refreshedAccess = "fresh-window-7749" + rotatedRefresh = "rotated-window-7749" + ) + authID := "ag-window-7749-" + uuid.NewString() + initialRefresh := "initial-window-7749-" + uuid.NewString() + + baseNow := time.Now().UTC().Truncate(time.Second) + var clockMu sync.Mutex + currentNow := baseNow + origNow := antigravityNow + antigravityNow = func() time.Time { + clockMu.Lock() + defer clockMu.Unlock() + return currentNow + } + t.Cleanup(func() { + antigravityNow = origNow + }) + + var ( + oauthCalls atomic.Int32 + failNext atomic.Bool + ) + failNext.Store(true) + + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + switch { + case req.URL.String() == "https://oauth2.googleapis.com/token": + oauthCalls.Add(1) + body := fmt.Sprintf(`{"access_token":%q,"refresh_token":%q,"expires_in":3600}`, refreshedAccess, rotatedRefresh) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "loadCodeAssist"): + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"tier","availableCredits":[]}}`)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "generateContent"): + if failNext.Load() { + return &http.Response{ + StatusCode: http.StatusInternalServerError, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":{"code":500,"message":"upstream failure"}}`)), + Request: req, + }, nil + } + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]}}]}}`)), + Request: req, + }, nil + default: + return nil, fmt.Errorf("unexpected request: %s", req.URL.String()) + } + }) + + store := newIssue7749MemoryStore() + hook := &issue7749ResultHook{} + manager := cliproxyauth.NewManager(store, nil, hook) + manager.SetRoundTripperProvider(issue7749StaticRTProvider{rt: transport}) + exec := NewAntigravityExecutor(&config.Config{}) + manager.RegisterExecutor(exec) + + // Token starts 10s OUTSIDE the 5m safety window during PrepareRequestAuth. + auth := &cliproxyauth.Auth{ + ID: authID, + FileName: authID + ".json", + Provider: "antigravity", + Status: cliproxyauth.StatusActive, + Metadata: map[string]any{ + "type": "antigravity", + "email": "ag-window-7749@example.com", + "project_id": "proj-window-7749", + "access_token": staleAccess, + "refresh_token": initialRefresh, + "expired": baseNow.Add(antigravityRequestTokenSafetyWindow + 10*time.Second).Format(time.RFC3339), + }, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "antigravity", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + payload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`) + opts := cliproxyexecutor.Options{ + SourceFormat: sdktranslator.FormatAntigravity, + RequestAfterAuthInterceptor: func(_ context.Context, _ cliproxyexecutor.RequestAfterAuthInterceptRequest) cliproxyexecutor.RequestAfterAuthInterceptResponse { + // Advance clock across the 5m safety window AFTER PrepareRequestAuth and BEFORE Execute. + clockMu.Lock() + currentNow = baseNow.Add(20 * time.Second) + clockMu.Unlock() + return cliproxyexecutor.RequestAfterAuthInterceptResponse{} + }, + } + + if _, errFirst := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: payload, + }, opts); errFirst == nil { + t.Fatal("first Execute unexpectedly succeeded on upstream 500") + } + + results := hook.snapshot() + if len(results) == 0 { + t.Fatal("expected MarkResult to record failed attempt") + } + if got := results[0].AccessToken; got != refreshedAccess { + t.Fatalf("failed Result.AccessToken after window crossing = %q, want %q", got, refreshedAccess) + } + + gotAuth, ok := manager.GetByID(authID) + if !ok || gotAuth == nil { + t.Fatalf("manager missing auth %s", authID) + } + if got := metaStringValue(gotAuth.Metadata, "access_token"); got != refreshedAccess { + t.Fatalf("manager access_token after window crossing = %q, want %q", got, refreshedAccess) + } + if got := metaStringValue(gotAuth.Metadata, "refresh_token"); got != rotatedRefresh { + t.Fatalf("manager refresh_token after window crossing = %q, want %q", got, rotatedRefresh) + } + savedAuth := store.get(authID) + if savedAuth == nil || metaStringValue(savedAuth.Metadata, "refresh_token") != rotatedRefresh { + t.Fatalf("store did not persist rotated refresh_token %q after window crossing", rotatedRefresh) + } + + // Second request must reuse the persisted refreshed token with zero additional OAuth calls. + failNext.Store(false) + clearIssue7749Cooldown(t, manager, gotAuth, modelID) + if _, errSecond := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: payload, + }, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatAntigravity}); errSecond != nil { + t.Fatalf("second Execute error = %v", errSecond) + } + if got := oauthCalls.Load(); got != 1 { + t.Fatalf("OAuth calls across window-crossing + follow-up request = %d, want 1", got) + } +} + +func TestIssue7749UnsupportedAttachmentWithExpiringTokenFailsLocallyWithoutOAuth(t *testing.T) { + const ( + geminiModelID = "gemini-3.7-flash" + claudeModelID = "claude-sonnet-4-5" + claudeFile = `{"max_tokens":8,"messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"container_upload","file_id":"file_not_stored"}]}]}` + openAIFile = `{"messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":[{"type":"file","file":{"file_id":"file-not-stored"}}]}]}` + ) + authID := "ag-unsupported-7749-" + uuid.NewString() + + var httpCalls atomic.Int32 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + httpCalls.Add(1) + return &http.Response{ + StatusCode: http.StatusInternalServerError, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":"oauth_must_not_be_called"}`)), + Request: req, + }, nil + }) + + store := newIssue7749MemoryStore() + manager := cliproxyauth.NewManager(store, nil, nil) + manager.SetRoundTripperProvider(issue7749StaticRTProvider{rt: transport}) + exec := NewAntigravityExecutor(&config.Config{}) + manager.RegisterExecutor(exec) + + auth := &cliproxyauth.Auth{ + ID: authID, + FileName: authID + ".json", + Provider: "antigravity", + Status: cliproxyauth.StatusActive, + Metadata: map[string]any{ + "type": "antigravity", + "email": "ag-unsupported-7749@example.com", + "project_id": "proj-unsupported-7749", + "access_token": "expiring-unsupported-7749", + "refresh_token": "refresh-unsupported-7749-" + uuid.NewString(), + "expired": time.Now().UTC().Add(2 * time.Minute).Format(time.RFC3339), + }, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "antigravity", []*registry.ModelInfo{ + {ID: geminiModelID}, + {ID: claudeModelID}, + }) + t.Cleanup(func() { + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + cases := []struct { + name string + model string + source string + payload string + wantPart string + }{ + {"claude source to gemini model", geminiModelID, "claude", claudeFile, "container_upload"}, + {"claude source to claude model", claudeModelID, "claude", claudeFile, "container_upload"}, + {"openai source to gemini model", geminiModelID, "openai", openAIFile, "file"}, + } + + for _, tc := range cases { + req := cliproxyexecutor.Request{Model: tc.model, Payload: []byte(tc.payload)} + opts := func(stream bool) cliproxyexecutor.Options { + return cliproxyexecutor.Options{SourceFormat: sdktranslator.FromString(tc.source), Stream: stream} + } + calls := map[string]func() error{ + "Execute": func() error { + _, err := manager.Execute(context.Background(), []string{"antigravity"}, req, opts(false)) + return err + }, + "ExecuteStream": func() error { + _, err := manager.ExecuteStream(context.Background(), []string{"antigravity"}, req, opts(true)) + return err + }, + "CountTokens": func() error { + _, err := manager.ExecuteCount(context.Background(), []string{"antigravity"}, req, opts(false)) + return err + }, + } + for method, call := range calls { + err := call() + var part *translatorcommon.UnsupportedPartError + if !errors.As(err, &part) || part.Type != tc.wantPart { + t.Errorf("%s %s: err = %v, want UnsupportedPartError(%s)", tc.name, method, err, tc.wantPart) + } + } + } + + if got := httpCalls.Load(); got != 0 { + t.Fatalf("HTTP/OAuth calls for locally-refused unsupported attachments = %d, want 0", got) + } +} + +func clearIssue7749Cooldown(t *testing.T, manager *cliproxyauth.Manager, auth *cliproxyauth.Auth, modelID string) { + t.Helper() + manager.MarkResult(context.Background(), cliproxyauth.Result{ + AuthID: auth.ID, + Provider: auth.Provider, + Model: modelID, + RouteModel: modelID, + Success: true, + CompletedResponse: true, + CredentialVersion: auth.CredentialVersion, + RegistrationEpoch: auth.RegistrationEpoch, + }) +} + +func TestIssue7749ConcurrentRequestsRefreshOnceAndSharePersistedToken(t *testing.T) { + const ( + modelID = "gemini-3.6-flash" + rotatedAccess = "access-concurrent-7749" + rotatedRefresh = "refresh-concurrent-7749" + ) + authID := "ag-concurrent-7749-" + uuid.NewString() + initialRefresh := "refresh-concurrent-init-7749-" + uuid.NewString() + + oauthStarted := make(chan struct{}) + releaseOAuth := make(chan struct{}) + var oauthCalls atomic.Int32 + + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + switch { + case req.URL.String() == "https://oauth2.googleapis.com/token": + if call := oauthCalls.Add(1); call == 1 { + close(oauthStarted) + <-releaseOAuth + body := fmt.Sprintf(`{"access_token":%q,"refresh_token":%q,"expires_in":3600}`, rotatedAccess, rotatedRefresh) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil + } + return &http.Response{ + StatusCode: http.StatusBadRequest, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":"invalid_grant"}`)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "loadCodeAssist"): + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"tier","availableCredits":[]}}`)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "generateContent"): + if got := req.Header.Get("Authorization"); got != "Bearer "+rotatedAccess { + return &http.Response{ + StatusCode: http.StatusUnauthorized, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"error":"stale token"}`)), + Request: req, + }, nil + } + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]}}]}}`)), + Request: req, + }, nil + default: + return nil, fmt.Errorf("unexpected request: %s", req.URL.String()) + } + }) + + store := newIssue7749MemoryStore() + manager := cliproxyauth.NewManager(store, nil, nil) + manager.SetRoundTripperProvider(issue7749StaticRTProvider{rt: transport}) + exec := NewAntigravityExecutor(&config.Config{}) + manager.RegisterExecutor(exec) + + auth := &cliproxyauth.Auth{ + ID: authID, + FileName: authID + ".json", + Provider: "antigravity", + Status: cliproxyauth.StatusActive, + Metadata: map[string]any{ + "type": "antigravity", + "email": "ag-concurrent-7749@example.com", + "project_id": "proj-concurrent-7749", + "access_token": "expiring-concurrent-7749", + "refresh_token": initialRefresh, + "expired": time.Now().UTC().Add(2 * time.Minute).Format(time.RFC3339), + }, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + registry.GetGlobalRegistry().RegisterClient(authID, "antigravity", []*registry.ModelInfo{{ID: modelID}}) + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + registry.GetGlobalRegistry().UnregisterClient(authID) + }) + + payload := []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`) + opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatAntigravity} + + // Delay the second request inside RequestAfterAuthInterceptor until the first + // request is already inside OAuth, then release both to exercise both the + // lock-wait and post-commit re-read paths. + secondEnteredInterceptor := make(chan struct{}) + releaseSecond := make(chan struct{}) + + errCh := make(chan error, 2) + go func() { + _, errExec := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: payload, + }, opts) + errCh <- errExec + }() + + select { + case <-oauthStarted: + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for first request to enter OAuth") + } + + go func() { + secondOpts := opts + secondOpts.RequestAfterAuthInterceptor = func(_ context.Context, _ cliproxyexecutor.RequestAfterAuthInterceptRequest) cliproxyexecutor.RequestAfterAuthInterceptResponse { + close(secondEnteredInterceptor) + <-releaseSecond + return cliproxyexecutor.RequestAfterAuthInterceptResponse{} + } + _, errExec := manager.Execute(context.Background(), []string{"antigravity"}, cliproxyexecutor.Request{ + Model: modelID, + Payload: payload, + }, secondOpts) + errCh <- errExec + }() + + select { + case <-secondEnteredInterceptor: + case <-time.After(3 * time.Second): + t.Fatal("timed out waiting for second request to capture stale pre-refresh auth snapshot") + } + + // Let first request finish OAuth and commit, then release the second request + // which still holds the pre-refresh auth clone. + close(releaseOAuth) + if errFirst := <-errCh; errFirst != nil { + t.Fatalf("first concurrent Execute error = %v", errFirst) + } + close(releaseSecond) + if errSecond := <-errCh; errSecond != nil { + t.Fatalf("second concurrent Execute error = %v", errSecond) + } + if got := oauthCalls.Load(); got != 1 { + t.Fatalf("concurrent OAuth calls = %d, want 1", got) + } + gotAuth, _ := manager.GetByID(authID) + if got := metaStringValue(gotAuth.Metadata, "refresh_token"); got != rotatedRefresh { + t.Fatalf("persisted refresh_token = %q, want %q", got, rotatedRefresh) + } +} + +func TestIssue7749PrepareHttpRequestPersistsRefreshedToken(t *testing.T) { + const ( + rotatedAccess = "access-prep-http-7749" + rotatedRefresh = "refresh-prep-http-7749" + ) + authID := "ag-prep-http-7749-" + uuid.NewString() + initialRefresh := "refresh-prep-http-init-7749-" + uuid.NewString() + + var oauthCalls atomic.Int32 + transport := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + switch { + case req.URL.String() == "https://oauth2.googleapis.com/token": + oauthCalls.Add(1) + body := fmt.Sprintf(`{"access_token":%q,"refresh_token":%q,"expires_in":3600}`, rotatedAccess, rotatedRefresh) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(body)), + Request: req, + }, nil + case strings.Contains(req.URL.Path, "loadCodeAssist"): + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"tier","availableCredits":[]}}`)), + Request: req, + }, nil + default: + return nil, fmt.Errorf("unexpected request: %s", req.URL.String()) + } + }) + + store := newIssue7749MemoryStore() + manager := cliproxyauth.NewManager(store, nil, nil) + exec := NewAntigravityExecutor(&config.Config{}) + manager.RegisterExecutor(exec) + + auth := &cliproxyauth.Auth{ + ID: authID, + FileName: authID + ".json", + Provider: "antigravity", + Status: cliproxyauth.StatusActive, + Metadata: map[string]any{ + "type": "antigravity", + "email": "ag-prep-http-7749@example.com", + "project_id": "proj-prep-http-7749", + "access_token": "expiring-prep-http-7749", + "refresh_token": initialRefresh, + "expired": time.Now().UTC().Add(2 * time.Minute).Format(time.RFC3339), + }, + } + registered, errReg := manager.Register(context.Background(), auth) + if errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + }) + + ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", http.RoundTripper(transport)) + req1, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.test/one", nil) + if errPrep := manager.PrepareHttpRequest(ctx, registered.Clone(), req1); errPrep != nil { + t.Fatalf("PrepareHttpRequest #1 error = %v", errPrep) + } + if got := req1.Header.Get("Authorization"); got != "Bearer "+rotatedAccess { + t.Fatalf("req1 Authorization = %q, want Bearer %s", got, rotatedAccess) + } + + latest, _ := manager.GetByID(authID) + req2, _ := http.NewRequestWithContext(ctx, http.MethodGet, "https://example.test/two", nil) + if errPrep := manager.PrepareHttpRequest(ctx, latest, req2); errPrep != nil { + t.Fatalf("PrepareHttpRequest #2 error = %v", errPrep) + } + if got := req2.Header.Get("Authorization"); got != "Bearer "+rotatedAccess { + t.Fatalf("req2 Authorization = %q, want Bearer %s", got, rotatedAccess) + } + if got := oauthCalls.Load(); got != 1 { + t.Fatalf("PrepareHttpRequest OAuth calls = %d, want 1", got) + } + savedAuth := store.get(authID) + if savedAuth == nil || metaStringValue(savedAuth.Metadata, "refresh_token") != rotatedRefresh { + t.Fatalf("store did not persist rotated refresh_token %q from PrepareHttpRequest", rotatedRefresh) + } +} + +func TestIssue7749PrepareRequestAuthProjectDiscoveryExcludesRequestProxy(t *testing.T) { + resetAntigravityCreditsRetryState() + t.Cleanup(resetAntigravityCreditsRetryState) + + t.Run("strips RequestProxyURL on both OAuth refresh and project discovery while preserving decorator", func(t *testing.T) { + var ( + oauthReqProxy atomic.Value + discoveryReqProxy atomic.Value + decoratorCallCount atomic.Int32 + ) + baseRT := roundTripperFunc(func(req *http.Request) (*http.Response, error) { + switch { + case strings.Contains(req.URL.String(), "oauth2.googleapis.com/token"): + oauthReqProxy.Store(cliproxyexecutor.RequestProxyURL(req.Context())) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"access_token":"fresh-disc-access","refresh_token":"rotated-disc-refresh","expires_in":3600,"token_type":"Bearer"}`)), + }, nil + case strings.Contains(req.URL.String(), "loadCodeAssist"): + discoveryReqProxy.Store(cliproxyexecutor.RequestProxyURL(req.Context())) + return &http.Response{ + StatusCode: http.StatusOK, + Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(`{"cloudaicompanionProject":"discovered-proj-ctx-7749","paidTier":{"id":"tier","availableCredits":[]}}`)), + }, nil + default: + return nil, fmt.Errorf("unexpected url: %s", req.URL.String()) + } + }) + + ctx := cliproxyexecutor.WithRequestProxyURL(context.Background(), "http://127.0.0.1:19999") + ctx = context.WithValue(ctx, "cliproxy.roundtripper", http.RoundTripper(baseRT)) + ctx = httptransport.WithDecorator(ctx, func(base http.RoundTripper) http.RoundTripper { + return roundTripperFunc(func(req *http.Request) (*http.Response, error) { + decoratorCallCount.Add(1) + return base.RoundTrip(req) + }) + }) + + authID := "ag-proj-ctx-7749-" + uuid.NewString() + auth := &cliproxyauth.Auth{ + ID: authID, + Provider: "antigravity", + Metadata: map[string]any{ + "access_token": "stale-disc-access", + "refresh_token": "old-disc-refresh-" + uuid.NewString(), + "expired": time.Now().UTC().Add(2 * time.Minute).Format(time.RFC3339), + }, + } + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + }) + + exec := NewAntigravityExecutor(&config.Config{}) + prepared, errPrep := exec.PrepareRequestAuth(ctx, auth) + if errPrep != nil { + t.Fatalf("PrepareRequestAuth() error = %v", errPrep) + } + if got := antigravityProjectIDFromAuth(prepared); got != "discovered-proj-ctx-7749" { + t.Fatalf("project_id = %q, want discovered-proj-ctx-7749", got) + } + if got, _ := oauthReqProxy.Load().(string); got != "" { + t.Fatalf("OAuth refresh RequestProxyURL = %q, want empty", got) + } + if got, _ := discoveryReqProxy.Load().(string); got != "" { + t.Fatalf("project discovery RequestProxyURL = %q, want empty", got) + } + if decoratorCallCount.Load() < 2 { + t.Fatalf("decorator called %d times, want >= 2 (OAuth + project discovery)", decoratorCallCount.Load()) + } + }) + + t.Run("routes project discovery through credential proxy rather than RequestProxyURL and honors caller cancel", func(t *testing.T) { + var ( + requestProxyHits atomic.Int32 + authProxyHits atomic.Int32 + globalProxyHits atomic.Int32 + ) + requestProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requestProxyHits.Add(1) + http.Error(w, "request proxy must not be used for project discovery", http.StatusBadGateway) + })) + defer requestProxy.Close() + + authProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + authProxyHits.Add(1) + http.Error(w, "auth proxy reached", http.StatusBadGateway) + })) + defer authProxy.Close() + + globalProxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + globalProxyHits.Add(1) + http.Error(w, "global proxy should not override auth proxy", http.StatusBadGateway) + })) + defer globalProxy.Close() + + exec := NewAntigravityExecutor(&config.Config{ + SDKConfig: sdkconfig.SDKConfig{ProxyURL: globalProxy.URL}, + }) + authID := "ag-proj-proxy-7749-" + uuid.NewString() + auth := &cliproxyauth.Auth{ + ID: authID, + Provider: "antigravity", + ProxyURL: authProxy.URL, + Metadata: map[string]any{ + "access_token": "valid-proj-proxy-access", + "expired": time.Now().UTC().Add(time.Hour).Format(time.RFC3339), + }, + } + t.Cleanup(func() { + if value, ok := antigravityCreditsHintRefreshByID.Load(authID); ok { + if state, okState := value.(*antigravityCreditsHintRefreshState); okState && state != nil { + waitForAntigravityCreditsRefresh(t, state) + } + } + }) + + ctx := cliproxyexecutor.WithRequestProxyURL(context.Background(), requestProxy.URL) + _, _ = exec.PrepareRequestAuth(ctx, auth) + if requestProxyHits.Load() != 0 { + t.Fatalf("project discovery used RequestProxyURL %d times, want 0", requestProxyHits.Load()) + } + if globalProxyHits.Load() != 0 { + t.Fatalf("project discovery used global proxy %d times, want 0", globalProxyHits.Load()) + } + if authProxyHits.Load() == 0 { + t.Fatal("project discovery did not use auth.ProxyURL") + } + + // Caller cancellation must still abort project discovery. + canceledCtx, cancel := context.WithCancel(cliproxyexecutor.WithRequestProxyURL(context.Background(), requestProxy.URL)) + cancel() + if _, errCancel := exec.PrepareRequestAuth(canceledCtx, auth.Clone()); !errors.Is(errCancel, context.Canceled) { + t.Fatalf("PrepareRequestAuth(canceledCtx) error = %v, want context.Canceled", errCancel) + } + }) +} diff --git a/sdk/cliproxy/auth/conductor_execution.go b/sdk/cliproxy/auth/conductor_execution.go index 7e1ffeb92f..ff4ec2fdef 100644 --- a/sdk/cliproxy/auth/conductor_execution.go +++ b/sdk/cliproxy/auth/conductor_execution.go @@ -1309,6 +1309,9 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req } preparedAuth, errPrepare := m.prepareRequestAuth(execCtx, executor, auth) if errPrepare != nil { + if preparedAuth != nil { + auth = preparedAuth + } errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare) if errCtx := execCtx.Err(); errCtx != nil { return cliproxyexecutor.Response{}, errCtx @@ -1387,11 +1390,28 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req return cliproxyexecutor.Response{}, errIntercept } execReq = attachResolvedExecutionModelInfo(routing, execReq, auth, routeModel, upstreamModel, restoreExecutionModel) - execCtx = withUpstreamAttemptProvider(syncMetadataSessionToContext(execCtx, execOpts.Metadata), provider) + var activeAuth atomic.Pointer[Auth] + activeAuth.Store(auth) + syncActiveAuth := func() { + if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != auth { + auth = currentAuth + } + } + refreshExecCtx := func(base context.Context) context.Context { + return m.withExecutionAuthRefresh(base, executionAuthRefreshOptions{ + onAuthUpdated: func(updated *Auth) { + if updated != nil { + activeAuth.Store(updated.Clone()) + } + }, + }) + } + execCtx = refreshExecCtx(withUpstreamAttemptProvider(syncMetadataSessionToContext(execCtx, execOpts.Metadata), provider)) executionSeq := m.nextExecutionSeq() startExec := time.Now() var preRefreshExecErr error resp, errExec := executor.Execute(execCtx, auth, execReq, execOpts) + syncActiveAuth() errExec = markUpstreamExecutionAttemptFromContext(execCtx, errExec) durationExec := time.Since(startExec) if errExec != nil { @@ -1403,13 +1423,15 @@ func (m *Manager) executeMixedOnce(ctx context.Context, providers []string, req if refreshed, okRefresh := m.tryRefreshAfterUnauthorized(refreshCtx, auth, errExec, didRefreshOnUnauthorized, execOpts.Headers); okRefresh { preRefreshExecErr = errExec auth = refreshed + activeAuth.Store(auth) publishSelectedAuthMetadata(execOpts.Metadata, auth) didRefreshOnUnauthorized = true - execCtx = withUpstreamAttemptProvider(m.newUpstreamAttemptContext(execCtx), provider) + execCtx = refreshExecCtx(withUpstreamAttemptProvider(m.newUpstreamAttemptContext(execCtx), provider)) execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata) executionSeq = m.nextExecutionSeq() startRetry := time.Now() resp, errExec = executor.Execute(execCtx, auth, execReq, execOpts) + syncActiveAuth() errExec = markUpstreamExecutionAttemptFromContext(execCtx, errExec) durationRetry := time.Since(startRetry) if errExec != nil { @@ -1591,6 +1613,9 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, } preparedAuth, errPrepare := m.prepareRequestAuth(execCtx, executor, auth) if errPrepare != nil { + if preparedAuth != nil { + auth = preparedAuth + } errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare) if errCtx := execCtx.Err(); errCtx != nil { return cliproxyexecutor.Response{}, errCtx @@ -1669,11 +1694,28 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, return cliproxyexecutor.Response{}, errIntercept } execReq = attachResolvedExecutionModelInfo(routing, execReq, auth, routeModel, upstreamModel, restoreExecutionModel) - execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata) + var activeAuth atomic.Pointer[Auth] + activeAuth.Store(auth) + syncActiveAuth := func() { + if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != auth { + auth = currentAuth + } + } + refreshExecCtx := func(base context.Context) context.Context { + return m.withExecutionAuthRefresh(base, executionAuthRefreshOptions{ + onAuthUpdated: func(updated *Auth) { + if updated != nil { + activeAuth.Store(updated.Clone()) + } + }, + }) + } + execCtx = refreshExecCtx(syncMetadataSessionToContext(execCtx, execOpts.Metadata)) executionSeq := m.nextExecutionSeq() startExec := time.Now() var preRefreshExecErr error resp, errExec := executor.CountTokens(execCtx, auth, execReq, execOpts) + syncActiveAuth() errExec = markUpstreamExecutionAttemptFromContext(execCtx, errExec) durationExec := time.Since(startExec) if errExec != nil { @@ -1685,13 +1727,15 @@ func (m *Manager) executeCountMixedOnce(ctx context.Context, providers []string, if refreshed, okRefresh := m.tryRefreshAfterUnauthorized(refreshCtx, auth, errExec, didRefreshOnUnauthorized, execOpts.Headers); okRefresh { preRefreshExecErr = errExec auth = refreshed + activeAuth.Store(auth) publishSelectedAuthMetadata(execOpts.Metadata, auth) didRefreshOnUnauthorized = true - execCtx = m.newUpstreamAttemptContext(execCtx) + execCtx = refreshExecCtx(m.newUpstreamAttemptContext(execCtx)) execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata) executionSeq = m.nextExecutionSeq() startRetry := time.Now() resp, errExec = executor.CountTokens(execCtx, auth, execReq, execOpts) + syncActiveAuth() errExec = markUpstreamExecutionAttemptFromContext(execCtx, errExec) durationRetry := time.Since(startRetry) if errExec != nil { @@ -2035,6 +2079,9 @@ func (m *Manager) executeStreamMixedOnce(ctx context.Context, providers []string preparedAuth, errPrepare = m.prepareRequestAuth(execCtx, executor, auth) } if errPrepare != nil { + if preparedAuth != nil { + auth = preparedAuth + } errPrepare = markUpstreamExecutionAttemptFromContext(execCtx, errPrepare) if errCtx := execCtx.Err(); errCtx != nil { if selection != nil { @@ -3014,27 +3061,62 @@ func (m *Manager) prepareRequestAuthInternal(ctx context.Context, preparer Reque if !preparer.ShouldPrepareRequestAuth(target) { return target, nil } + if ctx == nil { + ctx = context.Background() + } base := target.Clone() - updated, errPrepare := preparer.PrepareRequestAuth(ctx, base.Clone()) + currentExpectedVersion := expectedVersion + var latestCommitted *Auth + prepOpts := executionAuthRefreshOptions{ + holdRefreshLock: true, + expectedEpoch: expectedEpoch, + onAuthUpdated: func(saved *Auth) { + if saved != nil { + base = saved.Clone() + latestCommitted = saved.Clone() + } + }, + } + if expectedVersion != 0 { + prepOpts.expectedVersion = ¤tExpectedVersion + } + prepCtx := m.withExecutionAuthRefresh(ctx, prepOpts) + updated, errPrepare := preparer.PrepareRequestAuth(prepCtx, base.Clone()) if expectedVersion != 0 { currentAfter, okAfter := m.GetByID(id) if !okAfter || currentAfter == nil { return nil, errVerifyCredentialRemoved } - if (expectedEpoch != 0 && currentAfter.RegistrationEpoch != expectedEpoch) || currentAfter.CredentialVersion != expectedVersion { + if (expectedEpoch != 0 && currentAfter.RegistrationEpoch != expectedEpoch) || currentAfter.CredentialVersion != currentExpectedVersion { return nil, errVerifyCredentialSuperseded } } if errPrepare != nil { + if latestCommitted != nil { + return latestCommitted, errPrepare + } return auth, errPrepare } if updated == nil { + if latestCommitted != nil { + if errCtx := ctx.Err(); errCtx != nil { + return latestCommitted, errCtx + } + return latestCommitted, nil + } return target, nil } + if latestCommitted != nil && preparedAuthMatchesBase(base, updated) { + if errCtx := ctx.Err(); errCtx != nil { + return latestCommitted, errCtx + } + return latestCommitted, nil + } + commitCtx := context.WithoutCancel(ctx) if expectedVersion != 0 { - saved, committed, baseSuperseded, errUpdate := m.updatePreparedAuthStrict(ctx, base, updated) + saved, committed, baseSuperseded, errUpdate := m.updatePreparedAuthStrict(commitCtx, base, updated) if errUpdate != nil { if strings.Contains(errUpdate.Error(), "stale registration epoch") { return nil, errVerifyCredentialSuperseded @@ -3047,14 +3129,20 @@ func (m *Manager) prepareRequestAuthInternal(ctx context.Context, preparer Reque if !committed || baseSuperseded { return nil, errVerifyCredentialSuperseded } + if errCtx := ctx.Err(); errCtx != nil { + return saved, errCtx + } return saved, nil } - saved, errUpdate := m.UpdatePreparedAuth(ctx, base, updated) + saved, errUpdate := m.UpdatePreparedAuth(commitCtx, base, updated) if errUpdate != nil { return nil, errUpdate } if saved != nil { + if errCtx := ctx.Err(); errCtx != nil { + return saved, errCtx + } return saved, nil } if strings.EqualFold(strings.TrimSpace(auth.Provider), "meta") { @@ -3482,20 +3570,35 @@ func (m *Manager) InjectCredentials(req *http.Request, authID string) error { } m.mu.RLock() a := m.auths[authID] + var authClone *Auth var exec ProviderExecutor if a != nil { + authClone = a.Clone() exec, _ = m.executorLocked(executorKeyFromAuth(a)) } m.mu.RUnlock() - if a == nil || exec == nil { + if authClone == nil || exec == nil { return nil } if p, ok := exec.(RequestPreparer); ok && p != nil { - return p.PrepareRequest(req, a) + return m.prepareHTTPRequestWithExecutionAuthRefresh(req, authClone, p) } return nil } +func (m *Manager) prepareHTTPRequestWithExecutionAuthRefresh(req *http.Request, auth *Auth, preparer RequestPreparer) error { + origCtx := req.Context() + prepCtx := m.withExecutionAuthRefresh(origCtx, executionAuthRefreshOptions{}) + prepReq := req.WithContext(prepCtx) + errPrep := preparer.PrepareRequest(prepReq, auth) + finalCtx := origCtx + if updatedCtx := prepReq.Context(); updatedCtx != prepCtx { + finalCtx = context.WithValue(updatedCtx, executionAuthRefreshContextKey{}, nil) + } + *req = *prepReq.WithContext(finalCtx) + return errPrep +} + // PrepareHttpRequest injects provider credentials into the supplied HTTP request. func (m *Manager) PrepareHttpRequest(ctx context.Context, auth *Auth, req *http.Request) error { if m == nil { @@ -3522,7 +3625,7 @@ func (m *Manager) PrepareHttpRequest(ctx context.Context, auth *Auth, req *http. if !ok || preparer == nil { return &Error{Code: "not_supported", Message: "executor does not support http request preparation"} } - return preparer.PrepareRequest(req, auth) + return m.prepareHTTPRequestWithExecutionAuthRefresh(req, auth, preparer) } // NewHttpRequest constructs a new HTTP request and injects provider credentials into it. @@ -3570,7 +3673,10 @@ func (m *Manager) HttpRequest(ctx context.Context, auth *Auth, req *http.Request if exec == nil { return nil, &Error{Code: "provider_not_found", Message: "executor not registered for provider: " + providerKey} } - return exec.HttpRequest(ctx, auth, req) + if ctx == nil { + ctx = req.Context() + } + return exec.HttpRequest(m.withExecutionAuthRefresh(ctx, executionAuthRefreshOptions{}), auth, req) } func ensureCanonicalSessionMetadata(metadata map[string]any, headers http.Header, payload []byte) map[string]any { @@ -3996,6 +4102,12 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth, latest, _ := m.GetByID(auth.ID) return latest, verifyCredentialSupersededError() } + if preparedAuth != nil && preparedAuth.RegistrationEpoch == regEpoch { + auth = preparedAuth + accessToken = authAccessTokenForRequest(execCtx, auth, opts.Headers) + credVersion = auth.CredentialVersion + regEpoch = auth.RegistrationEpoch + } if errCancel := verifyCancellationError(execCtx, auth, errPrepare); errCancel != nil { updated, _ := m.GetByID(auth.ID) return updated, errCancel @@ -4026,9 +4138,40 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth, } executor = executorForAuth(baseExecutor, auth) + var activeVerifyAuth atomic.Pointer[Auth] + activeVerifyAuth.Store(auth) + syncVerifyAuth := func() { + if currentAuth := activeVerifyAuth.Load(); currentAuth != nil && currentAuth != auth { + auth = currentAuth + accessToken = authAccessTokenForRequest(execCtx, auth, opts.Headers) + credVersion = auth.CredentialVersion + regEpoch = auth.RegistrationEpoch + } + } + verifyRefreshCtx := func(base context.Context) context.Context { + return m.withExecutionAuthRefresh(base, executionAuthRefreshOptions{ + expectedEpoch: regEpoch, + expectedVersion: &credVersion, + onAuthUpdated: func(updated *Auth) { + if updated != nil { + activeVerifyAuth.Store(updated.Clone()) + } + }, + }) + } + for { - streamRes, errStream := executor.ExecuteStream(execCtx, auth, req, opts) + activeVerifyAuth.Store(auth) + streamRes, errStream := executor.ExecuteStream(verifyRefreshCtx(execCtx), auth, req, opts) + syncVerifyAuth() if errStream != nil { + if errors.Is(errStream, errVerifyCredentialRemoved) { + return nil, verifyCredentialRemovedError() + } + if errors.Is(errStream, errVerifyCredentialSuperseded) { + latest, _ := m.GetByID(auth.ID) + return latest, verifyCredentialSupersededError() + } if errCancel := verifyCancellationError(execCtx, auth, errStream); errCancel != nil { updated, _ := m.GetByID(auth.ID) return updated, errCancel @@ -4037,8 +4180,17 @@ func (m *Manager) VerifyInference(ctx context.Context, id, model string) (*Auth, if rerr != nil && rerr.HTTPStatus == http.StatusNotImplemented { opts.Stream = false for { - resp, errExec := executor.Execute(execCtx, auth, req, opts) + activeVerifyAuth.Store(auth) + resp, errExec := executor.Execute(verifyRefreshCtx(execCtx), auth, req, opts) + syncVerifyAuth() if errExec != nil { + if errors.Is(errExec, errVerifyCredentialRemoved) { + return nil, verifyCredentialRemovedError() + } + if errors.Is(errExec, errVerifyCredentialSuperseded) { + latest, _ := m.GetByID(auth.ID) + return latest, verifyCredentialSupersededError() + } if errCancel := verifyCancellationError(execCtx, auth, errExec); errCancel != nil { updated, _ := m.GetByID(auth.ID) return updated, errCancel diff --git a/sdk/cliproxy/auth/conductor_home.go b/sdk/cliproxy/auth/conductor_home.go index 9aa0dc6b17..932618890e 100644 --- a/sdk/cliproxy/auth/conductor_home.go +++ b/sdk/cliproxy/auth/conductor_home.go @@ -8,6 +8,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "github.com/MoeForge/moego/json" @@ -1920,6 +1921,9 @@ func (m *Manager) tryAntigravityCreditsExecute(ctx context.Context, req cliproxy creditsCtx = m.newUpstreamAttemptContext(creditsCtx) preparedAuth, errPrepare := m.prepareRequestAuth(creditsCtx, c.executor, c.auth) if errPrepare != nil { + if preparedAuth != nil { + c.auth = preparedAuth + } if errAbort := m.handleAntigravityCreditsPrepareError(creditsCtx, c, routeModel, creditsOpts, errPrepare); errAbort != nil { return cliproxyexecutor.Response{}, false, errAbort } @@ -1942,9 +1946,20 @@ func (m *Manager) tryAntigravityCreditsExecute(ctx context.Context, req cliproxy } return cliproxyexecutor.Response{}, false, errIntercept } - creditsCtx = syncMetadataSessionToContext(creditsCtx, execOpts.Metadata) + var activeAuth atomic.Pointer[Auth] + activeAuth.Store(c.auth) + creditsCtx = m.withExecutionAuthRefresh(syncMetadataSessionToContext(creditsCtx, execOpts.Metadata), executionAuthRefreshOptions{ + onAuthUpdated: func(updated *Auth) { + if updated != nil { + activeAuth.Store(updated.Clone()) + } + }, + }) executionSeq := m.nextExecutionSeq() resp, errExec := c.executor.Execute(creditsCtx, c.auth, execReq, execOpts) + if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != c.auth { + c.auth = currentAuth + } errExec = markUpstreamExecutionAttemptFromContext(creditsCtx, errExec) result := Result{AuthID: c.auth.ID, Provider: c.provider, Model: resultModel, RouteModel: routeModel, Success: errExec == nil, CompletedResponse: errExec == nil && !resp.Incomplete && isCompletedExecutionPayload(resp.Payload), Options: execOpts, AccessToken: authAccessTokenForRequest(creditsCtx, c.auth, execOpts.Headers), RefreshToken: authRefreshToken(c.auth), CredentialVersion: c.auth.CredentialVersion, RegistrationEpoch: c.auth.RegistrationEpoch, ExecutionSeq: executionSeq} if errExec != nil { @@ -2030,6 +2045,9 @@ func (m *Manager) tryAntigravityCreditsExecuteStream(ctx context.Context, req cl creditsCtx = m.newUpstreamAttemptContext(creditsCtx) preparedAuth, errPrepare := m.prepareRequestAuth(creditsCtx, c.executor, c.auth) if errPrepare != nil { + if preparedAuth != nil { + c.auth = preparedAuth + } if errAbort := m.handleAntigravityCreditsPrepareError(creditsCtx, c, routeModel, creditsOpts, errPrepare); errAbort != nil { return nil, false, errAbort } diff --git a/sdk/cliproxy/auth/conductor_home_execution.go b/sdk/cliproxy/auth/conductor_home_execution.go index 960ae2c37b..33474ca4f7 100644 --- a/sdk/cliproxy/auth/conductor_home_execution.go +++ b/sdk/cliproxy/auth/conductor_home_execution.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "sync" + "sync/atomic" "time" "github.com/MoeForge/moego/ojson" @@ -392,7 +393,17 @@ func (m *Manager) executeHomeOnce(ctx context.Context, providers []string, req c } return effectiveAuth.Clone(), AccessTokenSHA256(effectiveAuth) } - execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata) + var activeAuth atomic.Pointer[Auth] + activeAuth.Store(preparedAuth) + execCtx = m.withExecutionAuthRefresh(syncMetadataSessionToContext(execCtx, execOpts.Metadata), executionAuthRefreshOptions{ + ephemeral: true, + onAuthUpdated: func(updated *Auth) { + if updated != nil { + activeAuth.Store(updated.Clone()) + setEffectiveAuth(updated) + } + }, + }) executorCtx := execCtx if countTokens { executorCtx = withAccessTokenFingerprintObserver(execCtx, setEffectiveAuth) @@ -406,6 +417,9 @@ func (m *Manager) executeHomeOnce(ctx context.Context, providers []string, req c } startHomeExec := time.Now() response, errExecute = execute() + if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != preparedAuth { + preparedAuth = currentAuth + } errExecute = markUpstreamExecutionAttemptFromContext(execCtx, errExecute) durationHomeExec := time.Since(startHomeExec) if errCtx := execCtx.Err(); errCtx != nil { diff --git a/sdk/cliproxy/auth/conductor_stream.go b/sdk/cliproxy/auth/conductor_stream.go index eff27d6900..1beb89bec2 100644 --- a/sdk/cliproxy/auth/conductor_stream.go +++ b/sdk/cliproxy/auth/conductor_stream.go @@ -6,6 +6,7 @@ import ( "errors" "net/http" "strings" + "sync/atomic" "time" "github.com/MoeForge/moego/json" @@ -658,6 +659,14 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata) executionSeq := m.nextExecutionSeq() accessToken := authAccessTokenForRequest(execCtx, auth, execOpts.Headers) + var activeAuth atomic.Pointer[Auth] + activeAuth.Store(auth) + syncActiveAuth := func() { + if currentAuth := activeAuth.Load(); currentAuth != nil && currentAuth != auth { + auth = currentAuth + accessToken = authAccessTokenForRequest(execCtx, auth, execOpts.Headers) + } + } var cancelAttempt context.CancelFunc var attemptCleaned bool @@ -667,6 +676,14 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi } var attemptCtx context.Context attemptCtx, cancelAttempt = context.WithCancel(parent) + attemptCtx = m.withExecutionAuthRefresh(attemptCtx, executionAuthRefreshOptions{ + ephemeral: ephemeralResult, + onAuthUpdated: func(updated *Auth) { + if updated != nil { + activeAuth.Store(updated.Clone()) + } + }, + }) attemptCleaned = false return attemptCtx } @@ -688,9 +705,11 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi } var preRefreshStreamErr error + activeAuth.Store(auth) attemptCtx := startAttempt(execCtx) startStream := time.Now() streamResult, errStream := executor.ExecuteStream(attemptCtx, auth, execReq, execOpts) + syncActiveAuth() errStream = markUpstreamExecutionAttemptFromContext(attemptCtx, errStream) durationStream := time.Since(startStream) if errStream != nil { @@ -711,9 +730,11 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata) executionSeq = m.nextExecutionSeq() accessToken = authAccessTokenForRequest(execCtx, auth, execOpts.Headers) + activeAuth.Store(auth) attemptCtx = startAttempt(execCtx) startRetry := time.Now() streamResult, errStream = executor.ExecuteStream(attemptCtx, auth, execReq, execOpts) + syncActiveAuth() errStream = markUpstreamExecutionAttemptFromContext(attemptCtx, errStream) durationRetry := time.Since(startRetry) if errStream != nil { @@ -814,9 +835,11 @@ func (m *Manager) executeStreamWithModelPool(ctx context.Context, executor Provi execCtx = syncMetadataSessionToContext(execCtx, execOpts.Metadata) executionSeq = m.nextExecutionSeq() accessToken = authAccessTokenForRequest(execCtx, auth, execOpts.Headers) + activeAuth.Store(auth) attemptCtx = startAttempt(execCtx) startRetry := time.Now() retryStream, retryErr := executor.ExecuteStream(attemptCtx, auth, execReq, execOpts) + syncActiveAuth() retryErr = markUpstreamExecutionAttemptFromContext(attemptCtx, retryErr) retryStream, retryErr = validateStreamResult(retryStream, retryErr) retryErr = markUpstreamExecutionAttemptFromContext(attemptCtx, retryErr) diff --git a/sdk/cliproxy/auth/execution_auth_refresh.go b/sdk/cliproxy/auth/execution_auth_refresh.go new file mode 100644 index 0000000000..1a9c4a844a --- /dev/null +++ b/sdk/cliproxy/auth/execution_auth_refresh.go @@ -0,0 +1,237 @@ +package auth + +import ( + "context" + "fmt" + "reflect" + "strings" + "time" + + "github.com/router-for-me/CLIProxyAPI/v8/internal/registry" + log "github.com/sirupsen/logrus" +) + +type executionAuthRefreshHandler func(ctx context.Context, auth *Auth, refresh func(context.Context, *Auth) (*Auth, error)) (*Auth, error) + +type executionAuthRefreshContextKey struct{} + +type executionAuthRefreshOptions struct { + holdRefreshLock bool + ephemeral bool + expectedEpoch uint64 + expectedVersion *uint64 + onAuthUpdated func(*Auth) +} + +// RefreshExecutionAuth runs an executor's in-flight credential refresh through +// the Manager refresh coordinator attached to ctx, if present. +// +// When managed by Manager: +// - Refresh calls serialize under the per-credential refresh lock (unless the +// caller already holds it during PrepareRequestAuth) and re-read the latest +// registered credential snapshot before invoking refresh. +// - If refresh returns (nil, nil), no refresh was needed (for example because +// another request already refreshed the credential); the coordinator syncs +// the caller's active auth state to the latest snapshot and returns it. +// - If refresh returns a refreshed auth with err == nil, the coordinator +// commits and persists it using context.WithoutCancel so client +// cancellation never discards a rotated refresh token while preserving +// RegistrationEpoch and CredentialVersion checks, and notifies the active +// execution attempt so subsequent MarkResult / metadata records reflect the +// refreshed snapshot. +// +// When no coordinator is attached to ctx (for example in direct unit tests or +// unmanaged calls), RefreshExecutionAuth invokes refresh(ctx, auth) directly. +func RefreshExecutionAuth(ctx context.Context, auth *Auth, refresh func(context.Context, *Auth) (*Auth, error)) (*Auth, error) { + if auth == nil || refresh == nil { + return nil, nil + } + if ctx != nil { + if handler, ok := ctx.Value(executionAuthRefreshContextKey{}).(executionAuthRefreshHandler); ok && handler != nil { + return handler(ctx, auth, refresh) + } + } + return refresh(ctx, auth) +} + +func (m *Manager) withExecutionAuthRefresh(ctx context.Context, opts executionAuthRefreshOptions) context.Context { + if m == nil { + return ctx + } + if ctx == nil { + ctx = context.Background() + } + handler := func(callCtx context.Context, auth *Auth, refresh func(context.Context, *Auth) (*Auth, error)) (*Auth, error) { + if auth == nil || refresh == nil { + return nil, nil + } + if callCtx == nil { + callCtx = context.Background() + } + if errCtx := callCtx.Err(); errCtx != nil { + return nil, errCtx + } + + id := strings.TrimSpace(auth.ID) + if opts.ephemeral || id == "" || (m.HomeEnabled() && auth.RegistrationEpoch == 0) { + updated, errRefresh := refresh(callCtx, auth) + if errRefresh != nil { + return nil, errRefresh + } + if updated != nil && opts.onAuthUpdated != nil { + opts.onAuthUpdated(updated.Clone()) + } + if errCtx := callCtx.Err(); errCtx != nil { + return nil, errCtx + } + return updated, nil + } + + if !opts.holdRefreshLock { + releaseRefresh, errLock := m.lockRefreshContext(callCtx, id) + if errLock != nil { + return nil, errLock + } + defer releaseRefresh() + } + + m.mu.RLock() + current := m.auths[id] + var latest *Auth + if current != nil { + latest = current.Clone() + } + m.mu.RUnlock() + + strictVersion := opts.expectedVersion != nil && *opts.expectedVersion != 0 + if latest == nil { + if strictVersion { + return nil, errVerifyCredentialRemoved + } + if !m.HomeEnabled() && auth.RegistrationEpoch != 0 { + return nil, fmt.Errorf("refresh %s auth: credential no longer registered", prepareProviderLabel(auth.Provider)) + } + updated, errRefresh := refresh(callCtx, auth) + if errRefresh != nil { + return nil, errRefresh + } + if updated != nil && opts.onAuthUpdated != nil { + opts.onAuthUpdated(updated.Clone()) + } + if errCtx := callCtx.Err(); errCtx != nil { + return nil, errCtx + } + return updated, nil + } + + if auth.RegistrationEpoch != 0 && latest.RegistrationEpoch != auth.RegistrationEpoch { + if strictVersion { + return nil, errVerifyCredentialSuperseded + } + return nil, fmt.Errorf("refresh %s auth: stale registration epoch %d != %d", prepareProviderLabel(auth.Provider), auth.RegistrationEpoch, latest.RegistrationEpoch) + } + if opts.expectedEpoch != 0 && latest.RegistrationEpoch != opts.expectedEpoch { + return nil, errVerifyCredentialSuperseded + } + if strictVersion && latest.CredentialVersion != *opts.expectedVersion { + return nil, errVerifyCredentialSuperseded + } + + base := latest.Clone() + updated, errRefresh := refresh(callCtx, base.Clone()) + if errRefresh != nil { + return nil, errRefresh + } + if updated == nil { + if opts.onAuthUpdated != nil { + opts.onAuthUpdated(latest.Clone()) + } + if errCtx := callCtx.Err(); errCtx != nil { + return nil, errCtx + } + return latest, nil + } + + now := time.Now() + if updated.Runtime == nil { + updated.Runtime = base.Runtime + } + updated.LastRefreshedAt = now + updated.NextRefreshAfter = time.Time{} + updated.UpdatedAt = now + applyPreservedRenewalState(base, updated, updateModeRefresh, now) + if authHasUnchangedRejectedRefreshToken(updated) { + if exp, okExp := updated.AccessTokenExpirationTime(); okExp && !exp.IsZero() && exp.After(now) { + updated.NextRefreshAfter = exp + } + } + applyPreservedRejectedTokens(base, updated, true) + canServeWithAccessToken := !updated.RequiresSignIn || updated.HasValidAccessToken(now) + if canServeWithAccessToken && (updated.RejectedAccessToken == "" || authAccessToken(updated) != updated.RejectedAccessToken) { + updated.LastError = nil + updated.StatusMessage = "" + updated.Unavailable = false + updated.RefreshFailures = 0 + if updated.Status == StatusError || updated.Status == "" { + updated.Status = StatusActive + } + _ = clearUnauthorizedModelStates(updated, now) + } + if m.shouldRefresh(updated, now) { + updated.NextRefreshAfter = now.Add(refreshIneffectiveBackoff) + } + + // A successful refresh may have rotated upstream tokens after caller cancellation. + // Commit with context values intact while preserving epoch and version checks. + saved, committed, baseSuperseded, errUpdate := m.updateRefreshedAuthWithStatus(context.WithoutCancel(callCtx), base, updated) + if errUpdate != nil { + log.WithFields(log.Fields{"auth_id": base.ID, "credential": base.ID, "provider": base.Provider}).Warnf("persist refreshed auth %s (%s) failed: %v", base.Provider, base.ID, errUpdate) + if strictVersion && strings.Contains(errUpdate.Error(), "stale registration epoch") { + return nil, errVerifyCredentialSuperseded + } + return nil, errUpdate + } + if saved == nil { + if strictVersion { + return nil, errVerifyCredentialRemoved + } + return nil, fmt.Errorf("refresh %s auth: credential removed during refresh", prepareProviderLabel(base.Provider)) + } + if strictVersion { + if !committed || baseSuperseded { + return nil, errVerifyCredentialSuperseded + } + *opts.expectedVersion = saved.CredentialVersion + } + if committed { + supportedModels, regEpoch := registry.GetGlobalRegistry().GetModelsAndEpochForClient(id) + projections := make([]registry.ClientModelProjection, 0, len(supportedModels)) + for _, sm := range supportedModels { + if sm == nil || strings.TrimSpace(sm.ID) == "" { + continue + } + projections = append(projections, m.clientModelProjectionForAuth(saved, sm.ID, now)) + } + if len(projections) > 0 { + registry.GetGlobalRegistry().ApplyClientModelProjections(id, regEpoch, saved.Generation, projections) + } + } + if opts.onAuthUpdated != nil { + opts.onAuthUpdated(saved.Clone()) + } + if errCtx := callCtx.Err(); errCtx != nil { + return nil, errCtx + } + return saved.Clone(), nil + } + return context.WithValue(ctx, executionAuthRefreshContextKey{}, executionAuthRefreshHandler(handler)) +} + +func preparedAuthMatchesBase(base, updated *Auth) bool { + if base == nil || updated == nil { + return false + } + return base.ProxyURL == updated.ProxyURL && + reflect.DeepEqual(base.Metadata, updated.Metadata) && + reflect.DeepEqual(base.Attributes, updated.Attributes) +} diff --git a/sdk/cliproxy/auth/execution_auth_refresh_test.go b/sdk/cliproxy/auth/execution_auth_refresh_test.go new file mode 100644 index 0000000000..90345b07e1 --- /dev/null +++ b/sdk/cliproxy/auth/execution_auth_refresh_test.go @@ -0,0 +1,364 @@ +package auth + +import ( + "context" + "errors" + "net/http" + "sync" + "sync/atomic" + "testing" + + "github.com/MoeForge/moego/json" + internalconfig "github.com/router-for-me/CLIProxyAPI/v8/internal/config" + "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executionregistry" + cliproxyexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor" +) + +type issue7749SameIDHomeDispatcher struct { + homeAuth *Auth +} + +func (d *issue7749SameIDHomeDispatcher) RPopAuth(_ context.Context, _ string, _ string, _ http.Header, _ int) ([]byte, error) { + return json.Marshal(homeAuthDispatchResponse{Auth: *d.homeAuth.Clone()}) +} + +func (d *issue7749SameIDHomeDispatcher) HeartbeatOK() bool { return true } + +func (d *issue7749SameIDHomeDispatcher) AbortAmbiguousDispatch() {} + +type issue7749HomeRefreshExecutor struct { + mu sync.Mutex + seenTokens []string + refreshCalls atomic.Int32 +} + +func (e *issue7749HomeRefreshExecutor) Identifier() string { return "antigravity" } + +func (e *issue7749HomeRefreshExecutor) refreshIfExpiring(ctx context.Context, auth *Auth) (*Auth, error) { + updated, err := RefreshExecutionAuth(ctx, auth, func(_ context.Context, latest *Auth) (*Auth, error) { + if latest != nil && testStringValue(latest.Metadata["access_token"]) == "local-valid-token" { + // Local token looks fresh; returning (nil, nil) would adopt the local credential if Home leaked into m.auths. + return nil, nil + } + e.refreshCalls.Add(1) + out := latest.Clone() + if out.Metadata == nil { + out.Metadata = map[string]any{} + } + out.Metadata["access_token"] = "home-refreshed-token" + return out, nil + }) + if err != nil { + return nil, err + } + if updated != nil { + return updated, nil + } + return auth, nil +} + +func (e *issue7749HomeRefreshExecutor) recordToken(auth *Auth) { + e.mu.Lock() + e.seenTokens = append(e.seenTokens, testStringValue(auth.Metadata["access_token"])) + e.mu.Unlock() +} + +func (e *issue7749HomeRefreshExecutor) Execute(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + effective, err := e.refreshIfExpiring(ctx, auth) + if err != nil { + return cliproxyexecutor.Response{}, err + } + e.recordToken(effective) + return cliproxyexecutor.Response{Payload: []byte("ok")}, nil +} + +func (e *issue7749HomeRefreshExecutor) ExecuteStream(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + effective, err := e.refreshIfExpiring(ctx, auth) + if err != nil { + return nil, err + } + e.recordToken(effective) + ch := make(chan cliproxyexecutor.StreamChunk, 1) + ch <- cliproxyexecutor.StreamChunk{Payload: []byte("ok")} + close(ch) + return &cliproxyexecutor.StreamResult{Chunks: ch}, nil +} + +func (e *issue7749HomeRefreshExecutor) CountTokens(ctx context.Context, auth *Auth, _ cliproxyexecutor.Request, _ cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + effective, err := e.refreshIfExpiring(ctx, auth) + if err != nil { + return cliproxyexecutor.Response{}, err + } + e.recordToken(effective) + return cliproxyexecutor.Response{Payload: []byte("1")}, nil +} + +func (e *issue7749HomeRefreshExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) { + return auth, nil +} + +func (e *issue7749HomeRefreshExecutor) HttpRequest(_ context.Context, _ *Auth, _ *http.Request) (*http.Response, error) { + return nil, nil +} + +func TestIssue7749HomeExecutionRefreshDoesNotUseSameIDLocalAuth(t *testing.T) { + paths := []struct { + name string + run func(*Manager, context.Context) error + }{ + { + name: "Execute", + run: func(m *Manager, ctx context.Context) error { + _, err := m.Execute(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: "test-model"}, cliproxyexecutor.Options{}) + return err + }, + }, + { + name: "CountTokens", + run: func(m *Manager, ctx context.Context) error { + _, err := m.ExecuteCount(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: "test-model"}, cliproxyexecutor.Options{}) + return err + }, + }, + { + name: "ExecuteStream", + run: func(m *Manager, ctx context.Context) error { + res, err := m.ExecuteStream(ctx, []string{"antigravity"}, cliproxyexecutor.Request{Model: "test-model"}, cliproxyexecutor.Options{Stream: true}) + if err != nil { + return err + } + if res != nil && res.Chunks != nil { + for range res.Chunks { + } + } + return nil + }, + }, + } + + for _, tc := range paths { + t.Run(tc.name, func(t *testing.T) { + exec := &issue7749HomeRefreshExecutor{} + homeAuth := &Auth{ + ID: "same-id-7749", + Provider: "antigravity", + Status: StatusActive, + Metadata: map[string]any{"access_token": "home-expiring-token", "source": "home"}, + } + manager := NewManager(&requestPrepareStore{}, nil, nil) + manager.SetConfig(&internalconfig.Config{Home: internalconfig.HomeConfig{Enabled: true}}) + manager.PublishHomeDispatch(&issue7749SameIDHomeDispatcher{homeAuth: homeAuth}, executionregistry.New(), 1) + manager.RegisterExecutor(exec) + + localAuth := &Auth{ + ID: "same-id-7749", + Provider: "antigravity", + Status: StatusActive, + Metadata: map[string]any{"access_token": "local-valid-token", "source": "local"}, + } + if _, errReg := manager.Register(WithSkipPersist(context.Background()), localAuth); errReg != nil { + t.Fatalf("Register local auth: %v", errReg) + } + + if errRun := tc.run(manager, context.Background()); errRun != nil { + t.Fatalf("%s error = %v", tc.name, errRun) + } + + exec.mu.Lock() + tokens := append([]string(nil), exec.seenTokens...) + exec.mu.Unlock() + if len(tokens) != 1 || tokens[0] != "home-refreshed-token" { + t.Fatalf("%s used tokens %v, want [home-refreshed-token]", tc.name, tokens) + } + if exec.refreshCalls.Load() != 1 { + t.Fatalf("%s Home refresh calls = %d, want 1", tc.name, exec.refreshCalls.Load()) + } + + current, ok := manager.GetByID("same-id-7749") + if !ok || current == nil { + t.Fatal("local auth disappeared") + } + if got := testStringValue(current.Metadata["access_token"]); got != "local-valid-token" { + t.Fatalf("local auth access_token = %q, want unchanged local-valid-token", got) + } + }) + } +} + +type issue7749PrepAndHTTPExecutor struct { + id string + hostToSet string + seenHTTPCtx context.Context + seenReqCtx context.Context + prepareFn func(req *http.Request, auth *Auth) error +} + +func (e *issue7749PrepAndHTTPExecutor) Identifier() string { return e.id } +func (e *issue7749PrepAndHTTPExecutor) Execute(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, nil +} +func (e *issue7749PrepAndHTTPExecutor) ExecuteStream(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (*cliproxyexecutor.StreamResult, error) { + return nil, nil +} +func (e *issue7749PrepAndHTTPExecutor) CountTokens(context.Context, *Auth, cliproxyexecutor.Request, cliproxyexecutor.Options) (cliproxyexecutor.Response, error) { + return cliproxyexecutor.Response{}, nil +} +func (e *issue7749PrepAndHTTPExecutor) Refresh(_ context.Context, auth *Auth) (*Auth, error) { + return auth, nil +} +func (e *issue7749PrepAndHTTPExecutor) PrepareRequest(req *http.Request, auth *Auth) error { + if e.prepareFn != nil { + return e.prepareFn(req, auth) + } + if e.hostToSet != "" { + req.Host = e.hostToSet + } + req.Header.Set("Authorization", "Bearer prepared-tok") + return nil +} +func (e *issue7749PrepAndHTTPExecutor) HttpRequest(ctx context.Context, _ *Auth, req *http.Request) (*http.Response, error) { + e.seenHTTPCtx = ctx + e.seenReqCtx = req.Context() + if ctx != nil && ctx.Err() != nil { + return nil, ctx.Err() + } + return &http.Response{StatusCode: http.StatusOK}, nil +} + +func TestIssue7749InjectCredentialsConcurrentWithMarkResultNoRace(t *testing.T) { + exec := &issue7749PrepAndHTTPExecutor{id: "issue7749-race"} + manager := NewManager(nil, nil, nil) + manager.RegisterExecutor(exec) + + auth := &Auth{ + ID: "cred-race-7749", + Provider: "issue7749-race", + Status: StatusActive, + Metadata: map[string]any{"access_token": "tok-1"}, + } + if _, errReg := manager.Register(context.Background(), auth); errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://example.test/api", nil) + _ = manager.InjectCredentials(req, "cred-race-7749") + } + }() + go func() { + defer wg.Done() + for i := 0; i < 100; i++ { + manager.MarkResult(context.Background(), Result{ + AuthID: "cred-race-7749", + Provider: "issue7749-race", + Model: "model-" + string(rune('a'+(i%10))), + Success: i%2 == 0, + }) + } + }() + wg.Wait() +} + +func TestIssue7749ManagerHttpRequestNilContextPreservesRequestContext(t *testing.T) { + type reqCtxKey struct{} + + exec := &issue7749PrepAndHTTPExecutor{id: "issue7749-httpctx"} + manager := NewManager(nil, nil, nil) + manager.RegisterExecutor(exec) + + auth := &Auth{ + ID: "cred-httpctx-7749", + Provider: "issue7749-httpctx", + Status: StatusActive, + } + + reqCtx, cancel := context.WithCancel(context.WithValue(context.Background(), reqCtxKey{}, "req-marker-7749")) + cancel() + req, _ := http.NewRequestWithContext(reqCtx, http.MethodGet, "https://example.test/api", nil) + + _, errHTTP := manager.HttpRequest(nil, auth, req) + if !errors.Is(errHTTP, context.Canceled) { + t.Fatalf("Manager.HttpRequest(nil, auth, canceledReq) error = %v, want context.Canceled", errHTTP) + } + if exec.seenHTTPCtx == nil || exec.seenHTTPCtx.Value(reqCtxKey{}) != "req-marker-7749" { + t.Fatalf("executor HttpRequest ctx value = %v, want req-marker-7749 from req.Context()", exec.seenHTTPCtx) + } +} + +func TestIssue7749PrepareRequestPreservesHostMutation(t *testing.T) { + type origKey struct{} + type preparerKey struct{} + + exec := &issue7749PrepAndHTTPExecutor{ + id: "issue7749-host", + hostToSet: "custom-host.example.test", + prepareFn: func(req *http.Request, _ *Auth) error { + req.Host = "custom-host.example.test" + req.Header.Set("Authorization", "Bearer prepared-tok") + *req = *req.WithContext(context.WithValue(req.Context(), preparerKey{}, "from-preparer")) + return nil + }, + } + manager := NewManager(nil, nil, nil) + manager.RegisterExecutor(exec) + + auth := &Auth{ + ID: "cred-host-7749", + Provider: "issue7749-host", + Status: StatusActive, + } + registered, errReg := manager.Register(context.Background(), auth) + if errReg != nil { + t.Fatalf("Register auth: %v", errReg) + } + + t.Run("InjectCredentials", func(t *testing.T) { + origCtx := context.WithValue(context.Background(), origKey{}, "keep-7749") + req, _ := http.NewRequestWithContext(origCtx, http.MethodGet, "https://original.example.test/v1", nil) + if errInj := manager.InjectCredentials(req, registered.ID); errInj != nil { + t.Fatalf("InjectCredentials error = %v", errInj) + } + if req.Host != "custom-host.example.test" { + t.Fatalf("req.Host = %q, want custom-host.example.test", req.Host) + } + if got := req.Header.Get("Authorization"); got != "Bearer prepared-tok" { + t.Fatalf("Authorization = %q, want Bearer prepared-tok", got) + } + if req.Context().Value(origKey{}) != "keep-7749" { + t.Fatal("InjectCredentials lost original req.Context value") + } + if got := req.Context().Value(preparerKey{}); got != "from-preparer" { + t.Fatalf("InjectCredentials dropped preparer context value: got %v, want from-preparer", got) + } + if fn, ok := req.Context().Value(executionAuthRefreshContextKey{}).(executionAuthRefreshHandler); ok && fn != nil { + t.Fatal("InjectCredentials leaked executionAuthRefreshContextKey onto request context") + } + }) + + t.Run("PrepareHttpRequest", func(t *testing.T) { + origCtx := context.WithValue(context.Background(), origKey{}, "keep-prep-7749") + req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://original.example.test/v1", nil) + if errPrep := manager.PrepareHttpRequest(origCtx, registered.Clone(), req); errPrep != nil { + t.Fatalf("PrepareHttpRequest error = %v", errPrep) + } + if req.Host != "custom-host.example.test" { + t.Fatalf("req.Host = %q, want custom-host.example.test", req.Host) + } + if got := req.Header.Get("Authorization"); got != "Bearer prepared-tok" { + t.Fatalf("Authorization = %q, want Bearer prepared-tok", got) + } + if req.Context().Value(origKey{}) != "keep-prep-7749" { + t.Fatal("PrepareHttpRequest lost caller ctx value") + } + if got := req.Context().Value(preparerKey{}); got != "from-preparer" { + t.Fatalf("PrepareHttpRequest dropped preparer context value: got %v, want from-preparer", got) + } + if fn, ok := req.Context().Value(executionAuthRefreshContextKey{}).(executionAuthRefreshHandler); ok && fn != nil { + t.Fatal("PrepareHttpRequest leaked executionAuthRefreshContextKey onto request context") + } + }) +}