mirror of
https://github.com/router-for-me/CLIProxyAPI.git
synced 2026-12-04 16:41:55 +08:00
feat(gemini): add allow-vertex-signatures option for Vertex-backed relays
- Add opt-in allow-vertex-signatures (default false) to GeminiKey with v8 group inheritance, per-key override, config diff reporting, and synthesizer attribute propagation. - Select Vertex-preserving thought signature sanitization in GeminiExecutor across Execute, ExecuteStream, CountTokens, and native Interactions paths when enabled. - Add regression tests covering executor paths, legacy and v8 config decoding, synthesizer attributes, and config diffs. Closes: #8603
This commit is contained in:
@@ -668,6 +668,7 @@ upstream:
|
||||
# action: "stop" # "stop" (return error, no cooling), "stop-and-cooldown" (return error and cool down),
|
||||
# # "continue" (try next credential, no cooling), "continue-and-cooldown" (try next credential and cool down)
|
||||
# base-url: "https://generativelanguage.googleapis.com"
|
||||
# allow-vertex-signatures: false # optional: preserve Vertex bare-Tink thought signatures for Vertex-backed relays serving AI Studio paths
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
# # Values starting with "$" dynamically copy the header value from downstream client requests.
|
||||
@@ -727,6 +728,7 @@ upstream:
|
||||
# - "invalid_argument"
|
||||
# action: "continue"
|
||||
# base-url: "https://generativelanguage.googleapis.com"
|
||||
# allow-vertex-signatures: false # optional: preserve Vertex bare-Tink thought signatures for Vertex-backed relays
|
||||
# headers:
|
||||
# X-Custom-Header: "custom-value"
|
||||
# # Values starting with "$" dynamically copy the header value from downstream client requests.
|
||||
|
||||
@@ -1085,6 +1085,11 @@ type GeminiKey struct {
|
||||
|
||||
// RequestScopedErrors configures custom classification rules for upstream errors.
|
||||
RequestScopedErrors []RequestScopedErrorRule `yaml:"request-scoped-errors,omitempty" json:"request-scoped-errors,omitempty"`
|
||||
|
||||
// AllowVertexSignatures preserves Vertex AI bare-Tink thought signatures instead of
|
||||
// replacing them with the bypass sentinel, for custom base-url relays that serve
|
||||
// AI Studio paths backed by Vertex AI. Defaults to false.
|
||||
AllowVertexSignatures bool `yaml:"allow-vertex-signatures,omitempty" json:"allow-vertex-signatures,omitempty"`
|
||||
}
|
||||
|
||||
func (k GeminiKey) GetAPIKey() string { return k.APIKey }
|
||||
|
||||
@@ -400,6 +400,13 @@ var sharedKeyFields = map[string]bool{
|
||||
"connection-pool": true,
|
||||
}
|
||||
|
||||
func isAllowedV8GroupField(provider, field string) bool {
|
||||
if sharedKeyFields[field] {
|
||||
return true
|
||||
}
|
||||
return (provider == "gemini" || provider == "interactions") && field == "allow-vertex-signatures"
|
||||
}
|
||||
|
||||
func expandV8Groups(groups *yaml.Node, provider string) (*yaml.Node, error) {
|
||||
if groups.Kind != yaml.SequenceNode {
|
||||
return nil, fmt.Errorf("api-keys.%s must be a list", provider)
|
||||
@@ -432,7 +439,7 @@ func expandV8Groups(groups *yaml.Node, provider string) (*yaml.Node, error) {
|
||||
}
|
||||
for i := 0; i < len(group.Content); i += 2 {
|
||||
field := group.Content[i].Value
|
||||
if field != "name" && field != "base-url" && field != "keys" && !sharedKeyFields[field] {
|
||||
if field != "name" && field != "base-url" && field != "keys" && !isAllowedV8GroupField(provider, field) {
|
||||
return nil, fmt.Errorf("api-keys.%s: unsupported group field %s", provider, field)
|
||||
}
|
||||
}
|
||||
@@ -446,7 +453,7 @@ func expandV8Groups(groups *yaml.Node, provider string) (*yaml.Node, error) {
|
||||
item := &yaml.Node{Kind: yaml.MappingNode, Tag: "!!map"}
|
||||
for i := 0; i < len(group.Content); i += 2 {
|
||||
field := group.Content[i].Value
|
||||
if field == "base-url" || sharedKeyFields[field] {
|
||||
if field == "base-url" || isAllowedV8GroupField(provider, field) {
|
||||
setYAMLPath(item, field, group.Content[i+1])
|
||||
}
|
||||
}
|
||||
@@ -509,7 +516,7 @@ func groupLegacyKeys(keys *yaml.Node, provider string) *yaml.Node {
|
||||
key := deepCopyNode(entry)
|
||||
for i := 0; i < len(entry.Content); i += 2 {
|
||||
field := entry.Content[i].Value
|
||||
if field == "base-url" || sharedKeyFields[field] {
|
||||
if field == "base-url" || isAllowedV8GroupField(provider, field) {
|
||||
setYAMLPath(group, field, entry.Content[i+1])
|
||||
deleteYAMLPath(key, field)
|
||||
}
|
||||
|
||||
105
internal/config/gemini_allow_vertex_signatures_test.go
Normal file
105
internal/config/gemini_allow_vertex_signatures_test.go
Normal file
@@ -0,0 +1,105 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
||||
)
|
||||
|
||||
func TestGeminiAllowVertexSignaturesLegacyDecoding(t *testing.T) {
|
||||
const raw = `gemini-api-key:
|
||||
- api-key: key-default
|
||||
base-url: https://generativelanguage.googleapis.com
|
||||
- api-key: key-vertex-relay
|
||||
base-url: https://relay.example.com
|
||||
allow-vertex-signatures: true
|
||||
interactions-api-key:
|
||||
- api-key: inter-default
|
||||
- api-key: inter-vertex-relay
|
||||
base-url: https://relay.example.com
|
||||
allow-vertex-signatures: true
|
||||
`
|
||||
cfg, errParse := config.ParseConfigBytes([]byte(raw))
|
||||
if errParse != nil {
|
||||
t.Fatalf("ParseConfigBytes() error = %v", errParse)
|
||||
}
|
||||
if len(cfg.GeminiKey) != 2 {
|
||||
t.Fatalf("len(GeminiKey) = %d, want 2", len(cfg.GeminiKey))
|
||||
}
|
||||
if cfg.GeminiKey[0].AllowVertexSignatures {
|
||||
t.Fatal("GeminiKey[0].AllowVertexSignatures = true, want default false")
|
||||
}
|
||||
if !cfg.GeminiKey[1].AllowVertexSignatures {
|
||||
t.Fatal("GeminiKey[1].AllowVertexSignatures = false, want true")
|
||||
}
|
||||
if len(cfg.InteractionsKey) != 2 {
|
||||
t.Fatalf("len(InteractionsKey) = %d, want 2", len(cfg.InteractionsKey))
|
||||
}
|
||||
if cfg.InteractionsKey[0].AllowVertexSignatures {
|
||||
t.Fatal("InteractionsKey[0].AllowVertexSignatures = true, want default false")
|
||||
}
|
||||
if !cfg.InteractionsKey[1].AllowVertexSignatures {
|
||||
t.Fatal("InteractionsKey[1].AllowVertexSignatures = false, want true")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiAllowVertexSignaturesV8GroupAndKeyOverrides(t *testing.T) {
|
||||
for _, provider := range []string{"gemini", "interactions"} {
|
||||
t.Run(provider, func(t *testing.T) {
|
||||
raw := `config-version: 8
|
||||
api-keys:
|
||||
` + provider + `:
|
||||
- name: vertex-relay
|
||||
base-url: https://relay.example.com
|
||||
allow-vertex-signatures: true
|
||||
keys:
|
||||
- api-key: inherit-key
|
||||
- api-key: override-false
|
||||
allow-vertex-signatures: false
|
||||
- api-key: explicit-null
|
||||
allow-vertex-signatures: null
|
||||
- name: default-group
|
||||
base-url: https://generativelanguage.googleapis.com
|
||||
keys:
|
||||
- api-key: default-key
|
||||
- api-key: per-key-true
|
||||
allow-vertex-signatures: true
|
||||
`
|
||||
if errValidate := config.ValidateV8Config([]byte(raw)); errValidate != nil {
|
||||
t.Fatalf("ValidateV8Config() error = %v", errValidate)
|
||||
}
|
||||
cfg, errParse := config.ParseConfigBytes([]byte(raw))
|
||||
if errParse != nil {
|
||||
t.Fatalf("ParseConfigBytes() error = %v", errParse)
|
||||
}
|
||||
entries := cfg.GeminiKey
|
||||
if provider == "interactions" {
|
||||
entries = cfg.InteractionsKey
|
||||
}
|
||||
if len(entries) != 5 {
|
||||
t.Fatalf("len(%s) = %d, want 5", provider, len(entries))
|
||||
}
|
||||
want := []bool{true, false, true, false, true}
|
||||
for i, expected := range want {
|
||||
if entries[i].AllowVertexSignatures != expected {
|
||||
t.Fatalf("%s[%d] (%s) AllowVertexSignatures = %v, want %v",
|
||||
provider, i, entries[i].APIKey, entries[i].AllowVertexSignatures, expected)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiAllowVertexSignaturesRejectedOnOtherV8Providers(t *testing.T) {
|
||||
const raw = `config-version: 8
|
||||
api-keys:
|
||||
claude:
|
||||
- name: claude-1
|
||||
allow-vertex-signatures: true
|
||||
keys:
|
||||
- api-key: claude-key
|
||||
`
|
||||
if errValidate := config.ValidateV8Config([]byte(raw)); errValidate == nil {
|
||||
t.Fatal("ValidateV8Config() succeeded for allow-vertex-signatures on claude group, want error")
|
||||
}
|
||||
}
|
||||
@@ -166,7 +166,7 @@ func (e *GeminiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r
|
||||
requestPath := helps.PayloadRequestPath(opts)
|
||||
helps.SetStringIfDifferentDoc(doc, "model", baseModel)
|
||||
capGeminiMaxOutputTokensDoc(doc, baseModel)
|
||||
internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents")
|
||||
sanitizeGeminiThoughtSignaturesDoc(auth, doc, "contents")
|
||||
|
||||
action := "generateContent"
|
||||
if req.Metadata != nil {
|
||||
@@ -188,7 +188,7 @@ func (e *GeminiExecutor) Execute(ctx context.Context, auth *cliproxyauth.Auth, r
|
||||
return resp, errReplay
|
||||
}
|
||||
if changedReplay {
|
||||
internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents")
|
||||
sanitizeGeminiThoughtSignaturesDoc(auth, doc, "contents")
|
||||
}
|
||||
}
|
||||
baseURL := resolveGeminiBaseURL(auth)
|
||||
@@ -339,7 +339,7 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A
|
||||
requestPath := helps.PayloadRequestPath(opts)
|
||||
helps.SetStringIfDifferentDoc(doc, "model", baseModel)
|
||||
capGeminiMaxOutputTokensDoc(doc, baseModel)
|
||||
internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents")
|
||||
sanitizeGeminiThoughtSignaturesDoc(auth, doc, "contents")
|
||||
helps.EnsureGeminiBoundaryUserContentDoc(doc, "contents")
|
||||
replayScope := antigravityReasoningReplayScope{}
|
||||
var replayRequestPayload []byte
|
||||
@@ -351,7 +351,7 @@ func (e *GeminiExecutor) ExecuteStream(ctx context.Context, auth *cliproxyauth.A
|
||||
return nil, errReplay
|
||||
}
|
||||
if changedReplay {
|
||||
internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents")
|
||||
sanitizeGeminiThoughtSignaturesDoc(auth, doc, "contents")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -754,7 +754,7 @@ func (e *GeminiExecutor) executeInteractions(ctx context.Context, auth *cliproxy
|
||||
requestedModel := helps.PayloadRequestedModel(opts, req.Model)
|
||||
requestPath := helps.PayloadRequestPath(opts)
|
||||
fromProtocol := opts.SourceFormat.String()
|
||||
sanitizeGeminiInteractionsUnsupportedInputIDsDoc(doc)
|
||||
sanitizeGeminiInteractionsUnsupportedInputIDsDoc(auth, doc)
|
||||
continuation := helps.PrepareAntigravityInteractionsDoc(auth, req, opts, targetName, doc)
|
||||
|
||||
baseURL := resolveGeminiBaseURL(auth)
|
||||
@@ -846,7 +846,7 @@ func (e *GeminiExecutor) executeInteractionsStream(ctx context.Context, auth *cl
|
||||
requestedModel := helps.PayloadRequestedModel(opts, req.Model)
|
||||
requestPath := helps.PayloadRequestPath(opts)
|
||||
fromProtocol := opts.SourceFormat.String()
|
||||
sanitizeGeminiInteractionsUnsupportedInputIDsDoc(doc)
|
||||
sanitizeGeminiInteractionsUnsupportedInputIDsDoc(auth, doc)
|
||||
continuation := helps.PrepareAntigravityInteractionsDoc(auth, req, opts, targetName, doc)
|
||||
helps.SetBoolIfDifferentDoc(doc, "stream", true)
|
||||
baseURL := resolveGeminiBaseURL(auth)
|
||||
@@ -1046,7 +1046,7 @@ func (e *GeminiExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut
|
||||
_ = doc.Delete("generationConfig")
|
||||
_ = doc.Delete("safetySettings")
|
||||
helps.SetStringIfDifferentDoc(doc, "model", baseModel)
|
||||
internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents")
|
||||
sanitizeGeminiThoughtSignaturesDoc(auth, doc, "contents")
|
||||
helps.EnsureGeminiLeadingUserContentDoc(doc, "contents")
|
||||
if antigravityUsesReasoningReplayCache(baseModel) {
|
||||
changedReplay, errReplay := prepareGeminiTopLevelCountTokensReasoningReplayPayloadDoc(ctx, baseModel, req, opts, doc)
|
||||
@@ -1054,7 +1054,7 @@ func (e *GeminiExecutor) CountTokens(ctx context.Context, auth *cliproxyauth.Aut
|
||||
return cliproxyexecutor.Response{}, errReplay
|
||||
}
|
||||
if changedReplay {
|
||||
internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, "contents")
|
||||
sanitizeGeminiThoughtSignaturesDoc(auth, doc, "contents")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1217,8 +1217,33 @@ func sanitizeGeminiInteractionsUnsupportedInputIDs(body []byte) []byte {
|
||||
return helps.SanitizeGeminiInteractionsUnsupportedInputIDs(body, false)
|
||||
}
|
||||
|
||||
func sanitizeGeminiInteractionsUnsupportedInputIDsDoc(doc *ojson.Doc) bool {
|
||||
return helps.SanitizeGeminiInteractionsUnsupportedInputIDsDoc(doc, false)
|
||||
func sanitizeGeminiInteractionsUnsupportedInputIDsDoc(auth *cliproxyauth.Auth, doc *ojson.Doc) bool {
|
||||
return helps.SanitizeGeminiInteractionsUnsupportedInputIDsDoc(doc, allowVertexThoughtSignatures(auth))
|
||||
}
|
||||
|
||||
func allowVertexThoughtSignatures(auth *cliproxyauth.Auth) bool {
|
||||
if auth == nil {
|
||||
return false
|
||||
}
|
||||
if auth.Attributes != nil {
|
||||
if v := strings.TrimSpace(auth.Attributes["allow_vertex_signatures"]); v != "" {
|
||||
return strings.EqualFold(v, "true") || v == "1"
|
||||
}
|
||||
}
|
||||
if auth.Metadata != nil {
|
||||
if v, ok := auth.Metadata["allow_vertex_signatures"].(bool); ok {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func sanitizeGeminiThoughtSignaturesDoc(auth *cliproxyauth.Auth, doc *ojson.Doc, contentsPath string) {
|
||||
if allowVertexThoughtSignatures(auth) {
|
||||
internalsignature.SanitizeGeminiRequestThoughtSignaturesDoc(doc, contentsPath)
|
||||
return
|
||||
}
|
||||
internalsignature.SanitizeNonVertexGeminiRequestThoughtSignaturesDoc(doc, contentsPath)
|
||||
}
|
||||
|
||||
func translateGeminiInteractionsRequestBody(ctx context.Context, cfg *config.Config, model string, payload []byte, opts cliproxyexecutor.Options, stream, isCompat bool) ([]byte, error) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"github.com/MoeForge/moego/ojson"
|
||||
internalcache "github.com/router-for-me/CLIProxyAPI/v8/internal/cache"
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
||||
internalsignature "github.com/router-for-me/CLIProxyAPI/v8/internal/signature"
|
||||
cliproxyauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
|
||||
@@ -118,3 +119,257 @@ func TestGeminiVertexSanitizePreservesBareTinkSignature(t *testing.T) {
|
||||
t.Fatalf("Vertex path signature = %q, want original bare-Tink value", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeminiExecutorAllowVertexSignaturesPreservesBareTink(t *testing.T) {
|
||||
sig := testVertexBareTinkSignature()
|
||||
|
||||
newServer := func(t *testing.T, captured *[]byte) *httptest.Server {
|
||||
t.Helper()
|
||||
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, errRead := io.ReadAll(r.Body)
|
||||
if errRead != nil {
|
||||
t.Errorf("read request body: %v", errRead)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
*captured = append([]byte(nil), body...)
|
||||
switch {
|
||||
case bytes.Contains([]byte(r.URL.Path), []byte("streamGenerateContent")):
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: " + vertexBareTinkTestOKResponse + "\n\n"))
|
||||
case bytes.Contains([]byte(r.URL.Path), []byte("countTokens")):
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"totalTokens": 42}`))
|
||||
case bytes.Contains([]byte(r.URL.Path), []byte("/interactions")):
|
||||
if ojson.GetBytes(body, "stream").Bool() {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: {\"event_type\":\"interaction.complete\",\"interaction\":{\"id\":\"inter_1\",\"status\":\"completed\",\"outputs\":[{\"type\":\"text\",\"text\":\"ok\"}]}}\n\n"))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"id":"inter_1","status":"completed","outputs":[{"type":"text","text":"ok"}]}`))
|
||||
default:
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(vertexBareTinkTestOKResponse))
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
assertFunctionCallSig := func(t *testing.T, body []byte, want string) {
|
||||
t.Helper()
|
||||
contents := ojson.GetBytes(body, "contents").Array()
|
||||
found := false
|
||||
for _, content := range contents {
|
||||
for _, part := range content.Get("parts").Array() {
|
||||
if !part.Get("functionCall").Exists() {
|
||||
continue
|
||||
}
|
||||
found = true
|
||||
if got := part.Get("thoughtSignature").String(); got != want {
|
||||
t.Fatalf("functionCall thoughtSignature = %q, want %q; body=%s", got, want, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("functionCall missing from upstream body: %s", body)
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("execute_gemini_history", func(t *testing.T) {
|
||||
var captured []byte
|
||||
server := newServer(t, &captured)
|
||||
defer server.Close()
|
||||
|
||||
exec := NewGeminiExecutor(&config.Config{})
|
||||
auth := &cliproxyauth.Auth{Attributes: map[string]string{
|
||||
"api_key": "test-key",
|
||||
"base_url": server.URL,
|
||||
"allow_vertex_signatures": "true",
|
||||
}}
|
||||
req := cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview", Payload: vertexBareTinkGeminiHistory(sig)}
|
||||
if _, errExec := exec.Execute(context.Background(), auth, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatGemini}); errExec != nil {
|
||||
t.Fatalf("Execute() error = %v", errExec)
|
||||
}
|
||||
assertFunctionCallSig(t, captured, sig)
|
||||
})
|
||||
|
||||
t.Run("execute_stream_claude_carrier", func(t *testing.T) {
|
||||
var captured []byte
|
||||
server := newServer(t, &captured)
|
||||
defer server.Close()
|
||||
|
||||
exec := NewGeminiExecutor(&config.Config{})
|
||||
auth := &cliproxyauth.Auth{Attributes: map[string]string{
|
||||
"api_key": "test-key",
|
||||
"base_url": server.URL,
|
||||
"allow_vertex_signatures": "true",
|
||||
}}
|
||||
doc := ojson.NewDocString(`{"model":"gemini-3.1-pro-preview","max_tokens":1024,"tools":[{"name":"list_dir","description":"list","input_schema":{"type":"object","properties":{"path":{"type":"string"}}}}],"messages":[{"role":"user","content":"list"},{"role":"assistant","content":[{"type":"thinking","thinking":"","signature":""},{"type":"tool_use","id":"call_1","name":"list_dir","input":{"path":"."}}]},{"role":"user","content":[{"type":"tool_result","tool_use_id":"call_1","content":"ok"}]}]}`)
|
||||
_ = doc.Set("messages.1.content.0.signature", sig)
|
||||
req := cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview", Payload: doc.Bytes()}
|
||||
streamRes, errStream := exec.ExecuteStream(context.Background(), auth, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatClaude})
|
||||
if errStream != nil {
|
||||
t.Fatalf("ExecuteStream() error = %v", errStream)
|
||||
}
|
||||
for chunk := range streamRes.Chunks {
|
||||
if chunk.Err != nil {
|
||||
t.Fatalf("stream chunk error = %v", chunk.Err)
|
||||
}
|
||||
}
|
||||
assertFunctionCallSig(t, captured, sig)
|
||||
})
|
||||
|
||||
t.Run("count_tokens", func(t *testing.T) {
|
||||
var captured []byte
|
||||
server := newServer(t, &captured)
|
||||
defer server.Close()
|
||||
|
||||
exec := NewGeminiExecutor(&config.Config{})
|
||||
auth := &cliproxyauth.Auth{Attributes: map[string]string{
|
||||
"api_key": "test-key",
|
||||
"base_url": server.URL,
|
||||
"allow_vertex_signatures": "true",
|
||||
}}
|
||||
req := cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview", Payload: vertexBareTinkGeminiHistory(sig)}
|
||||
if _, errCount := exec.CountTokens(context.Background(), auth, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatGemini}); errCount != nil {
|
||||
t.Fatalf("CountTokens() error = %v", errCount)
|
||||
}
|
||||
assertFunctionCallSig(t, captured, sig)
|
||||
})
|
||||
|
||||
t.Run("foreign_claude_signature_still_replaced_when_enabled", func(t *testing.T) {
|
||||
var captured []byte
|
||||
server := newServer(t, &captured)
|
||||
defer server.Close()
|
||||
|
||||
exec := NewGeminiExecutor(&config.Config{})
|
||||
auth := &cliproxyauth.Auth{Attributes: map[string]string{
|
||||
"api_key": "test-key",
|
||||
"base_url": server.URL,
|
||||
"allow_vertex_signatures": "true",
|
||||
}}
|
||||
req := cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview", Payload: vertexBareTinkGeminiHistory(testClaudeCAISSample)}
|
||||
if _, errExec := exec.Execute(context.Background(), auth, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatGemini}); errExec != nil {
|
||||
t.Fatalf("Execute() error = %v", errExec)
|
||||
}
|
||||
assertFunctionCallSig(t, captured, internalsignature.GeminiSkipThoughtSignatureValidator)
|
||||
})
|
||||
|
||||
t.Run("explicit_false_replaces_bare_tink", func(t *testing.T) {
|
||||
var captured []byte
|
||||
server := newServer(t, &captured)
|
||||
defer server.Close()
|
||||
|
||||
exec := NewGeminiExecutor(&config.Config{})
|
||||
auth := &cliproxyauth.Auth{Attributes: map[string]string{
|
||||
"api_key": "test-key",
|
||||
"base_url": server.URL,
|
||||
"allow_vertex_signatures": "false",
|
||||
}}
|
||||
req := cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview", Payload: vertexBareTinkGeminiHistory(sig)}
|
||||
if _, errExec := exec.Execute(context.Background(), auth, req, cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatGemini}); errExec != nil {
|
||||
t.Fatalf("Execute() error = %v", errExec)
|
||||
}
|
||||
assertFunctionCallSig(t, captured, internalsignature.GeminiSkipThoughtSignatureValidator)
|
||||
})
|
||||
|
||||
t.Run("post_replay_preserves_bare_tink_when_enabled", func(t *testing.T) {
|
||||
internalcache.ClearAntigravityReasoningReplayCache()
|
||||
t.Cleanup(internalcache.ClearAntigravityReasoningReplayCache)
|
||||
|
||||
const model = "gemini-3.8-flash"
|
||||
asymOpts := cliproxyexecutor.Options{
|
||||
SourceFormat: sdktranslator.FormatOpenAIResponse,
|
||||
ResponseFormat: sdktranslator.FormatOpenAIResponse,
|
||||
Headers: http.Header{"X-Session-Id": []string{"sess-gemini-allow-vertex-replay"}},
|
||||
}
|
||||
turn1 := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather"}]}]}`)
|
||||
doc1 := ojson.NewDoc(turn1)
|
||||
scope1, replayReq1, _, errPrepare1 := prepareGeminiTopLevelReasoningReplayPayloadDoc(
|
||||
context.Background(),
|
||||
model,
|
||||
cliproxyexecutor.Request{Model: model, Payload: turn1},
|
||||
asymOpts,
|
||||
doc1,
|
||||
)
|
||||
if errPrepare1 != nil || !scope1.valid() {
|
||||
t.Fatalf("prepare turn 1: scope=%+v err=%v", scope1, errPrepare1)
|
||||
}
|
||||
vertexResp := []byte(`{"candidates":[{"content":{"role":"model","parts":[{"thoughtSignature":"`)
|
||||
vertexResp = append(vertexResp, []byte(sig)...)
|
||||
vertexResp = append(vertexResp, []byte(`","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_tink"}}]},"finishReason":"STOP"}]}`)...)
|
||||
cacheAntigravityReasoningReplayFromResponse(context.Background(), scope1, replayReq1, vertexResp)
|
||||
|
||||
turn2 := []byte(`{"contents":[{"role":"user","parts":[{"text":"Call get_weather"}]},{"role":"model","parts":[{"thoughtSignature":"skip_thought_signature_validator","functionCall":{"name":"get_weather","args":{"city":"Tokyo"},"id":"call_tink"}}]},{"role":"user","parts":[{"functionResponse":{"name":"get_weather","id":"call_tink","response":{"result":"clear"}}}]}]}`)
|
||||
doc2 := ojson.NewDoc(turn2)
|
||||
_, _, changed2, errPrepare2 := prepareGeminiTopLevelReasoningReplayPayloadDoc(
|
||||
context.Background(),
|
||||
model,
|
||||
cliproxyexecutor.Request{Model: model, Payload: turn2},
|
||||
asymOpts,
|
||||
doc2,
|
||||
)
|
||||
if errPrepare2 != nil || !changed2 {
|
||||
t.Fatalf("prepare turn 2: changed=%v err=%v", changed2, errPrepare2)
|
||||
}
|
||||
auth := &cliproxyauth.Auth{Attributes: map[string]string{"allow_vertex_signatures": "true"}}
|
||||
sanitizeGeminiThoughtSignaturesDoc(auth, doc2, "contents")
|
||||
if got := doc2.Get("contents.1.parts.0.thoughtSignature").String(); got != sig {
|
||||
t.Fatalf("post-replay sanitized signature = %q, want %q", got, sig)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("interactions_preserves_bare_tink_only_when_enabled", func(t *testing.T) {
|
||||
for _, allow := range []bool{false, true} {
|
||||
for _, stream := range []bool{false, true} {
|
||||
var captured []byte
|
||||
server := newServer(t, &captured)
|
||||
exec := NewGeminiExecutor(&config.Config{})
|
||||
attrs := map[string]string{
|
||||
"api_key": "test-key",
|
||||
"base_url": server.URL,
|
||||
}
|
||||
if allow {
|
||||
attrs["allow_vertex_signatures"] = "true"
|
||||
}
|
||||
auth := &cliproxyauth.Auth{
|
||||
Provider: "gemini-interactions",
|
||||
Attributes: attrs,
|
||||
}
|
||||
payload := []byte(`{"model":"gemini-3.1-pro-preview","input":[{"type":"thought","signature":"` + sig + `"},{"type":"text","text":"next"}]}`)
|
||||
req := cliproxyexecutor.Request{Model: "gemini-3.1-pro-preview", Payload: payload}
|
||||
opts := cliproxyexecutor.Options{SourceFormat: sdktranslator.FormatInteractions}
|
||||
if stream {
|
||||
streamRes, errStream := exec.ExecuteStream(context.Background(), auth, req, opts)
|
||||
if errStream != nil {
|
||||
server.Close()
|
||||
t.Fatalf("allow=%v stream=true ExecuteStream() error = %v", allow, errStream)
|
||||
}
|
||||
for chunk := range streamRes.Chunks {
|
||||
if chunk.Err != nil {
|
||||
server.Close()
|
||||
t.Fatalf("allow=%v stream=true chunk error = %v", allow, chunk.Err)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if _, errExec := exec.Execute(context.Background(), auth, req, opts); errExec != nil {
|
||||
server.Close()
|
||||
t.Fatalf("allow=%v stream=false Execute() error = %v", allow, errExec)
|
||||
}
|
||||
}
|
||||
server.Close()
|
||||
|
||||
gotSig := ojson.GetBytes(captured, "input.0.signature").String()
|
||||
if allow {
|
||||
if gotSig != sig {
|
||||
t.Fatalf("allow=true stream=%v input.0.signature = %q, want %q; body=%s", stream, gotSig, sig, captured)
|
||||
}
|
||||
} else {
|
||||
if bytes.Contains(captured, []byte(sig)) {
|
||||
t.Fatalf("allow=false stream=%v leaked bare-Tink signature; body=%s", stream, captured)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -265,6 +265,9 @@ func BuildConfigChangeDetails(oldCfg, newCfg *config.Config) []string {
|
||||
changes = append(changes, fmt.Sprintf("gemini[%d].excluded-models: updated (%d -> %d entries)", i, oldExcluded.count, newExcluded.count))
|
||||
}
|
||||
changes = appendOptionalIntChange(changes, fmt.Sprintf("gemini[%d].request-retry", i), o.RequestRetry, n.RequestRetry)
|
||||
if o.AllowVertexSignatures != n.AllowVertexSignatures {
|
||||
changes = append(changes, fmt.Sprintf("gemini[%d].allow-vertex-signatures: %t -> %t", i, o.AllowVertexSignatures, n.AllowVertexSignatures))
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(oldCfg.InteractionsKey) != len(newCfg.InteractionsKey) {
|
||||
@@ -301,6 +304,9 @@ func BuildConfigChangeDetails(oldCfg, newCfg *config.Config) []string {
|
||||
changes = append(changes, fmt.Sprintf("interactions[%d].excluded-models: updated (%d -> %d entries)", i, oldExcluded.count, newExcluded.count))
|
||||
}
|
||||
changes = appendOptionalIntChange(changes, fmt.Sprintf("interactions[%d].request-retry", i), o.RequestRetry, n.RequestRetry)
|
||||
if o.AllowVertexSignatures != n.AllowVertexSignatures {
|
||||
changes = append(changes, fmt.Sprintf("interactions[%d].allow-vertex-signatures: %t -> %t", i, o.AllowVertexSignatures, n.AllowVertexSignatures))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
39
internal/watcher/diff/gemini_allow_vertex_signatures_test.go
Normal file
39
internal/watcher/diff/gemini_allow_vertex_signatures_test.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package diff
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
||||
)
|
||||
|
||||
func TestBuildConfigChangeDetailsIncludesAllowVertexSignatures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
oldCfg *config.Config
|
||||
newCfg *config.Config
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "gemini false to true",
|
||||
oldCfg: &config.Config{GeminiKey: []config.GeminiKey{{APIKey: "gemini-key"}}},
|
||||
newCfg: &config.Config{GeminiKey: []config.GeminiKey{{APIKey: "gemini-key", AllowVertexSignatures: true}}},
|
||||
want: "gemini[0].allow-vertex-signatures: false -> true",
|
||||
},
|
||||
{
|
||||
name: "interactions true to false",
|
||||
oldCfg: &config.Config{InteractionsKey: []config.GeminiKey{{APIKey: "inter-key", AllowVertexSignatures: true}}},
|
||||
newCfg: &config.Config{InteractionsKey: []config.GeminiKey{{APIKey: "inter-key", AllowVertexSignatures: false}}},
|
||||
want: "interactions[0].allow-vertex-signatures: true -> false",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
changes := strings.Join(BuildConfigChangeDetails(tc.oldCfg, tc.newCfg), "\n")
|
||||
if !strings.Contains(changes, tc.want) {
|
||||
t.Fatalf("BuildConfigChangeDetails() = %q, want substring %q", changes, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -164,6 +164,9 @@ func (s *ConfigSynthesizer) synthesizeGeminiKeyEntries(ctx *SynthesisContext, en
|
||||
if base != "" {
|
||||
attrs["base_url"] = base
|
||||
}
|
||||
if entry.AllowVertexSignatures {
|
||||
attrs["allow_vertex_signatures"] = "true"
|
||||
}
|
||||
if hash := diff.ComputeGeminiModelsHash(entry.Models); hash != "" {
|
||||
attrs["models_hash"] = hash
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package synthesizer
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
|
||||
)
|
||||
|
||||
func TestConfigSynthesizerGeminiAllowVertexSignatures(t *testing.T) {
|
||||
cfg := &config.Config{
|
||||
GeminiKey: []config.GeminiKey{
|
||||
{APIKey: "gemini-default", BaseURL: "https://generativelanguage.googleapis.com"},
|
||||
{APIKey: "gemini-vertex", BaseURL: "https://relay.example.com", AllowVertexSignatures: true},
|
||||
},
|
||||
InteractionsKey: []config.GeminiKey{
|
||||
{APIKey: "inter-default"},
|
||||
{APIKey: "inter-vertex", BaseURL: "https://relay.example.com", AllowVertexSignatures: true},
|
||||
},
|
||||
}
|
||||
|
||||
synth := NewConfigSynthesizer()
|
||||
auths, errSynth := synth.Synthesize(&SynthesisContext{
|
||||
Config: cfg,
|
||||
Now: time.Now(),
|
||||
IDGenerator: NewStableIDGenerator(),
|
||||
})
|
||||
if errSynth != nil {
|
||||
t.Fatalf("Synthesize() error = %v", errSynth)
|
||||
}
|
||||
if len(auths) != 4 {
|
||||
t.Fatalf("len(auths) = %d, want 4", len(auths))
|
||||
}
|
||||
|
||||
wantByKey := map[string]string{
|
||||
"gemini-default": "",
|
||||
"gemini-vertex": "true",
|
||||
"inter-default": "",
|
||||
"inter-vertex": "true",
|
||||
}
|
||||
for _, a := range auths {
|
||||
apiKey := a.Attributes["api_key"]
|
||||
want, ok := wantByKey[apiKey]
|
||||
if !ok {
|
||||
t.Fatalf("unexpected api_key %q", apiKey)
|
||||
}
|
||||
if got := a.Attributes["allow_vertex_signatures"]; got != want {
|
||||
t.Fatalf("api_key=%s allow_vertex_signatures = %q, want %q", apiKey, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user