mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-11-29 21:33:01 +08:00
Revert "fix(antigravity): set X-Goog-User-Project header on Cloud Code PA requests"
This reverts commit acf238f6a9.
This commit is contained in:
@@ -233,12 +233,10 @@ func fetchModelsFromBaseURLs(ctx context.Context, auth *coreauth.Auth, baseURLs
|
||||
for _, baseURL := range baseURLs {
|
||||
modelsURL := baseURL + antigravityModelsPath
|
||||
|
||||
var projectID string
|
||||
var payload []byte
|
||||
if auth != nil && auth.Metadata != nil {
|
||||
if pid, ok := auth.Metadata["project_id"].(string); ok && strings.TrimSpace(pid) != "" {
|
||||
projectID = strings.TrimSpace(pid)
|
||||
payload = []byte(fmt.Sprintf(`{"project": "%s"}`, projectID))
|
||||
payload = []byte(fmt.Sprintf(`{"project": "%s"}`, strings.TrimSpace(pid)))
|
||||
}
|
||||
}
|
||||
if len(payload) == 0 {
|
||||
@@ -254,9 +252,6 @@ func fetchModelsFromBaseURLs(ctx context.Context, auth *coreauth.Auth, baseURLs
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
httpReq.Header.Set("User-Agent", misc.AntigravityUserAgent())
|
||||
if projectID != "" {
|
||||
httpReq.Header.Set("X-Goog-User-Project", projectID)
|
||||
}
|
||||
|
||||
httpClient := client
|
||||
if httpClient == nil {
|
||||
@@ -266,12 +261,6 @@ func fetchModelsFromBaseURLs(ctx context.Context, auth *coreauth.Auth, baseURLs
|
||||
httpClient.Transport = transport
|
||||
}
|
||||
}
|
||||
} else {
|
||||
cloned := *httpClient
|
||||
httpClient = &cloned
|
||||
}
|
||||
httpClient.CheckRedirect = func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
httpResp, errDo := httpClient.Do(httpReq)
|
||||
if errDo != nil {
|
||||
|
||||
@@ -125,87 +125,3 @@ func TestFetchModelsFallbackAfterTwoAttempts(t *testing.T) {
|
||||
t.Fatalf("expected endpoint 2 to be called 1 time, got %d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchModelsSetsUserProjectHeader(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
projectID string
|
||||
wantHeader string
|
||||
wantExists bool
|
||||
}{
|
||||
{name: "sets trimmed project_id header", projectID: " test-project ", wantHeader: "test-project", wantExists: true},
|
||||
{name: "omits header when project_id absent", projectID: "", wantHeader: "", wantExists: false},
|
||||
{name: "omits header when project_id whitespace", projectID: " ", wantHeader: "", wantExists: false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var gotHeaders http.Header
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotHeaders = r.Header.Clone()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"models":{"gemini-3-flash":{"displayName":"Gemini 3 Flash"}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
meta := map[string]interface{}{
|
||||
"access_token": "test-token",
|
||||
}
|
||||
if tc.projectID != "" {
|
||||
meta["project_id"] = tc.projectID
|
||||
}
|
||||
auth := &coreauth.Auth{Metadata: meta}
|
||||
|
||||
models := fetchModelsFromBaseURLs(context.Background(), auth, []string{server.URL}, server.Client())
|
||||
if len(models) != 1 {
|
||||
t.Fatalf("expected 1 model, got %d", len(models))
|
||||
}
|
||||
_, exists := gotHeaders["X-Goog-User-Project"]
|
||||
if exists != tc.wantExists {
|
||||
t.Fatalf("X-Goog-User-Project exists = %v, want %v (headers=%v)", exists, tc.wantExists, gotHeaders)
|
||||
}
|
||||
if got := gotHeaders.Get("X-Goog-User-Project"); got != tc.wantHeader {
|
||||
t.Fatalf("X-Goog-User-Project = %q, want %q", got, tc.wantHeader)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("does not follow cross-origin redirect and falls back without leaking header", func(t *testing.T) {
|
||||
var leakedHits atomic.Int32
|
||||
redirectTarget := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
leakedHits.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"models":{"leaked-model":{"displayName":"Leaked"}}}`))
|
||||
}))
|
||||
defer redirectTarget.Close()
|
||||
|
||||
redirectSource := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, redirectTarget.URL+"/steal", http.StatusFound)
|
||||
}))
|
||||
defer redirectSource.Close()
|
||||
|
||||
fallback := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"models":{"gemini-3-flash":{"displayName":"Gemini 3 Flash"}}}`))
|
||||
}))
|
||||
defer fallback.Close()
|
||||
|
||||
auth := &coreauth.Auth{
|
||||
Metadata: map[string]interface{}{
|
||||
"access_token": "test-token",
|
||||
"project_id": "test-project",
|
||||
},
|
||||
}
|
||||
|
||||
models := fetchModelsFromBaseURLs(context.Background(), auth, []string{redirectSource.URL, fallback.URL}, redirectSource.Client())
|
||||
if got := leakedHits.Load(); got != 0 {
|
||||
t.Fatalf("cross-origin redirect target hits = %d, want 0", got)
|
||||
}
|
||||
if len(models) != 1 || models[0].ID != "gemini-3-flash" {
|
||||
t.Fatalf("models = %#v, want fallback gemini-3-flash", models)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -497,14 +496,7 @@ func antigravityCredentialScope(prefix, secret string) string {
|
||||
// The underlying Transport is always shared so keep-alive connections survive across
|
||||
// requests instead of forcing a fresh TCP + TLS handshake every time.
|
||||
func newAntigravityHTTPClient(ctx context.Context, cfg *config.Config, auth *cliproxyauth.Auth, timeout time.Duration) (clientOut *http.Client) {
|
||||
defer func() {
|
||||
var attrs map[string]string
|
||||
if auth != nil {
|
||||
attrs = auth.Attributes
|
||||
}
|
||||
installAntigravityHTTPRequestRedirectPolicy(clientOut, attrs)
|
||||
clientOut = httptransport.Decorate(ctx, clientOut)
|
||||
}()
|
||||
defer func() { clientOut = httptransport.Decorate(ctx, clientOut) }()
|
||||
// Native Antigravity reuses one transport across requests. Opt into a
|
||||
// credential-scoped proxy transport only here so other providers keep their
|
||||
// existing lifecycle and different OAuth identities remain isolated.
|
||||
@@ -1061,15 +1053,7 @@ func (e *AntigravityExecutor) prepareRequestWithAuth(req *http.Request, auth *cl
|
||||
if strings.TrimSpace(token) == "" {
|
||||
return nil, statusErr{code: http.StatusUnauthorized, msg: "missing access token"}
|
||||
}
|
||||
if req.Header == nil {
|
||||
req.Header = make(http.Header)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
if projectID := antigravityProjectIDFromAuth(auth); projectID != "" && isAntigravityCloudCodeEndpoint(req.URL, auth) {
|
||||
req.Header.Set("X-Goog-User-Project", projectID)
|
||||
} else {
|
||||
req.Header.Del("X-Goog-User-Project")
|
||||
}
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
@@ -1130,48 +1114,10 @@ func (e *AntigravityExecutor) HttpRequest(ctx context.Context, auth *cliproxyaut
|
||||
util.ApplyCustomHeadersFromAttrs(httpReq, attrs)
|
||||
|
||||
httpClient := helps.WithAntigravityHTTPClientTrace(newAntigravityHTTPClient(ctx, e.cfg, auth, 0), auth, "http_request")
|
||||
installAntigravityHTTPRequestRedirectPolicy(httpClient, attrs)
|
||||
return httpClient.Do(httpReq)
|
||||
}
|
||||
|
||||
var antigravityCloudCodeBaseURLs = []*url.URL{
|
||||
mustParseAntigravityURL(antigravityBaseURLDaily),
|
||||
mustParseAntigravityURL(antigravitySandboxBaseURLDaily),
|
||||
mustParseAntigravityURL(antigravityBaseURLProd),
|
||||
}
|
||||
|
||||
func mustParseAntigravityURL(raw string) *url.URL {
|
||||
parsed, errParse := url.Parse(raw)
|
||||
if errParse != nil {
|
||||
return nil
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func isAntigravityCloudCodeEndpoint(targetURL *url.URL, auth *cliproxyauth.Auth) bool {
|
||||
if targetURL == nil || targetURL.Hostname() == "" {
|
||||
return false
|
||||
}
|
||||
for _, base := range antigravityCloudCodeBaseURLs {
|
||||
if antigravitySameRedirectOrigin(base, targetURL) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
customBase := resolveCustomAntigravityBaseURL(auth)
|
||||
if customBase == "" {
|
||||
return false
|
||||
}
|
||||
parsedCustom, errParse := url.Parse(customBase)
|
||||
if errParse != nil || !antigravitySameRedirectOrigin(parsedCustom, targetURL) {
|
||||
return false
|
||||
}
|
||||
basePath := strings.TrimRight(path.Clean("/"+parsedCustom.Path), "/")
|
||||
if basePath == "" {
|
||||
return true
|
||||
}
|
||||
targetPath := path.Clean("/" + targetURL.Path)
|
||||
return targetPath == basePath || strings.HasPrefix(targetPath, basePath+"/")
|
||||
}
|
||||
|
||||
func installAntigravityHTTPRequestRedirectPolicy(client *http.Client, attrs map[string]string) {
|
||||
if client == nil {
|
||||
return
|
||||
@@ -1220,7 +1166,7 @@ func stripAntigravityCrossOriginHeaders(req *http.Request, customNames map[strin
|
||||
req.Host = ""
|
||||
for name := range req.Header {
|
||||
lower := strings.ToLower(name)
|
||||
if lower == "authorization" || lower == "host" || lower == "x-goog-user-project" {
|
||||
if lower == "authorization" || lower == "host" {
|
||||
delete(req.Header, name)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1553,257 +1553,6 @@ func TestAntigravityExecute_CaseInsensitiveGeminiRouteToStreamHelper(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityBuildRequest_SetsUserProjectHeader(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
stream bool
|
||||
}{
|
||||
{name: "generateContent", stream: false},
|
||||
{name: "streamGenerateContent", stream: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
executor := &AntigravityExecutor{cfg: &config.Config{}}
|
||||
auth := &cliproxyauth.Auth{
|
||||
ID: "auth-user-project-build",
|
||||
Metadata: map[string]any{
|
||||
"project_id": " aicode-consumers ",
|
||||
},
|
||||
}
|
||||
httpReq, errBuild := executor.buildRequest(context.Background(), auth, "token", "gemini-3-flash", []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`), tc.stream, "", "https://daily-cloudcode-pa.googleapis.com")
|
||||
if errBuild != nil {
|
||||
t.Fatalf("buildRequest() error = %v", errBuild)
|
||||
}
|
||||
if got := httpReq.Header.Get("X-Goog-User-Project"); got != "aicode-consumers" {
|
||||
t.Fatalf("X-Goog-User-Project = %q, want %q", got, "aicode-consumers")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("allows custom header override", func(t *testing.T) {
|
||||
executor := &AntigravityExecutor{cfg: &config.Config{}}
|
||||
auth := &cliproxyauth.Auth{
|
||||
ID: "auth-user-project-override",
|
||||
Attributes: map[string]string{
|
||||
"header:X-Goog-User-Project": "custom-project-override",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"project_id": "aicode-consumers",
|
||||
},
|
||||
}
|
||||
httpReq, errBuild := executor.buildRequest(context.Background(), auth, "token", "gemini-3-flash", []byte(`{"request":{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}}`), false, "", "https://daily-cloudcode-pa.googleapis.com")
|
||||
if errBuild != nil {
|
||||
t.Fatalf("buildRequest() error = %v", errBuild)
|
||||
}
|
||||
if got := httpReq.Header.Get("X-Goog-User-Project"); got != "custom-project-override" {
|
||||
t.Fatalf("X-Goog-User-Project = %q, want %q", got, "custom-project-override")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAntigravityCountTokens_SetsUserProjectHeader(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
projectID string
|
||||
attrs map[string]string
|
||||
wantHeader string
|
||||
wantExists bool
|
||||
}{
|
||||
{
|
||||
name: "sets trimmed project_id header",
|
||||
projectID: " aicode-consumers ",
|
||||
wantHeader: "aicode-consumers",
|
||||
wantExists: true,
|
||||
},
|
||||
{
|
||||
name: "omits header when project_id is empty",
|
||||
projectID: " ",
|
||||
wantHeader: "",
|
||||
wantExists: false,
|
||||
},
|
||||
{
|
||||
name: "allows custom header override",
|
||||
projectID: "aicode-consumers",
|
||||
attrs: map[string]string{
|
||||
"header:X-Goog-User-Project": "custom-count-project",
|
||||
},
|
||||
wantHeader: "custom-count-project",
|
||||
wantExists: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var gotHeaders http.Header
|
||||
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", roundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
gotHeaders = req.Header.Clone()
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: http.Header{"Content-Type": []string{"application/json"}},
|
||||
Body: io.NopCloser(strings.NewReader(`{"totalTokens":42}`)),
|
||||
}, nil
|
||||
}))
|
||||
|
||||
executor := &AntigravityExecutor{cfg: &config.Config{}}
|
||||
meta := map[string]any{
|
||||
"access_token": "token-123",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
}
|
||||
if tc.projectID != "" {
|
||||
meta["project_id"] = tc.projectID
|
||||
}
|
||||
auth := &cliproxyauth.Auth{
|
||||
ID: "auth-count-user-project",
|
||||
Attributes: tc.attrs,
|
||||
Metadata: meta,
|
||||
}
|
||||
_, errCount := executor.CountTokens(ctx, auth, cliproxyexecutor.Request{
|
||||
Model: "gemini-3-flash",
|
||||
Payload: []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`),
|
||||
}, cliproxyexecutor.Options{
|
||||
SourceFormat: sdktranslator.FormatGemini,
|
||||
ResponseFormat: sdktranslator.FormatGemini,
|
||||
})
|
||||
if errCount != nil {
|
||||
t.Fatalf("CountTokens() error = %v", errCount)
|
||||
}
|
||||
_, exists := gotHeaders["X-Goog-User-Project"]
|
||||
if exists != tc.wantExists {
|
||||
t.Fatalf("X-Goog-User-Project exists = %v, want %v (headers=%v)", exists, tc.wantExists, gotHeaders)
|
||||
}
|
||||
if got := gotHeaders.Get("X-Goog-User-Project"); got != tc.wantHeader {
|
||||
t.Fatalf("X-Goog-User-Project = %q, want %q", got, tc.wantHeader)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAntigravityRequests_StripUserProjectHeaderOnCrossOriginRedirect(t *testing.T) {
|
||||
type hopCapture struct {
|
||||
url string
|
||||
userProject string
|
||||
authHeader string
|
||||
}
|
||||
newRedirectCtx := func(hops *[]hopCapture, okHeader http.Header, okBody string) context.Context {
|
||||
return context.WithValue(context.Background(), "cliproxy.roundtripper", roundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
*hops = append(*hops, hopCapture{
|
||||
url: req.URL.String(),
|
||||
userProject: req.Header.Get("X-Goog-User-Project"),
|
||||
authHeader: req.Header.Get("Authorization"),
|
||||
})
|
||||
if req.URL.Host == "daily-cloudcode-pa.googleapis.com" {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusFound,
|
||||
Header: http.Header{"Location": {"https://other-origin.example/redirected"}},
|
||||
Body: http.NoBody,
|
||||
}, nil
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: okHeader.Clone(),
|
||||
Body: io.NopCloser(strings.NewReader(okBody)),
|
||||
}, nil
|
||||
}))
|
||||
}
|
||||
newAuth := func(id string) *cliproxyauth.Auth {
|
||||
return &cliproxyauth.Auth{
|
||||
ID: id,
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-redirect",
|
||||
"project_id": "aicode-consumers",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
}
|
||||
assertRedirectHops := func(t *testing.T, hops []hopCapture) {
|
||||
t.Helper()
|
||||
if len(hops) != 2 {
|
||||
t.Fatalf("hops = %d, want 2 (%+v)", len(hops), hops)
|
||||
}
|
||||
if hops[0].userProject != "aicode-consumers" {
|
||||
t.Fatalf("initial hop X-Goog-User-Project = %q, want %q", hops[0].userProject, "aicode-consumers")
|
||||
}
|
||||
if hops[1].url != "https://other-origin.example/redirected" {
|
||||
t.Fatalf("second hop URL = %q, want redirected origin", hops[1].url)
|
||||
}
|
||||
if hops[1].userProject != "" {
|
||||
t.Fatalf("cross-origin hop leaked X-Goog-User-Project = %q, want empty", hops[1].userProject)
|
||||
}
|
||||
if hops[1].authHeader != "" {
|
||||
t.Fatalf("cross-origin hop leaked Authorization = %q, want empty", hops[1].authHeader)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("Execute non-stream", func(t *testing.T) {
|
||||
var hops []hopCapture
|
||||
ctx := newRedirectCtx(&hops, http.Header{"Content-Type": {"application/json"}}, `{"response":{"candidates":[{"content":{"role":"model","parts":[{"text":"ok"}]},"finishReason":"STOP"}]}}`)
|
||||
executor := &AntigravityExecutor{cfg: &config.Config{}}
|
||||
_, errExec := executor.Execute(ctx, newAuth("auth-redirect-exec"), cliproxyexecutor.Request{
|
||||
Model: "gemini-3-flash",
|
||||
Payload: []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`),
|
||||
}, cliproxyexecutor.Options{
|
||||
SourceFormat: sdktranslator.FormatGemini,
|
||||
ResponseFormat: sdktranslator.FormatGemini,
|
||||
})
|
||||
if errExec != nil {
|
||||
t.Fatalf("Execute() error = %v", errExec)
|
||||
}
|
||||
assertRedirectHops(t, hops)
|
||||
})
|
||||
|
||||
t.Run("Execute Claude non-stream", func(t *testing.T) {
|
||||
var hops []hopCapture
|
||||
ctx := newRedirectCtx(&hops, http.Header{"Content-Type": {"text/event-stream"}}, "data: {\"response\":{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}}\n\n")
|
||||
executor := &AntigravityExecutor{cfg: &config.Config{}}
|
||||
_, errExec := executor.Execute(ctx, newAuth("auth-redirect-claude-exec"), cliproxyexecutor.Request{
|
||||
Model: "claude-sonnet-4-5",
|
||||
Payload: []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`),
|
||||
}, cliproxyexecutor.Options{
|
||||
SourceFormat: sdktranslator.FormatGemini,
|
||||
ResponseFormat: sdktranslator.FormatGemini,
|
||||
})
|
||||
if errExec != nil {
|
||||
t.Fatalf("Execute(claude) error = %v", errExec)
|
||||
}
|
||||
assertRedirectHops(t, hops)
|
||||
})
|
||||
|
||||
t.Run("ExecuteStream", func(t *testing.T) {
|
||||
var hops []hopCapture
|
||||
ctx := newRedirectCtx(&hops, http.Header{"Content-Type": {"text/event-stream"}}, "data: {\"response\":{\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"ok\"}]},\"finishReason\":\"STOP\"}]}}\n\n")
|
||||
executor := &AntigravityExecutor{cfg: &config.Config{}}
|
||||
streamRes, errStream := executor.ExecuteStream(ctx, newAuth("auth-redirect-stream"), cliproxyexecutor.Request{
|
||||
Model: "gemini-3-flash",
|
||||
Payload: []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`),
|
||||
}, cliproxyexecutor.Options{
|
||||
SourceFormat: sdktranslator.FormatGemini,
|
||||
ResponseFormat: sdktranslator.FormatGemini,
|
||||
})
|
||||
if errStream != nil {
|
||||
t.Fatalf("ExecuteStream() error = %v", errStream)
|
||||
}
|
||||
for range streamRes.Chunks {
|
||||
}
|
||||
assertRedirectHops(t, hops)
|
||||
})
|
||||
|
||||
t.Run("CountTokens", func(t *testing.T) {
|
||||
var hops []hopCapture
|
||||
ctx := newRedirectCtx(&hops, http.Header{"Content-Type": {"application/json"}}, `{"totalTokens":42}`)
|
||||
executor := &AntigravityExecutor{cfg: &config.Config{}}
|
||||
_, errCount := executor.CountTokens(ctx, newAuth("auth-redirect-count"), cliproxyexecutor.Request{
|
||||
Model: "gemini-3-flash",
|
||||
Payload: []byte(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`),
|
||||
}, cliproxyexecutor.Options{
|
||||
SourceFormat: sdktranslator.FormatGemini,
|
||||
ResponseFormat: sdktranslator.FormatGemini,
|
||||
})
|
||||
if errCount != nil {
|
||||
t.Fatalf("CountTokens() error = %v", errCount)
|
||||
}
|
||||
assertRedirectHops(t, hops)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAntigravitySessionIDDistributionIncludesPositiveAndNegative(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
|
||||
@@ -701,9 +701,6 @@ func (e *AntigravityExecutor) updateAntigravityCreditsBalanceForTask(ctx context
|
||||
httpReq.Header.Set("Authorization", "Bearer "+token)
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("User-Agent", userAgent)
|
||||
if projectID := antigravityProjectIDFromAuth(auth); projectID != "" {
|
||||
httpReq.Header.Set("X-Goog-User-Project", projectID)
|
||||
}
|
||||
if host := resolveHost(baseURL); host != "" {
|
||||
httpReq.Host = host
|
||||
}
|
||||
|
||||
@@ -1938,130 +1938,3 @@ func TestUpdateAntigravityCreditsBalanceForTask_ForbiddenTOSViolation(t *testing
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestUpdateAntigravityCreditsBalanceForTask_UserProjectHeader(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
projectID string
|
||||
attrs map[string]string
|
||||
wantHeader string
|
||||
wantExists bool
|
||||
}{
|
||||
{
|
||||
name: "sets trimmed project_id header",
|
||||
projectID: " aicode-consumers ",
|
||||
wantHeader: "aicode-consumers",
|
||||
wantExists: true,
|
||||
},
|
||||
{
|
||||
name: "omits header when project_id is absent",
|
||||
projectID: "",
|
||||
wantHeader: "",
|
||||
wantExists: false,
|
||||
},
|
||||
{
|
||||
name: "allows custom header override",
|
||||
projectID: "aicode-consumers",
|
||||
attrs: map[string]string{
|
||||
"header:X-Goog-User-Project": "custom-credits-project",
|
||||
},
|
||||
wantHeader: "custom-credits-project",
|
||||
wantExists: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
resetAntigravityCreditsRetryState()
|
||||
t.Cleanup(resetAntigravityCreditsRetryState)
|
||||
|
||||
var gotHeaders http.Header
|
||||
exec := NewAntigravityExecutor(&config.Config{
|
||||
QuotaExceeded: config.QuotaExceeded{AntigravityCredits: true},
|
||||
})
|
||||
meta := map[string]any{}
|
||||
if tc.projectID != "" {
|
||||
meta["project_id"] = tc.projectID
|
||||
}
|
||||
auth := &cliproxyauth.Auth{
|
||||
ID: "auth-credits-user-project-" + tc.name,
|
||||
Attributes: tc.attrs,
|
||||
Metadata: meta,
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
cliproxyauth.SetAntigravityCreditsHint(auth.ID, cliproxyauth.AntigravityCreditsHint{})
|
||||
})
|
||||
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", roundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
gotHeaders = req.Header.Clone()
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"pro","availableCredits":[]}}`)),
|
||||
}, nil
|
||||
}))
|
||||
|
||||
exec.updateAntigravityCreditsBalance(ctx, auth, "token")
|
||||
|
||||
_, exists := gotHeaders["X-Goog-User-Project"]
|
||||
if exists != tc.wantExists {
|
||||
t.Fatalf("X-Goog-User-Project exists = %v, want %v (headers=%v)", exists, tc.wantExists, gotHeaders)
|
||||
}
|
||||
if got := gotHeaders.Get("X-Goog-User-Project"); got != tc.wantHeader {
|
||||
t.Fatalf("X-Goog-User-Project = %q, want %q", got, tc.wantHeader)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("strips X-Goog-User-Project on cross-origin redirect", func(t *testing.T) {
|
||||
resetAntigravityCreditsRetryState()
|
||||
t.Cleanup(resetAntigravityCreditsRetryState)
|
||||
|
||||
type hopCapture struct {
|
||||
url string
|
||||
userProject string
|
||||
}
|
||||
var hops []hopCapture
|
||||
exec := NewAntigravityExecutor(&config.Config{
|
||||
QuotaExceeded: config.QuotaExceeded{AntigravityCredits: true},
|
||||
})
|
||||
auth := &cliproxyauth.Auth{
|
||||
ID: "auth-credits-user-project-redirect",
|
||||
Metadata: map[string]any{
|
||||
"project_id": "aicode-consumers",
|
||||
},
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
cliproxyauth.SetAntigravityCreditsHint(auth.ID, cliproxyauth.AntigravityCreditsHint{})
|
||||
})
|
||||
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", roundTripperFunc(func(req *http.Request) (*http.Response, error) {
|
||||
hops = append(hops, hopCapture{
|
||||
url: req.URL.String(),
|
||||
userProject: req.Header.Get("X-Goog-User-Project"),
|
||||
})
|
||||
if req.URL.Host == "daily-cloudcode-pa.googleapis.com" {
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusFound,
|
||||
Header: http.Header{"Location": {"https://other-origin.example/credits"}},
|
||||
Body: http.NoBody,
|
||||
}, nil
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(`{"paidTier":{"id":"pro","availableCredits":[]}}`)),
|
||||
}, nil
|
||||
}))
|
||||
|
||||
exec.updateAntigravityCreditsBalance(ctx, auth, "token")
|
||||
|
||||
if len(hops) != 2 {
|
||||
t.Fatalf("hops = %d, want 2 (%+v)", len(hops), hops)
|
||||
}
|
||||
if hops[0].userProject != "aicode-consumers" {
|
||||
t.Fatalf("initial hop X-Goog-User-Project = %q, want %q", hops[0].userProject, "aicode-consumers")
|
||||
}
|
||||
if hops[1].userProject != "" {
|
||||
t.Fatalf("cross-origin hop leaked X-Goog-User-Project = %q, want empty", hops[1].userProject)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -563,320 +563,3 @@ func TestAntigravityHttpRequest_SetsHostAndCustomAuthHeaders(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAntigravityHttpRequest_UserProjectHeader(t *testing.T) {
|
||||
t.Run("sets X-Goog-User-Project on Cloud Code PA HttpRequest and strips on cross-origin redirect", func(t *testing.T) {
|
||||
resetAntigravityCreditsRetryState()
|
||||
t.Cleanup(resetAntigravityCreditsRetryState)
|
||||
|
||||
exec := NewAntigravityExecutor(&config.Config{})
|
||||
auth := &cliproxyauth.Auth{
|
||||
ID: "ag-http-req-user-project",
|
||||
Provider: "antigravity",
|
||||
Status: cliproxyauth.StatusActive,
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-1",
|
||||
"project_id": " project-7837 ",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
|
||||
type hopCapture struct {
|
||||
url string
|
||||
userProject string
|
||||
}
|
||||
var hops []hopCapture
|
||||
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
hops = append(hops, hopCapture{
|
||||
url: r.URL.String(),
|
||||
userProject: r.Header.Get("X-Goog-User-Project"),
|
||||
})
|
||||
switch r.URL.String() {
|
||||
case antigravityBaseURLDaily + "/v1internal:start":
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusFound,
|
||||
Header: http.Header{"Location": {antigravityBaseURLDaily + "/v1internal:same"}},
|
||||
Body: http.NoBody,
|
||||
}, nil
|
||||
case antigravityBaseURLDaily + "/v1internal:same":
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusFound,
|
||||
Header: http.Header{"Location": {"https://origin-b.example/other"}},
|
||||
Body: http.NoBody,
|
||||
}, nil
|
||||
case "https://origin-b.example/other":
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusFound,
|
||||
Header: http.Header{"Location": {antigravityBaseURLDaily + "/v1internal:bounce"}},
|
||||
Body: http.NoBody,
|
||||
}, nil
|
||||
default:
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: http.NoBody,
|
||||
}, nil
|
||||
}
|
||||
}))
|
||||
|
||||
req, errReq := http.NewRequest(http.MethodGet, antigravityBaseURLDaily+"/v1internal:start", nil)
|
||||
if errReq != nil {
|
||||
t.Fatalf("http.NewRequest() error = %v", errReq)
|
||||
}
|
||||
resp, errDo := exec.HttpRequest(ctx, auth, req)
|
||||
if errDo != nil {
|
||||
t.Fatalf("HttpRequest() error = %v", errDo)
|
||||
}
|
||||
if errClose := resp.Body.Close(); errClose != nil {
|
||||
t.Fatalf("close response body error: %v", errClose)
|
||||
}
|
||||
|
||||
if len(hops) != 4 {
|
||||
t.Fatalf("hops = %d, want 4 (%+v)", len(hops), hops)
|
||||
}
|
||||
if hops[0].userProject != "project-7837" {
|
||||
t.Fatalf("initial hop X-Goog-User-Project = %q, want %q", hops[0].userProject, "project-7837")
|
||||
}
|
||||
if hops[1].userProject != "project-7837" {
|
||||
t.Fatalf("same-origin hop X-Goog-User-Project = %q, want %q", hops[1].userProject, "project-7837")
|
||||
}
|
||||
if hops[2].userProject != "" {
|
||||
t.Fatalf("cross-origin hop leaked X-Goog-User-Project = %q, want empty", hops[2].userProject)
|
||||
}
|
||||
if hops[3].userProject != "" {
|
||||
t.Fatalf("post-cross-origin bounce hop leaked X-Goog-User-Project = %q, want empty", hops[3].userProject)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("omits X-Goog-User-Project for non-Cloud-Code-PA URLs and honors configured base_url", func(t *testing.T) {
|
||||
resetAntigravityCreditsRetryState()
|
||||
t.Cleanup(resetAntigravityCreditsRetryState)
|
||||
|
||||
exec := NewAntigravityExecutor(&config.Config{})
|
||||
auth := &cliproxyauth.Auth{
|
||||
ID: "ag-http-req-endpoint-scope",
|
||||
Provider: "antigravity",
|
||||
Status: cliproxyauth.StatusActive,
|
||||
Attributes: map[string]string{
|
||||
"base_url": "https://proxy.example.com:8443/ag",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-1",
|
||||
"project_id": "project-scoped",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
targetURL string
|
||||
wantHeader string
|
||||
wantExists bool
|
||||
}{
|
||||
{name: "built-in daily cloudcode-pa", targetURL: antigravityBaseURLDaily + "/v1internal:fetchUserInfo", wantHeader: "project-scoped", wantExists: true},
|
||||
{name: "built-in prod cloudcode-pa", targetURL: antigravityBaseURLProd + "/v1internal:fetchUserInfo", wantHeader: "project-scoped", wantExists: true},
|
||||
{name: "built-in sandbox cloudcode-pa", targetURL: antigravitySandboxBaseURLDaily + "/v1internal:fetchUserInfo", wantHeader: "project-scoped", wantExists: true},
|
||||
{name: "configured custom base_url path", targetURL: "https://proxy.example.com:8443/ag/v1internal:fetchUserInfo", wantHeader: "project-scoped", wantExists: true},
|
||||
{name: "configured custom host different path", targetURL: "https://proxy.example.com:8443/other/service", wantHeader: "", wantExists: false},
|
||||
{name: "non-Cloud-Code Google endpoint", targetURL: "https://www.googleapis.com/oauth2/v2/userinfo", wantHeader: "", wantExists: false},
|
||||
{name: "arbitrary third-party origin", targetURL: "https://origin-a.example/start", wantHeader: "", wantExists: false},
|
||||
{name: "http downgrade of Cloud Code host", targetURL: "http://daily-cloudcode-pa.googleapis.com/v1internal:fetchUserInfo", wantHeader: "", wantExists: false},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var gotHeaders http.Header
|
||||
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
gotHeaders = r.Header.Clone()
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: http.NoBody,
|
||||
}, nil
|
||||
}))
|
||||
|
||||
req, errReq := http.NewRequest(http.MethodPost, tc.targetURL, nil)
|
||||
if errReq != nil {
|
||||
t.Fatalf("http.NewRequest() error = %v", errReq)
|
||||
}
|
||||
resp, errDo := exec.HttpRequest(ctx, auth, req)
|
||||
if errDo != nil {
|
||||
t.Fatalf("HttpRequest() error = %v", errDo)
|
||||
}
|
||||
if errClose := resp.Body.Close(); errClose != nil {
|
||||
t.Fatalf("close response body error: %v", errClose)
|
||||
}
|
||||
_, exists := gotHeaders["X-Goog-User-Project"]
|
||||
if exists != tc.wantExists || gotHeaders.Get("X-Goog-User-Project") != tc.wantHeader {
|
||||
t.Fatalf("HttpRequest(%s) X-Goog-User-Project = %q (exists=%v), want %q (exists=%v)", tc.targetURL, gotHeaders.Get("X-Goog-User-Project"), exists, tc.wantHeader, tc.wantExists)
|
||||
}
|
||||
|
||||
prepReq, errPrepReq := http.NewRequest(http.MethodPost, tc.targetURL, nil)
|
||||
if errPrepReq != nil {
|
||||
t.Fatalf("http.NewRequest() error = %v", errPrepReq)
|
||||
}
|
||||
if errPrep := exec.PrepareRequest(prepReq, auth); errPrep != nil {
|
||||
t.Fatalf("PrepareRequest() error = %v", errPrep)
|
||||
}
|
||||
_, prepExists := prepReq.Header["X-Goog-User-Project"]
|
||||
if prepExists != tc.wantExists || prepReq.Header.Get("X-Goog-User-Project") != tc.wantHeader {
|
||||
t.Fatalf("PrepareRequest(%s) X-Goog-User-Project = %q (exists=%v), want %q (exists=%v)", tc.targetURL, prepReq.Header.Get("X-Goog-User-Project"), prepExists, tc.wantHeader, tc.wantExists)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("allows custom header override and omits when project_id absent", func(t *testing.T) {
|
||||
resetAntigravityCreditsRetryState()
|
||||
t.Cleanup(resetAntigravityCreditsRetryState)
|
||||
|
||||
exec := NewAntigravityExecutor(&config.Config{})
|
||||
authWithOverride := &cliproxyauth.Auth{
|
||||
ID: "ag-http-req-user-project-override",
|
||||
Provider: "antigravity",
|
||||
Status: cliproxyauth.StatusActive,
|
||||
Attributes: map[string]string{
|
||||
"header:X-Goog-User-Project": "override-project",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-1",
|
||||
"project_id": "project-7837",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
var gotHeaders http.Header
|
||||
ctx := context.WithValue(context.Background(), "cliproxy.roundtripper", roundTripperFunc(func(r *http.Request) (*http.Response, error) {
|
||||
gotHeaders = r.Header.Clone()
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: http.NoBody,
|
||||
}, nil
|
||||
}))
|
||||
|
||||
req, errReq := http.NewRequest(http.MethodPost, antigravityBaseURLDaily+"/v1internal:fetchUserInfo", nil)
|
||||
if errReq != nil {
|
||||
t.Fatalf("http.NewRequest() error = %v", errReq)
|
||||
}
|
||||
resp, errDo := exec.HttpRequest(ctx, authWithOverride, req)
|
||||
if errDo != nil {
|
||||
t.Fatalf("HttpRequest() error = %v", errDo)
|
||||
}
|
||||
if errClose := resp.Body.Close(); errClose != nil {
|
||||
t.Fatalf("close response body error: %v", errClose)
|
||||
}
|
||||
if got := gotHeaders.Get("X-Goog-User-Project"); got != "override-project" {
|
||||
t.Fatalf("override X-Goog-User-Project = %q, want %q", got, "override-project")
|
||||
}
|
||||
|
||||
authWithoutProject := &cliproxyauth.Auth{
|
||||
ID: "ag-http-req-no-project",
|
||||
Provider: "antigravity",
|
||||
Status: cliproxyauth.StatusActive,
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-1",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
resp2, errDo2 := exec.HttpRequest(ctx, authWithoutProject, req)
|
||||
if errDo2 != nil {
|
||||
t.Fatalf("HttpRequest() without project error = %v", errDo2)
|
||||
}
|
||||
if errClose2 := resp2.Body.Close(); errClose2 != nil {
|
||||
t.Fatalf("close response body error: %v", errClose2)
|
||||
}
|
||||
if _, exists := gotHeaders["X-Goog-User-Project"]; exists {
|
||||
t.Fatalf("unexpected X-Goog-User-Project header when project_id absent: %v", gotHeaders["X-Goog-User-Project"])
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PrepareRequest sets X-Goog-User-Project when project_id is present", func(t *testing.T) {
|
||||
exec := NewAntigravityExecutor(&config.Config{})
|
||||
auth := &cliproxyauth.Auth{
|
||||
ID: "ag-prepare-user-project",
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-1",
|
||||
"project_id": " project-prep ",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
req, errReq := http.NewRequest(http.MethodPost, antigravityBaseURLDaily+"/v1internal:fetchUserInfo", nil)
|
||||
if errReq != nil {
|
||||
t.Fatalf("http.NewRequest() error = %v", errReq)
|
||||
}
|
||||
if errPrep := exec.PrepareRequest(req, auth); errPrep != nil {
|
||||
t.Fatalf("PrepareRequest() error = %v", errPrep)
|
||||
}
|
||||
if got := req.Header.Get("X-Goog-User-Project"); got != "project-prep" {
|
||||
t.Fatalf("PrepareRequest X-Goog-User-Project = %q, want %q", got, "project-prep")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("PrepareRequest clears stale X-Goog-User-Project when switching to auth without project_id or non-matching endpoint", func(t *testing.T) {
|
||||
exec := NewAntigravityExecutor(&config.Config{})
|
||||
authA := &cliproxyauth.Auth{
|
||||
ID: "ag-prepare-switch-a",
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-a",
|
||||
"project_id": "project-a",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
authB := &cliproxyauth.Auth{
|
||||
ID: "ag-prepare-switch-b",
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-b",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
req, errReq := http.NewRequest(http.MethodPost, antigravityBaseURLDaily+"/v1internal:fetchUserInfo", nil)
|
||||
if errReq != nil {
|
||||
t.Fatalf("http.NewRequest() error = %v", errReq)
|
||||
}
|
||||
if errPrepA := exec.PrepareRequest(req, authA); errPrepA != nil {
|
||||
t.Fatalf("PrepareRequest(authA) error = %v", errPrepA)
|
||||
}
|
||||
if got := req.Header.Get("X-Goog-User-Project"); got != "project-a" {
|
||||
t.Fatalf("after authA X-Goog-User-Project = %q, want %q", got, "project-a")
|
||||
}
|
||||
if errPrepB := exec.PrepareRequest(req, authB); errPrepB != nil {
|
||||
t.Fatalf("PrepareRequest(authB) error = %v", errPrepB)
|
||||
}
|
||||
if got := req.Header.Get("Authorization"); got != "Bearer token-b" {
|
||||
t.Fatalf("after authB Authorization = %q, want %q", got, "Bearer token-b")
|
||||
}
|
||||
if _, exists := req.Header["X-Goog-User-Project"]; exists {
|
||||
t.Fatalf("after authB stale X-Goog-User-Project remained: %v", req.Header["X-Goog-User-Project"])
|
||||
}
|
||||
|
||||
// Switching from a credential with a matching custom base_url to another credential
|
||||
// whose base_url does not match must also clear the prior header instead of leaking either project.
|
||||
authCustom := &cliproxyauth.Auth{
|
||||
ID: "ag-prepare-switch-custom",
|
||||
Attributes: map[string]string{
|
||||
"base_url": "https://custom-a.example",
|
||||
},
|
||||
Metadata: map[string]any{
|
||||
"access_token": "token-custom",
|
||||
"project_id": "project-custom",
|
||||
"expired": time.Now().Add(time.Hour).Format(time.RFC3339),
|
||||
},
|
||||
}
|
||||
customReq, errCustomReq := http.NewRequest(http.MethodPost, "https://custom-a.example/v1internal:fetchUserInfo", nil)
|
||||
if errCustomReq != nil {
|
||||
t.Fatalf("http.NewRequest() error = %v", errCustomReq)
|
||||
}
|
||||
if errPrepCustom := exec.PrepareRequest(customReq, authCustom); errPrepCustom != nil {
|
||||
t.Fatalf("PrepareRequest(authCustom) error = %v", errPrepCustom)
|
||||
}
|
||||
if got := customReq.Header.Get("X-Goog-User-Project"); got != "project-custom" {
|
||||
t.Fatalf("after authCustom X-Goog-User-Project = %q, want %q", got, "project-custom")
|
||||
}
|
||||
if errPrepOther := exec.PrepareRequest(customReq, authA); errPrepOther != nil {
|
||||
t.Fatalf("PrepareRequest(authA on custom-a) error = %v", errPrepOther)
|
||||
}
|
||||
if _, exists := customReq.Header["X-Goog-User-Project"]; exists {
|
||||
t.Fatalf("after switching to non-matching authA stale X-Goog-User-Project remained: %v", customReq.Header["X-Goog-User-Project"])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -113,9 +113,6 @@ func (e *AntigravityExecutor) buildRequestDoc(ctx context.Context, auth *cliprox
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+token)
|
||||
httpReq.Header.Set("User-Agent", resolveUserAgent(auth))
|
||||
if projectID != "" {
|
||||
httpReq.Header.Set("X-Goog-User-Project", projectID)
|
||||
}
|
||||
if host := resolveHost(base); host != "" {
|
||||
httpReq.Host = host
|
||||
}
|
||||
|
||||
@@ -124,9 +124,6 @@ func (e *AntigravityExecutor) CountTokens(ctx context.Context, auth *cliproxyaut
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+token)
|
||||
httpReq.Header.Set("User-Agent", resolveUserAgent(auth))
|
||||
if projectID := antigravityProjectIDFromAuth(auth); projectID != "" {
|
||||
httpReq.Header.Set("X-Goog-User-Project", projectID)
|
||||
}
|
||||
if host := resolveHost(base); host != "" {
|
||||
httpReq.Host = host
|
||||
}
|
||||
|
||||
@@ -119,8 +119,7 @@ func FetchAntigravityAvailableModels(ctx context.Context, req AntigravityModelPr
|
||||
}
|
||||
|
||||
doc := ojson.NewDoc([]byte("{}"))
|
||||
projectID := strings.TrimSpace(req.ProjectID)
|
||||
if projectID != "" {
|
||||
if projectID := strings.TrimSpace(req.ProjectID); projectID != "" {
|
||||
doc.Set("project", projectID)
|
||||
}
|
||||
httpReq, errReq := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+AntigravityModelsPath, bytes.NewReader(doc.Bytes()))
|
||||
@@ -134,9 +133,6 @@ func FetchAntigravityAvailableModels(ctx context.Context, req AntigravityModelPr
|
||||
httpReq.Header.Set("Content-Type", "application/json")
|
||||
httpReq.Header.Set("Authorization", "Bearer "+accessToken)
|
||||
httpReq.Header.Set("User-Agent", userAgent)
|
||||
if projectID != "" {
|
||||
httpReq.Header.Set("X-Goog-User-Project", projectID)
|
||||
}
|
||||
|
||||
resp, errDo := client.Do(httpReq)
|
||||
if errDo != nil {
|
||||
|
||||
@@ -752,44 +752,3 @@ func TestFetchAntigravityAvailableModels_OmitsEmptyProject(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchAntigravityAvailableModels_UserProjectHeader(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
projectID string
|
||||
wantHeader string
|
||||
wantExists bool
|
||||
}{
|
||||
{name: "empty project id omits header", projectID: "", wantHeader: "", wantExists: false},
|
||||
{name: "whitespace project id omits header", projectID: " \t\n ", wantHeader: "", wantExists: false},
|
||||
{name: "non-empty project id sets trimmed header", projectID: " aicode-consumers ", wantHeader: "aicode-consumers", wantExists: true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var gotHeaders http.Header
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotHeaders = r.Header.Clone()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write([]byte(`{"models":{"gemini-3-flash":{}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
_, status := FetchAntigravityAvailableModels(context.Background(), AntigravityModelProbeRequest{
|
||||
BaseURLs: []string{server.URL},
|
||||
AccessToken: "test-token",
|
||||
ProjectID: tc.projectID,
|
||||
})
|
||||
if status != AntigravityProbeStatusSuccess {
|
||||
t.Fatalf("status = %v, want %v", status, AntigravityProbeStatusSuccess)
|
||||
}
|
||||
_, exists := gotHeaders["X-Goog-User-Project"]
|
||||
if exists != tc.wantExists {
|
||||
t.Fatalf("X-Goog-User-Project exists = %v, want %v (headers=%v)", exists, tc.wantExists, gotHeaders)
|
||||
}
|
||||
if got := gotHeaders.Get("X-Goog-User-Project"); got != tc.wantHeader {
|
||||
t.Fatalf("X-Goog-User-Project = %q, want %q", got, tc.wantHeader)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user