Merge branch 'main' into feature/composite-ollama-unified

This commit is contained in:
alfadb committed 2026-11-23 17:44:44 +08:00
commit e8e8557a25
191 files changed
+11860 -618

No files matched your search

+1 -1
View File
@@ -1 +1 @@
0.2.23
0.2.24
+1 -1
View File
@@ -197,7 +197,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) {
adminAccountRepository := repository.NewAdminAccountRepository(client, db, schedulerCache)
proxyExitInfoProber := repository.NewProxyExitInfoProber(configConfig)
proxyLatencyCache := repository.NewProxyLatencyCache(redisClient)
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, billingService)
adminService := service.NewAdminService(configConfig, userRepository, adminGroupRepository, adminAccountRepository, proxyRepository, apiKeyRepository, redeemCodeRepository, userGroupRateRepository, userRPMCache, billingCacheService, proxyExitInfoProber, proxyLatencyCache, apiKeyAuthCacheInvalidator, client, settingService, subscriptionService, userSubscriptionRepository, privacyClientFactory, openAIGatewayService, affiliateService, compositeModelRouteRepository, compositeRouteResolver, channelService, billingService, serviceUserPlatformQuotaRepository)
adminUserHandler := admin.NewUserHandler(adminService, concurrencyService, serviceUserPlatformQuotaRepository, billingCache, totpService, userService, settingService)
groupCapacityService := service.NewGroupCapacityService(accountRepository, groupRepository, concurrencyService, sessionLimitCache, rpmCache)
groupHandler := admin.NewGroupHandlerWithConfig(adminService, dashboardService, groupCapacityService, configConfig)
@@ -14,6 +14,7 @@ import (
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/handler/dto"
"github.com/Wei-Shaw/sub2api/internal/pkg/ctxkey"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
middleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
@@ -23,6 +24,43 @@ import (
"github.com/tidwall/gjson"
)
func TestOpenAIResponsesUsageReportsConfigurationUpdateEffort(t *testing.T) {
const input = `[{"role":"user","content":"hello"},{"type":"configuration_update","reasoning":{"effort":"high"}}]`
const body = `{"model":"gpt-6.1-sol","input":` + input + `,"reasoning":{"effort":"medium"}}`
upstream := newAstraProCapturedUpstream(&http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"id":"resp_effort","model":"gpt-6.1-sol","status":"completed","output":[],"usage":{"input_tokens":10,"output_tokens":1}}`)),
})
account := service.Account{
ID: 1, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
Status: service.StatusActive, Schedulable: true, Credentials: map[string]any{"api_key": "test-key"},
}
usageRepo := &openAIWSUsageHandlerUsageLogRepoStub{created: make(chan *service.UsageLog, 1)}
cfg := &config.Config{RunMode: config.RunModeSimple}
billing := service.NewBillingCacheService(nil, nil, nil, nil, nil, nil, cfg, nil)
t.Cleanup(billing.Stop)
gateway := service.NewOpenAIGatewayService(
&openAIWSUsageHandlerAccountRepoStub{account: account}, usageRepo, nil, nil, nil, nil, nil, cfg,
nil, nil, service.NewBillingService(cfg, nil), nil, billing, upstream, &service.DeferredService{},
nil, nil, nil, nil, nil, nil, nil,
)
h := NewOpenAIGatewayHandler(gateway, service.NewConcurrencyService(nil), billing,
service.NewAPIKeyService(nil, nil, nil, nil, nil, nil, cfg), nil, nil, nil, nil, cfg)
c, rec := newAstraProFailoverContext(t, body)
h.Responses(c)
require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())
_, _, bodies := upstream.snapshot()
require.Len(t, bodies, 1)
require.Equal(t, "medium", gjson.GetBytes(bodies[0], "reasoning.effort").String())
require.JSONEq(t, input, gjson.GetBytes(bodies[0], "input").Raw)
require.Len(t, usageRepo.created, 1)
log := dto.UsageLogFromService(<-usageRepo.created)
require.NotNil(t, log.ReasoningEffort)
require.Equal(t, "high", *log.ReasoningEffort)
}
type compatEffortPolicyUpstream struct {
service.HTTPUpstream
bodies [][]byte
@@ -1338,6 +1338,22 @@ func (h *GatewayHandler) Models(c *gin.Context) {
// Get available models from account configurations for the selected group platform.
availableModels := h.gatewayService.GetAvailableModels(c.Request.Context(), groupID, platform)
if platform == service.PlatformAnthropic {
var group *service.Group
if apiKey != nil {
group = apiKey.Group
}
source := availableModels
if group != nil && group.ModelAllowlistEnabled() {
source = modelListingSource(platform, availableModels, defaultModelIDsForPlatform(platform))
} else if len(source) == 0 {
source = defaultModelIDsForPlatform(platform)
}
expanded := h.gatewayService.ExpandAnthropicLongContextModels(c.Request.Context(), group, source)
if len(availableModels) > 0 || len(expanded) > len(source) || (group != nil && group.ModelAllowlistEnabled()) {
availableModels = expanded
}
}
if apiKey != nil && apiKey.Group != nil && apiKey.Group.ModelAllowlistEnabled() {
source := modelListingSource(platform, availableModels, defaultModelIDsForPlatform(platform))
writeAllowlistedModelsList(c, platform, apiKey.Group.ModelAllowlist.FilterForListing(source))
@@ -174,8 +174,10 @@ func (h *GatewayHandler) ChatCompletions(c *gin.Context) {
defer inflightRelease()
// Parse request for session hash
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。
bodyRef := service.NewRequestBodyRef(body)
parsedReq, _ := service.ParseGatewayRequest(bodyRef, "chat_completions")
parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "chat_completions")
if parsedReq == nil {
parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef}
}
@@ -106,7 +106,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
// 里的任何工具声明(含 Codex 被动 image_gen namespace)而关闭。生图意图
// 仅用于能力路由与图片计费;独立图片/视频端点才在利润门范围之外。
requestCtx, pricingAt := service.WithGatewayTokenRequestPricing(requestCtx)
if service.IsImageGenerationIntentForPlatform("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) {
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此走跳过校验的
// 变体,避免对同一份字节再全量校验一次。
if service.IsImageGenerationIntentForPlatformValidated("/v1/responses", reqModel, body, openAICompatibleRequestPlatform(c.Request.Context(), apiKey)) {
requestCtx = service.WithOpenAIImageGenerationIntent(requestCtx)
}
c.Request = c.Request.WithContext(requestCtx)
@@ -178,8 +181,10 @@ func (h *GatewayHandler) Responses(c *gin.Context) {
defer inflightRelease()
// Parse request for session hash
// body 已在本函数开头用 gjson.ValidBytes 校验过,之后只经过 sjson 改写
// (applyOpenAIReasoningEffortPolicyForRequest),合法性保持,因此跳过重复校验。
bodyRef := service.NewRequestBodyRef(body)
parsedReq, _ := service.ParseGatewayRequest(bodyRef, "responses")
parsedReq, _ := service.ParseGatewayRequestValidated(bodyRef, "responses")
if parsedReq == nil {
parsedReq = &service.ParsedRequest{Model: reqModel, Stream: reqStream, Body: bodyRef}
}
@@ -23,6 +23,82 @@ type gatewayModelsAccountRepoStub struct {
byGroup map[int64][]service.Account
}
func TestGatewayModelsAnthropicLongContextVariants(t *testing.T) {
gin.SetMode(gin.TestMode)
const groupID int64 = 8880
for _, test := range []struct {
name string
platform string
mapping map[string]any
metadata map[string]service.UpstreamModelMetadata
allowlist []string
routing map[string][]int64
otherAccounts []service.Account
wantVariants []string
absent []string
}{
{name: "mapped target and threshold", mapping: map[string]any{"public": "upstream", "short": "short", "max-only": "max-only"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 900_000}, "short": {ContextWindow: 899_999}, "max-only": {MaxContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}},
wantVariants: []string{"public[1m]"}, absent: []string{"upstream", "upstream[1m]", "hidden", "hidden[1m]", "short[1m]", "max-only[1m]", claude.DefaultModels[0].ID}},
{name: "wildcard mappings are not concrete variants", mapping: map[string]any{"public*": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public*[1m]"}},
{name: "source metadata cannot override mapped target", mapping: map[string]any{"public": "short"},
metadata: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}, "short": {ContextWindow: 200_000}}, absent: []string{"public[1m]"}},
{name: "no duplicate suffix", mapping: map[string]any{"public": "upstream", "public[1m]": "upstream", "other[1M]": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, wantVariants: []string{"public[1m]", "other[1M]"}, absent: []string{"public[1m][1m]", "other[1M][1m]"}},
{name: "allowlist filters variants", mapping: map[string]any{"public": "upstream", "private": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public"}, absent: []string{"public[1m]", "private", "private[1m]"}},
{name: "allowlist can select variant", mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, allowlist: []string{"public[1m]"}, wantVariants: []string{"public[1m]"}, absent: []string{"public"}},
{name: "routing excludes metadata account", mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"public": {2}}, absent: []string{"public[1m]"}},
{name: "routing includes metadata account", mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, routing: map[string][]int64{"pub*": {1}}, wantVariants: []string{"public[1m]"}},
{name: "non-Anthropic listing", platform: service.PlatformOpenAI, mapping: map[string]any{"public": "upstream"},
metadata: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}, absent: []string{"public[1m]"}},
{name: "unmapped defaults", metadata: map[string]service.UpstreamModelMetadata{claude.DefaultModels[0].ID: {ContextWindow: 1_000_000}, "hidden": {ContextWindow: 1_000_000}},
wantVariants: []string{claude.DefaultModels[0].ID + "[1m]"}, absent: []string{"hidden", "hidden[1m]"}},
{name: "other platform account metadata", mapping: map[string]any{"public": "upstream"},
otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformOpenAI, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}},
{name: "unsupported model metadata", mapping: map[string]any{"public": "upstream"},
otherAccounts: []service.Account{{ID: 2, Platform: service.PlatformAnthropic, Credentials: map[string]any{"model_mapping": map[string]any{"private": "private"}}, Extra: map[string]any{service.UpstreamModelMetadataExtraKey: service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"public": {ContextWindow: 1_000_000}}}}}}, absent: []string{"public[1m]"}},
} {
t.Run(test.name, func(t *testing.T) {
platform := test.platform
if platform == "" {
platform = service.PlatformAnthropic
}
account := service.Account{ID: 1, Platform: platform, Type: service.AccountTypeOAuth, Credentials: map[string]any{"model_mapping": test.mapping}}
account.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: test.metadata})
outsideAccount := service.Account{ID: 3, Platform: service.PlatformAnthropic}
outsideAccount.SetUpstreamModelMetadataSnapshot(service.UpstreamModelMetadataSnapshot{Models: map[string]service.UpstreamModelMetadata{"upstream": {ContextWindow: 1_000_000}}})
h := newGatewayModelsHandlerForTest(&gatewayModelsAccountRepoStub{byGroup: map[int64][]service.Account{
groupID: append([]service.Account{account}, test.otherAccounts...), groupID + 1: {outsideAccount},
}})
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Request = httptest.NewRequest(http.MethodGet, "/v1/models", nil)
ctx.Set(string(middleware2.ContextKeyAPIKey), &service.APIKey{Group: &service.Group{
ID: groupID, Platform: platform,
ModelAllowlist: service.GroupModelAllowlist{Enabled: test.allowlist != nil, Models: test.allowlist},
ModelRoutingEnabled: test.routing != nil, ModelRouting: test.routing,
}})
h.Models(ctx)
require.Equal(t, http.StatusOK, rec.Code)
var response gatewayModelsResponseForTest
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &response))
ids := modelIDsForTest(response.Data)
for _, variant := range test.wantVariants {
require.Contains(t, ids, variant)
}
for _, absent := range test.absent {
require.NotContains(t, ids, absent)
}
require.Len(t, mergeModelIDs(ids, nil), len(ids))
})
}
}
type gatewayModelsRouteRepoStub struct {
service.CompositeModelRouteRepository
routes []service.CompositeModelRoute
+5
View File
@@ -400,6 +400,11 @@ func (h *OpenAIGatewayHandler) handleGrokMedia(c *gin.Context, endpoint service.
service.SetOpsLatencyMs(c, service.OpsResponseLatencyMsKey, responseLatencyMs)
if err != nil {
var validationErr *service.GrokMediaInputValidationError
if errors.As(err, &validationErr) {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", validationErr.Error())
return
}
var failoverErr *service.UpstreamFailoverError
if errors.As(err, &failoverErr) {
if failoverClientGone(c) {
@@ -3,12 +3,18 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"testing/iotest"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
@@ -17,6 +23,168 @@ import (
"github.com/tidwall/gjson"
)
func TestGrokImageEditLocalValidationSyncAndAsync(t *testing.T) {
enableGrokMediaValidationTestScheduler(t)
for _, oauth := range []bool{false, true} {
for _, async := range []bool{false, true} {
for _, format := range []string{"json", "multipart"} {
for _, count := range []int{3, 4, 5, 6} {
t.Run(fmt.Sprintf("oauth=%t/async=%t/%s/%d", oauth, async, format, count), func(t *testing.T) {
h, slots, _, upstream := newGrokMediaSlotHandler(t, oauth, false)
h.grokMediaEligibilityProber = grokMediaSlotProber(func(context.Context, int64) (bool, string, error) {
return true, "eligible", nil
})
upstream.call = func(req *http.Request, _ int64) (*http.Response, error) {
assert.Equal(t, "/v1/images/edits", req.URL.Path)
body, err := io.ReadAll(req.Body)
assert.NoError(t, err)
assert.Len(t, gjson.GetBytes(body, "images").Array(), count)
assert.NotEmpty(t, gjson.GetBytes(body, "mask.url").String())
return &http.Response{StatusCode: http.StatusBadRequest, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"code":"invalid_image","error":"upstream image rejection"}`))}, nil
}
body, contentType := grokImageEditLimitBody(t, format, count)
c, recorder := grokMediaSlotContext(context.Background(), true)
path := "/v1/images/edits"
if async {
path += "/async"
}
c.Request = httptest.NewRequest(http.MethodPost, path, bytes.NewReader(body))
c.Request.Header.Set("Content-Type", contentType)
responseBody := []byte(nil)
if async {
store := &asyncImageMemoryStore{tasks: make(map[string]*service.ImageTaskRecord)}
tasks := service.NewImageTaskServiceWithUploader(store, nil, time.Hour, time.Minute)
asyncHandler := NewAsyncImageHandler(tasks, h)
asyncHandler.Submit(c)
require.Equal(t, http.StatusAccepted, recorder.Code, recorder.Body.String())
taskID := gjson.GetBytes(recorder.Body.Bytes(), "task_id").String()
owner := service.ImageTaskOwner{UserID: 10, APIKeyID: 20}
require.Eventually(t, func() bool {
task, err := tasks.Get(context.Background(), owner, taskID)
return err == nil && task.Status != service.ImageTaskStatusProcessing
}, time.Second, 10*time.Millisecond)
poll, pollRecorder := grokMediaSlotContext(context.Background(), false)
poll.Params[0].Key, poll.Params[0].Value = "task_id", taskID
asyncHandler.Get(poll)
require.Equal(t, http.StatusOK, pollRecorder.Code)
responseBody = pollRecorder.Body.Bytes()
require.Equal(t, service.ImageTaskStatusFailed, gjson.GetBytes(responseBody, "status").String())
require.Equal(t, int64(http.StatusBadRequest), gjson.GetBytes(responseBody, "http_status").Int())
} else {
h.GrokImages(c)
require.Equal(t, http.StatusBadRequest, recorder.Code, recorder.Body.String())
responseBody = recorder.Body.Bytes()
}
require.Equal(t, "invalid_request_error", gjson.GetBytes(responseBody, "error.type").String())
metrics := h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics()
if count > 5 {
require.Equal(t, "a maximum of 5 source images is supported for image edits", gjson.GetBytes(responseBody, "error.message").String())
require.Zero(t, upstream.calls)
require.Zero(t, metrics.RuntimeStatsAccountCount, "local rejection must report neither success nor failure")
} else {
require.Equal(t, "upstream image rejection", gjson.GetBytes(responseBody, "error.message").String())
require.Equal(t, 1, upstream.calls)
require.Equal(t, 1, metrics.RuntimeStatsAccountCount, "real upstream failures still report failure")
}
require.Zero(t, metrics.AccountSwitchTotal)
slots.assertReleased(t)
})
}
}
}
}
}
func grokImageEditLimitBody(t *testing.T, format string, count int) ([]byte, string) {
t.Helper()
if format == "json" {
images := make([]string, count)
for index := range images {
images[index] = fmt.Sprintf("https://example.test/%d.png", index)
}
body, err := json.Marshal(map[string]any{"model": "grok-imagine-image-2.0", "prompt": "test", "images": images, "mask": "https://example.test/mask.png"})
require.NoError(t, err)
return body, "application/json"
}
var buffer bytes.Buffer
writer := multipart.NewWriter(&buffer)
require.NoError(t, writer.WriteField("model", "grok-imagine-image-2.0"))
require.NoError(t, writer.WriteField("prompt", "test"))
for index := 0; index < count; index++ {
if index%2 == 0 {
require.NoError(t, writer.WriteField("image", fmt.Sprintf("https://example.test/%d.png", index)))
} else {
part, err := writer.CreateFormFile("image[]", fmt.Sprintf("%d.png", index))
require.NoError(t, err)
_, err = part.Write([]byte("\x89PNG\r\n\x1a\nsynthetic"))
require.NoError(t, err)
}
}
part, err := writer.CreateFormFile("mask", "mask.png")
require.NoError(t, err)
_, err = part.Write([]byte("\x89PNG\r\n\x1a\nmask"))
require.NoError(t, err)
require.NoError(t, writer.Close())
return buffer.Bytes(), writer.FormDataContentType()
}
func TestGrokImageEditInternalAndRetryableErrorsRemainUpstreamErrors(t *testing.T) {
enableGrokMediaValidationTestScheduler(t)
for _, retryable := range []bool{false, true} {
t.Run(fmt.Sprintf("retryable=%t", retryable), func(t *testing.T) {
h, slots, _, upstream := newGrokMediaSlotHandler(t, false, false)
upstream.call = func(*http.Request, int64) (*http.Response, error) {
if !retryable {
return &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(iotest.ErrReader(errors.New("internal response read failure")))}, nil
}
return &http.Response{StatusCode: http.StatusServiceUnavailable, Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"error":"temporarily unavailable"}`))}, nil
}
c, recorder := grokMediaSlotContext(context.Background(), true)
body, contentType := grokImageEditLimitBody(t, "json", 3)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/images/edits", bytes.NewReader(body))
c.Request.Header.Set("Content-Type", contentType)
h.GrokImages(c)
require.GreaterOrEqual(t, recorder.Code, http.StatusInternalServerError, recorder.Body.String())
require.NotEqual(t, "invalid_request_error", gjson.GetBytes(recorder.Body.Bytes(), "error.type").String())
metrics := h.gatewayService.SnapshotOpenAIAccountSchedulerMetrics()
require.Positive(t, metrics.RuntimeStatsAccountCount, "calls=%d response=%s", upstream.calls, recorder.Body.String())
if retryable {
require.Greater(t, upstream.calls, 1)
require.Positive(t, metrics.AccountSwitchTotal)
} else {
require.Equal(t, http.StatusBadGateway, recorder.Code)
require.Equal(t, 1, upstream.calls)
require.Zero(t, metrics.AccountSwitchTotal)
}
slots.assertReleased(t)
})
}
}
type grokMediaValidationSettingsRepo struct {
service.SettingRepository
}
func (grokMediaSlotRepo) SetTempUnschedulable(context.Context, int64, time.Time, string) error {
return nil
}
func (*grokMediaValidationSettingsRepo) SetMultiple(context.Context, map[string]string) error {
return nil
}
func enableGrokMediaValidationTestScheduler(t *testing.T) {
t.Helper()
settings := service.NewSettingService(&grokMediaValidationSettingsRepo{}, nil)
require.NoError(t, settings.UpdateSettings(context.Background(), &service.SystemSettings{OpenAIAdvancedSchedulerEnabled: true}))
t.Cleanup(func() {
require.NoError(t, settings.UpdateSettings(context.Background(), &service.SystemSettings{}))
})
}
func TestGrokImagesPreservesUpstreamErrorOnSyncAndAsyncRoutes(t *testing.T) {
for _, oauth := range []bool{false, true} {
accountType := "api-key"
@@ -1382,7 +1382,6 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
return
}
bindOpenAIReasoningEffortPolicyForMessagesRequest(c, apiKey, body)
routingModel := service.NormalizeOpenAICompatRequestedModel(reqModel)
preferredMappedModel := resolveOpenAIMessagesDispatchMappedModel(c, apiKey, reqModel)
reqStream := gjson.GetBytes(body, "stream").Bool()
@@ -1405,6 +1404,10 @@ func (h *OpenAIGatewayHandler) Messages(c *gin.Context) {
channelMappingMsg = service.ChannelMappingResult{MappedModel: reqModel}
}
mappedBodyForMessages := newOpenAIModelMappedBodyCache(body, h.gatewayService.ReplaceModelInBody)
// Schedule by the channel-mapped model, as the Responses and Chat Completions
// paths do: the forwarded body carries that model, so account model filters
// must judge it rather than the client's alias.
routingModel := service.NormalizeOpenAICompatRequestedModel(openAIChannelForwardModel(channelMappingMsg, reqModel))
// 绑定错误透传服务,允许 service 层在非 failover 错误场景复用规则。
if h.errorPassthroughService != nil {
@@ -2793,12 +2796,23 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 必须在合成路由解析和上游模型映射之前执行。
// 与 HTTP 准入一致:帧内重复 model 键/大小写变体可能被上游按末值绑定,
// 全部候选值逐一校验,任一未命中即拒绝。
if blocked := blockedModelAllowlistCandidate(apiKey.Group, requestmodel.FromBodyCandidates("", "application/json", firstMessage)); blocked != "" {
firstModelCandidates := requestmodel.FromBodyCandidates("", "application/json", firstMessage)
if blocked := blockedModelAllowlistCandidate(apiKey.Group, firstModelCandidates); blocked != "" {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed)
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for this group", blocked))
return
}
// 帧内重复字段(model、service_tier、reasoning.effort 等,含大小写变体与
// 嵌套对象)会让计费/策略读到的首个值与上游实际绑定的值分叉;取值相同也不
// 放行,因为网关的 sjson 改写只动首个(GHSA-p3r4-jcm3-2hph)。与 HTTP 入口
// (RejectConflictingRequestFields)同一规则,对所有分组生效。放在白名单
// 之后,白名单的拒绝原因保持不变。
if field, conflict := requestmodel.ConflictingField("application/json", firstMessage); conflict {
middleware2.MarkIngressRejected(c, middleware2.IngressRejectConflictingRequestFields)
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, fmt.Sprintf("response.create payload declares field %.64q more than once", field))
return
}
// Keep the client model in the frame for admission, response identity and usage.
// Apply the resolved upstream model through MapRequestModel on every turn.
wsRouteModel := reqModel
@@ -3270,12 +3284,19 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) {
// 则关闭整条连接,与推理强度 deny 一致。实际生效模型始终参与校验;
// 帧内重复 model 键/大小写变体/嵌套 session.model 额外逐一校验,
// 防止候选集非空时掩盖被轮换掉的禁用模型。
candidates := append([]string{model}, requestmodel.FromBodyCandidates("", "application/json", payload)...)
frameModelCandidates := requestmodel.FromBodyCandidates("", "application/json", payload)
candidates := append([]string{model}, frameModelCandidates...)
if blocked := blockedModelAllowlistCandidate(apiKey.Group, candidates); blocked != "" {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalModelConfiguration)
middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed)
return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for this group", blocked), nil)
}
// 后续 turn 同首帧:帧内有重复字段即关闭连接,避免计费/策略读到的
// 值与上游实际绑定的值分叉。
if field, conflict := requestmodel.ConflictingField("application/json", payload); conflict {
middleware2.MarkIngressRejected(c, middleware2.IngressRejectConflictingRequestFields)
return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("websocket request payload declares field %.64q more than once", field), nil)
}
if decision := h.checkSecurityAuditStage(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIResponses, model, payload, "subsequent_turn"); decision != nil && !decision.AllowNextStage {
writeSecurityAuditWSError(ctx, wsConn, decision)
return service.NewOpenAIWSClientCloseError(securityAuditWSCloseStatus(decision), securityAuditWSCloseReason(decision), nil)
@@ -1959,6 +1959,8 @@ type openAIResponsesWSUsageLogCase struct {
firstFrameCloseExpected bool
// secondTurnCloseExpected:第二个 turn 被拒(连接被 1008 关闭)。
secondTurnCloseExpected bool
// midFrameCloseExpected:midPayload 被拒(连接被 1008 关闭),帧不到达上游。
midFrameCloseExpected bool
}
type openAIResponsesWSUsageLogResult struct {
@@ -3236,6 +3238,19 @@ func runOpenAIResponsesWebSocketUsageLogCase(t *testing.T, tc openAIResponsesWSU
err = clientConn.Write(writeCtx, coderws.MessageText, []byte(tc.midPayload))
cancelWrite()
require.NoError(t, err)
if tc.midFrameCloseExpected {
readCtx, cancelRead := context.WithTimeout(context.Background(), 3*time.Second)
_, _, readErr := clientConn.Read(readCtx)
cancelRead()
require.Error(t, readErr, "mid frame should have been rejected with a close")
var closeErr coderws.CloseError
require.ErrorAs(t, readErr, &closeErr)
require.Equal(t, coderws.StatusPolicyViolation, closeErr.Code)
require.Contains(t, closeErr.Reason, tc.closeReason)
require.Len(t, upstreamPayloadCh, 1, "rejected mid frame must not reach upstream")
_ = clientConn.CloseNow()
return openAIResponsesWSUsageLogResult{}
}
readCompleted()
}
if strings.TrimSpace(tc.secondPayload) != "" && (turnCount >= 2) {
@@ -127,6 +127,8 @@ func TestOpenAIResponsesWebSocket_FirstFrameCaseVariantModelKeyRejected(t *testi
// 后续 turn 含重复 model 键(首个在白名单、末个不在):拒绝并关闭连接。
func TestOpenAIResponsesWebSocket_SubsequentTurnDuplicateModelKeysRejected(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
// 两种模式都在读取任何字段之前先做字段歧义检查(帧必须在兼容归一化等
// 重编码之前拦截),所以由歧义检查而不是白名单关闭连接,帧不到达上游。
t.Run(mode, func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
@@ -134,21 +136,21 @@ func TestOpenAIResponsesWebSocket_SubsequentTurnDuplicateModelKeysRejected(t *te
group: wsAllowlistGroup(true, "gpt-5.4"),
ingressMode: mode,
secondTurnCloseExpected: true,
closeReason: `declares field "model" more than once`,
})
})
}
}
// 重复但同值的 model 键不误伤,连接正常完成两个 turn。
func TestOpenAIResponsesWebSocket_DuplicateIdenticalModelKeysAllowed(t *testing.T) {
got := runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","model":"gpt-5.4","stream":false}`,
secondPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(true, "gpt-5.4"),
// 重复但同值的 model 键:白名单本身放行(两个候选都在名单内),但字段歧义检查
// 拒绝——网关的 sjson 模型改写只改首个,改写后两者就会分叉(GHSA-p3r4-jcm3-2hph)。
func TestOpenAIResponsesWebSocket_DuplicateIdenticalModelKeysRejected(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(true, "gpt-5.4"),
firstFrameCloseExpected: true,
closeReason: `declares field "model" more than once`,
})
if len(got.clientEvents) != 2 {
t.Fatalf("expected two completed events, got %d", len(got.clientEvents))
}
}
// session.update 轮换绕过:首帧用白名单内模型建立会话,session.update 把会话
@@ -0,0 +1,128 @@
package handler
import (
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
)
const wsModelConflictCloseReason = "more than once"
// 没有开启白名单的分组:首帧里重复 model 键取值不一致(计费按第一个、上游可能
// 按最后一个绑定)必须以 1008 关闭,帧不到达上游。
func TestOpenAIResponsesWebSocket_FirstFrameConflictingModelKeysRejectedWithoutAllowlist(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
t.Run(mode, func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4-nano","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
firstFrameCloseExpected: true,
closeReason: wsModelConflictCloseReason,
})
})
}
}
// 大小写变体键同样会被 encoding/json 绑定到同一个字段。
func TestOpenAIResponsesWebSocket_FirstFrameConflictingCaseVariantModelKeyRejected(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4-nano","Model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: service.OpenAIWSIngressModePassthrough,
firstFrameCloseExpected: true,
closeReason: wsModelConflictCloseReason,
})
}
// 白名单开启且两个模型都在名单内:白名单放行,模型歧义检查仍要拒绝。
func TestOpenAIResponsesWebSocket_FirstFrameConflictingAllowlistedModelKeysRejected(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4-nano","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(true, "gpt-5.4-nano", "gpt-5.4"),
ingressMode: service.OpenAIWSIngressModePassthrough,
firstFrameCloseExpected: true,
closeReason: wsModelConflictCloseReason,
})
}
// 后续 turn 的帧同样检查。
func TestOpenAIResponsesWebSocket_SubsequentTurnConflictingModelKeysRejectedWithoutAllowlist(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
t.Run(mode, func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
secondPayload: `{"type":"response.create","model":"gpt-5.4-nano","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
secondTurnCloseExpected: true,
closeReason: wsModelConflictCloseReason,
})
})
}
}
// 取值相同的重复键同样拒绝:网关的 sjson 改写(模型映射、推理强度降级)只改
// 首个,改写后两者就会分叉。首帧与后续 turn 都要关闭连接。
func TestOpenAIResponsesWebSocket_IdenticalDuplicateKeysRejectedWithoutAllowlist(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
t.Run(mode+"/first_frame", func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
firstFrameCloseExpected: true,
closeReason: `declares field "model" more than once`,
})
})
t.Run(mode+"/subsequent_turn", func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
secondPayload: `{"type":"response.create","model":"gpt-5.4","reasoning":{"effort":"xhigh","effort":"xhigh"},"stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
secondTurnCloseExpected: true,
closeReason: `declares field "reasoning.effort" more than once`,
})
})
}
}
// 非 model 字段同样参与计费与策略:首帧 service_tier、后续 turn 嵌套的
// reasoning.effort 取值不一致都必须关闭连接。
func TestOpenAIResponsesWebSocket_ConflictingBillingFieldsRejected(t *testing.T) {
for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} {
t.Run(mode+"/first_frame_service_tier", func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","service_tier":"flex","stream":false,"service_tier":"priority"}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
firstFrameCloseExpected: true,
closeReason: `declares field "service_tier" more than once`,
})
})
t.Run(mode+"/subsequent_turn_reasoning_effort", func(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
secondPayload: `{"type":"response.create","model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"stream":false}`,
group: wsAllowlistGroup(false),
ingressMode: mode,
secondTurnCloseExpected: true,
closeReason: `declares field "reasoning.effort" more than once`,
})
})
}
}
// passthrough 原样转发 session.update 等非 response.create 事件:帧内重复字段
// 同样必须关闭连接,不能到达上游。
func TestOpenAIResponsesWebSocket_PassthroughSessionUpdateDuplicateRejected(t *testing.T) {
runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{
firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`,
midPayload: `{"type":"session.update","session":{"model":"gpt-5.4","model":"gpt-4.1"}}`,
group: wsAllowlistGroup(false),
ingressMode: service.OpenAIWSIngressModePassthrough,
midFrameCloseExpected: true,
closeReason: `declares field "session.model" more than once`,
})
}
@@ -14,7 +14,10 @@ var codexSelectedPageName = regexp.MustCompile(`^codex_apps_selected_page_part_(
// Codex injects external context as standalone outputs, without a model tool call.
// Use the legacy user-message representation for HTTP Responses interoperability.
func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
if !mayContainCodexCallOutputCandidate(body, "codex_apps_open_page", "codex_apps_selected_page_part_", "browser_info", "goal_objective", "untrusted_context") || !hasUniqueJSONMembers(body) {
if !mayContainCodexCallOutputCandidate(body,
"codex_apps_open_page", "codex_apps_selected_page_part_",
"browser_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan",
) || !hasUniqueJSONMembers(body) {
return body, false
}
var request map[string]json.RawMessage
@@ -45,13 +48,14 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
continue
}
}
name, output := readString("name"), readString("output")
if !validCodexUntrustedContext(name, output) {
name := readString("name")
var output *string
if json.Unmarshal(item["output"], &output) != nil || output == nil || !validCodexUntrustedContext(name, *output) {
continue
}
text := "<external_" + name + ">" + output + "</external_" + name + ">"
if validCodexPageContext(name, output) {
text = "<external_" + name + ">\n" + output + "\n</external_" + name + ">"
text := "<external_" + name + ">" + *output + "</external_" + name + ">"
if validCodexPageContext(name, *output) {
text = "<external_" + name + ">\n" + *output + "\n</external_" + name + ">"
}
message := map[string]any{
"type": "message",
@@ -85,8 +89,14 @@ func normalizeCodexUntrustedContext(body []byte) ([]byte, bool) {
func validCodexUntrustedContext(name, output string) bool {
switch name {
case "browser_info", "goal_objective", "untrusted_context":
case "browser_info", "goal_objective", "untrusted_context", "ide_context":
return strings.TrimSpace(output) != ""
case "untrusted_content":
// Codex's fallback for an unnamed context source can carry any text, including an empty value.
return true
case "proposed_plan":
// Codex splits an approved plan by byte length, so a chunk can be all whitespace.
return output != ""
default:
return validCodexPageContext(name, output)
}
@@ -54,18 +54,24 @@ func TestNormalizeCodexPageContextFirstMessage(t *testing.T) {
require.Equal(t, got, again)
}
var codexTextContextNamesForTest = []string{"browser_info", "goal_objective", "untrusted_context", "untrusted_content", "ide_context", "proposed_plan"}
func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
// AdditionalContextToolOutput derives names from caller-provided context keys.
// Codex 0.169.0 enables this representation by default (openai/codex#60487).
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
for _, name := range codexTextContextNamesForTest {
t.Run(name, func(t *testing.T) {
output := "external context\nline two"
body := pageContextRequest(t, pageContextItem(name, output),
if name == "ide_context" {
output = "# Context from my IDE setup:\n\n## Active file: main.go\n\n## Active selection of the file:\nfunc main() {}"
}
contextItem := map[string]any{"type": "function_call_output", "namespace": "agent", "name": name, "output": output}
body := pageContextRequest(t, contextItem,
map[string]any{"role": "user", "content": "continue"})
h := &OpenAIGatewayHandler{}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
require.False(t, h.validateFunctionCallOutputRequest(c, body, zap.NewNop()))
require.Equal(t, 400, w.Code)
require.Contains(t, w.Body.String(), "function_call_output requires call_id")
got, changed := normalizeCodexUntrustedContext(body)
require.True(t, changed)
@@ -87,7 +93,7 @@ func TestNormalizeCodexAdditionalUntrustedContext(t *testing.T) {
}
func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutputs(t *testing.T) {
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
for _, name := range codexTextContextNamesForTest {
for _, override := range []map[string]any{
{"call_id": "call_real"},
{"call_id": nil},
@@ -96,7 +102,6 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput
{"namespace": nil},
{"namespace": 42},
{"output": []any{map[string]any{"type": "encrypted_content", "encrypted_content": "sealed"}}},
{"output": " "},
{"output": nil},
} {
item := pageContextItem(name, "context")
@@ -108,12 +113,14 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput
require.False(t, changed, "name=%s override=%v", name, override)
require.Equal(t, body, got)
}
item := pageContextItem(name, "context")
delete(item, "namespace")
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
for _, field := range []string{"namespace", "output"} {
item := pageContextItem(name, "context")
delete(item, field)
body := pageContextRequest(t, item)
got, changed := normalizeCodexUntrustedContext(body)
require.False(t, changed)
require.Equal(t, body, got)
}
}
// Recognized external context cannot make an unrelated tool result valid.
body := pageContextRequest(t, pageContextItem("browser_info", "tab"),
@@ -138,7 +145,7 @@ func TestNormalizeCodexAdditionalUntrustedContextPreservesRealAndMalformedOutput
}
func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *testing.T) {
names := []string{"browser_info", "goal_objective", "untrusted_context"}
names := codexTextContextNamesForTest
for _, callID := range []string{"", " \t\n"} {
items := make([]any, 0, len(names))
for _, name := range names {
@@ -158,7 +165,7 @@ func TestNormalizeCodexAdditionalUntrustedContextBlankCallIDsAndMixedInput(t *te
}
func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *testing.T) {
for _, name := range []string{"browser_info", "goal_objective", "untrusted_context"} {
for _, name := range codexTextContextNamesForTest {
for _, body := range []string{
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","call_id":"real","call_id":"","output":"context"}]}`,
`{"input":[{"type":"function_call_output","namespace":"agent","name":"` + name + `","output":"first","output":"second"}]}`,
@@ -170,6 +177,38 @@ func TestNormalizeCodexAdditionalUntrustedContextRejectsDuplicateMembers(t *test
}
}
func TestNormalizeCodexProposedPlanChunks(t *testing.T) {
chunks := []string{"# Plan\n", " \n\t", "1. Run tests."}
var items []any
for _, chunk := range chunks {
items = append(items, pageContextItem("proposed_plan", chunk))
}
got, changed := normalizeCodexUntrustedContext(pageContextRequest(t, items...))
require.True(t, changed)
messages := gjson.GetBytes(got, "input").Array()
require.Len(t, messages, len(chunks))
for i, message := range messages {
require.Equal(t, "user", message.Get("role").String())
require.Equal(t, "<external_proposed_plan>"+chunks[i]+"</external_proposed_plan>", message.Get("content.0.text").String())
}
}
func TestNormalizeCodexAdditionalUntrustedContextBlankOutput(t *testing.T) {
for _, name := range codexTextContextNamesForTest {
for _, output := range []string{"", " \t"} {
body := pageContextRequest(t, pageContextItem(name, output))
got, changed := normalizeCodexUntrustedContext(body)
wantChange := name == "untrusted_content" || (name == "proposed_plan" && output != "")
require.Equal(t, wantChange, changed, "name=%s output=%q", name, output)
if wantChange {
require.Equal(t, "<external_"+name+">"+output+"</external_"+name+">", gjson.GetBytes(got, "input.0.content.0.text").String())
} else {
require.Equal(t, body, got)
}
}
}
}
func TestNormalizeCodexPageContextPreservesHistoryAndToolValidation(t *testing.T) {
body := []byte(`{"model":"gpt-5","previous_response_id":"resp_history","metadata":{"large":9007199254740993},"input":[{"type":"function_call","name":"read_file","call_id":"call_real","arguments":"{}"},{"type":"function_call_output","call_id":"call_real","output":"result"},{"type":"function_call_output","namespace":"agent","name":"codex_apps_open_page","output":"{\"page_id\":\"page_1\"}"}]}`)
got, changed := normalizeCodexUntrustedContext(body)
@@ -1,7 +1,6 @@
package handler
import (
"fmt"
"net/http"
"github.com/Wei-Shaw/sub2api/internal/config"
@@ -26,18 +25,6 @@ func handleRequestBodyReadError(c *gin.Context, reqLog *zap.Logger, err error) b
return middleware2.RejectRequestBodyMemoryOverload(c, err)
}
func formatBodyLimit(limit int64) string {
const mb = 1024 * 1024
if limit >= mb {
return fmt.Sprintf("%dMB", limit/mb)
}
return fmt.Sprintf("%dB", limit)
}
func buildBodyTooLargeMessage(limit int64) string {
return fmt.Sprintf("Request body too large, limit is %s", formatBodyLimit(limit))
}
func readLenientJSONRequestBodyWithPrealloc(req *http.Request, cfg *config.Config) ([]byte, error) {
return pkghttputil.ReadLenientJSONRequestBodyWithPrealloc(req, gatewayMaxBodySize(cfg))
}
@@ -10,6 +10,7 @@ import (
"os"
"testing"
pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
@@ -37,7 +38,7 @@ func TestRequestBodyLimitTooLarge(t *testing.T) {
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusRequestEntityTooLarge, recorder.Code)
require.Contains(t, recorder.Body.String(), buildBodyTooLargeMessage(limit))
require.Contains(t, recorder.Body.String(), pkghttputil.BodyTooLargeMessage(limit))
}
func TestHandleRequestBodyReadErrorCancellation(t *testing.T) {
@@ -16,11 +16,10 @@ import (
// logging request content.
func requestBodyReadFailure(reqLog *zap.Logger, req *http.Request, err error) (int, string) {
failure := pkghttputil.DescribeRequestBodyReadFailure(req, err)
if failure.Kind == pkghttputil.RequestBodyReadErrorMaxBytes {
return failure.Status, buildBodyTooLargeMessage(failure.MaxBytesLimit)
if failure.Kind != pkghttputil.RequestBodyReadErrorMaxBytes {
logRequestBodyReadFailure(reqLog, failure)
}
logRequestBodyReadFailure(reqLog, failure)
return failure.Status, failure.Message
return failure.Status, failure.ClientMessage()
}
func logRequestBodyReadFailure(reqLog *zap.Logger, failure pkghttputil.RequestBodyReadFailure) {
@@ -16,6 +16,7 @@ import (
"testing"
"testing/iotest"
pkghttputil "github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
"github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
@@ -47,7 +48,7 @@ func TestRequestBodyReadFailureKeepsBodyLimitMessageWithoutLogging(t *testing.T)
log, logs := newObservedLogger(t)
status, message := requestBodyReadFailure(log, nil, &http.MaxBytesError{Limit: 2 << 20})
require.Equal(t, http.StatusRequestEntityTooLarge, status)
require.Equal(t, buildBodyTooLargeMessage(2<<20), message)
require.Equal(t, pkghttputil.BodyTooLargeMessage(2<<20), message)
require.Empty(t, logs.All())
}
@@ -0,0 +1,271 @@
package apicompat
import (
"encoding/json"
"strings"
)
// ToolSearchToolName is Claude Code's client-executed tool-search tool. Under
// the native protocol it maps to the Responses `tool_search` tool, its
// tool_use to a `tool_search_call` and its tool_result to a
// `tool_search_output`; an upstream tool_search_call comes back under this name.
const ToolSearchToolName = "ToolSearch"
// emptyToolResultOutput is what convertToolResultOutput emits for a
// tool_result without text.
const emptyToolResultOutput = "(empty)"
// ApplyNativeToolSearch rewrites a Responses request produced by
// AnthropicToResponses so Claude Code's ToolSearch uses the native
// client-executed tool_search protocol of the ChatGPT/Codex backend.
//
// Deferred tools never reach the top-level tools: revealed definitions ride in
// the history's tool_search_output instead, so the top-level tools (the head of
// the prompt-cache prefix) stay identical before and after a reveal.
func ApplyNativeToolSearch(req *AnthropicRequest, out *ResponsesRequest) error {
declared := false
deferred := make(map[string]bool)
for _, t := range req.Tools {
if t.DeferLoading {
deferred[t.Name] = true
} else if t.Name == ToolSearchToolName {
declared = true
}
}
// The Responses API has no tool_choice value that forces tool_search or a
// tool declared only in tool_search_output, so a request forcing either
// keeps every tool and call as a plain function.
if !declared || forcesHiddenTool(req.ToolChoice, deferred) {
return nil
}
schemas := make(map[string]AnthropicTool, len(req.Tools))
kept := make([]AnthropicTool, 0, len(req.Tools))
for _, t := range req.Tools {
schemas[t.Name] = t
if t.DeferLoading {
continue
}
kept = append(kept, t)
}
tools := convertAnthropicToolsToResponses(kept)
for i, t := range kept {
if t.Name == ToolSearchToolName {
// Codex declares this tool without a name or strict.
tools[i] = ResponsesTool{
Type: "tool_search",
Execution: "client",
Description: t.Description,
Parameters: normalizeToolParameters(t.InputSchema),
}
}
}
out.Tools = tools
revealed := toolSearchReveals(req.Messages)
if len(revealed) == 0 {
return nil
}
var items []json.RawMessage
if err := json.Unmarshal(out.Input, &items); err != nil {
return err
}
rewritten := make([]json.RawMessage, 0, len(items))
var pendingText []string
flush := func(next json.RawMessage) (json.RawMessage, error) {
text := strings.Join(pendingText, "\n\n")
pendingText = nil
return userMessageWithLeadingText(next, text)
}
for _, raw := range items {
var item ResponsesInputItem
if err := json.Unmarshal(raw, &item); err != nil {
return err
}
if len(pendingText) > 0 && item.Type != "function_call_output" {
// A tool_search_output has no field for the result text, so it rides
// in the user message that follows the run of tool outputs.
merged, err := flush(raw)
if err != nil {
return err
}
if item.Type == "message" && item.Role == "user" {
raw = merged
} else {
rewritten = append(rewritten, merged)
}
}
names, isSearch := revealed[item.CallID]
if !isSearch {
rewritten = append(rewritten, raw)
continue
}
var native any
switch item.Type {
case "function_call":
native = map[string]any{
"type": "tool_search_call",
"call_id": item.CallID,
"execution": "client",
"status": "completed",
"arguments": jsonObjectOrEmpty(item.Arguments),
}
case "function_call_output":
loaded := make([]any, 0, len(names))
for _, name := range names {
t, ok := schemas[name]
if !ok {
continue
}
loaded = append(loaded, map[string]any{
"type": "function",
"name": name,
"description": t.Description,
"defer_loading": true,
"strict": false,
"parameters": normalizeToolParameters(t.InputSchema),
})
}
native = map[string]any{
"type": "tool_search_output",
"call_id": item.CallID,
"execution": "client",
"status": "completed",
"tools": loaded,
}
if item.Output != "" && item.Output != emptyToolResultOutput {
pendingText = append(pendingText, item.Output)
}
default:
rewritten = append(rewritten, raw)
continue
}
encoded, err := json.Marshal(native)
if err != nil {
return err
}
rewritten = append(rewritten, encoded)
}
if len(pendingText) > 0 {
tail, err := flush(nil)
if err != nil {
return err
}
rewritten = append(rewritten, tail)
}
input, err := json.Marshal(rewritten)
if err != nil {
return err
}
out.Input = input
return nil
}
// userMessageWithLeadingText returns next with a separate input_text part for
// text placed ahead of its existing parts when next is a user message, and
// otherwise a new user message holding text. Existing parts stay untouched.
func userMessageWithLeadingText(next json.RawMessage, text string) (json.RawMessage, error) {
lead, err := json.Marshal(ResponsesContentPart{Type: "input_text", Text: text})
if err != nil {
return nil, err
}
var msg ResponsesInputItem
if len(next) > 0 && json.Unmarshal(next, &msg) == nil && msg.Type == "message" && msg.Role == "user" {
var parts []json.RawMessage
if json.Unmarshal(msg.Content, &parts) == nil {
content, err := json.Marshal(append([]json.RawMessage{lead}, parts...))
if err != nil {
return nil, err
}
msg.Content = content
return json.Marshal(msg)
}
}
content, err := json.Marshal([]json.RawMessage{lead})
if err != nil {
return nil, err
}
return json.Marshal(ResponsesInputItem{Type: "message", Role: "user", Content: content})
}
func forcesHiddenTool(raw json.RawMessage, deferred map[string]bool) bool {
var choice struct {
Type string `json:"type"`
Name string `json:"name"`
}
if len(raw) == 0 || json.Unmarshal(raw, &choice) != nil {
return false
}
return choice.Type == "tool" && (choice.Name == ToolSearchToolName || deferred[choice.Name])
}
// toolSearchReveals maps each ToolSearch tool_use id in the history to the
// tool names its tool_result referenced, first occurrence first.
func toolSearchReveals(msgs []AnthropicMessage) map[string][]string {
reveals := make(map[string][]string)
for _, m := range msgs {
var blocks []AnthropicContentBlock
if json.Unmarshal(m.Content, &blocks) != nil {
continue
}
for _, b := range blocks {
switch {
case b.Type == "tool_use" && b.Name == ToolSearchToolName && b.ID != "":
reveals[toResponsesCallID(b.ID)] = nil
case b.Type == "tool_result":
id := toResponsesCallID(b.ToolUseID)
if _, isSearch := reveals[id]; !isSearch {
continue
}
var inner []AnthropicContentBlock
_ = json.Unmarshal(b.Content, &inner)
seen := make(map[string]bool)
for _, ib := range inner {
if ib.Type == "tool_reference" && ib.ToolName != "" && !seen[ib.ToolName] {
seen[ib.ToolName] = true
reveals[id] = append(reveals[id], ib.ToolName)
}
}
}
}
}
return reveals
}
// toolSearchCallToolUse turns an upstream tool_search_call back into the
// ToolSearch tool_use Claude Code executes; its call_id round-trips as the
// tool_use id that the next turn's tool_result answers.
func toolSearchCallToolUse(item ResponsesOutput) AnthropicContentBlock {
return AnthropicContentBlock{
Type: "tool_use",
ID: fromResponsesCallID(item.CallID),
Name: ToolSearchToolName,
Input: jsonObjectOrEmpty(item.Arguments),
}
}
// jsonObjectOrEmpty keeps raw when it is a JSON object; both tool_search_call
// arguments and tool_use input must be objects.
func jsonObjectOrEmpty(raw string) json.RawMessage {
var probe map[string]json.RawMessage
if json.Unmarshal([]byte(raw), &probe) != nil || probe == nil {
return json.RawMessage(`{}`)
}
return json.RawMessage(raw)
}
func resToAnthHandleToolSearchDone(evt *ResponsesStreamEvent, state *ResponsesEventToAnthropicState) []AnthropicStreamEvent {
events := closeCurrentBlock(state)
block := toolSearchCallToolUse(*evt.Item)
input := block.Input
block.Input = json.RawMessage(`{}`)
idx := state.ContentBlockIndex
state.HasToolCall = true
events = append(events,
AnthropicStreamEvent{Type: "content_block_start", Index: &idx, ContentBlock: &block},
AnthropicStreamEvent{Type: "content_block_delta", Index: &idx, Delta: &AnthropicDelta{Type: "input_json_delta", PartialJSON: string(input)}},
AnthropicStreamEvent{Type: "content_block_stop", Index: &idx},
)
state.ContentBlockIndex++
return events
}
@@ -0,0 +1,256 @@
//go:build unit
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
const toolSearchTestSchema = `{"type":"object","properties":{"query":{"type":"string"},"max_results":{"type":"number"}},"required":["query","max_results"]}`
func toolSearchTestRequest(t *testing.T, raw string) *AnthropicRequest {
t.Helper()
var req AnthropicRequest
require.NoError(t, json.Unmarshal([]byte(raw), &req))
return &req
}
func nativeToolSearchJSON(t *testing.T, req *AnthropicRequest) []byte {
t.Helper()
out, err := AnthropicToResponses(req)
require.NoError(t, err)
require.NoError(t, ApplyNativeToolSearch(req, out))
body, err := json.Marshal(out)
require.NoError(t, err)
return body
}
// Before the reveal Claude Code sends Bash + ToolSearch; after it, the revealed
// WebFetch schema joins tools[] with defer_loading:true and the history carries
// the ToolSearch call plus its tool_reference result.
const toolSearchBeforeReveal = `{"model":"gpt-6-astra","max_tokens":64,
"tools":[
{"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}},
{"name":"ToolSearch","description":"search deferred tools","input_schema":` + toolSearchTestSchema + `}],
"messages":[{"role":"user","content":"fetch the page"}]}`
const toolSearchAfterReveal = `{"model":"gpt-6-astra","max_tokens":64,
"tools":[
{"name":"Bash","description":"run","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}},
{"name":"ToolSearch","description":"search deferred tools","input_schema":` + toolSearchTestSchema + `},
{"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object","properties":{"url":{"type":"string"}},"required":["url"]},"defer_loading":true}],
"messages":[
{"role":"user","content":"fetch the page"},
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"select:WebFetch","max_results":5}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search","content":[{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"WebFetch"},{"type":"tool_reference","tool_name":"Unknown"}]}]}]}`
func TestApplyNativeToolSearch_TopLevelToolsStableAcrossReveal(t *testing.T) {
before := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchBeforeReveal))
after := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchAfterReveal))
require.JSONEq(t, gjson.GetBytes(before, "tools").Raw, gjson.GetBytes(after, "tools").Raw,
"top-level tools must not change when a deferred tool is revealed (prompt cache prefix)")
tools := gjson.GetBytes(after, "tools").Array()
require.Len(t, tools, 2)
require.Equal(t, "function", tools[0].Get("type").String())
require.Equal(t, "Bash", tools[0].Get("name").String())
search := tools[1]
require.Equal(t, "tool_search", search.Get("type").String())
require.Equal(t, "client", search.Get("execution").String())
require.Equal(t, "search deferred tools", search.Get("description").String())
require.JSONEq(t, toolSearchTestSchema, search.Get("parameters").Raw)
require.False(t, search.Get("name").Exists(), "tool_search carries no function name")
require.False(t, search.Get("strict").Exists(), "tool_search is declared without strict")
}
func TestApplyNativeToolSearch_HistoryMapsToNativeItems(t *testing.T) {
body := nativeToolSearchJSON(t, toolSearchTestRequest(t, toolSearchAfterReveal))
input := gjson.GetBytes(body, "input").Array()
require.Len(t, input, 3)
call := input[1]
require.Equal(t, "tool_search_call", call.Get("type").String())
require.Equal(t, "toolu_search", call.Get("call_id").String())
require.Equal(t, "client", call.Get("execution").String())
require.Equal(t, "completed", call.Get("status").String())
require.True(t, call.Get("arguments").IsObject(), "tool_search_call arguments are a JSON object")
require.Equal(t, "select:WebFetch", call.Get("arguments.query").String())
output := input[2]
require.Equal(t, "tool_search_output", output.Get("type").String())
require.Equal(t, "toolu_search", output.Get("call_id").String())
require.Equal(t, "client", output.Get("execution").String())
require.Equal(t, "completed", output.Get("status").String())
revealed := output.Get("tools").Array()
require.Len(t, revealed, 1, "duplicate and unknown references are dropped")
require.Equal(t, "function", revealed[0].Get("type").String())
require.Equal(t, "WebFetch", revealed[0].Get("name").String())
require.Equal(t, "fetch a url", revealed[0].Get("description").String())
require.True(t, revealed[0].Get("defer_loading").Bool())
require.False(t, revealed[0].Get("strict").Bool())
require.True(t, revealed[0].Get("strict").Exists())
require.Equal(t, "url", revealed[0].Get("parameters.required.0").String())
}
func TestApplyNativeToolSearch_NoToolSearchDeclaredKeepsFunctionTools(t *testing.T) {
req := toolSearchTestRequest(t, toolSearchAfterReveal)
tools := req.Tools[:0:0]
for _, tool := range req.Tools {
if tool.Name != "ToolSearch" {
tools = append(tools, tool)
}
}
req.Tools = tools
body := nativeToolSearchJSON(t, req)
var names []string
for _, tool := range gjson.GetBytes(body, "tools").Array() {
require.Equal(t, "function", tool.Get("type").String())
names = append(names, tool.Get("name").String())
}
require.Equal(t, []string{"Bash", "WebFetch"}, names)
require.NotContains(t, string(body), "tool_search_call")
}
func TestApplyNativeToolSearch_ForcedHiddenToolLeavesRequestUntouched(t *testing.T) {
for _, name := range []string{"ToolSearch", "WebFetch"} {
for _, raw := range []string{toolSearchBeforeReveal, toolSearchAfterReveal} {
req := toolSearchTestRequest(t, raw)
if name == "WebFetch" {
req.Tools = append(req.Tools, AnthropicTool{Name: "WebFetch", InputSchema: json.RawMessage(`{"type":"object"}`), DeferLoading: true})
}
req.ToolChoice = json.RawMessage(`{"type":"tool","name":"` + name + `"}`)
want, err := AnthropicToResponses(req)
require.NoError(t, err)
wantBody, err := json.Marshal(want)
require.NoError(t, err)
require.Equal(t, string(wantBody), string(nativeToolSearchJSON(t, req)), name)
require.NotContains(t, string(wantBody), "tool_search", name)
}
}
}
func TestApplyNativeToolSearch_OtherToolChoicesKeepNativeMapping(t *testing.T) {
for _, choice := range []string{
`{"type":"tool","name":"Bash"}`,
`{"type":"auto"}`,
`{"type":"any"}`,
} {
req := toolSearchTestRequest(t, toolSearchAfterReveal)
req.ToolChoice = json.RawMessage(choice)
body := nativeToolSearchJSON(t, req)
require.Equal(t, "tool_search", gjson.GetBytes(body, "tools.1.type").String(), choice)
require.Contains(t, string(body), "tool_search_output", choice)
}
}
func toolSearchResultRequest(t *testing.T, result string, trailing string) *AnthropicRequest {
t.Helper()
return toolSearchTestRequest(t, `{"model":"gpt-6-astra","max_tokens":64,
"tools":[
{"name":"ToolSearch","description":"search deferred tools","input_schema":`+toolSearchTestSchema+`},
{"name":"WebFetch","description":"fetch a url","input_schema":{"type":"object"},"defer_loading":true}],
"messages":[
{"role":"user","content":"fetch the page"},
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_search","name":"ToolSearch","input":{"query":"x","max_results":5}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_search",`+result+`}`+trailing+`]}]}`)
}
func TestApplyNativeToolSearch_ResultTextRidesInFollowingUserMessage(t *testing.T) {
cases := []struct {
name, result, trailing, wantText, wantUser string
wantTools int
}{
{"error", `"is_error":true,"content":"<tool_use_error>InputValidationError</tool_use_error>"`, "", "<tool_use_error>InputValidationError</tool_use_error>", "", 0},
{"no match string", `"content":"No matching deferred tools found"`, "", "No matching deferred tools found", "", 0},
{"text with reference", `"content":[{"type":"text","text":"found one"},{"type":"tool_reference","tool_name":"WebFetch"}]`, "", "found one", "", 1},
{"separate part ahead of following text", `"content":"No matching deferred tools found"`, `,{"type":"text","text":"retry"}`, "No matching deferred tools found", "retry", 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
body := nativeToolSearchJSON(t, toolSearchResultRequest(t, tc.result, tc.trailing))
input := gjson.GetBytes(body, "input").Array()
require.Len(t, input, 4)
require.Equal(t, "tool_search_call", input[1].Get("type").String())
require.Equal(t, "tool_search_output", input[2].Get("type").String())
require.Len(t, input[2].Get("tools").Array(), tc.wantTools)
require.Equal(t, "message", input[3].Get("type").String())
require.Equal(t, "user", input[3].Get("role").String())
parts := input[3].Get("content").Array()
require.Equal(t, tc.wantText, parts[0].Get("text").String())
if tc.wantUser == "" {
require.Len(t, parts, 1)
return
}
require.Len(t, parts, 2)
require.Equal(t, `{"type":"input_text","text":"`+tc.wantUser+`"}`, parts[1].Raw)
})
}
t.Run("reference only adds no message", func(t *testing.T) {
body := nativeToolSearchJSON(t, toolSearchResultRequest(t, `"content":[{"type":"tool_reference","tool_name":"WebFetch"}]`, ""))
require.Len(t, gjson.GetBytes(body, "input").Array(), 3)
})
}
func TestResponsesToAnthropic_RestoresToolSearchCall(t *testing.T) {
var resp ResponsesResponse
require.NoError(t, json.Unmarshal([]byte(`{"id":"resp_1","status":"completed","output":[
{"type":"tool_search_call","call_id":"call_search","execution":"client","status":"completed","arguments":{"query":"select:WebFetch","max_results":5}}]}`), &resp))
out := ResponsesToAnthropic(&resp, "gpt-6-astra")
require.Len(t, out.Content, 1)
block := out.Content[0]
require.Equal(t, "tool_use", block.Type)
require.Equal(t, "call_search", block.ID)
require.Equal(t, "ToolSearch", block.Name)
require.JSONEq(t, `{"query":"select:WebFetch","max_results":5}`, string(block.Input))
require.Equal(t, "tool_use", AnthropicStopReasonString(out.StopReason))
}
func TestResponsesEventToAnthropic_RestoresToolSearchCall(t *testing.T) {
state := NewResponsesEventToAnthropicState()
var events []AnthropicStreamEvent
for _, raw := range []string{
`{"type":"response.created","response":{"id":"resp_1","model":"gpt-6-astra"}}`,
`{"type":"response.output_item.added","output_index":0,"item":{"type":"tool_search_call","call_id":"call_search","execution":"client"}}`,
`{"type":"response.output_item.done","output_index":0,"item":{"type":"tool_search_call","call_id":"call_search","execution":"client","status":"completed","arguments":{"query":"docs","max_results":5}}}`,
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`,
} {
var evt ResponsesStreamEvent
require.NoError(t, json.Unmarshal([]byte(raw), &evt))
events = append(events, ResponsesEventToAnthropicEvents(&evt, state)...)
}
var start, delta, stop *AnthropicStreamEvent
for i := range events {
switch events[i].Type {
case "content_block_start":
start = &events[i]
case "content_block_delta":
delta = &events[i]
case "content_block_stop":
stop = &events[i]
}
}
require.NotNil(t, start)
require.Equal(t, "tool_use", start.ContentBlock.Type)
require.Equal(t, "call_search", start.ContentBlock.ID)
require.Equal(t, "ToolSearch", start.ContentBlock.Name)
require.NotNil(t, delta)
require.Equal(t, "input_json_delta", delta.Delta.Type)
require.JSONEq(t, `{"query":"docs","max_results":5}`, delta.Delta.PartialJSON)
require.NotNil(t, stop)
require.Equal(t, *start.Index, *stop.Index)
last := events[len(events)-2]
require.Equal(t, "message_delta", last.Type)
require.Equal(t, "tool_use", last.Delta.StopReason)
}
@@ -61,6 +61,7 @@ func ResponsesToChatCompletionsRequestWithOptions(req *ResponsesRequest, opts *R
Stream: req.Stream,
ServiceTier: req.ServiceTier,
ParallelToolCalls: req.ParallelToolCalls,
Stop: req.Stop,
}
if req.Reasoning != nil {
out.ReasoningEffort = req.Reasoning.Effort
@@ -53,9 +53,24 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo
Type: "tool_use",
ID: fromResponsesCallID(item.CallID),
Name: item.Name,
Input: sanitizeAnthropicToolUseInput(item.Name, item.Arguments),
Input: anthropicToolUseInput(item.Type, item.Name, item.Arguments),
})
case "custom_tool_call":
if !resp.RenderCustomToolCalls || (resp.XAIServerSideSearch && IsServerSideSearchCall(item.Type, item.CallID)) {
continue
}
blocks = append(blocks, AnthropicContentBlock{
Type: "tool_use",
ID: fromResponsesCallID(item.CallID),
Name: item.Name,
Input: anthropicToolUseInput(item.Type, item.Name, item.Input),
})
case "tool_search_call":
blocks = append(blocks, toolSearchCallToolUse(item))
case "web_search_call":
if item.Status != "completed" {
continue
}
toolUseID := "srvtoolu_" + item.ID
query := ""
if item.Action != nil {
@@ -68,11 +83,10 @@ func ResponsesToAnthropic(resp *ResponsesResponse, model string) *AnthropicRespo
Name: "web_search",
Input: inputJSON,
})
emptyResults, _ := json.Marshal([]struct{}{})
blocks = append(blocks, AnthropicContentBlock{
Type: "web_search_tool_result",
ToolUseID: toolUseID,
Content: emptyResults,
Content: webSearchCallResults(&item),
})
}
}
@@ -142,6 +156,26 @@ func containsAnthropicToolUseBlock(blocks []AnthropicContentBlock) bool {
return false
}
// anthropicToolUseInput returns the input of a non-streaming tool_use block,
// which must be a JSON object. An object is kept as it is. A function_call whose
// arguments are not an object (truncated by max_output_tokens, or empty) gets {};
// a custom_tool_call's free-form input is wrapped in the same {"input": ...}
// shape that downgrades a custom tool to a function tool, so that
// extractCustomToolCallInput gives the text back; an empty custom input is {} as
// it is in the streamed tool_use.
func anthropicToolUseInput(itemType, name, raw string) json.RawMessage {
if trimmed := strings.TrimSpace(raw); strings.HasPrefix(trimmed, "{") && json.Valid([]byte(trimmed)) {
return sanitizeAnthropicToolUseInput(name, raw)
}
if itemType == "custom_tool_call" && raw != "" {
wrapped, err := json.Marshal(map[string]string{"input": raw})
if err == nil {
return wrapped
}
}
return json.RawMessage("{}")
}
func sanitizeAnthropicToolUseInput(name string, raw string) json.RawMessage {
if name != "Read" || raw == "" {
return json.RawMessage(raw)
@@ -638,6 +672,10 @@ func resToAnthHandleOutputItemDone(evt *ResponsesStreamEvent, state *ResponsesEv
if evt.Item.Type == "web_search_call" && evt.Item.Status == "completed" {
return resToAnthHandleWebSearchDone(evt, state)
}
// The native tool_search_call carries its arguments only on done.
if evt.Item.Type == "tool_search_call" {
return resToAnthHandleToolSearchDone(evt, state)
}
// Capture encrypted_content on reasoning item done (often only present here).
if evt.Item.Type == "reasoning" {
@@ -685,9 +723,6 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve
state.ContentBlockIndex++
// Emit web_search_tool_result block (start + stop).
// Content is empty because OpenAI does not expose individual search results;
// the model consumes them internally and produces text output.
emptyResults, _ := json.Marshal([]struct{}{})
idx2 := state.ContentBlockIndex
events = append(events, AnthropicStreamEvent{
Type: "content_block_start",
@@ -695,7 +730,7 @@ func resToAnthHandleWebSearchDone(evt *ResponsesStreamEvent, state *ResponsesEve
ContentBlock: &AnthropicContentBlock{
Type: "web_search_tool_result",
ToolUseID: toolUseID,
Content: emptyResults,
Content: webSearchCallResults(evt.Item),
},
})
events = append(events, AnthropicStreamEvent{
@@ -0,0 +1,80 @@
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestAnthropicToolUseInput(t *testing.T) {
tests := []struct {
name string
itemType string
raw string
want string
}{
{"object kept", "function_call", "{\"a\":1}", "{\"a\":1}"},
{"object with padding kept", "function_call", " {\"a\": 1}\n", " {\"a\": 1}\n"},
{"truncated function arguments", "function_call", "{\"a\":1", "{}"},
{"empty function arguments", "function_call", "", "{}"},
{"non-object function arguments", "function_call", "[1]", "{}"},
{"custom input wrapped", "custom_tool_call", "dir /b", "{\"input\":\"dir /b\"}"},
{"empty custom input is an empty object", "custom_tool_call", "", "{}"},
{"custom input that is an object kept", "custom_tool_call", "{\"a\":1}", "{\"a\":1}"},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := anthropicToolUseInput(tc.itemType, "exec", tc.raw)
require.Equal(t, tc.want, string(got))
require.True(t, json.Valid(got))
})
}
}
// The wrapper must round-trip through the helper that undoes the custom tool
// downgrade, including text that is itself valid JSON or has outer whitespace.
func TestAnthropicToolUseInputCustomRoundTrip(t *testing.T) {
for _, text := range []string{"dir", " padded text\n", "", "\"quoted\"", "[1,2]", "line1\nline2"} {
wrapped := anthropicToolUseInput("custom_tool_call", "exec", text)
require.Equal(t, text, extractCustomToolCallInput(string(wrapped)), text)
}
}
func TestResponsesToAnthropicInvalidToolInputStillMarshals(t *testing.T) {
resp := &ResponsesResponse{ID: "resp_1", Status: "incomplete", IncompleteDetails: &ResponsesIncompleteDetails{Reason: "max_output_tokens"}, Output: []ResponsesOutput{
{Type: "reasoning", Summary: []ResponsesSummary{{Type: "summary_text", Text: "plan"}}},
{Type: "function_call", CallID: "call_1", Name: "get", Arguments: "{\"a\":1"},
{Type: "custom_tool_call", CallID: "call_2", Name: "exec", Input: "dir"},
}, RenderCustomToolCalls: true}
out := ResponsesToAnthropic(resp, "m")
body, err := json.Marshal(out)
require.NoError(t, err)
require.Len(t, out.Content, 3)
require.Equal(t, "thinking", out.Content[0].Type)
require.Equal(t, "{}", string(out.Content[1].Input))
require.Equal(t, "{\"input\":\"dir\"}", string(out.Content[2].Input))
require.Equal(t, "max_tokens", *out.StopReason, string(body))
}
func TestResponsesToChatCompletionsRendersCustomToolCall(t *testing.T) {
resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{
{Type: "custom_tool_call", CallID: "call_1", Name: "exec", Input: "dir"},
}, RenderCustomToolCalls: true}
out := ResponsesToChatCompletions(resp, "m")
require.Len(t, out.Choices[0].Message.ToolCalls, 1)
require.Equal(t, "dir", out.Choices[0].Message.ToolCalls[0].Function.Arguments)
require.Equal(t, "tool_calls", out.Choices[0].FinishReason)
}
// An output the upstream delivered keeps custom_tool_call items unrendered.
func TestResponsesToAnthropicAndChatSkipDeliveredCustomToolCall(t *testing.T) {
resp := &ResponsesResponse{ID: "resp_1", Status: "completed", Output: []ResponsesOutput{
{Type: "custom_tool_call", CallID: "xs_123", Name: "x_keyword_search", Input: "{}"},
}}
require.Len(t, ResponsesToAnthropic(resp, "m").Content, 1)
require.Equal(t, "text", ResponsesToAnthropic(resp, "m").Content[0].Type)
chat := ResponsesToChatCompletions(resp, "m")
require.Empty(t, chat.Choices[0].Message.ToolCalls)
require.Equal(t, "stop", chat.Choices[0].FinishReason)
}
@@ -56,6 +56,18 @@ func ResponsesToChatCompletions(resp *ResponsesResponse, model string) *ChatComp
Arguments: item.Arguments,
},
})
case "custom_tool_call":
if !resp.RenderCustomToolCalls || (resp.XAIServerSideSearch && IsServerSideSearchCall(item.Type, item.CallID)) {
continue
}
toolCalls = append(toolCalls, ChatToolCall{
ID: item.CallID,
Type: "function",
Function: ChatFunctionCall{
Name: item.Name,
Arguments: item.Input,
},
})
case "reasoning":
reasoningText += responsesReasoningText(item)
case "web_search_call":
@@ -522,6 +534,9 @@ type bufferedFuncCall struct {
// so that non-streaming handlers can reconstruct output when the terminal event
// (response.completed / response.done) carries an empty output array.
type BufferedResponseAccumulator struct {
// tool_search_call items arrive complete on output_item.done.
toolSearchCalls []ResponsesOutput
text strings.Builder
refusal strings.Builder
reasoning strings.Builder
@@ -585,6 +600,10 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent)
_, _ = a.funcCalls[idx].Args.WriteString(completed)
}
}
case "response.output_item.done":
if event.Item != nil && event.Item.Type == "tool_search_call" {
a.toolSearchCalls = append(a.toolSearchCalls, *event.Item)
}
case "response.reasoning_summary_text.delta", "response.reasoning_text.delta":
if event.Delta != "" {
_, _ = a.reasoning.WriteString(event.Delta)
@@ -594,7 +613,7 @@ func (a *BufferedResponseAccumulator) ProcessEvent(event *ResponsesStreamEvent)
// HasContent reports whether any content has been accumulated.
func (a *BufferedResponseAccumulator) HasContent() bool {
return a.text.Len() > 0 || a.refusal.Len() > 0 || len(a.funcCalls) > 0 || a.reasoning.Len() > 0
return a.text.Len() > 0 || a.refusal.Len() > 0 || len(a.funcCalls) > 0 || len(a.toolSearchCalls) > 0 || a.reasoning.Len() > 0
}
// BuildOutput constructs a []ResponsesOutput from the accumulated delta
@@ -648,6 +667,7 @@ func (a *BufferedResponseAccumulator) BuildOutput() []ResponsesOutput {
Arguments: a.funcCalls[i].Args.String(),
})
}
out = append(out, a.toolSearchCalls...)
return out
}
@@ -0,0 +1,60 @@
package apicompat
import (
"encoding/json"
"slices"
)
const webSearchSourcesInclude = "web_search_call.action.sources"
// IncludeWebSearchSources asks a hosted web_search to report the pages it
// used; without it a web_search_call carries only its query.
func IncludeWebSearchSources(req *ResponsesRequest) {
for _, tool := range req.Tools {
if tool.Type == "web_search" {
if !slices.Contains(req.Include, webSearchSourcesInclude) {
req.Include = append(req.Include, webSearchSourcesInclude)
}
return
}
}
}
type webSearchResult struct {
Type string `json:"type"`
URL string `json:"url"`
Title string `json:"title"`
}
// webSearchCallResults is the web_search_tool_result content for one call: a
// search's action.sources, or the single page an open_page opened. Callers
// pass completed calls only. Sources and the page URL are decoded leniently, so
// a malformed value cannot fail the terminal event that carries the call.
func webSearchCallResults(item *ResponsesOutput) json.RawMessage {
results := []webSearchResult{}
if action := item.Action; action != nil {
var sources []json.RawMessage
if json.Unmarshal(action.Sources, &sources) == nil && sources != nil {
for _, raw := range sources {
var source map[string]any
_ = json.Unmarshal(raw, &source)
if rawURL, ok := source["url"].(string); ok && rawURL != "" {
results = append(results, newWebSearchResult(rawURL))
}
}
} else if action.Type == "open_page" {
var pageURL string
if json.Unmarshal(action.URL, &pageURL) == nil && pageURL != "" {
results = append(results, newWebSearchResult(pageURL))
}
}
}
out, _ := json.Marshal(results)
return out
}
// newWebSearchResult uses the URL as the title because Responses sources carry
// no title and the Anthropic block requires one.
func newWebSearchResult(rawURL string) webSearchResult {
return webSearchResult{Type: "web_search_result", URL: rawURL, Title: rawURL}
}
@@ -0,0 +1,130 @@
//go:build unit
package apicompat
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
const (
webSearchCallWithTwoSources = `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q1","sources":[` +
`{"type":"url","url":"https://a.example/1"},{"type":"url","url":"https://a.example/2"}]}}`
webSearchCallWithOneSource = `{"type":"web_search_call","id":"ws_2","status":"completed","action":{"type":"search","query":"q2","sources":[` +
`{"type":"url","url":"https://b.example/1"}]}}`
webSearchSourcesWantWS1 = `[{"type":"web_search_result","url":"https://a.example/1","title":"https://a.example/1"},` +
`{"type":"web_search_result","url":"https://a.example/2","title":"https://a.example/2"}]`
webSearchSourcesWantWS2 = `[{"type":"web_search_result","url":"https://b.example/1","title":"https://b.example/1"}]`
)
func decodeWebSearchItem(t *testing.T, raw string) ResponsesOutput {
t.Helper()
var item ResponsesOutput
require.NoError(t, json.Unmarshal([]byte(raw), &item))
return item
}
// webSearchResultContents returns each web_search_tool_result content keyed by
// the server_tool_use id it answers.
func webSearchResultContents(blocks []AnthropicContentBlock) map[string]string {
out := map[string]string{}
for _, block := range blocks {
if block.Type == "web_search_tool_result" {
out[block.ToolUseID] = string(block.Content)
}
}
return out
}
func nonStreamingWebSearchResults(t *testing.T, items ...string) map[string]string {
t.Helper()
resp := &ResponsesResponse{ID: "resp_ws", Status: "completed"}
for _, raw := range items {
resp.Output = append(resp.Output, decodeWebSearchItem(t, raw))
}
return webSearchResultContents(ResponsesToAnthropic(resp, "gpt-5.5").Content)
}
func streamingWebSearchResults(t *testing.T, items ...string) map[string]string {
t.Helper()
state := NewResponsesEventToAnthropicState()
events := ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.created",
Response: &ResponsesResponse{ID: "resp_ws", Model: "gpt-5.5"},
}, state)
for i, raw := range items {
item := decodeWebSearchItem(t, raw)
events = append(events, ResponsesEventToAnthropicEvents(&ResponsesStreamEvent{
Type: "response.output_item.done",
OutputIndex: i,
Item: &item,
}, state)...)
}
var blocks []AnthropicContentBlock
for _, evt := range events {
if evt.Type == "content_block_start" && evt.ContentBlock != nil {
blocks = append(blocks, *evt.ContentBlock)
}
}
return webSearchResultContents(blocks)
}
func TestResponsesEventToAnthropic_WebSearchSources(t *testing.T) {
got := streamingWebSearchResults(t, webSearchCallWithTwoSources, webSearchCallWithOneSource)
require.Len(t, got, 2)
require.JSONEq(t, webSearchSourcesWantWS1, got["srvtoolu_ws_1"])
require.JSONEq(t, webSearchSourcesWantWS2, got["srvtoolu_ws_2"])
}
func TestResponsesToAnthropic_WebSearchSources(t *testing.T) {
got := nonStreamingWebSearchResults(t, webSearchCallWithTwoSources, webSearchCallWithOneSource)
require.Len(t, got, 2)
require.JSONEq(t, webSearchSourcesWantWS1, got["srvtoolu_ws_1"])
require.JSONEq(t, webSearchSourcesWantWS2, got["srvtoolu_ws_2"])
}
func TestWebSearchSourcesEntryRules(t *testing.T) {
got := nonStreamingWebSearchResults(t, `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"q",`+
`"sources":[{"url":"https://a"},{"url":""},{"url":1},"https://b",{"title":"x"}]}}`)
require.JSONEq(t, `[{"type":"web_search_result","url":"https://a","title":"https://a"}]`, got["srvtoolu_ws_1"])
}
func TestWebSearchOpenPageReturnsSinglePage(t *testing.T) {
got := nonStreamingWebSearchResults(t, `{"type":"web_search_call","id":"ws_1","status":"completed",`+
`"action":{"type":"open_page","url":"https://docs.example/page?id=1#top"}}`)
require.JSONEq(t, `[{"type":"web_search_result","url":"https://docs.example/page?id=1#top","title":"https://docs.example/page?id=1#top"}]`,
got["srvtoolu_ws_1"])
}
func TestWebSearchOpenPageRequiresCompletedURL(t *testing.T) {
for name, item := range map[string]string{
"empty url": `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":""}}`,
} {
t.Run(name, func(t *testing.T) {
require.JSONEq(t, `[]`, nonStreamingWebSearchResults(t, item)["srvtoolu_ws_1"])
})
}
}
func TestWebSearchNonStringActionURLKeepsEvent(t *testing.T) {
for name, url := range map[string]string{"number": `123`, "object": `{"a":1}`, "array": `["a"]`} {
t.Run(name, func(t *testing.T) {
raw := `{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"open_page","url":` + url + `}}`
got := nonStreamingWebSearchResults(t, raw)
require.JSONEq(t, `[]`, got["srvtoolu_ws_1"])
require.JSONEq(t, `[]`, streamingWebSearchResults(t, raw)["srvtoolu_ws_1"])
})
}
}
func TestWebSearchCallsThatDidNotCompleteProduceNoBlocks(t *testing.T) {
for _, status := range []string{"failed", "in_progress"} {
t.Run(status, func(t *testing.T) {
raw := `{"type":"web_search_call","id":"ws_1","status":"` + status + `","action":{"type":"search","query":"q","sources":[{"url":"https://a.example/1"}]}}`
require.Empty(t, nonStreamingWebSearchResults(t, raw))
require.Empty(t, streamingWebSearchResults(t, raw))
})
}
}
+29
View File
@@ -80,6 +80,9 @@ type AnthropicContentBlock struct {
ToolUseID string `json:"tool_use_id,omitempty"`
Content json.RawMessage `json:"content,omitempty"` // string or []AnthropicContentBlock
IsError bool `json:"is_error,omitempty"`
// type=tool_reference (inside a ToolSearch tool_result)
ToolName string `json:"tool_name,omitempty"`
}
func (b AnthropicContentBlock) MarshalJSON() ([]byte, error) {
@@ -122,6 +125,8 @@ type AnthropicTool struct {
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"input_schema,omitempty"` // JSON Schema object
CacheControl *AnthropicCacheControl `json:"cache_control,omitempty"`
// DeferLoading marks a tool Claude Code reveals through ToolSearch.
DeferLoading bool `json:"defer_loading,omitempty"`
}
// AnthropicCacheControl 对应 Anthropic API 的 cache_control 字段。
@@ -342,6 +347,10 @@ type ResponsesRequest struct {
ServiceTier string `json:"service_tier,omitempty"`
PromptCacheKey string `json:"prompt_cache_key,omitempty"`
PreviousResponseID string `json:"previous_response_id,omitempty"`
// Stop 在 Chat Completions 里是原生字段,Responses 协议本身没有。这里保留原样
// (string 或 []string),仅在降级到 Chat Completions 时透传,避免客户端设的
// 停止序列在转换层被静默丢弃。
Stop json.RawMessage `json:"stop,omitempty"`
}
// ResponsesReasoning configures reasoning effort in the Responses API.
@@ -427,6 +436,8 @@ type ResponsesTool struct {
Description string `json:"description,omitempty"`
Parameters json.RawMessage `json:"parameters,omitempty"`
Strict *bool `json:"strict,omitempty"`
// type=tool_search: "client" means the caller executes the search.
Execution string `json:"execution,omitempty"`
// type=namespace 的子工具列表(tools 与 children 二选一,语义相同)。
Tools []ResponsesTool `json:"tools,omitempty"`
@@ -477,6 +488,16 @@ type ResponsesResponse struct {
// Error is present when status="failed"
Error *ResponsesError `json:"error,omitempty"`
// RenderCustomToolCalls is set on an output rebuilt from stream events, where
// the accumulator has always handed custom_tool_call items to the converters
// as tool calls. An output the upstream delivered keeps them unrendered.
RenderCustomToolCalls bool `json:"-"`
// XAIServerSideSearch is set with RenderCustomToolCalls when the upstream is
// xAI. A custom_tool_call that IsServerSideSearchCall then stays in the
// output but is not rendered as a tool call, because xAI runs it itself.
XAIServerSideSearch bool `json:"-"`
}
// ResponsesError describes an error in a failed response.
@@ -585,6 +606,10 @@ func (o *ResponsesOutput) UnmarshalJSON(data []byte) error {
type WebSearchAction struct {
Type string `json:"type,omitempty"` // "search"
Query string `json:"query,omitempty"` // primary search query
// URL and Sources stay raw: a strictly typed value of an unexpected shape
// would fail decoding the whole terminal event that carries this call.
URL json.RawMessage `json:"url,omitempty"` // open_page / find_in_page target
Sources json.RawMessage `json:"sources,omitempty"`
}
// ResponsesSummary is a summary text block inside a reasoning output.
@@ -603,6 +628,10 @@ type ResponsesUsage struct {
// Optional detailed breakdown
InputTokensDetails *ResponsesInputTokensDetails `json:"input_tokens_details,omitempty"`
OutputTokensDetails *ResponsesOutputTokensDetails `json:"output_tokens_details,omitempty"`
// ServerSideToolUsageDetails is xAI's per-class success count object,
// kept raw so Grok search counting can read it from a decoded response.
ServerSideToolUsageDetails json.RawMessage `json:"server_side_tool_usage_details,omitempty"`
}
func (u *ResponsesUsage) UnmarshalJSON(data []byte) error {
+21
View File
@@ -0,0 +1,21 @@
package claude
import "strings"
var temperatureRejectingFamilies = []string{
"claude-opus-4-7",
"claude-opus-4-8",
}
func RejectsTemperature(model string) bool {
if IsOpus55(model) || IsFable52(model) || IsMythos52(model) {
return true
}
id := normalizeEffortModelID(model)
for _, family := range temperatureRejectingFamilies {
if id == family || strings.HasPrefix(id, family+"-") {
return true
}
}
return false
}
@@ -0,0 +1,40 @@
package claude
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestRejectsTemperature(t *testing.T) {
t.Parallel()
tests := []struct {
model string
want bool
}{
{model: "claude-opus-4-8", want: true},
{model: "claude-opus-4-8-20260529", want: true},
{model: "claude-opus-4-7", want: true},
{model: "anthropic/claude-opus-4-8", want: true},
{model: "us.anthropic.claude-opus-4-8-v1", want: true},
{model: "claude-opus-5-5", want: true},
{model: "anthropic/claude-opus-5.5", want: true},
{model: "claude-fable-5-2", want: true},
{model: "claude-mythos-5-2", want: true},
{model: "claude-opus-4-6", want: false},
{model: "claude-opus-4-5-20251101", want: false},
{model: "claude-sonnet-4-6", want: false},
{model: "claude-sonnet-5-5", want: false},
{model: "claude-haiku-5-5", want: false},
{model: "claude-haiku-4-5-20251001", want: false},
{model: "gpt-5.6", want: false},
{model: "", want: false},
}
for _, tt := range tests {
t.Run(tt.model, func(t *testing.T) {
t.Parallel()
require.Equal(t, tt.want, RejectsTemperature(tt.model))
})
}
}
@@ -3,6 +3,7 @@ package httputil
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
@@ -102,6 +103,24 @@ func DescribeRequestBodyReadFailure(req *http.Request, err error) RequestBodyRea
return failure
}
// ClientMessage returns the message shown to the client. A size-limit failure
// names the limit so callers can tell which limit they hit.
func (f RequestBodyReadFailure) ClientMessage() string {
if f.Kind == RequestBodyReadErrorMaxBytes {
return BodyTooLargeMessage(f.MaxBytesLimit)
}
return f.Message
}
// BodyTooLargeMessage formats the 413 message for a request body limit.
func BodyTooLargeMessage(limit int64) string {
const mb = 1024 * 1024
if limit >= mb {
return fmt.Sprintf("Request body too large, limit is %dMB", limit/mb)
}
return fmt.Sprintf("Request body too large, limit is %dB", limit)
}
// LogFields returns diagnostics that never include request content or error
// text, which may embed peer addresses or decoder input.
func (f RequestBodyReadFailure) LogFields() []zap.Field {
@@ -0,0 +1,472 @@
package requestmodel
import (
"bytes"
"hash/maphash"
"io"
"mime"
"mime/multipart"
"strconv"
"strings"
"unicode"
"unicode/utf16"
"unicode/utf8"
)
// utf8BOM 是部分客户端写在 JSON 文档前的 UTF-8 字节序标记。网关 handler 的宽容
// 读取(httputil.ReadLenientJSONRequestBodyWithPrealloc)会先剥掉它再解析,
// 准入与歧义检查必须看同一份字节。
var utf8BOM = []byte{0xEF, 0xBB, 0xBF}
// TrimUTF8BOM 去掉请求体开头的 UTF-8 BOM(与宽容读取的规则一致),否则原样返回。
func TrimUTF8BOM(body []byte) []byte {
return bytes.TrimPrefix(body, utf8BOM)
}
// LooksLikeJSON 判断(已去 BOM 的)请求体首个非空白字节是否为 JSON 对象或数组。
//
// 是否按 JSON 检查只看内容、不看 Content-Type:JSON handler 从不校验请求头,
// 把 JSON 请求体标成 multipart/form-data 不能绕过检查。
func LooksLikeJSON(body []byte) bool {
for _, c := range body {
// 与 gjson 一致:首个值之前所有 <= 0x20 的字节都当空白跳过。
if c <= ' ' {
continue
}
return c == '{' || c == '['
}
return false
}
// ConflictingField 返回请求体中第一个重复声明的字段路径。
//
// 网关读取 model、service_tier、reasoning.effort 等字段用的是 gjson(重复键取
// 第一个、大小写敏感),sjson 改写(模型映射、推理强度降级、fast policy 删除
// service_tier)也只改第一个;而改写并转发请求体的路径会经过 encoding/json
// (解码到 map 时重复键取最后一个,绑定到结构体时键名大小写不敏感、取最后一个),
// 上游解析器也可能取最后一个。同名字段一旦重复,准入、计费、策略看到的值和上游
// 实际收到的值就可能分叉,例如 {"model":"便宜模型",...,"model":"贵模型"} 按便宜
// 模型计费、转发贵模型。取值相同的重复同样拒绝:网关自己的 sjson 改写只动第一个,
// 改写后两者就不再相同。调用方应在任何解析器读取字段之前拒绝这类请求。
//
// 判定范围:
// - JSON(按内容识别,见 LooksLikeJSON):任意深度的对象(含数组元素)内,
// 成员名经转义解码(无效 UTF-8 与孤立代理项按 encoding/json 替换为 U+FFFD)
// 后按 encoding/json 结构体绑定的大小写折叠规则相同。用户自定义键空间
// (JSON Schema 的 properties/$defs、工具调用参数、模板变量等,见
// isFreeformMember)内只比较精确名字,因为 id 与 ID 在那里是合法的不同键。
// 字段路径形如 reasoning.effort、messages[1].role。
// - multipart(按 Content-Type 声明):见 multipartConflictingField。
// - 声明为 multipart、请求体又以 JSON 开头且解析出了表单 part:两种解读并存,
// 报告 Content-Type。
//
// 扫描是一次线性遍历,键名以带随机种子的 64 位哈希判重,CPU 与内存都与请求体
// 大小成线性关系;嵌套超过 maxConflictDepth 的部分只计括号不检查(encoding/json
// 本身拒绝这种深度),其后的同层成员仍继续检查。扫描在首个顶层值结束时停止,
// 与 gjson 读取的范围一致(其后的内容 encoding/json 会拒绝)。
func ConflictingField(contentType string, body []byte) (string, bool) {
// 两种解读都要检查:JSON handler 不看请求头,按 JSON 读首个值;multipart
// handler 按 boundary 解析,并跳过首个 boundary 之前的前导内容(RFC 2046
// preamble),前导内容可以是任意 JSON。
looksJSON := LooksLikeJSON(TrimUTF8BOM(body))
if looksJSON {
if field, conflict := scanDuplicateMember(TrimUTF8BOM(body)); conflict {
return field, true
}
}
if !isMultipartContentType(contentType) {
return "", false
}
field, conflict, parts := multipartConflictingField(contentType, body)
if conflict {
return field, true
}
if looksJSON && parts > 0 {
// 同一请求体既是 JSON 又含 multipart 字段:合成路由、白名单、JSON 与
// multipart handler 会各取一种解读(例如前导 JSON 的 model 与表单的
// model),整体视为歧义。
return "Content-Type", true
}
return "", false
}
// maxConflictDepth 与 encoding/json 的嵌套上限一致。
const maxConflictDepth = 10000
// conflictLinearScanLimit 以内的对象线性比较哈希,超过后改用 map。
const conflictLinearScanLimit = 32
// conflictHashSeed 每个进程随机生成:客户端无法构造哈希碰撞。碰撞只会让请求被
// 误拒(fail closed),不会放过重复键。
var conflictHashSeed = maphash.MakeSeed()
type scanFrame struct {
object bool
fold bool // 是否按大小写折叠比较本对象的成员名
wantKey bool // object:下一个字符串是成员名
// 当前成员名在请求体中的原始范围(不含引号),用于路径与自由键判定。
keyStart, keyEnd int
keyEscaped bool
index int // array:当前元素下标
hashStart int // object:本对象成员哈希在 scanner.hashes 中的起点
seen map[uint64]struct{}
}
type duplicateScanner struct {
body []byte
stack []scanFrame
hashes []uint64
hash maphash.Hash
runes []byte
names []byte
}
func scanDuplicateMember(body []byte) (string, bool) {
s := duplicateScanner{body: body}
s.hash.SetSeed(conflictHashSeed)
overflow := 0 // 超过 maxConflictDepth 后未闭合的括号数
for i := 0; i < len(body); {
switch c := body[i]; c {
case '{', '[':
if overflow > 0 || len(s.stack) >= maxConflictDepth {
overflow++
} else {
s.push(c == '{')
}
i++
case '}', ']':
if overflow > 0 {
overflow--
} else if n := len(s.stack); n > 0 {
if top := s.stack[n-1]; top.object {
s.hashes = s.hashes[:top.hashStart]
}
s.stack = s.stack[:n-1]
if n == 1 {
return "", false
}
}
i++
case ',':
if n := len(s.stack); overflow == 0 && n > 0 {
if top := &s.stack[n-1]; top.object {
top.wantKey = true
} else {
top.index++
}
}
i++
case '"':
end, escaped := scanJSONString(body, i+1)
if n := len(s.stack); overflow == 0 && n > 0 && s.stack[n-1].object && s.stack[n-1].wantKey {
top := &s.stack[n-1]
top.wantKey = false
top.keyStart, top.keyEnd, top.keyEscaped = i+1, end, escaped
if s.repeated(top) {
return s.path(), true
}
}
i = end + 1
default:
i++
}
}
return "", false
}
func (s *duplicateScanner) push(object bool) {
fold := true
if n := len(s.stack); n > 0 {
parent := &s.stack[n-1]
fold = parent.fold
if fold && parent.object {
s.names = appendMemberName(s.names[:0], s.body[parent.keyStart:parent.keyEnd], parent.keyEscaped, false)
fold = !isFreeformMember(s.names, n > 1)
}
}
s.stack = append(s.stack, scanFrame{object: object, fold: fold, wantKey: object, hashStart: len(s.hashes)})
}
// repeated 登记 top 的当前成员名,返回它是否与本对象中更早的成员重名。
func (s *duplicateScanner) repeated(top *scanFrame) bool {
s.hash.Reset()
s.runes = appendMemberName(s.runes[:0], s.body[top.keyStart:top.keyEnd], top.keyEscaped, top.fold)
_, _ = s.hash.Write(s.runes)
sum := s.hash.Sum64()
if top.seen != nil {
if _, dup := top.seen[sum]; dup {
return true
}
top.seen[sum] = struct{}{}
return false
}
for _, seen := range s.hashes[top.hashStart:] {
if seen == sum {
return true
}
}
s.hashes = append(s.hashes, sum)
if len(s.hashes)-top.hashStart > conflictLinearScanLimit {
// 子对象的哈希总在其闭合时截掉,本对象的哈希在切片末尾连续。
top.seen = make(map[uint64]struct{}, 4*conflictLinearScanLimit)
for _, seen := range s.hashes[top.hashStart:] {
top.seen[seen] = struct{}{}
}
s.hashes = s.hashes[:top.hashStart]
}
return false
}
// path 把当前栈拼成 a.b[0].c;结果是新分配的字符串,不引用请求体。
func (s *duplicateScanner) path() string {
var out []byte
for _, frame := range s.stack {
if !frame.object {
out = append(out, '[')
out = strconv.AppendInt(out, int64(frame.index), 10)
out = append(out, ']')
continue
}
if len(out) > 0 {
out = append(out, '.')
}
out = appendMemberName(out, s.body[frame.keyStart:frame.keyEnd], frame.keyEscaped, false)
}
return string(out)
}
// freeformMembers 的值是用户自定义键空间:JSON Schema 的属性表与取值、工具调用
// 参数、提示词模板变量、MCP 请求头、标签。这些子树内的成员名只做精确比较(成员名
// 解码后不区分大小写地匹配本表)。它们都不在网关计费/策略读取、也不被结构体绑定
// 的字段路径上;input / response 只在非顶层时算(顶层 input 是 Responses 的输入
// 列表,顶层 response 是 realtime response.create 的参数)。metadata 不在表内:
// Antigravity 把 metadata.user_id 绑定到结构体(大小写不敏感),而网关的粘性会话
// 用 gjson 读它。
var freeformMembers = []string{
"properties", "patternProperties", "$defs", "definitions", "dependentSchemas",
"dependentRequired", "dependencies", "default", "const", "examples", "enum",
"args", "arguments", "variables", "headers", "labels",
}
func isFreeformMember(name []byte, nested bool) bool {
for _, candidate := range freeformMembers {
if bytes.EqualFold(name, []byte(candidate)) {
return true
}
}
return nested && (bytes.EqualFold(name, []byte("input")) || bytes.EqualFold(name, []byte("response")))
}
// scanJSONString 从字符串内容起点 i 找到闭合引号的下标(找不到返回 len(b)),
// 并报告内容中是否含转义。每个字节最多访问常数次:先找下一个引号,再看它前面
// 连续反斜杠的个数,奇数说明引号被转义,从引号之后继续找。
func scanJSONString(b []byte, i int) (int, bool) {
escaped := false
for i < len(b) {
quote := bytes.IndexByte(b[i:], '"')
if quote < 0 {
return len(b), escaped || bytes.IndexByte(b[i:], '\\') >= 0
}
end := i + quote
if !escaped && bytes.IndexByte(b[i:end], '\\') >= 0 {
escaped = true
}
backslashes := 0
for j := end - 1; j >= i && b[j] == '\\'; j-- {
backslashes++
}
if backslashes%2 == 0 {
return end, escaped
}
i = end + 1
}
return len(b), escaped
}
// appendMemberName 把原始成员名按 encoding/json 的规则解码(转义、无效 UTF-8 与
// 孤立代理项替换为 U+FFFD)后追加到 dst;fold 时逐字符做大小写折叠。
func appendMemberName(dst, raw []byte, escaped, fold bool) []byte {
for i := 0; i < len(raw); {
var r rune
if raw[i] == '\\' && escaped && i+1 < len(raw) {
r, i = decodeJSONEscape(raw, i)
} else if raw[i] < utf8.RuneSelf {
r = rune(raw[i])
i++
} else {
var size int
r, size = utf8.DecodeRune(raw[i:])
i += size
}
if fold {
r = foldRune(r)
}
dst = utf8.AppendRune(dst, r)
}
return dst
}
// decodeJSONEscape 解码 raw[i] 处的转义序列,返回字符与下一个下标。
func decodeJSONEscape(raw []byte, i int) (rune, int) {
switch raw[i+1] {
case 'b':
return '\b', i + 2
case 'f':
return '\f', i + 2
case 'n':
return '\n', i + 2
case 'r':
return '\r', i + 2
case 't':
return '\t', i + 2
case 'u':
r, ok := hex4(raw, i+2)
if !ok {
return rune(raw[i+1]), i + 2
}
if utf16.IsSurrogate(r) {
if i+11 < len(raw) && raw[i+6] == '\\' && raw[i+7] == 'u' {
if r2, ok := hex4(raw, i+8); ok {
if dec := utf16.DecodeRune(r, r2); dec != unicode.ReplacementChar {
return dec, i + 12
}
}
}
return unicode.ReplacementChar, i + 6
}
return r, i + 6
default:
return rune(raw[i+1]), i + 2
}
}
func hex4(raw []byte, i int) (rune, bool) {
if i+4 > len(raw) {
return 0, false
}
var r rune
for _, c := range raw[i : i+4] {
switch {
case '0' <= c && c <= '9':
c -= '0'
case 'a' <= c && c <= 'f':
c = c - 'a' + 10
case 'A' <= c && c <= 'F':
c = c - 'A' + 10
default:
return 0, false
}
r = r*16 + rune(c)
}
return r, true
}
// foldRune 返回 r 所在大小写折叠轨道上的固定代表,只有大小写不同的字符映射到
// 同一个值(与 encoding/json 结构体字段的大小写不敏感匹配一致,覆盖 ſ、开尔文
// 符号 K)。拉丁字母取小写。
func foldRune(r rune) rune {
if r < utf8.RuneSelf {
// ASCII 字母的轨道代表就是其小写(k、s 的非 ASCII 成员都更大)。
if 'A' <= r && r <= 'Z' {
return r + 'a' - 'A'
}
return r
}
folded := r
for next := unicode.SimpleFold(r); next != r; next = unicode.SimpleFold(next) {
if next < folded {
folded = next
}
}
if folded >= 'A' && folded <= 'Z' {
folded += 'a' - 'A'
}
return folded
}
// hasExtendedNameParam 报告 Content-Disposition 是否带 RFC 2231 扩展形式的字段名
// 参数(name*=、name*0=、name*0*=)。Go 以扩展值优先,忽略扩展参数的上游读的是
// name=,同一 part 会被读成两个不同的字段。filename* 是非 ASCII 文件名的合法写法,
// 不在此列。
func hasExtendedNameParam(disposition string) bool {
lower := strings.ToLower(disposition)
for i := 0; ; {
idx := strings.Index(lower[i:], "name*")
if idx < 0 {
return false
}
idx += i
start := idx
for start > 0 && (lower[start-1] == ' ' || lower[start-1] == '\t') {
start--
}
if start == 0 || lower[start-1] == ';' {
return true
}
i = idx + len("name*")
}
}
// isRepeatableMultipartField 报告表单字段是否按列表语义合法重复:以 [] 结尾的
// 数组字段(如 timestamp_granularities[])、多图输入(image、image[...]、
// Grok 媒体的 image_url)。其余文本字段(model、n、size、quality、duration 等
// 计费/策略标量)出现多次即为歧义。
func isRepeatableMultipartField(name string) bool {
return strings.HasSuffix(name, "[]") || name == "image" || name == "image_url" || strings.HasPrefix(name, "image[")
}
// multipartConflictingField 检查 multipart 表单:同名标量字段出现多次(文件与
// 文本 part 合并计数,列表字段见 isRepeatableMultipartField);名为 model /
// session 的文件 part(网关 handler 跳过文件 part,宽容的上游可能当字段读);
// 没有可解析名字、带多个 Content-Disposition 头或 RFC 2231 扩展字段名参数的 part
// (各解析器可能取不同的名字);session 字段的 JSON 值内部按 JSON 规则检查。
//
// parts 返回成功解析出的 part 数,供调用方判断请求体是否同时含 multipart 内容。
func multipartConflictingField(contentType string, body []byte) (field string, conflict bool, parts int) {
_, params, err := mime.ParseMediaType(strings.TrimSpace(contentType))
if err != nil {
return "", false, 0
}
boundary := strings.TrimSpace(params["boundary"])
if boundary == "" {
return "", false, 0
}
reader := multipart.NewReader(bytes.NewReader(body), boundary)
seen := make(map[string]struct{})
for {
part, err := reader.NextPart()
if err != nil {
return "", false, parts
}
parts++
name := strings.TrimSpace(part.FormName())
dispositions := part.Header.Values("Content-Disposition")
if name == "" || len(dispositions) > 1 || hasExtendedNameParam(dispositions[0]) {
return "Content-Disposition", true, parts
}
isFile := part.FileName() != ""
if isFile && (name == "model" || name == "session") {
return name, true, parts
}
if isRepeatableMultipartField(name) {
continue
}
if _, dup := seen[name]; dup {
return name, true, parts
}
seen[name] = struct{}{}
if isFile || name != "session" {
continue
}
data, err := io.ReadAll(part)
if err != nil {
continue
}
if doc := TrimUTF8BOM(data); LooksLikeJSON(doc) {
if field, conflict := scanDuplicateMember(doc); conflict {
return "session." + field, true, parts
}
}
}
}
@@ -0,0 +1,379 @@
package requestmodel
import (
"bytes"
"encoding/json"
"fmt"
"mime/multipart"
"runtime"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestConflictingFieldJSONReportsDuplicates(t *testing.T) {
tests := []struct {
name string
body string
want string
}{
{name: "重复 model 取值不同", body: `{"model":"claude-3-5-haiku-20241022","max_tokens":64,"model":"claude-opus-4-8"}`, want: "model"},
{name: "取值相同的重复 model", body: `{"model":"gpt-5.4","input":"hi","model":"gpt-5.4"}`, want: "model"},
{name: "三个 model", body: `{"model":"a","model":"a","model":"b"}`, want: "model"},
{name: "大小写变体", body: `{"model":"gpt-5.4-nano","MODEL":"gpt-5.4"}`, want: "MODEL"},
{name: "取值相同的大小写变体", body: `{"model":"gpt-5.4","Model":"gpt-5.4"}`, want: "Model"},
{name: "转义写法", body: `{"model":"cheap","\u006dodel":"expensive"}`, want: "model"},
{name: "代理对转义", body: `{"\ud83d\ude00":1,"` + "\U0001F600" + `":2}`, want: "\U0001F600"},
{name: "孤立代理项与无效 UTF-8 都解码为 U+FFFD", body: "{\"m\\ud800\":1,\"m\xff\":2}", want: "m\uFFFD"},
{name: "长 s 折叠为 s", body: "{\"service_tier\":\"flex\",\"\u017Fervice_tier\":\"priority\"}", want: "\u017Fervice_tier"},
{name: "开尔文符号折叠为 k", body: "{\"top_k\":1,\"top_\u212a\":2}", want: "top_\u212a"},
{name: "service_tier 取值不同", body: `{"model":"gpt-5.4","service_tier":"default","input":"hi","service_tier":"priority"}`, want: "service_tier"},
{name: "类型不同", body: `{"model":"cheap","model":null}`, want: "model"},
{name: "内容字段", body: `{"messages":[],"model":"a","messages":[{"role":"user","content":"hi"}]}`, want: "messages"},
{name: "session 内的 model", body: `{"sdp":"v=0","session":{"model":"gpt-live-a","model":"gpt-live-b"}}`, want: "session.model"},
{name: "前导空白", body: " \n" + `{"model":"a","model":"b"}`, want: "model"},
{name: "UTF-8 BOM", body: "\xef\xbb\xbf" + `{"model":"a","model":"b"}`, want: "model"},
{name: "嵌套 reasoning.effort 取值不同", body: `{"model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"input":"hi"}`, want: "reasoning.effort"},
{name: "嵌套 reasoning.effort 取值相同", body: `{"model":"gpt-5.4","reasoning":{"effort":"xhigh","effort":"xhigh"},"input":"hi"}`, want: "reasoning.effort"},
{name: "嵌套大小写变体", body: `{"model":"gpt-5.4","input":"hi","reasoning":{"effort":"low","Effort":"xhigh"}}`, want: "reasoning.Effort"},
{name: "output_config 大小写变体", body: `{"model":"m","output_config":{"effort":"low","EFFORT":"max"}}`, want: "output_config.EFFORT"},
{name: "嵌套 thinking.type", body: `{"model":"m","thinking":{"type":"disabled","budget_tokens":1024,"type":"enabled"}}`, want: "thinking.type"},
{name: "嵌套对象里的重复键", body: `{"model":"a","metadata":{"user_id":"1","user_id":"2"}}`, want: "metadata.user_id"},
{name: "数组元素里的重复键", body: `{"messages":[{"role":"user","content":"a"},{"role":"user","role":"assistant"}]}`, want: "messages[1].role"},
{name: "嵌套转义写法", body: `{"reasoning":{"effort":"low","\u0065ffort":"xhigh"}}`, want: "reasoning.effort"},
{name: "深层嵌套", body: `{"a":[[{"b":{"c":1,"c":2}}]]}`, want: "a[0][0].b.c"},
{name: "session 内嵌套", body: `{"session":{"audio":{"voice":"a","voice":"b"}}}`, want: "session.audio.voice"},
{name: "自由键空间内的精确重复", body: `{"tools":[{"input_schema":{"properties":{"id":{},"id":{}}}}]}`, want: "tools[0].input_schema.properties.id"},
{name: "metadata 大小写变体(Antigravity 结构体绑定)", body: `{"metadata":{"user_id":"A","USER_ID":"B"}}`, want: "metadata.USER_ID"},
{name: "前导控制字节(gjson 当空白跳过)", body: "\x0b{\"model\":\"a\",\"model\":\"b\"}", want: "model"},
{name: "顶层 input 仍做折叠", body: `{"input":[{"role":"user","Role":"system","content":"x"}]}`, want: "input[0].Role"},
{name: "超深子树之后的同层重复", body: `{"model":"a","x":` + strings.Repeat("[", maxConflictDepth+5) + strings.Repeat("]", maxConflictDepth+5) + `,"model":"b"}`, want: "model"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, conflict := ConflictingField("application/json", []byte(tt.body))
require.True(t, conflict)
require.Equal(t, tt.want, got)
})
}
}
func TestConflictingFieldJSONAcceptsUnambiguousBodies(t *testing.T) {
tests := []struct {
name string
body string
}{
{name: "空请求体", body: ""},
{name: "空对象", body: `{}`},
{name: "普通请求", body: `{"model":"a","max_tokens":1,"stream":true,"messages":[]}`},
{name: "相近但不同的字段名", body: `{"model":"a","models":"b","model_id":"c"}`},
{name: "兄弟对象里的同名键", body: `{"a":{"x":1},"b":{"x":2},"c":[{"x":1},{"x":2}]}`},
{name: "父子对象同名键", body: `{"model":"m","metadata":{"model":"other"}}`},
{name: "schema 属性大小写不同", body: `{"tools":[{"input_schema":{"type":"object","properties":{"id":{"type":"string"},"ID":{"type":"integer"}}}}]}`},
{name: "tool_use 参数大小写不同", body: `{"messages":[{"role":"assistant","content":[{"type":"tool_use","id":"t","name":"f","input":{"path":"a","Path":"b"}}]}]}`},
{name: "Gemini 函数参数与返回大小写不同", body: `{"contents":[{"parts":[{"functionCall":{"name":"f","args":{"k":1,"K":2}}},{"functionResponse":{"name":"f","response":{"v":1,"V":2}}}]}]}`},
{name: "提示词模板变量大小写不同", body: `{"prompt":{"id":"p","variables":{"name":"a","Name":"b"}}}`},
{name: "MCP 请求头大小写不同", body: `{"tools":[{"type":"mcp","headers":{"Authorization":"a","authorization":"b"}}]}`},
{name: "dependentRequired 大小写不同", body: `{"s":{"dependentRequired":{"a":[],"A":[]}}}`},
{name: "转义写法的自由键名", body: `{"tools":[{"input_schema":{"prop\u0065rties":{"id":{},"ID":{}}}}]}`},
{name: "只读首个顶层值", body: `{"model":"a"}{"model":"a","model":"b"}`},
{name: "字符串值里出现字段名", body: `{"model":"a","input":"{\"model\":\"b\",\"model\":\"c\"}"}`},
{name: "字符串里的括号与逗号", body: `{"a":"{[,\"]}","b":"\\","c":1}`},
{name: "顶层数组里的不同对象", body: `[{"model":"a"},{"model":"b"}]`},
{name: "不是 JSON", body: `model=a&model=b`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, conflict := ConflictingField("application/json", []byte(tt.body))
require.False(t, conflict, got)
require.Empty(t, got)
})
}
}
// 回归:JSON handler 不看 Content-Type,把 JSON 请求体标成 multipart 不能绕过检查。
func TestConflictingFieldIgnoresMultipartLabelOnJSONBody(t *testing.T) {
body := []byte(`{"model":"claude-3-5-haiku-20241022","messages":[],"model":"claude-opus-4-8"}`)
for _, contentType := range []string{"multipart/form-data", "multipart/form-data; boundary=zzz", `Multipart/Form-Data; boundary="a"`, "text/plain", ""} {
got, conflict := ConflictingField(contentType, body)
require.True(t, conflict, contentType)
require.Equal(t, "model", got)
}
}
// 规则和它要防的解析器行为绑在一起:未报告冲突的请求体,gjson(首个、大小写
// 敏感)和 encoding/json 结构体绑定(末值、大小写不敏感)读到的值必须一致。
func TestConflictingFieldMatchesParserDisagreement(t *testing.T) {
tests := []struct {
body string
conflict bool
parsersDisagree bool
}{
{body: `{"model":"first","model":"last"}`, conflict: true, parsersDisagree: true},
{body: `{"model":"first","MODEL":"last"}`, conflict: true, parsersDisagree: true},
{body: `{"MODEL":"first","model":"last"}`, conflict: true},
{body: `{"model":"same","Model":"same"}`, conflict: true},
{body: `{"model":"only","reasoning":{"effort":"low","Effort":"xhigh"}}`, conflict: true},
{body: `{"model":"only","reasoning":{"effort":"low"}}`},
}
for _, tt := range tests {
t.Run(tt.body, func(t *testing.T) {
var decoded struct {
Model string `json:"model"`
Reasoning struct {
Effort string `json:"effort"`
} `json:"reasoning"`
}
require.NoError(t, json.Unmarshal([]byte(tt.body), &decoded))
first := gjson.Get(tt.body, "model").String()
require.Equal(t, tt.parsersDisagree, first != decoded.Model)
_, conflict := ConflictingField("application/json", []byte(tt.body))
require.Equal(t, tt.conflict, conflict)
if !conflict {
require.Equal(t, first, decoded.Model)
require.Equal(t, gjson.Get(tt.body, "reasoning.effort").String(), decoded.Reasoning.Effort)
}
})
}
}
func TestConflictingFieldReturnsIndependentCopy(t *testing.T) {
body := []byte(`{"outer":{"model":"a","model":"b"}}`)
got, conflict := ConflictingField("application/json", body)
require.True(t, conflict)
for i := range body {
body[i] = 'x'
}
require.Equal(t, "outer.model", got)
}
func TestConflictingFieldManyMembersUsesIndex(t *testing.T) {
var b strings.Builder
_, _ = b.WriteString(`{"model":"m","tool":{`)
for i := 0; i < 100; i++ {
fmt.Fprintf(&b, `"k%d":%d,`, i, i)
}
body := b.String()
got, conflict := ConflictingField("application/json", []byte(body+`"K3":3}}`))
require.True(t, conflict, "duplicates past the linear-scan limit must be found")
require.Equal(t, "tool.K3", got)
_, conflict = ConflictingField("application/json", []byte(body+`"k100":0}}`))
require.False(t, conflict)
}
// 回归:扫描是线性的,深嵌套不能放大 CPU(逐层递归时 1 MB、9990 层约 1.6 s)。
func TestConflictingFieldDeepNestingIsLinear(t *testing.T) {
depth := maxConflictDepth - 10
body := []byte(`{"input":` + strings.Repeat("[", depth) + `"` + strings.Repeat("a", 1<<20) + `"` + strings.Repeat("]", depth) + `}`)
start := time.Now()
_, conflict := ConflictingField("application/json", body)
require.False(t, conflict)
require.Less(t, time.Since(start), 200*time.Millisecond)
objects := []byte(strings.Repeat(`{"a":`, maxConflictDepth+50) + "1" + strings.Repeat("}", maxConflictDepth+50))
_, conflict = ConflictingField("application/json", objects)
require.False(t, conflict)
}
// 回归:大对象的判重内存与请求体同一量级(逐键存字符串时峰值约为请求体的 16 倍)。
// 64 位哈希 map 含扩容过程的累计分配约 6~7 倍,峰值约 2~3 倍。
func TestConflictingFieldManyKeysMemoryIsBounded(t *testing.T) {
var b strings.Builder
_, _ = b.WriteString(`{"x":{`)
const keys = 1 << 20
for i := 0; i < keys; i++ {
if i > 0 {
_ = b.WriteByte(',')
}
fmt.Fprintf(&b, `"%d":1`, i)
}
_, _ = b.WriteString(`}}`)
body := []byte(b.String())
var before, after runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&before)
_, conflict := ConflictingField("application/json", body)
runtime.ReadMemStats(&after)
require.False(t, conflict)
require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(8*len(body)))
}
// 回归:字符串扫描对转义数量是线性的(此前每个转义都会重扫到字符串末尾,
// 20 万个 \n 约 0.56 s)。
func TestConflictingFieldManyEscapesIsLinear(t *testing.T) {
body := []byte(`{"model":"m","input":"` + strings.Repeat(`\n`, 1<<20) + `\\","model":"x"}`)
start := time.Now()
got, conflict := ConflictingField("application/json", body)
require.Less(t, time.Since(start), 100*time.Millisecond)
require.True(t, conflict)
require.Equal(t, "model", got)
for _, tricky := range []string{
`{"a":"\\","a":1}`,
`{"a":"x\\\"y","a":1}`,
`{"a":"\\\\\\\\","a":1}`,
`{"a":"\"","a":1}`,
} {
got, conflict := ConflictingField("application/json", []byte(tricky))
require.True(t, conflict, tricky)
require.Equal(t, "a", got, tricky)
}
}
func multipartBody(t *testing.T, fields ...[2]string) (string, []byte) {
t.Helper()
var body bytes.Buffer
writer := multipart.NewWriter(&body)
for _, field := range fields {
require.NoError(t, writer.WriteField(field[0], field[1]))
}
require.NoError(t, writer.Close())
return writer.FormDataContentType(), body.Bytes()
}
func TestConflictingFieldMultipart(t *testing.T) {
reject := []struct {
name string
fields [][2]string
want string
}{
{name: "model 字段取值不同", fields: [][2]string{{"model", "gpt-image-1"}, {"prompt", "cat"}, {"model", "gpt-image-1.5"}}, want: "model"},
{name: "model 字段取值相同", fields: [][2]string{{"model", "gpt-image-1"}, {"model", "gpt-image-1"}}, want: "model"},
{name: "计费标量 size 重复", fields: [][2]string{{"model", "gpt-image-1"}, {"size", "1024x1024"}, {"size", "1536x1024"}}, want: "size"},
{name: "计费标量 n 重复", fields: [][2]string{{"n", "1"}, {"n", "8"}}, want: "n"},
{name: "session 字段重复", fields: [][2]string{{"sdp", "v=0"}, {"session", `{"model":"a"}`}, {"session", `{"model":"b"}`}}, want: "session"},
{name: "session JSON 内的 model 重复", fields: [][2]string{{"sdp", "v=0"}, {"session", `{"model":"a","instructions":"hi","model":"b"}`}}, want: "session.model"},
{name: "session JSON 内的嵌套重复", fields: [][2]string{{"sdp", "v=0"}, {"session", `{"model":"a","audio":{"voice":"x","voice":"y"}}`}}, want: "session.audio.voice"},
}
for _, tt := range reject {
t.Run(tt.name, func(t *testing.T) {
contentType, body := multipartBody(t, tt.fields...)
got, conflict := ConflictingField(contentType, body)
require.True(t, conflict)
require.Equal(t, tt.want, got)
})
}
accept := []struct {
name string
fields [][2]string
}{
{name: "普通表单", fields: [][2]string{{"model", "gpt-image-1"}, {"prompt", `{"model":"a","model":"b"}`}}},
{name: "数组字段", fields: [][2]string{{"model", "whisper-1"}, {"timestamp_granularities[]", "word"}, {"timestamp_granularities[]", "segment"}}},
{name: "多图输入", fields: [][2]string{{"model", "grok-imagine"}, {"image_url", "https://a"}, {"image_url", "https://b"}, {"image", "https://c"}, {"image", "https://d"}}},
}
for _, tt := range accept {
t.Run(tt.name, func(t *testing.T) {
contentType, body := multipartBody(t, tt.fields...)
got, conflict := ConflictingField(contentType, body)
require.False(t, conflict, got)
})
}
}
func BenchmarkConflictingField(b *testing.B) {
var sb strings.Builder
_, _ = sb.WriteString(`{"model":"claude-sonnet-4-5","max_tokens":4096,"stream":true,"system":[{"type":"text","text":"sys"}],"tools":[`)
for i := 0; i < 40; i++ {
if i > 0 {
_, _ = sb.WriteString(",")
}
fmt.Fprintf(&sb, `{"name":"tool_%d","description":"%s","input_schema":{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path"]}}`, i, strings.Repeat("d", 200))
}
_, _ = sb.WriteString(`],"messages":[`)
for i := 0; i < 200; i++ {
if i > 0 {
_, _ = sb.WriteString(",")
}
fmt.Fprintf(&sb, `{"role":"user","content":[{"type":"text","text":"%s"}]}`, strings.Repeat("t", 1000))
}
_, _ = sb.WriteString(`]}`)
body := []byte(sb.String())
b.SetBytes(int64(len(body)))
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, conflict := ConflictingField("application/json", body); conflict {
b.Fatal("unexpected conflict")
}
}
}
// rawMultipart 用固定 boundary 拼出原始 multipart 请求体,便于构造畸形 part。
func rawMultipart(preamble string, parts ...string) (string, []byte) {
var b strings.Builder
_, _ = b.WriteString(preamble)
for _, part := range parts {
_, _ = b.WriteString("--BOUNDARY\r\n")
_, _ = b.WriteString(part)
_, _ = b.WriteString("\r\n")
}
_, _ = b.WriteString("--BOUNDARY--\r\n")
return "multipart/form-data; boundary=BOUNDARY", []byte(b.String())
}
func textPart(name, value string) string {
return "Content-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value
}
// 回归:multipart handler 跳过首个 boundary 之前的前导内容;前导内容是 JSON 时
// 不能让请求体只被当成 JSON 检查,也不能让 JSON 与表单两种解读并存。
func TestConflictingFieldMultipartPreambleAndMalformedParts(t *testing.T) {
cases := []struct {
name string
build func() (string, []byte)
want string
}{
{name: "JSON 前导内容后的重复 n", want: "n", build: func() (string, []byte) {
return rawMultipart("{}\r\n", textPart("model", "gpt-image-2"), textPart("n", "8"), textPart("n", "1"))
}},
{name: "JSON 前导内容与表单 model 并存", want: "Content-Type", build: func() (string, []byte) {
return rawMultipart(`{"model":"gpt-image-1-mini"}`+"\r\n", textPart("model", "gpt-image-2"))
}},
{name: "数组前导内容", want: "Content-Type", build: func() (string, []byte) {
return rawMultipart("[]\r\n", textPart("model", "gpt-image-2"))
}},
{name: "名为 model 的文件 part", want: "model", build: func() (string, []byte) {
return rawMultipart("", "Content-Disposition: form-data; name=\"model\"; filename=\"m.txt\"\r\n\r\ngpt-image-2")
}},
{name: "文件与文本同名", want: "size", build: func() (string, []byte) {
return rawMultipart("", textPart("size", "1024x1024"), "Content-Disposition: form-data; name=\"size\"; filename=\"s\"\r\n\r\n1536x1024")
}},
{name: "无法解析名字的 part", want: "Content-Disposition", build: func() (string, []byte) {
return rawMultipart("", "Content-Disposition: form-data; name=\"a\"; name=\"model\"\r\n\r\ngpt-image-2")
}},
{name: "RFC 2231 扩展字段名", want: "Content-Disposition", build: func() (string, []byte) {
return rawMultipart("", "Content-Disposition: form-data; name=\"model\"; name*=UTF-8''prompt\r\n\r\ngpt-image-2")
}},
{name: "分段的扩展字段名", want: "Content-Disposition", build: func() (string, []byte) {
return rawMultipart("", "Content-Disposition: form-data; name=\"model\";name*0=\"pro\"; name*1=\"mpt\"\r\n\r\ngpt-image-2")
}},
{name: "两个 Content-Disposition 头", want: "Content-Disposition", build: func() (string, []byte) {
return rawMultipart("", "Content-Disposition: form-data; name=\"prompt\"\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\ngpt-image-2")
}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
contentType, body := tc.build()
got, conflict := ConflictingField(contentType, body)
require.True(t, conflict)
require.Equal(t, tc.want, got)
})
}
contentType, body := rawMultipart("", textPart("model", "gpt-image-2"), textPart("prompt", "cat"))
_, conflict := ConflictingField(contentType, body)
require.False(t, conflict, "a well-formed form must pass")
// 非 ASCII 文件名的 filename* 写法是合法的,不能误拒。
contentType, body = rawMultipart("", textPart("model", "gpt-image-2"), "Content-Disposition: form-data; name=\"image\"; filename=\"a.png\"; filename*=UTF-8''%E5%9B%BE.png\r\nContent-Type: image/png\r\n\r\nPNG")
_, conflict = ConflictingField(contentType, body)
require.False(t, conflict, "filename* must not be treated as an extended field name")
}
@@ -44,15 +44,19 @@ func IsLiveRequestRoute(routePath string) bool {
// (为空回落 session 候选)。候选包含重复键、大小写变体的全部出现。
func FromBodyCandidates(routePath, contentType string, body []byte) []string {
var topLevel, session []string
if doc := TrimUTF8BOM(body); LooksLikeJSON(doc) {
// 按内容识别 JSON,不看 Content-Type:JSON handler 不校验请求头,且宽容
// 读取会剥掉 BOM,两者都不能成为绕过准入的手段。gjson 只读首个顶层值。
topLevel = jsonModelCandidates(doc)
session = jsonSessionModelCandidates(doc)
}
if isMultipartContentType(contentType) {
// 声明为 multipart 的请求体只做 multipart 解析——gjson 的部分扫描
// 会在 multipart 字节流里误匹配 session JSON 内的 model 字段。
// multipart handler 跳过首个 boundary 之前的前导内容(可以是任意 JSON),
// 所以两种解读的候选都要收集。只有声明为 multipart 时才按 multipart 解析,
// 不对非 multipart 字节流做 gjson 部分扫描。
models, sessions := multipartModelCandidates(contentType, body)
topLevel = models
session = sessionModelCandidates(sessions)
} else {
topLevel = jsonModelCandidates(body)
session = jsonSessionModelCandidates(body)
topLevel = append(topLevel, models...)
session = append(session, sessionModelCandidates(sessions)...)
}
if IsLiveRequestRoute(routePath) {
@@ -255,3 +255,40 @@ func TestFromBodyForRouteReturnsFirstCandidate(t *testing.T) {
t.Fatalf("dispatch helper keeps gjson-first semantics, got %q", got)
}
}
// 回归:JSON handler 不看 Content-Type、宽容读取会剥掉 BOM,准入候选必须与之
// 一致,否则把请求体标成 multipart 或加 BOM 就能让白名单拿不到任何模型而放行。
func TestFromBodyCandidatesFollowsWhatJSONHandlersParse(t *testing.T) {
body := []byte(`{"model":"claude-opus-4-8","messages":[]}`)
cases := []struct {
name string
contentType string
body []byte
}{
{name: "multipart 标签", contentType: "multipart/form-data; boundary=zzz", body: body},
{name: "无 boundary 的 multipart 标签", contentType: "multipart/form-data", body: body},
{name: "UTF-8 BOM", contentType: "application/json", body: append([]byte{0xEF, 0xBB, 0xBF}, body...)},
{name: "BOM 加 multipart 标签", contentType: "multipart/form-data", body: append([]byte{0xEF, 0xBB, 0xBF}, body...)},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := FromBodyCandidates("/v1/messages", tc.contentType, tc.body)
if len(got) != 1 || got[0] != "claude-opus-4-8" {
t.Fatalf("candidates = %v, want [claude-opus-4-8]", got)
}
if route := FromBodyForRoute("/v1/messages", tc.contentType, tc.body); route != "claude-opus-4-8" {
t.Fatalf("route model = %q", route)
}
})
}
}
// 回归:multipart handler 跳过首个 boundary 之前的前导内容,前导内容是 JSON 时
// 白名单必须同时看到表单里的 model,不能只取 JSON 解读。
func TestFromBodyCandidatesMultipartWithJSONPreamble(t *testing.T) {
body := []byte("{}\r\n--B\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\ngpt-image-2\r\n--B--\r\n")
got := FromBodyCandidates("/v1/images/edits", "multipart/form-data; boundary=B", body)
if len(got) != 1 || got[0] != "gpt-image-2" {
t.Fatalf("candidates = %v, want [gpt-image-2]", got)
}
}
+112
View File
@@ -0,0 +1,112 @@
package websearch
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
const (
exaSearchEndpoint = "https://api.exa.ai/search"
exaProviderName = "exa"
)
// ExaProvider implements web search via the Exa Search API.
type ExaProvider struct {
apiKey string
httpClient *http.Client
}
// NewExaProvider creates an Exa Search provider.
// The caller is responsible for configuring the http.Client with proxy/timeouts.
func NewExaProvider(apiKey string, httpClient *http.Client) *ExaProvider {
if httpClient == nil {
httpClient = http.DefaultClient
}
return &ExaProvider{apiKey: apiKey, httpClient: httpClient}
}
func (e *ExaProvider) Name() string { return exaProviderName }
func (e *ExaProvider) Search(ctx context.Context, req SearchRequest) (*SearchResponse, error) {
numResults := req.MaxResults
if numResults <= 0 {
numResults = defaultMaxResults
}
// Search type and highlight length are left to Exa's defaults.
payload := exaRequest{
Query: req.Query,
NumResults: numResults,
Contents: exaContents{Highlights: true},
}
bodyBytes, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("exa: encode request: %w", err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, exaSearchEndpoint, bytes.NewReader(bodyBytes))
if err != nil {
return nil, fmt.Errorf("exa: build request: %w", err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("x-api-key", e.apiKey)
resp, err := e.httpClient.Do(httpReq)
if err != nil {
return nil, fmt.Errorf("exa: request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseSize))
if err != nil {
return nil, fmt.Errorf("exa: read body: %w", err)
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("exa: status %d: %s", resp.StatusCode, truncateBody(body))
}
var raw exaResponse
if err := json.Unmarshal(body, &raw); err != nil {
return nil, fmt.Errorf("exa: decode response: %w", err)
}
results := make([]SearchResult, 0, len(raw.Results))
for _, r := range raw.Results {
results = append(results, SearchResult{
URL: r.URL,
Title: r.Title,
Snippet: strings.Join(r.Highlights, "\n"),
PageAge: r.PublishedDate,
})
}
return &SearchResponse{Results: results, Query: req.Query}, nil
}
type exaRequest struct {
Query string `json:"query"`
NumResults int `json:"numResults"`
Contents exaContents `json:"contents"`
}
type exaContents struct {
Highlights bool `json:"highlights"`
}
type exaResponse struct {
Results []exaResult `json:"results"`
}
type exaResult struct {
URL string `json:"url"`
Title string `json:"title"`
PublishedDate string `json:"publishedDate"`
Highlights []string `json:"highlights"`
}
@@ -0,0 +1,91 @@
package websearch
import (
"context"
"encoding/json"
"io"
"net/http"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
type exaRoundTripFunc func(*http.Request) (*http.Response, error)
func (f exaRoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func exaTestClient(status int, body string, seen *http.Request, seenBody *[]byte) *http.Client {
return &http.Client{Transport: exaRoundTripFunc(func(r *http.Request) (*http.Response, error) {
*seen = *r
b, _ := io.ReadAll(r.Body)
*seenBody = b
return &http.Response{
StatusCode: status,
Body: io.NopCloser(strings.NewReader(body)),
Header: make(http.Header),
}, nil
})}
}
func TestExaProvider_Name(t *testing.T) {
require.Equal(t, "exa", NewExaProvider("key", nil).Name())
}
func TestManagerBuildsExaProvider(t *testing.T) {
p := (&Manager{}).buildProvider(ProviderConfig{Type: ProviderTypeExa, APIKey: "k"}, nil)
require.IsType(t, &ExaProvider{}, p)
}
func TestExaProvider_Search(t *testing.T) {
var seen http.Request
var seenBody []byte
resp := `{"requestId":"r1","results":[` +
`{"url":"https://go.dev","title":"Go","publishedDate":"2026-10-01T00:00:00.000Z","highlights":["Go is a language.","It compiles fast."]},` +
`{"url":"https://example.com","title":"Example","publishedDate":null,"highlights":[]}]}`
p := NewExaProvider("exa-key", exaTestClient(http.StatusOK, resp, &seen, &seenBody))
out, err := p.Search(context.Background(), SearchRequest{Query: "golang", MaxResults: 3})
require.NoError(t, err)
require.Equal(t, http.MethodPost, seen.Method)
require.Equal(t, "https://api.exa.ai/search", seen.URL.String())
require.Equal(t, "exa-key", seen.Header.Get("x-api-key"))
require.Equal(t, "application/json", seen.Header.Get("Content-Type"))
var body map[string]any
require.NoError(t, json.Unmarshal(seenBody, &body))
require.Equal(t, map[string]any{
"query": "golang",
"numResults": float64(3),
"contents": map[string]any{"highlights": true},
}, body)
require.Equal(t, "golang", out.Query)
require.Equal(t, []SearchResult{
{URL: "https://go.dev", Title: "Go", Snippet: "Go is a language.\nIt compiles fast.", PageAge: "2026-10-01T00:00:00.000Z"},
{URL: "https://example.com", Title: "Example"},
}, out.Results)
}
func TestExaProvider_SearchDefaultsNumResults(t *testing.T) {
var seen http.Request
var seenBody []byte
p := NewExaProvider("k", exaTestClient(http.StatusOK, `{"results":[]}`, &seen, &seenBody))
_, err := p.Search(context.Background(), SearchRequest{Query: "q"})
require.NoError(t, err)
var body map[string]any
require.NoError(t, json.Unmarshal(seenBody, &body))
require.Equal(t, float64(defaultMaxResults), body["numResults"])
}
func TestExaProvider_SearchHTTPError(t *testing.T) {
var seen http.Request
var seenBody []byte
p := NewExaProvider("bad", exaTestClient(http.StatusUnauthorized, `{"error":"invalid api key"}`, &seen, &seenBody))
_, err := p.Search(context.Background(), SearchRequest{Query: "q"})
require.ErrorContains(t, err, "exa: status 401")
}
+3 -1
View File
@@ -21,7 +21,7 @@ import (
// ProviderConfig holds the configuration for a single search provider.
type ProviderConfig struct {
Type string `json:"type"` // ProviderTypeBrave | ProviderTypeTavily
Type string `json:"type"` // ProviderTypeBrave | ProviderTypeTavily | ProviderTypeExa
APIKey string `json:"api_key"` // secret
QuotaLimit int64 `json:"quota_limit"` // 0 = unlimited
SubscribedAt *int64 `json:"subscribed_at,omitempty"` // subscription start (unix seconds); quota resets monthly from this date
@@ -464,6 +464,8 @@ func (m *Manager) buildProvider(cfg ProviderConfig, client *http.Client) Provide
return NewBraveProvider(cfg.APIKey, client)
case tavilyProviderName:
return NewTavilyProvider(cfg.APIKey, client)
case exaProviderName:
return NewExaProvider(cfg.APIKey, client)
default:
slog.Warn("websearch: unknown provider type, falling back to brave",
"type", cfg.Type)
+1 -1
View File
@@ -4,7 +4,7 @@ import "context"
// Provider is the interface every search backend must implement.
type Provider interface {
// Name returns the provider identifier ("brave" or "tavily").
// Name returns the provider identifier ("brave", "tavily" or "exa").
Name() string
// Search executes a web search and returns results.
Search(ctx context.Context, req SearchRequest) (*SearchResponse, error)
+1
View File
@@ -27,4 +27,5 @@ const defaultMaxResults = 5
const (
ProviderTypeBrave = "brave"
ProviderTypeTavily = "tavily"
ProviderTypeExa = "exa"
)
+25 -1
View File
@@ -1657,6 +1657,29 @@ func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged(
expectedCredentials map[string]any,
expectedProxyID *int64,
credentials map[string]any,
) (bool, error) {
return r.updateOAuthCredentialsIfUnchanged(ctx, id, service.PlatformGrok, expectedCredentials, expectedProxyID, credentials)
}
// UpdateOpenAIOAuthCredentialsIfUnchanged preserves a completed token rotation
// without overwriting concurrent reauthorization or writing to a credential shadow.
func (r *accountRepository) UpdateOpenAIOAuthCredentialsIfUnchanged(
ctx context.Context,
id int64,
expectedCredentials map[string]any,
expectedProxyID *int64,
credentials map[string]any,
) (bool, error) {
return r.updateOAuthCredentialsIfUnchanged(ctx, id, service.PlatformOpenAI, expectedCredentials, expectedProxyID, credentials)
}
func (r *accountRepository) updateOAuthCredentialsIfUnchanged(
ctx context.Context,
id int64,
platform string,
expectedCredentials map[string]any,
expectedProxyID *int64,
credentials map[string]any,
) (bool, error) {
if r == nil || r.sql == nil {
return false, errors.New("account repository SQL executor is not configured")
@@ -1680,6 +1703,7 @@ func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged(
AND a.type = $4
AND a.credentials = $5::jsonb
AND a.proxy_id IS NOT DISTINCT FROM $6
AND ($3 <> 'openai' OR a.parent_account_id IS NULL)
RETURNING a.id
)
INSERT INTO scheduler_outbox (event_type, account_id, group_id, payload)
@@ -1687,7 +1711,7 @@ func (r *accountRepository) UpdateGrokOAuthCredentialsIfUnchanged(
`,
string(credentialsJSON),
id,
service.PlatformGrok,
platform,
service.AccountTypeOAuth,
string(expectedJSON),
expectedProxyID,
@@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"regexp"
"strings"
"testing"
@@ -258,9 +259,83 @@ func TestAccountRepository_UpdateGrokOAuthCredentialsIfUnchanged_UsesExactAttemp
require.Contains(t, normalized, "proxy_id IS NOT DISTINCT FROM $6")
require.Contains(t, normalized, "INSERT INTO scheduler_outbox")
require.Len(t, exec.execArgs[0], 7)
require.Equal(t, service.PlatformGrok, exec.execArgs[0][2])
require.Equal(t, &proxyID, exec.execArgs[0][5])
}
func TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_UsesExactAttemptStateAndAtomicOutbox(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(1)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
proxyID := int64(29)
applied, err := repo.UpdateOpenAIOAuthCredentialsIfUnchanged(
context.Background(),
42,
map[string]any{"refresh_token": "attempted", "_token_version": int64(9)},
&proxyID,
map[string]any{"refresh_token": "rotated", "_token_version": int64(10)},
)
require.NoError(t, err)
require.True(t, applied)
require.Len(t, exec.execQueries, 1, "credential update and outbox insertion must share one SQL statement")
normalized := normalizeSQLWhitespace(exec.execQueries[0])
require.Contains(t, normalized, "WITH updated AS ( UPDATE accounts AS a SET credentials = $1::jsonb")
require.Contains(t, normalized, "a.deleted_at IS NULL")
require.Contains(t, normalized, "a.platform = $3")
require.Contains(t, normalized, "a.type = $4")
require.Contains(t, normalized, "a.credentials = $5::jsonb")
require.Contains(t, normalized, "a.proxy_id IS NOT DISTINCT FROM $6")
require.Contains(t, normalized, "($3 <> 'openai' OR a.parent_account_id IS NULL)")
require.Contains(t, normalized, "RETURNING a.id ) INSERT INTO scheduler_outbox")
require.Contains(t, normalized, "SELECT $7, updated.id, NULL, NULL FROM updated")
require.Len(t, exec.execArgs[0], 7)
arg0, ok := exec.execArgs[0][0].(string)
require.True(t, ok)
require.JSONEq(t, `{"refresh_token":"rotated","_token_version":10}`, arg0)
require.Equal(t, int64(42), exec.execArgs[0][1])
require.Equal(t, service.PlatformOpenAI, exec.execArgs[0][2])
require.Equal(t, service.AccountTypeOAuth, exec.execArgs[0][3])
arg4, ok := exec.execArgs[0][4].(string)
require.True(t, ok)
require.JSONEq(t, `{"refresh_token":"attempted","_token_version":9}`, arg4)
require.Equal(t, &proxyID, exec.execArgs[0][5])
require.Equal(t, service.SchedulerOutboxEventAccountChanged, exec.execArgs[0][6])
}
func TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_NoMatchDoesNotApply(t *testing.T) {
exec := &recordingSQLExecutor{result: rowsAffectedResult(0)}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
applied, err := repo.UpdateOpenAIOAuthCredentialsIfUnchanged(
context.Background(), 42, map[string]any{"refresh_token": "attempted"}, nil,
map[string]any{"refresh_token": "rotated"},
)
require.NoError(t, err)
require.False(t, applied)
require.Len(t, exec.execQueries, 1)
require.Nil(t, exec.execArgs[0][5], "a nil proxy must match only a database NULL proxy")
require.Contains(t, normalizeSQLWhitespace(exec.execQueries[0]), "SELECT $7, updated.id, NULL, NULL FROM updated",
"a CAS miss must not insert an independent invalidation event")
}
func TestAccountRepository_UpdateOpenAIOAuthCredentialsIfUnchanged_OutboxFailureDoesNotReportSuccess(t *testing.T) {
outboxErr := errors.New("scheduler outbox insert failed")
exec := &recordingSQLExecutor{err: outboxErr}
repo := newAccountRepositoryWithSQL(nil, exec, nil)
applied, err := repo.UpdateOpenAIOAuthCredentialsIfUnchanged(
context.Background(), 42, map[string]any{"refresh_token": "attempted"}, nil,
map[string]any{"refresh_token": "rotated"},
)
require.ErrorIs(t, err, outboxErr)
require.False(t, applied)
require.Len(t, exec.execQueries, 1)
require.Contains(t, normalizeSQLWhitespace(exec.execQueries[0]), "INSERT INTO scheduler_outbox")
}
func TestAccountRepository_ListOAuthRefreshCandidatePage_SQLFilter(t *testing.T) {
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherRegexp))
require.NoError(t, err)
@@ -44,7 +44,7 @@ func TestScopedAdminReviewGroupPriorityAndStatus(t *testing.T) {
cache := &scopedReviewSchedulerCache{accounts: make(map[int64]*service.Account)}
repo := NewAdminAccountRepository(client, db, cache)
groups := NewAdminGroupRepository(client, db)
admin := service.NewAdminService(nil, nil, groups, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, client, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
admin := service.NewAdminService(nil, nil, groups, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, client, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
scoped := admin.(service.ScopedAdminAccounts)
ctx := context.Background()
a, err := client.Group.Create().SetName("授权组").Save(ctx)
@@ -39,12 +39,8 @@ WITH stats AS (
ul.model AS model,
COUNT(*)::bigint AS request_count,
ROUND(
AVG(
CASE
WHEN ul.duration_ms > 0 AND ul.output_tokens > 0
THEN ul.output_tokens * 1000.0 / ul.duration_ms
END
)::numeric,
1000.0 * (SUM(ul.output_tokens) FILTER (WHERE ul.duration_ms > 0 AND ul.output_tokens > 0))
/ (SUM(ul.duration_ms) FILTER (WHERE ul.duration_ms > 0 AND ul.output_tokens > 0)),
2
)::float8 AS avg_tokens_per_sec,
ROUND(AVG(ul.first_token_ms)::numeric, 2)::float8 AS avg_first_token_ms,
@@ -0,0 +1,66 @@
//go:build integration
package repository
import (
"context"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestOpsRepositoryGetOpenAITokenStats_WeightsRateByDuration(t *testing.T) {
ctx := context.Background()
client := testEntClient(t)
user := mustCreateUser(t, client, &service.User{})
group := mustCreateGroup(t, client, &service.Group{Name: "ops-token-stats"})
account := mustCreateAccount(t, client, &service.Account{Name: "ops-token-stats"})
key := mustCreateApiKey(t, client, &service.APIKey{UserID: user.ID})
t.Cleanup(func() {
_, err := integrationDB.ExecContext(ctx, "DELETE FROM usage_logs WHERE group_id = $1", group.ID)
require.NoError(t, err)
_, err = integrationDB.ExecContext(ctx, "DELETE FROM api_keys WHERE id = $1", key.ID)
require.NoError(t, err)
_, err = integrationDB.ExecContext(ctx, "DELETE FROM accounts WHERE id = $1", account.ID)
require.NoError(t, err)
_, err = integrationDB.ExecContext(ctx, "DELETE FROM groups WHERE id = $1", group.ID)
require.NoError(t, err)
_, err = integrationDB.ExecContext(ctx, "DELETE FROM users WHERE id = $1", user.ID)
require.NoError(t, err)
})
now := time.Now().UTC()
_, err := integrationDB.ExecContext(ctx, `
INSERT INTO usage_logs (user_id, api_key_id, account_id, group_id, created_at, model, output_tokens, duration_ms)
VALUES
($1, $2, $3, $4, $5, 'gpt-mixed-durations', 100, 1000),
($1, $2, $3, $4, $5, 'gpt-mixed-durations', 100, 4000),
($1, $2, $3, $4, $5, 'gpt-mixed-durations', 0, 9000),
($1, $2, $3, $4, $5, 'gpt-mixed-durations', 10, 0),
($1, $2, $3, $4, $5, 'gpt-mixed-durations', 7, NULL),
($1, $2, $3, $4, $5, 'gpt-no-valid-samples', 0, 1000)
`, user.ID, key.ID, account.ID, group.ID, now)
require.NoError(t, err)
repo := NewOpsRepository(integrationDB)
stats, err := repo.GetOpenAITokenStats(ctx, &service.OpsOpenAITokenStatsFilter{
StartTime: now.Add(-time.Minute),
EndTime: now.Add(time.Minute),
GroupID: &group.ID,
TopN: 10,
})
require.NoError(t, err)
require.Len(t, stats.Items, 2)
mixed := stats.Items[0]
require.Equal(t, "gpt-mixed-durations", mixed.Model)
require.NotNil(t, mixed.AvgTokensPerSec)
require.Equal(t, 40.0, *mixed.AvgTokensPerSec)
require.Equal(t, int64(5), mixed.RequestCount)
require.Equal(t, int64(217), mixed.TotalOutputTokens)
require.Equal(t, "gpt-no-valid-samples", stats.Items[1].Model)
require.Nil(t, stats.Items[1].AvgTokensPerSec)
}
@@ -1345,6 +1345,10 @@ func newSchedulerAccountMetaRevision() string {
}
func marshalSchedulerCacheAccount(account service.Account) ([]byte, []byte, error) {
// Hydration needs account configuration and group membership, not expanded
// group objects (also repeated in AccountGroups). Keep the caller's graph intact.
account.Groups = nil
account.AccountGroups = filterSchedulerAccountGroups(account.AccountGroups)
fullPayload, err := json.Marshal(account)
if err != nil {
return nil, nil, fmt.Errorf("marshal account: %w", err)
@@ -57,6 +57,7 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T)
SessionWindowEnd: &windowEnd,
SessionWindowStatus: "active",
GroupIDs: []int64{bucket.GroupID},
Groups: []*service.Group{{ID: bucket.GroupID, Description: strings.Repeat("unused group configuration", 1024)}},
AccountGroups: []service.AccountGroup{
{
AccountID: 101,
@@ -101,8 +102,14 @@ func TestSchedulerCacheSnapshotUsesSlimMetadataButKeepsFullAccount(t *testing.T)
require.NotNil(t, full)
require.Equal(t, "secret-access-token", full.GetCredential("access_token"))
require.Equal(t, strings.Repeat("x", 4096), full.GetCredential("huge_blob"))
require.Equal(t, account.GroupIDs, full.GroupIDs)
require.Empty(t, full.Groups)
require.Len(t, full.AccountGroups, 1)
require.NotNil(t, full.AccountGroups[0].Group)
require.Equal(t, account.ID, full.AccountGroups[0].AccountID)
require.Equal(t, bucket.GroupID, full.AccountGroups[0].GroupID)
require.Equal(t, 5, full.AccountGroups[0].Priority)
require.Nil(t, full.AccountGroups[0].Group)
require.Nil(t, full.AccountGroups[0].Account)
}
func TestSchedulerCacheRetireAndReopenFencesOldEpochIntegration(t *testing.T) {
@@ -0,0 +1,116 @@
//go:build unit
package repository
import (
"context"
"encoding/json"
"fmt"
"strconv"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/stretchr/testify/require"
)
func TestSchedulerCacheAccountOmitsExpandedGroups(t *testing.T) {
for _, groupCount := range []int{1, 10, 100, 241} {
t.Run(strconv.Itoa(groupCount), func(t *testing.T) {
ctx := context.Background()
cache := newSchedulerCacheUnit(t)
now := time.Date(2026, time.November, 16, 12, 0, 0, 0, time.UTC)
resetAt := now.Add(time.Hour)
rate := 0.0
proxyID := int64(5)
expected := service.Account{
ID: 8842, Name: "multi-group", Platform: service.PlatformOpenAI,
Type: service.AccountTypeOAuth, Status: service.StatusActive, Schedulable: true,
Credentials: map[string]any{
"access_token": "fixture-access", "refresh_token": "fixture-refresh",
"openai_capabilities": []any{"responses"},
"model_mapping": map[string]any{"public-model": "upstream-model"},
},
Extra: map[string]any{"custom_account_setting": "keep", "openai_oauth_passthrough": true},
ProxyID: &proxyID, Proxy: &service.Proxy{ID: proxyID, Protocol: "http", Host: "proxy.example", Port: 8080},
Concurrency: 3, Priority: 7, RateMultiplier: &rate,
RateLimitResetAt: &resetAt, LastUsedAt: &now,
CreatedAt: now, UpdatedAt: now,
}
for i := 1; i <= groupCount; i++ {
expected.GroupIDs = append(expected.GroupIDs, int64(i))
expected.AccountGroups = append(expected.AccountGroups, service.AccountGroup{
AccountID: expected.ID, GroupID: int64(i), Priority: i, CreatedAt: now,
})
}
account := expected
account.AccountGroups = append([]service.AccountGroup(nil), expected.AccountGroups...)
for i := range account.AccountGroups {
group := &service.Group{
ID: int64(i + 1), Name: fmt.Sprintf("group-%d", i+1),
Description: strings.Repeat("unused group configuration ", 128),
}
account.Groups = append(account.Groups, group)
account.AccountGroups[i].Group = group
account.AccountGroups[i].Account = &service.Account{ID: account.ID, Name: "unused account edge"}
}
original, err := json.Marshal(account)
require.NoError(t, err)
// Both account updates and bucket rebuilds write the same global record.
for _, write := range []string{"account", "snapshot"} {
t.Run(write, func(t *testing.T) {
if write == "account" {
require.NoError(t, cache.SetAccount(ctx, &account))
} else {
bucket := service.SchedulerBucket{GroupID: 1, Platform: account.Platform, Mode: service.SchedulerModeSingle}
token, err := cache.CaptureBucketWriteToken(ctx, bucket)
require.NoError(t, err)
require.NoError(t, cache.SetSnapshot(ctx, bucket, token, []service.Account{account}))
snapshot, hit, err := cache.GetSnapshot(ctx, bucket)
require.NoError(t, err)
require.True(t, hit)
require.Len(t, snapshot, 1)
require.Equal(t, expected.GroupIDs, snapshot[0].GroupIDs)
require.Equal(t, expected.AccountGroups, snapshot[0].AccountGroups)
}
full, err := cache.GetAccount(ctx, account.ID)
require.NoError(t, err)
require.NotNil(t, full)
require.Zero(t, len(full.Groups), "full cache must omit expanded groups")
for _, membership := range full.AccountGroups {
require.True(t, membership.Group == nil && membership.Account == nil, "full cache must omit relationship objects")
}
require.Equal(t, &expected, full, "hydration must retain account configuration and membership")
payload, err := cache.rdb.Get(ctx, schedulerAccountKey(strconv.FormatInt(account.ID, 10))).Bytes()
require.NoError(t, err)
require.NotContains(t, string(payload), "unused group configuration")
require.NotContains(t, string(payload), "unused account edge")
require.Less(t, len(payload)*4, len(original))
t.Logf("groups=%d expanded_bytes=%d cached_bytes=%d", groupCount, len(original), len(payload))
})
}
// Serialization must not detach relationships from the repository's object.
after, err := json.Marshal(account)
require.NoError(t, err)
require.Equal(t, original, after)
})
}
}
func TestSchedulerCacheReadsLegacyExpandedGroups(t *testing.T) {
ctx := context.Background()
cache := newSchedulerCacheUnit(t)
account := service.Account{
ID: 8843, GroupIDs: []int64{2}, Groups: []*service.Group{{ID: 2, Name: "legacy"}},
AccountGroups: []service.AccountGroup{{AccountID: 8843, GroupID: 2, Priority: 4, Group: &service.Group{ID: 2}}},
}
payload, err := json.Marshal(account)
require.NoError(t, err)
require.NoError(t, cache.rdb.Set(ctx, schedulerAccountKey("8843"), payload, 0).Err())
full, err := cache.GetAccount(ctx, account.ID)
require.NoError(t, err)
require.Equal(t, &account, full, "rolling upgrades can still read records written by old instances")
}
@@ -276,7 +276,6 @@ func TestMarshalSchedulerCacheAccountKeepsEncodingJSONWireFormat(t *testing.T) {
Credentials: map[string]any{},
Extra: map[string]any{},
GroupIDs: []int64{},
Groups: []*service.Group{},
}},
{name: "nested maps and escaping", account: service.Account{
ID: 803,
@@ -13,6 +13,8 @@ type LegacyEngine interface {
type PromptEngine interface {
EffectiveMode() Mode
// Enqueue borrows req read-only for this call; implementations must copy
// any request memory retained after returning.
Enqueue(ctx context.Context, req Request) error
Evaluate(ctx context.Context, req Request) (*PromptDecision, error)
}
@@ -38,7 +40,7 @@ func (c *Coordinator) Check(ctx context.Context, req Request) Decision {
case ModeAsync:
// Enqueue is deliberately best-effort. The implementation owns a bounded
// context and copies request memory before it can outlive the Handler.
_ = c.prompt.Enqueue(ctx, req.Clone())
_ = c.prompt.Enqueue(ctx, req)
legacy, _ := c.checkLegacy(ctx, req)
return prioritize(legacy, nil)
case ModeBlocking:
@@ -0,0 +1,225 @@
package securityaudit
import (
"context"
"math/rand"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/require"
)
func memoryTestPromptService(cfg ActiveConfig, repo JobRepository) *PromptService {
store := &fakeConfigStore{cfg: cfg, active: true}
metrics := NewAtomicMetrics()
return &PromptService{config: store, metrics: metrics, background: context.Background(), enqueueSlots: make(chan struct{}, 128),
enqueuer: NewEnqueuer(store, repo, &fakePayloadStore{}, metrics)}
}
func TestAsyncAuditOutOfScopeSkipsLargeBodyCopy(t *testing.T) {
cfg := asyncConfig()
cfg.AllGroups = false
cfg.GroupIDs = []int64{1}
groupID := int64(2)
svc := memoryTestPromptService(cfg, &fakeJobRepository{})
req := Request{GroupID: &groupID, Protocol: "openai_responses", Body: []byte(`{"input":"` + strings.Repeat("x", 1<<20) + `"}`)}
runtime.GC()
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
decision := NewCoordinator(nil, svc).Check(context.Background(), req)
svc.enqueueWG.Wait()
runtime.ReadMemStats(&after)
require.True(t, decision.AllowNextStage)
require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(len(req.Body)/2), "out-of-scope audit must not copy the body")
runtime.KeepAlive(req)
}
func TestTrimRunesMatchesOriginalWithoutAllocatingTheWholePrompt(t *testing.T) {
for _, value := range []string{"", "abc", "中文😀suffix", "a\xff\xfebc", strings.Repeat("x", 1<<20)} {
for _, limit := range []int{0, 1, 3, 96} {
want := ""
if limit > 0 {
runes := []rune(value)
want = value
if len(runes) > limit {
want = string(runes[:limit]) + "…"
}
}
require.Equal(t, want, TrimRunes(value, limit))
}
}
value := strings.Repeat("x", 1<<20)
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
out := TrimRunes(value, 96)
runtime.ReadMemStats(&after)
require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<10))
runtime.KeepAlive(out)
}
func TestSplitRunesPreservesChunksWithoutWholeTranscriptCopies(t *testing.T) {
for _, value := range []string{"", "abcdef", "中文😀suffix", "a\xff\xfebc", "abc" + promptAuditPrioritySeparator + "中文😀"} {
for _, limit := range []int{1, 3, 4000} {
want := []string{}
for _, segment := range strings.Split(value, promptAuditPrioritySeparator) {
runes := []rune(segment)
for start := 0; start < len(runes); start += limit {
want = append(want, string(runes[start:min(start+limit, len(runes))]))
}
}
require.Equal(t, want, SplitRunes(value, limit))
}
}
value := strings.Repeat("x", 1<<20)
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
chunks := SplitRunes(value, 4000)
runtime.ReadMemStats(&after)
require.Equal(t, value, strings.Join(chunks, ""))
require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<10))
runtime.KeepAlive(chunks)
}
func TestRedactPreviewPreservesCompleteInputReplacementOrder(t *testing.T) {
for _, value := range []string{
"Bearer abcdefghijklmnop token=abcdefghijkl USER_CANARY_example user@example.org +86 138 1234 5678",
strings.Repeat("x", 1<<20),
strings.Repeat("前缀😀", 40) + " Bearer abcdefghijklmnop",
"short password:abcdefghijkl suffix",
} {
want := bearerPattern.ReplaceAllString(value, "Bearer ***")
want = apiKeyPattern.ReplaceAllStringFunc(want, func(match string) string {
if index := strings.IndexAny(match, ":= \t"); index >= 0 {
return match[:index+1] + "***"
}
return "***"
})
want = canaryPattern.ReplaceAllString(want, "${1}***")
want = emailPattern.ReplaceAllString(want, "***@***")
want = phonePattern.ReplaceAllString(want, "***PHONE***")
require.Equal(t, TrimRunes(want, 96), RedactPreview(value, 96))
}
value := strings.Repeat("x", 1<<20)
var before, after runtime.MemStats
runtime.ReadMemStats(&before)
out := RedactPreview(value, 96)
runtime.ReadMemStats(&after)
require.Less(t, after.TotalAlloc-before.TotalAlloc, uint64(64<<10))
runtime.KeepAlive(out)
}
type memoryTestGatedConfig struct {
*fakeConfigStore
reads atomic.Int32
resume <-chan struct{}
}
func (c *memoryTestGatedConfig) Active() (ActiveConfig, bool) {
if c.reads.Add(1) >= 2 {
<-c.resume
}
return c.fakeConfigStore.Active()
}
type memoryTestLegacyMutation struct{ mutate func(Request) }
func (l memoryTestLegacyMutation) Check(_ context.Context, req Request) (*LegacyDecision, error) {
l.mutate(req)
return &LegacyDecision{Allowed: true}, nil
}
func TestAsyncAuditOwnsCopyBeforeLegacyOrHandlerCanMutateInput(t *testing.T) {
cfg := asyncConfig()
cfg.AllGroups = false
cfg.GroupIDs = []int64{1}
resume := make(chan struct{})
store := &memoryTestGatedConfig{fakeConfigStore: &fakeConfigStore{cfg: cfg, active: true}, resume: resume}
repo := &fakeJobRepository{}
svc := memoryTestPromptService(cfg, repo)
svc.config, svc.enqueuer.config = store, store
groupID := int64(1)
req := asyncRequest()
req.GroupID = &groupID
want, err := ExtractPromptSnapshot(req)
require.NoError(t, err)
legacy := memoryTestLegacyMutation{mutate: func(borrowed Request) {
borrowed.Body[0] = '!'
*borrowed.GroupID = 2
close(resume)
}}
decision := NewCoordinator(legacy, svc).Check(context.Background(), req)
svc.enqueueWG.Wait()
require.True(t, decision.AllowNextStage)
require.Equal(t, AuditMetricsSnapshot{Enqueued: 1}, svc.metrics.AuditSnapshot())
require.Equal(t, want.PromptHash, repo.createdSnapshot.PromptHash)
require.Equal(t, int64(1), *repo.createdSnapshot.GroupID)
}
func TestAsyncAuditConcurrentRequestsStillEnqueueWithoutNewDrops(t *testing.T) {
svc := memoryTestPromptService(asyncConfig(), &fakeJobRepository{})
coordinator := NewCoordinator(nil, svc)
req := asyncRequest()
var callers sync.WaitGroup
for i := 0; i < 8; i++ {
callers.Add(1)
go func() { defer callers.Done(); coordinator.Check(context.Background(), req) }()
}
callers.Wait()
svc.enqueueWG.Wait()
require.Equal(t, AuditMetricsSnapshot{Enqueued: 8}, svc.metrics.AuditSnapshot())
}
func originalTrimRunesForMemoryTest(value string, limit int) string {
if limit <= 0 {
return ""
}
runes := []rune(value)
if len(runes) <= limit {
return value
}
return string(runes[:limit]) + "…"
}
func originalRedactForMemoryTest(value string, limit int) string {
value = bearerPattern.ReplaceAllString(value, "Bearer ***")
value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string {
if index := strings.IndexAny(match, ":= \t"); index >= 0 {
return match[:index+1] + "***"
}
return "***"
})
value = canaryPattern.ReplaceAllString(value, "${1}***")
value = emailPattern.ReplaceAllString(value, "***@***")
value = phonePattern.ReplaceAllString(value, "***PHONE***")
return originalTrimRunesForMemoryTest(value, limit)
}
func TestAuditTextOptimizationsMatchOriginalOnDeterministicCorpus(t *testing.T) {
rng := rand.New(rand.NewSource(20261111))
atoms := []string{"x", "中文", "😀", " ", "\xff\xfe", "\x00", "Bearer abcdefghijklmnop", " secret:abcdefghijkl ", " user@example.org ", " +86 138 1234 5678 ", promptAuditPrioritySeparator}
for sample := 0; sample < 100; sample++ {
var builder strings.Builder
for n := rng.Intn(128); n > 0; n-- {
_, _ = builder.WriteString(atoms[rng.Intn(len(atoms))])
}
value := builder.String()
for _, limit := range []int{0, 1, 24, 96, 4000} {
require.Equal(t, originalTrimRunesForMemoryTest(value, limit), TrimRunes(value, limit))
require.Equal(t, originalRedactForMemoryTest(value, limit), RedactPreview(value, limit))
var want []string
if limit > 0 {
want = []string{}
for _, segment := range strings.Split(value, promptAuditPrioritySeparator) {
runes := []rune(segment)
for start := 0; start < len(runes); start += limit {
want = append(want, string(runes[start:min(start+limit, len(runes))]))
}
}
}
require.Equal(t, want, SplitRunes(value, limit))
}
}
}
@@ -5,6 +5,7 @@ import (
"sort"
"strings"
"time"
"unicode/utf8"
)
func SplitRunes(value string, limit int) []string {
@@ -14,18 +15,28 @@ func SplitRunes(value string, limit int) []string {
segments := strings.Split(value, promptAuditPrioritySeparator)
chunks := make([]string, 0, len(segments))
for _, segment := range segments {
runes := []rune(segment)
for start := 0; start < len(runes); start += limit {
end := start + limit
if end > len(runes) {
end = len(runes)
start, count := 0, 0
for end := range segment {
if count == limit {
chunks = append(chunks, promptScanChunk(segment[start:end]))
start, count = end, 0
}
chunks = append(chunks, string(runes[start:end]))
count++
}
if start < len(segment) {
chunks = append(chunks, promptScanChunk(segment[start:]))
}
}
return chunks
}
func promptScanChunk(value string) string {
if utf8.ValidString(value) {
return value // immutable substring; no full-transcript rune buffer/copy
}
return string([]rune(value)) // preserve the previous invalid-UTF-8 behavior
}
func AggregateResults(results []*NormalizedResult, latency time.Duration) (*NormalizedResult, error) {
if len(results) == 0 {
return nil, errors.New("prompt guard produced no complete result")
@@ -112,6 +112,21 @@ func (s *PromptService) Enqueue(_ context.Context, req Request) error {
if s == nil || s.enqueuer == nil || s.EffectiveMode() != ModeAsync {
return nil
}
// Enqueuer rechecks configuration before persistence. Check it here too so
// requests outside the audit scope never copy their potentially large body.
cfg, ok := s.config.Active()
if !ok || cfg.EffectiveMode() != ModeAsync {
return nil
}
if !cfg.IncludesGroup(req.GroupID) {
LogInfo(EventEnqueueSkipped, mergeLogFields(requestLogFields(req), map[string]any{"config_version": cfg.ConfigVersion, "status": "skipped", "error_code": "group_out_of_scope"}))
return nil
}
if len(cfg.EnabledEndpoints()) == 0 {
s.enqueuer.recordDropped()
LogWarn(EventEnqueueDropped, mergeLogFields(requestLogFields(req), map[string]any{"config_version": cfg.ConfigVersion, "status": "dropped", "error_code": "no_enabled_endpoint"}))
return nil
}
select {
case s.enqueueSlots <- struct{}{}:
default:
@@ -636,16 +636,29 @@ func systemPromptSegments(texts []string) []promptSegment {
}
func RedactPreview(value string, maxRunes int) string {
value = bearerPattern.ReplaceAllString(value, "Bearer ***")
value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string {
if index := strings.IndexAny(match, ":= \t"); index >= 0 {
return match[:index+1] + "***"
}
return "***"
})
value = canaryPattern.ReplaceAllString(value, "${1}***")
value = emailPattern.ReplaceAllString(value, "***@***")
value = phonePattern.ReplaceAllString(value, "***PHONE***")
// ReplaceAllString copies even an unchanged input. Most prompts do not
// match these patterns, so avoid ten full-text allocations just to build a
// short preview. Preserve the replacement order and complete-input matching.
if bearerPattern.MatchString(value) {
value = bearerPattern.ReplaceAllString(value, "Bearer ***")
}
if apiKeyPattern.MatchString(value) {
value = apiKeyPattern.ReplaceAllStringFunc(value, func(match string) string {
if index := strings.IndexAny(match, ":= \t"); index >= 0 {
return match[:index+1] + "***"
}
return "***"
})
}
if canaryPattern.MatchString(value) {
value = canaryPattern.ReplaceAllString(value, "${1}***")
}
if emailPattern.MatchString(value) {
value = emailPattern.ReplaceAllString(value, "***@***")
}
if phonePattern.MatchString(value) {
value = phonePattern.ReplaceAllString(value, "***PHONE***")
}
return TrimRunes(value, maxRunes)
}
@@ -713,11 +726,21 @@ func TrimRunes(value string, limit int) string {
if limit <= 0 {
return ""
}
runes := []rune(value)
if len(runes) <= limit {
return value
count := 0
for index := range value {
if count == limit {
// Decode only the retained prefix. Converting the entire prompt to
// []rune just to keep 96/65536 runes allocates four bytes per rune.
// Keep the old replacement behavior for invalid UTF-8 prefixes.
prefix := value[:index]
if utf8.ValidString(prefix) {
return prefix + "…"
}
return string([]rune(prefix)) + "…"
}
count++
}
return string(runes[:limit]) + "…"
return value
}
func stringValue(value any) string {
+1 -1
View File
@@ -1502,7 +1502,7 @@ func newContractDeps(t *testing.T) *contractDeps {
settingRepo := newStubSettingRepo()
settingService := service.NewSettingService(settingRepo, cfg)
adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
adminService := service.NewAdminService(nil, userRepo, groupRepo, &accountRepo, proxyRepo, apiKeyRepo, redeemRepo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
authHandler := handler.NewAuthHandler(cfg, nil, userService, settingService, nil, redeemService, nil, nil)
apiKeyHandler := handler.NewAPIKeyHandler(apiKeyService)
usageHandler := handler.NewUsageHandler(usageService, apiKeyService, nil, nil)
@@ -141,8 +141,9 @@ func TestGroupModelAllowlistRequestBodyTooLargePassesThrough413(t *testing.T) {
if w.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("expected 413, got %d: %s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), "Request body is too large") {
t.Fatalf("expected too-large message, got %s", w.Body.String())
// 与 handler 读取失败时一致:Messages 入口用 Anthropic 格式,文案带上限。
if !strings.Contains(w.Body.String(), "Request body too large, limit is 64B") || !strings.Contains(w.Body.String(), `"type":"error"`) {
t.Fatalf("expected Anthropic-shaped too-large message, got %s", w.Body.String())
}
if len(*calls) != 0 {
t.Fatalf("expected handler not to run, got %v", *calls)
@@ -29,6 +29,8 @@ const (
IngressRejectInvalidAuthRateLimited IngressRejectReason = "invalid_auth_rate_limited"
IngressRejectAPIKeyAuthOverloaded IngressRejectReason = "api_key_auth_overloaded"
IngressRejectModelNotAllowed IngressRejectReason = "model_not_allowed"
// IngressRejectConflictingRequestFields:请求体同名字段重复声明(GHSA-p3r4-jcm3-2hph)。
IngressRejectConflictingRequestFields IngressRejectReason = "conflicting_request_fields"
)
const ingressRejectReasonContextKey = "ingress_reject_reason"
@@ -9,13 +9,16 @@ import (
// AbortWithRequestBodyReadFailure writes the shared response for a failed body
// read in middleware that inspects the body before the handler. It applies the
// same classification and payload-free diagnostics as the gateway handlers.
// same classification, client message, protocol-shaped error body and
// payload-free diagnostics as the gateway handlers, so a body read in
// middleware fails exactly as it would in the handler.
func AbortWithRequestBodyReadFailure(c *gin.Context, component string, err error) {
failure := httputil.DescribeRequestBodyReadFailure(c.Request, err)
if failure.Kind != httputil.RequestBodyReadErrorMaxBytes {
logRequestBodyReadFailure(c, component, failure)
}
c.AbortWithStatusJSON(failure.Status, gin.H{"error": gin.H{"type": "invalid_request_error", "message": failure.Message}})
writeGatewayInvalidRequest(c, failure.Status, failure.ClientMessage())
c.Abort()
}
func logRequestBodyReadFailure(c *gin.Context, component string, failure httputil.RequestBodyReadFailure) {
@@ -0,0 +1,95 @@
package middleware
import (
"fmt"
"net/http"
"strings"
"github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
"github.com/Wei-Shaw/sub2api/internal/pkg/requestmodel"
"github.com/gin-gonic/gin"
)
// RejectConflictingRequestFields 拒绝「同名字段重复声明」的网关请求。
//
// 挂载位置:每条网关链的 GroupModelAllowlist 之后、compositeTarget 之前,
// 白名单对不在名单内的模型仍按原有格式拒绝。与白名单准入不同,这里对所有分组
// 生效:重复 model 键让计费模型(gjson 取第一个)和实际转发的模型
// (encoding/json 重新序列化后取最后一个)分叉,和分组是否开启白名单无关;
// service_tier、reasoning.effort 等按首个值做计费/策略判断、由 sjson 只改首个的
// 字段也是如此(GHSA-p3r4-jcm3-2hph)。
//
// 行为:
// - 只检查带请求体的方法(POST/PUT/PATCH)。
// - JSON 按内容识别(不看 Content-Type),开头的 UTF-8 BOM 在这里剥掉后回填
// (PrereadBody,下游零拷贝重读),与 handler 宽容读取的规则一致,保证
// 合成路由、handler 与这里检查的是同一份字节。
// - 判定规则见 requestmodel.ConflictingField;不是 JSON 也不是 multipart 的
// 请求体放行,交给 handler 自己校验。
// - 拒绝:按入口协议格式返回 400,标记 ingress 拒绝原因
// conflicting_request_fields,请求不会进入合成路由、调度和计费。
//
// Responses WebSocket 的帧不经过这里,由 ResponsesWebSocket 对每一帧执行同一规则。
func RejectConflictingRequestFields() gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request == nil || c.Request.Body == nil || c.Request.Body == http.NoBody {
c.Next()
return
}
switch c.Request.Method {
case http.MethodPost, http.MethodPut, http.MethodPatch:
default:
c.Next()
return
}
body, err := httputil.ReadRequestBodyWithPrealloc(c.Request)
if err != nil {
if RejectRequestBodyReadError(c, "middleware.request_field_conflict", err) {
return
}
AbortWithRequestBodyReadFailure(c, "middleware.request_field_conflict", err)
return
}
if doc := requestmodel.TrimUTF8BOM(body); len(doc) != len(body) && requestmodel.LooksLikeJSON(doc) {
body = doc
}
requestmodel.ResetRequestBody(c.Request, body)
field, conflict := requestmodel.ConflictingField(c.GetHeader("Content-Type"), body)
if !conflict {
c.Next()
return
}
MarkIngressRejected(c, IngressRejectConflictingRequestFields)
// 字段名来自客户端请求体,回显时加引号并限制在 64 个字符以内。
writeGatewayInvalidRequest(c, http.StatusBadRequest, fmt.Sprintf("Request body declares field %.64q more than once", field))
c.Abort()
}
}
// writeGatewayInvalidRequest 按入口协议输出 invalid_request_error:
// Gemini 原生(/v1beta、/antigravity/v1beta)用 Google 格式,Messages 入口用
// Anthropic 格式,其余用 OpenAI 格式。协议划分与 groupModelAllowlistErrorWriter
// 相同;不复用它,是因为现有的 Anthropic / OpenAI 写入器把非 404/403 的状态写成
// api_error / model_not_found。
func writeGatewayInvalidRequest(c *gin.Context, status int, message string) {
path := ""
if c.Request != nil && c.Request.URL != nil {
path = c.Request.URL.Path
}
switch {
case strings.HasPrefix(path, "/v1beta") || strings.HasPrefix(path, "/antigravity/v1beta"):
GoogleErrorWriter(c, status, message)
case strings.Contains(path, "/messages"):
c.JSON(status, gin.H{
"type": "error",
"error": gin.H{"type": "invalid_request_error", "message": message},
})
default:
c.JSON(status, gin.H{
"error": gin.H{"type": "invalid_request_error", "message": message},
})
}
}
@@ -0,0 +1,282 @@
package middleware
import (
"bytes"
"mime/multipart"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/httputil"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)
// newRequestFieldConflictTestRouter 按网关链的顺序挂载:白名单准入在前,
// 字段歧义拒绝在后。handlerBodies 记录 handler 实际读到的请求体。
func newRequestFieldConflictTestRouter(apiKey *service.APIKey) (*gin.Engine, *[]string) {
gin.SetMode(gin.TestMode)
router := gin.New()
var handlerBodies []string
router.Use(func(c *gin.Context) {
if apiKey != nil {
c.Set(string(ContextKeyAPIKey), apiKey)
}
c.Next()
})
router.Use(GroupModelAllowlist())
router.Use(RejectConflictingRequestFields())
handler := func(c *gin.Context) {
body, _ := httputil.ReadRequestBodyWithPrealloc(c.Request)
handlerBodies = append(handlerBodies, string(body))
c.Status(http.StatusOK)
}
for _, path := range []string{
"/v1/messages", "/v1/responses", "/v1/chat/completions", "/v1/images/edits", "/v1/live",
"/v1beta/models/*modelAction",
} {
router.POST(path, handler)
}
router.GET("/v1/models", handler)
return router, &handlerBodies
}
// 复现报告的请求体:第一个 model 是便宜模型,最后一个是贵模型。分组没有开启
// 白名单时旧行为是放行并按第一个计费,现在必须在进入 handler 之前拒绝。
func TestRejectConflictingRequestFieldsBlocksDisagreeingModelWithoutAllowlist(t *testing.T) {
for _, apiKey := range []*service.APIKey{nil, {}, allowlistAPIKey(false)} {
router, handlerBodies := newRequestFieldConflictTestRouter(apiKey)
w := doJSON(t, router, http.MethodPost, "/v1/responses",
`{"model":"gpt-5.4-nano","stream":false,"input":"hi","model":"gpt-5.4"}`)
if w.Code != http.StatusBadRequest {
t.Fatalf("conflicting model keys must be rejected, got %d: %s", w.Code, w.Body.String())
}
if !strings.Contains(w.Body.String(), `\"model\"`) || !strings.Contains(w.Body.String(), "invalid_request_error") {
t.Fatalf("expected the field name and invalid_request_error, got %s", w.Body.String())
}
if len(*handlerBodies) != 0 {
t.Fatalf("expected handler not to run, got %v", *handlerBodies)
}
}
}
// 白名单开启且两个模型都在名单内时,白名单会放行;字段歧义检查仍要拒绝,
// 否则计费模型和转发模型照样分叉。
func TestRejectConflictingRequestFieldsBlocksEvenWhenAllCandidatesAllowlisted(t *testing.T) {
router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(true, "claude-3-5-haiku-20241022", "claude-opus-4-8"))
w := doJSON(t, router, http.MethodPost, "/v1/messages",
`{"model":"claude-3-5-haiku-20241022","max_tokens":64,"messages":[{"role":"user","content":"hi"}],"model":"claude-opus-4-8"}`)
if w.Code != http.StatusBadRequest {
t.Fatalf("conflicting model keys must be rejected, got %d: %s", w.Code, w.Body.String())
}
if len(*handlerBodies) != 0 {
t.Fatalf("expected handler not to run, got %v", *handlerBodies)
}
}
func TestRejectConflictingRequestFieldsCoversOtherFields(t *testing.T) {
router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false))
for _, body := range []string{
`{"model":"gpt-5.4","service_tier":"default","input":"hi","service_tier":"priority"}`,
`{"model":"gpt-5.4","Model":"gpt-5.4-nano"}`,
`{"model":"gpt-5.4","messages":[],"messages":[{"role":"user","content":"hi"}]}`,
} {
w := doJSON(t, router, http.MethodPost, "/v1/chat/completions", body)
if w.Code != http.StatusBadRequest {
t.Fatalf("body %s must be rejected, got %d: %s", body, w.Code, w.Body.String())
}
}
if len(*handlerBodies) != 0 {
t.Fatalf("expected handler not to run, got %v", *handlerBodies)
}
}
func TestRejectConflictingRequestFieldsErrorFormats(t *testing.T) {
router, _ := newRequestFieldConflictTestRouter(allowlistAPIKey(false))
body := `{"model":"a","contents":[],"model":"b"}`
openai := doJSON(t, router, http.MethodPost, "/v1/responses", body)
if !strings.Contains(openai.Body.String(), `"error":{"message"`) || strings.Contains(openai.Body.String(), "model_not_found") {
t.Fatalf("unexpected OpenAI error format: %s", openai.Body.String())
}
anthropic := doJSON(t, router, http.MethodPost, "/v1/messages", body)
if !strings.Contains(anthropic.Body.String(), `"type":"error"`) || !strings.Contains(anthropic.Body.String(), `"type":"invalid_request_error"`) {
t.Fatalf("unexpected Anthropic error format: %s", anthropic.Body.String())
}
google := doJSON(t, router, http.MethodPost, "/v1beta/models/gemini-2.5-pro:generateContent", body)
if google.Code != http.StatusBadRequest || !strings.Contains(google.Body.String(), `"status":"INVALID_ARGUMENT"`) {
t.Fatalf("unexpected Google error format: %d %s", google.Code, google.Body.String())
}
}
// 普通请求体和非对象请求体都放行,handler 读到的请求体与客户端发送的完全一致。
func TestRejectConflictingRequestFieldsPassesUnambiguousBodiesUnchanged(t *testing.T) {
for _, body := range []string{
`{"model":"gpt-5.4","input":"hi"}`,
`{"model":"gpt-5.4","prompt":{"id":"p","variables":{"k":"1","K":"1"}}}`,
`not json`,
``,
} {
router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false))
w := doJSON(t, router, http.MethodPost, "/v1/responses", body)
if w.Code != http.StatusOK {
t.Fatalf("body %q should pass, got %d: %s", body, w.Code, w.Body.String())
}
if len(*handlerBodies) != 1 || (*handlerBodies)[0] != body {
t.Fatalf("handler must read the original body %q, got %v", body, *handlerBodies)
}
}
}
func TestRejectConflictingRequestFieldsMultipart(t *testing.T) {
send := func(models ...string) *httptest.ResponseRecorder {
router, _ := newRequestFieldConflictTestRouter(allowlistAPIKey(false))
var body bytes.Buffer
writer := multipart.NewWriter(&body)
for _, model := range models {
_ = writer.WriteField("model", model)
}
_ = writer.WriteField("prompt", "cat")
_ = writer.Close()
req := httptest.NewRequest(http.MethodPost, "/v1/images/edits", &body)
req.Header.Set("Content-Type", writer.FormDataContentType())
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
if w := send("gpt-image-1", "gpt-image-1.5"); w.Code != http.StatusBadRequest {
t.Fatalf("conflicting multipart model fields must be rejected, got %d: %s", w.Code, w.Body.String())
}
if w := send("gpt-image-1", "gpt-image-1"); w.Code != http.StatusBadRequest {
t.Fatalf("repeated multipart model fields must be rejected even when identical, got %d: %s", w.Code, w.Body.String())
}
if w := send("gpt-image-1"); w.Code != http.StatusOK {
t.Fatalf("single multipart model field should pass, got %d: %s", w.Code, w.Body.String())
}
}
func TestRejectConflictingRequestFieldsLiveSessionModel(t *testing.T) {
router, _ := newRequestFieldConflictTestRouter(allowlistAPIKey(false))
w := doJSON(t, router, http.MethodPost, "/v1/live", `{"sdp":"v=0","session":{"model":"gpt-live-a","model":"gpt-live-b"}}`)
if w.Code != http.StatusBadRequest || !strings.Contains(w.Body.String(), "session.model") {
t.Fatalf("conflicting session.model must be rejected, got %d: %s", w.Code, w.Body.String())
}
}
// GET/DELETE 不带需要检查的请求体:中间件不读取,直接放行。
func TestRejectConflictingRequestFieldsDoesNotReadBodylessMethods(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(RejectConflictingRequestFields())
called := false
router.GET("/v1/models", func(c *gin.Context) {
called = true
c.Status(http.StatusOK)
})
body := &readTrackingBody{Reader: strings.NewReader(`{"model":"a","model":"b"}`)}
req := httptest.NewRequest(http.MethodGet, "/v1/models", body)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusOK || !called {
t.Fatalf("GET must reach the handler, got %d", w.Code)
}
if body.read {
t.Fatal("middleware must not read the body of a GET request")
}
}
// 413 传递:请求体超过上限时保持现有的 413 响应,不被改写成 400。
func TestRejectConflictingRequestFieldsRequestBodyTooLargePassesThrough413(t *testing.T) {
router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false))
bigBody := `{"model":"a","padding":"` + strings.Repeat("x", 512) + `","model":"b"}`
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(bigBody))
req.Header.Set("Content-Type", "application/json")
req.Body = http.MaxBytesReader(httptest.NewRecorder(), req.Body, 64)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("expected 413, got %d: %s", w.Code, w.Body.String())
}
// 与 handler 读取失败时一致:Messages 入口用 Anthropic 格式,文案带上限。
if !strings.Contains(w.Body.String(), `"type":"error"`) || !strings.Contains(w.Body.String(), "Request body too large, limit is 64B") {
t.Fatalf("expected an Anthropic-shaped 413 naming the limit, got %s", w.Body.String())
}
if len(*handlerBodies) != 0 {
t.Fatalf("expected handler not to run, got %v", *handlerBodies)
}
}
// 取值相同的重复字段同样拒绝:网关的 sjson 改写(推理强度降级、模型映射、
// fast policy 删除 service_tier)只改首个,改写后两者就会分叉。
func TestRejectConflictingRequestFieldsRejectsIdenticalDuplicates(t *testing.T) {
for _, body := range []string{
`{"model":"gpt-5.4","input":"hi","model":"gpt-5.4"}`,
`{"model":"gpt-5.4","input":"hi","reasoning":{"effort":"xhigh","effort":"xhigh"}}`,
`{"model":"gpt-5.4","service_tier":"priority","input":"hi","service_tier":"priority"}`,
} {
router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false))
w := doJSON(t, router, http.MethodPost, "/v1/responses", body)
if w.Code != http.StatusBadRequest || len(*handlerBodies) != 0 {
t.Fatalf("body %q must be rejected before the handler, got %d: %s", body, w.Code, w.Body.String())
}
}
}
// JSON handler 不看 Content-Type:把 JSON 请求体标成 multipart 不能绕过检查。
func TestRejectConflictingRequestFieldsIgnoresMultipartLabelOnJSONBody(t *testing.T) {
for _, contentType := range []string{"multipart/form-data", "multipart/form-data; boundary=zzz", "text/plain"} {
router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false))
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(`{"model":"haiku","messages":[],"model":"opus"}`))
req.Header.Set("Content-Type", contentType)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest || len(*handlerBodies) != 0 {
t.Fatalf("Content-Type %q must not bypass the check, got %d: %s", contentType, w.Code, w.Body.String())
}
}
}
// BOM 在这里剥掉后回填:合成路由与 handler 读到的是本层检查过的同一份字节。
func TestRejectConflictingRequestFieldsStripsBOMForDownstream(t *testing.T) {
router, handlerBodies := newRequestFieldConflictTestRouter(allowlistAPIKey(false))
w := doJSON(t, router, http.MethodPost, "/v1/responses", "\xef\xbb\xbf"+`{"model":"gpt-5.4","input":"hi"}`)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
}
if len(*handlerBodies) != 1 || (*handlerBodies)[0] != `{"model":"gpt-5.4","input":"hi"}` {
t.Fatalf("handler must read the BOM-free body, got %q", *handlerBodies)
}
w = doJSON(t, router, http.MethodPost, "/v1/responses", "\xef\xbb\xbf"+`{"model":"a","input":"hi","model":"b"}`)
if w.Code != http.StatusBadRequest {
t.Fatalf("BOM-prefixed duplicate must be rejected, got %d: %s", w.Code, w.Body.String())
}
}
func TestRejectConflictingRequestFieldsMarksIngressReject(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
var reason any
router.Use(func(c *gin.Context) {
c.Next()
reason, _ = c.Get(ingressRejectReasonContextKey)
})
router.Use(RejectConflictingRequestFields())
router.POST("/v1/responses", func(c *gin.Context) { c.Status(http.StatusOK) })
w := doJSON(t, router, http.MethodPost, "/v1/responses", `{"model":"a","model":"b"}`)
if w.Code != http.StatusBadRequest || reason != IngressRejectConflictingRequestFields {
t.Fatalf("expected 400 with ingress reason %q, got %d reason=%v", IngressRejectConflictingRequestFields, w.Code, reason)
}
}
@@ -426,3 +426,83 @@ func TestCompositeLiveRouteDispatchesBySessionModelNotTopLevelAlias(t *testing.T
require.Equal(t, http.StatusNoContent, w.Code)
}
// A route that rewrites the model to a Claude 5.5 model also rewrites a
// thinking mode that model rejects into the nearest one it accepts; a route
// that keeps the client's model leaves thinking as the client sent it.
func TestCompositeTargetPlatformMiddlewareAdaptsThinkingToRewrittenModel(t *testing.T) {
cases := []struct {
name string
publicModel string
upstreamModel string
thinking string
wantThinking string
}{
{
name: "enabled becomes adaptive on opus 5.5",
publicModel: "claude-sonnet-5",
upstreamModel: "claude-opus-5-5",
thinking: `{"type":"enabled","budget_tokens":4096}`,
wantThinking: `{"type":"adaptive"}`,
},
{
name: "disabled becomes between_tools on sonnet 5.5",
publicModel: "claude-sonnet-5",
upstreamModel: "claude-sonnet-5-5",
thinking: `{"type":"disabled"}`,
wantThinking: `{"type":"between_tools"}`,
},
{
name: "model not rewritten keeps enabled",
publicModel: "claude-opus-5-5",
upstreamModel: "claude-opus-5-5",
thinking: `{"type":"enabled","budget_tokens":4096}`,
wantThinking: `{"type":"enabled","budget_tokens":4096}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
resolver := service.NewCompositeRouteResolver(compositeRouteRepoStub{
routes: []service.CompositeModelRoute{{
ID: 1,
GroupID: 1,
PublicModel: tc.publicModel,
MatchType: service.CompositeRouteMatchExact,
TargetPlatform: service.PlatformAnthropic,
UpstreamModel: tc.upstreamModel,
Endpoint: service.CompositeRouteEndpointAny,
Priority: 100,
Enabled: true,
}},
})
router.Use(gin.HandlerFunc(servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
groupID := int64(1)
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{
GroupID: &groupID,
Group: &service.Group{ID: groupID, Platform: service.PlatformComposite},
})
c.Next()
})))
router.Use(compositeTargetPlatformMiddleware(resolver))
router.POST("/v1/messages", func(c *gin.Context) {
body, err := io.ReadAll(c.Request.Body)
require.NoError(t, err)
require.JSONEq(t,
`{"model":"`+tc.upstreamModel+`","max_tokens":64,"thinking":`+tc.wantThinking+`,"messages":[]}`,
string(body))
c.Status(http.StatusNoContent)
})
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(
`{"model":"`+tc.publicModel+`","max_tokens":64,"thinking":`+tc.thinking+`,"messages":[]}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNoContent, w.Code)
})
}
}
@@ -169,7 +169,7 @@ func (r *scopedRouteAllowlistRepository) ScopedAdminUpdateGroupModels(ctx contex
func TestScopedAdminRegisteredGroupModelsUseUpstreamAllowlistSemantics(t *testing.T) {
gin.SetMode(gin.TestMode)
repo := &scopedRouteAllowlistRepository{}
api := service.NewAdminService(nil, nil, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
api := service.NewAdminService(nil, nil, repo, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
settings := service.NewSettingService(nil, nil)
settings.SetScopedAdminKeyRepository(&scopedRouteKeys{})
key, _, err := settings.CreateScopedAdminKey(context.Background(), service.ScopedAdminKeyInput{Name: "白名单验证", Enabled: true, Policy: adminaccess.Policy{Rules: []adminaccess.Rule{{Permissions: []string{"groups.models.read", "groups.models.write"}, GroupIDs: []int64{2}, Platforms: []string{service.PlatformOpenAI}}}}}, 9)
+33 -12
View File
@@ -15,7 +15,6 @@ import (
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
// RegisterGatewayRoutes 注册 API 网关路由(Claude/OpenAI/Gemini 兼容)
@@ -33,6 +32,21 @@ func RegisterGatewayRoutes(
bodyMemoryBudget := pkghttputil.NewBodyMemoryBudget(cfg.Gateway.RequestBodyMemoryBudgetBytes)
bodyLimit := middleware.RequestBodyLimit(cfg.Gateway.MaxBodySize, bodyMemoryBudget)
textBodyLimit := middleware.RequestBodyLimit(cfg.Gateway.TextMaxBodySize, bodyMemoryBudget)
// 分组链上的中间件(白名单、字段歧义检查、合成路由)会在 handler 之前读完
// 请求体,路由级的上限来不及生效;纯文本入口的上限必须在分组层按路由选择。
textBodyRoutes := map[string]bool{
"/v1/systemone": true,
"/v1/alpha/search": true,
"/v1/embeddings": true,
"/backend-api/codex/alpha/search": true,
}
groupBodyLimit := func(c *gin.Context) {
if textBodyRoutes[c.FullPath()] {
textBodyLimit(c)
return
}
bodyLimit(c)
}
clientRequestID := middleware.ClientRequestID()
opsErrorLogger := handler.OpsErrorLoggerMiddleware(opsService)
endpointNorm := handler.InboundEndpointMiddleware()
@@ -47,6 +61,11 @@ func RegisterGatewayRoutes(
// 保证校验发生在合成路由改写与调度之前,且只看客户端书写的模型名。
groupModelAllowlist := middleware.GroupModelAllowlist()
// 请求体字段歧义拒绝:同名字段重复且取值不一致(如两个不同的 model)时,
// 计费读到的值和实际转发的值会分叉。对所有分组生效,紧跟在白名单准入之后、
// 合成路由改写之前,白名单的拒绝响应保持不变。
rejectConflictingFields := middleware.RejectConflictingRequestFields()
// 单目标与账号池统一走 dispatcher:池候选全属 OpenAI 兼容族进 OpenAI
// CountTokens,其余(跨族池 / 非兼容族单目标)落通用网关。
countTokensHandler := func(c *gin.Context) {
@@ -170,13 +189,14 @@ func RegisterGatewayRoutes(
// API网关(Claude API兼容)
gateway := r.Group("/v1")
gateway.Use(bodyLimit)
gateway.Use(groupBodyLimit)
gateway.Use(clientRequestID)
gateway.Use(opsErrorLogger)
gateway.Use(endpointNorm)
gateway.Use(gin.HandlerFunc(apiKeyAuth))
gateway.GET("/sub2api/billing", h.Gateway.KeyBillingInfo)
gateway.Use(groupModelAllowlist)
gateway.Use(rejectConflictingFields)
gateway.Use(compositeTarget)
gateway.Use(requireGroupAnthropic)
{
@@ -184,8 +204,8 @@ func RegisterGatewayRoutes(
gateway.POST("/messages", func(c *gin.Context) {
dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Messages, h.Gateway.Messages)
})
// System One carries only JSON text, so it uses the text body limit.
gateway.POST("/systemone", textBodyLimit, h.Gateway.SystemOne)
// System One carries only JSON text; groupBodyLimit applies the text body limit.
gateway.POST("/systemone", h.Gateway.SystemOne)
// /v1/messages/count_tokens: OpenAI bridges upstream, Grok estimates
// locally, and Anthropic-compatible platforms retain their existing path.
gateway.POST("/messages/count_tokens", countTokensHandler)
@@ -205,7 +225,7 @@ func RegisterGatewayRoutes(
gateway.POST("/responses/*subpath", guardResponsesSubpath(func(c *gin.Context) {
dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.Responses, h.Gateway.Responses)
}))
gateway.POST("/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch)
gateway.POST("/alpha/search", h.OpenAIGateway.AlphaSearch)
gateway.GET("/responses", func(c *gin.Context) {
h.OpenAIGateway.ResponsesWebSocket(c)
})
@@ -213,7 +233,7 @@ func RegisterGatewayRoutes(
gateway.POST("/chat/completions", func(c *gin.Context) {
dispatchOpenAICompatibleGateway(c, h.OpenAIGateway.ChatCompletions, h.Gateway.ChatCompletions)
})
gateway.POST("/embeddings", textBodyLimit, func(c *gin.Context) {
gateway.POST("/embeddings", func(c *gin.Context) {
if !isOpenAIOnlyEndpointGatewayPlatform(c) {
service.MarkOpsClientBusinessLimited(c, service.OpsClientBusinessLimitedReasonLocalFeatureGate)
c.JSON(http.StatusNotFound, gin.H{
@@ -318,6 +338,7 @@ func RegisterGatewayRoutes(
gemini.Use(endpointNorm)
gemini.Use(middleware.APIKeyAuthWithSubscriptionGoogle(apiKeyService, subscriptionService, cfg))
gemini.Use(groupModelAllowlist)
gemini.Use(rejectConflictingFields)
gemini.Use(compositeGeminiTarget)
gemini.Use(requireGroupGoogle)
{
@@ -340,7 +361,7 @@ func RegisterGatewayRoutes(
// 根路径别名共用中间件链:白名单准入在 apiKeyAuth 之后、compositeTarget
// 之前,避免逐条路由手工维护链导致漏挂。
rootRoute := func(method, path string, limit gin.HandlerFunc, handler gin.HandlerFunc) {
r.Handle(method, path, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic, handler)
r.Handle(method, path, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, rejectConflictingFields, compositeTarget, requireGroupAnthropic, handler)
}
for _, prefix := range []string{"/api/v3", "/v3", "/v1", ""} {
rootRoute(http.MethodPost, prefix+"/contents/generations/tasks", bodyLimit, h.OpenAIGateway.SeedanceTasks)
@@ -357,13 +378,13 @@ func RegisterGatewayRoutes(
rootRoute(http.MethodGet, "/models/:model", bodyLimit, h.Gateway.Models)
rootRoute(http.MethodPost, "/messages/count_tokens", bodyLimit, countTokensHandler)
codexDirect := r.Group("/backend-api/codex")
codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic)
codexDirect.Use(groupBodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, rejectConflictingFields, compositeTarget, requireGroupAnthropic)
{
codexDirect.POST("/realtime/calls", h.OpenAIGateway.Live)
codexDirect.GET("/:call_id", h.OpenAIGateway.LiveSideband)
codexDirect.POST("/responses", responsesHandler)
codexDirect.POST("/responses/*subpath", guardResponsesSubpath(responsesHandler))
codexDirect.POST("/alpha/search", textBodyLimit, h.OpenAIGateway.AlphaSearch)
codexDirect.POST("/alpha/search", h.OpenAIGateway.AlphaSearch)
codexDirect.GET("/responses", func(c *gin.Context) {
h.OpenAIGateway.ResponsesWebSocket(c)
})
@@ -467,6 +488,7 @@ func RegisterGatewayRoutes(
antigravityV1.Use(middleware.ForcePlatform(service.PlatformAntigravity))
antigravityV1.Use(gin.HandlerFunc(apiKeyAuth))
antigravityV1.Use(groupModelAllowlist)
antigravityV1.Use(rejectConflictingFields)
antigravityV1.Use(requireGroupAnthropic)
{
antigravityV1.POST("/messages", h.Gateway.Messages)
@@ -483,6 +505,7 @@ func RegisterGatewayRoutes(
antigravityV1Beta.Use(middleware.ForcePlatform(service.PlatformAntigravity))
antigravityV1Beta.Use(middleware.APIKeyAuthWithSubscriptionGoogle(apiKeyService, subscriptionService, cfg))
antigravityV1Beta.Use(groupModelAllowlist)
antigravityV1Beta.Use(rejectConflictingFields)
antigravityV1Beta.Use(requireGroupGoogle)
{
antigravityV1Beta.GET("/models", h.Gateway.GeminiV1BetaListModels)
@@ -689,9 +712,7 @@ func compositeTargetPlatformMiddleware(resolver *service.CompositeRouteResolver)
c.Request = c.Request.WithContext(service.WithCompositeRouteDecision(c.Request.Context(), decision))
if upstreamModel := strings.TrimSpace(decision.UpstreamModel); upstreamModel != "" && upstreamModel != model && gjson.ValidBytes(body) {
if _, modelPath := requestmodel.JSONModelPathForRoute(routePath, body); modelPath != "" {
if rewritten, rewriteErr := sjson.SetBytes(body, modelPath, upstreamModel); rewriteErr == nil {
body = rewritten
}
body = service.RewriteCompositeRequestModel(body, modelPath, upstreamModel)
}
}
}
@@ -69,7 +69,7 @@ func TestGatewayRoutesGroupModelAllowlistMountedOnEveryGatewayRoute(t *testing.T
source := string(routeSource)
// rootRoute helper:apiKeyAuth 之后、compositeTarget 之前。
rootHelper := regexp.MustCompile(regexp.QuoteMeta(`r.Handle(method, path, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic, handler)`))
rootHelper := regexp.MustCompile(regexp.QuoteMeta(`r.Handle(method, path, limit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, rejectConflictingFields, compositeTarget, requireGroupAnthropic, handler)`))
require.Regexp(t, rootHelper, source,
"root alias helper must place the allowlist between apiKeyAuth and compositeTarget")
@@ -94,7 +94,7 @@ func TestGatewayRoutesGroupModelAllowlistMountedOnEveryGatewayRoute(t *testing.T
}
// codexDirect 链是一条 Use 调用,直接断言顺序。
codexDirect := regexp.MustCompile(regexp.QuoteMeta(`codexDirect.Use(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, compositeTarget, requireGroupAnthropic)`))
codexDirect := regexp.MustCompile(regexp.QuoteMeta(`codexDirect.Use(groupBodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, rejectConflictingFields, compositeTarget, requireGroupAnthropic)`))
require.Regexp(t, codexDirect, source, "codexDirect chain must mount the allowlist after auth and before compositeTarget")
// 所有带 apiKeyAuth 的根路径路由必须收敛到 rootRoute,避免漏挂。
@@ -0,0 +1,238 @@
package routes
import (
"net/http"
"net/http/httptest"
"os"
"regexp"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/handler"
servermiddleware "github.com/Wei-Shaw/sub2api/internal/server/middleware"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// TestGatewayRoutesRejectConflictingFieldsMountedOnEveryGatewayRoute 沿用
// gateway_model_allowlist_test.go 的源码级断言:每条网关链都必须紧跟在白名单
// 准入之后挂载 rejectConflictingFields,这样它也在合成路由改写之前。
func TestGatewayRoutesRejectConflictingFieldsMountedOnEveryGatewayRoute(t *testing.T) {
routeSource, err := os.ReadFile("gateway.go")
require.NoError(t, err)
source := string(routeSource)
// 每一处白名单挂载点后面都紧跟着字段歧义拒绝,两者数量一致。
allowlistUses := regexp.MustCompile(`\bgroupModelAllowlist\b`).FindAllStringIndex(source, -1)
followedByConflict := regexp.MustCompile(`\bgroupModelAllowlist(\)\s+\w+\.Use\(|, )rejectConflictingFields\b`).FindAllStringIndex(source, -1)
// allowlistUses 里有一处是变量定义本身。
require.Len(t, followedByConflict, len(allowlistUses)-1,
"every chain that mounts groupModelAllowlist must mount rejectConflictingFields right after it")
require.GreaterOrEqual(t, len(followedByConflict), 6, "gateway, gemini, root aliases, codexDirect and both antigravity chains")
// 带合成路由改写的链:歧义拒绝必须在改写之前。
for _, chain := range []string{
`gateway.Use(rejectConflictingFields)` + "\n\t" + `gateway.Use(compositeTarget)`,
`gemini.Use(rejectConflictingFields)` + "\n\t" + `gemini.Use(compositeGeminiTarget)`,
`groupModelAllowlist, rejectConflictingFields, compositeTarget, requireGroupAnthropic, handler)`,
`groupModelAllowlist, rejectConflictingFields, compositeTarget, requireGroupAnthropic)`,
} {
require.Contains(t, source, chain)
}
}
// TestGatewayRoutesRejectConflictingFieldsCoversGatewayRoutes 用没有开启白名单
// 的分组请求各个入口:重复声明且取值不一致的 model 必须在进入 handler 之前
// 得到 400。分组不需要任何额外配置,这正是计费绕过的前提条件。
func TestGatewayRoutesRejectConflictingFieldsCoversGatewayRoutes(t *testing.T) {
router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(service.PlatformOpenAI, false))
const duplicate = `"model":"gpt-5.4-nano","input":"hi","model":"gpt-5.4"`
paths := []struct {
path string
body string
}{
{"/responses", `{` + duplicate + `}`},
{"/responses/compact", `{` + duplicate + `}`},
{"/chat/completions", `{` + duplicate + `}`},
{"/embeddings", `{` + duplicate + `}`},
{"/images/generations", `{` + duplicate + `}`},
{"/videos/generations", `{` + duplicate + `}`},
{"/messages/count_tokens", `{` + duplicate + `}`},
{"/tts", `{` + duplicate + `}`},
{"/alpha/search", `{` + duplicate + `}`},
{"/v1/responses", `{` + duplicate + `}`},
{"/v1/messages", `{` + duplicate + `}`},
{"/v1/messages/count_tokens", `{` + duplicate + `}`},
{"/v1/chat/completions", `{` + duplicate + `}`},
{"/v1/embeddings", `{` + duplicate + `}`},
{"/v1/images/generations", `{` + duplicate + `}`},
{"/v1/videos/generations", `{` + duplicate + `}`},
{"/v1/systemone", `{` + duplicate + `}`},
{"/v1/contents/generations/tasks", `{` + duplicate + `}`},
{"/api/v3/contents/generations/tasks", `{` + duplicate + `}`},
{"/v1/live", `{"sdp":"v=0","session":{"model":"gpt-live-a","model":"gpt-live-b"}}`},
{"/backend-api/codex/responses", `{` + duplicate + `}`},
{"/backend-api/codex/realtime/calls", `{"sdp":"v=0","session":{"model":"gpt-live-a","model":"gpt-live-b"}}`},
{"/antigravity/v1/messages", `{` + duplicate + `}`},
}
for _, tc := range paths {
req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code, "POST %s should be rejected, got body: %s", tc.path, w.Body.String())
require.Contains(t, w.Body.String(), "more than once", "POST %s", tc.path)
}
}
// 白名单开启时,不在名单内的模型仍由白名单按原有格式拒绝(404),不会被这层
// 改写成 400;两个候选都在名单内但取值不同时,由这层拒绝。
func TestGatewayRoutesRejectConflictingFieldsKeepsAllowlistResponse(t *testing.T) {
router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(service.PlatformOpenAI, true, "gpt-5.4", "gpt-5.4-nano"))
send := func(body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
blocked := send(`{"model":"gpt-5.4","input":"hi","model":"gpt-4.1"}`)
require.Equal(t, http.StatusNotFound, blocked.Code, blocked.Body.String())
require.Contains(t, blocked.Body.String(), "not available for this group")
bothAllowed := send(`{"model":"gpt-5.4-nano","input":"hi","model":"gpt-5.4"}`)
require.Equal(t, http.StatusBadRequest, bothAllowed.Code, bothAllowed.Body.String())
require.Contains(t, bothAllowed.Body.String(), "more than once")
}
// 取值相同的重复字段同样拒绝:网关的 sjson 改写只改首个,改写后两者就会分叉。
func TestGatewayRoutesRejectConflictingFieldsRejectsIdenticalDuplicates(t *testing.T) {
router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(service.PlatformOpenAI, false))
req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.4","input":"hi","reasoning":{"effort":"xhigh","effort":"xhigh"}}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
require.Contains(t, w.Body.String(), "reasoning.effort")
}
// 回归:Content-Type 标成 multipart 的 JSON 请求体,既不能绕过歧义检查,也不能
// 绕过分组白名单(此前白名单按请求头只做 multipart 解析,拿不到模型就放行)。
func TestGatewayRoutesMultipartLabelDoesNotBypassChecks(t *testing.T) {
send := func(group *service.Group, contentType, body string) *httptest.ResponseRecorder {
router := newGatewayRoutesTestRouterWithGroup(group)
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader(body))
req.Header.Set("Content-Type", contentType)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
for _, contentType := range []string{"multipart/form-data", "multipart/form-data; boundary=zzz"} {
w := send(allowlistGroup(service.PlatformAnthropic, false), contentType, `{"model":"claude-3-5-haiku-20241022","messages":[],"model":"claude-opus-4-8"}`)
require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
require.Contains(t, w.Body.String(), "more than once")
w = send(allowlistGroup(service.PlatformAnthropic, true, "claude-3-5-haiku-20241022"), contentType, `{"model":"claude-opus-4-8","messages":[]}`)
require.Equal(t, http.StatusNotFound, w.Code, w.Body.String())
require.Contains(t, w.Body.String(), "not available for this group")
}
}
// 回归:带 UTF-8 BOM 的请求体(handler 宽容读取会剥掉 BOM)不能绕过分组白名单。
func TestGatewayRoutesBOMDoesNotBypassAllowlist(t *testing.T) {
router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(service.PlatformAnthropic, true, "claude-3-5-haiku-20241022"))
req := httptest.NewRequest(http.MethodPost, "/v1/messages", strings.NewReader("\xef\xbb\xbf"+`{"model":"claude-opus-4-8","messages":[]}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusNotFound, w.Code, w.Body.String())
require.Contains(t, w.Body.String(), "not available for this group")
}
// 回归:纯文本入口的上限必须在分组中间件读体之前生效,否则中间件会先按通用
// 上限把请求体整体读入并解析。超出文本上限的请求体直接 413,不会走到歧义检查。
func TestGatewayRoutesTextBodyLimitAppliesBeforeGroupMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
RegisterGatewayRoutes(
router,
&handler.Handlers{Gateway: &handler.GatewayHandler{}, OpenAIGateway: &handler.OpenAIGatewayHandler{}, AsyncImage: handler.NewAsyncImageHandler(nil, nil)},
servermiddleware.APIKeyAuthMiddleware(func(c *gin.Context) {
groupID := int64(1)
c.Set(string(servermiddleware.ContextKeyAPIKey), &service.APIKey{GroupID: &groupID, Group: allowlistGroup(service.PlatformOpenAI, false)})
c.Next()
}),
nil, nil, nil, nil, nil,
&config.Config{Gateway: config.GatewayConfig{MaxBodySize: 1 << 20, TextMaxBodySize: 256}},
)
body := `{"model":"a","input":"` + strings.Repeat("x", 1024) + `","model":"b"}`
for _, path := range []string{"/v1/embeddings", "/v1/alpha/search", "/v1/systemone", "/backend-api/codex/alpha/search", "/embeddings", "/alpha/search"} {
req := httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusRequestEntityTooLarge, w.Code, "POST %s: %s", path, w.Body.String())
require.Contains(t, w.Body.String(), "limit is 256B", "POST %s", path)
}
}
// 嵌套字段取值不一致(reasoning.effort 参与计费倍率与分组推理强度上限、
// thinking.type 决定是否清洗 thinking 块)同样在进入 handler 之前拒绝。
func TestGatewayRoutesRejectConflictingNestedFields(t *testing.T) {
cases := []struct {
platform string
path string
body string
field string
}{
{service.PlatformOpenAI, "/v1/responses", `{"model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"input":"hi"}`, `reasoning.effort`},
{service.PlatformOpenAI, "/backend-api/codex/responses", `{"model":"gpt-5.4","input":[{"role":"user","content":"a","role":"system"}]}`, `input[0].role`},
{service.PlatformAnthropic, "/v1/messages", `{"model":"claude-sonnet-4-5","thinking":{"type":"disabled","type":"enabled","budget_tokens":1024},"messages":[]}`, `thinking.type`},
}
for _, tc := range cases {
t.Run(tc.path, func(t *testing.T) {
router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(tc.platform, false))
req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String())
require.Contains(t, w.Body.String(), "invalid_request_error")
require.Contains(t, w.Body.String(), tc.field)
})
}
}
// 回归:multipart handler 跳过首个 boundary 之前的前导内容。前导内容是 JSON 时,
// 白名单必须看到表单里的 model,表单里的重复标量字段也必须被拒绝。
func TestGatewayRoutesMultipartJSONPreambleDoesNotBypassChecks(t *testing.T) {
part := func(name, value string) string {
return "--B\r\nContent-Disposition: form-data; name=\"" + name + "\"\r\n\r\n" + value + "\r\n"
}
send := func(group *service.Group, body string) *httptest.ResponseRecorder {
router := newGatewayRoutesTestRouterWithGroup(group)
req := httptest.NewRequest(http.MethodPost, "/v1/images/edits", strings.NewReader(body))
req.Header.Set("Content-Type", "multipart/form-data; boundary=B")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
return w
}
blocked := send(allowlistGroup(service.PlatformOpenAI, true, "gpt-image-1-mini"), "{}\r\n"+part("model", "gpt-image-2")+part("prompt", "cat")+"--B--\r\n")
require.Equal(t, http.StatusNotFound, blocked.Code, blocked.Body.String())
require.Contains(t, blocked.Body.String(), "gpt-image-2")
repeated := send(allowlistGroup(service.PlatformOpenAI, false), "{}\r\n"+part("model", "gpt-image-2")+part("n", "8")+part("n", "1")+"--B--\r\n")
require.Equal(t, http.StatusBadRequest, repeated.Code, repeated.Body.String())
require.Contains(t, repeated.Body.String(), `\"n\"`)
}
+9 -3
View File
@@ -1017,8 +1017,8 @@ func resolveRequestedModelInMapping(mapping map[string]string, requestedModel st
// IsModelSupported 检查模型是否在 model_mapping 中(支持通配符)
// 如果未配置 mapping,返回 true(允许所有模型)。
//
// 例外:OpenAI OAuth 账号(Codex 上游)的空映射会排除明确属于其他厂商
// 家族的模型(deepseek-*/glm-* 等)——转发阶段 normalizeOpenAIModelForUpstream
// 例外:OpenAI OAuth 账号(Codex 上游)的空映射与透传模式都会排除明确属于
// 其他厂商家族的模型(claude-*/deepseek-*/glm-* 等)——转发阶段 normalizeOpenAIModelForUpstream
// 会把未知模型原样透传,Codex 上游对这类模型必然返回不可重试的 400,导致
// 请求卡死在该账号上、无法 failover 到真正支持该模型的 API Key 账号(#3662)。
// 未知/自定义别名仍保持允许(兼容渠道级映射),见 isOpenAIOAuthServableModel。
@@ -1031,11 +1031,17 @@ func (a *Account) IsModelSupported(requestedModel string) bool {
}
func (a *Account) isModelMappingSupported(requestedModel string) bool {
// 透传模式仅替换认证、模型语义完全交由上游决定,因此放行所有模型。
// 透传模式仅替换认证、模型语义交由上游决定,因此除下面 OAuth 的异族厂商模型外放行所有模型。
// 该短路必须在 model_mapping 判定之前:账号从"白名单模式"切换到透传后,
// credentials 里常残留旧的非空 model_mapping,若不在此放行,透传账号会被
// model_mapping 白名单错误排除出候选集,导致 no available accounts / 404(issue #4936)。
if a.IsOpenAIPassthroughEnabled() {
// OAuth 与 Setup Token 透传的出口恒为 chatgpt.com/backend-api/codex(见
// buildUpstreamRequestOpenAIPassthrough),异族厂商模型在那里必然是不可重试的 400,
// 因此透传也要在调度阶段跳过它们;API Key 透传的上游由 base_url 决定,不受此限。
if a.IsOpenAIOAuthLike() && !isOpenAIOAuthServableModel(requestedModel) {
return false
}
if !a.IsOpenAIPassthroughModelFilterEnabled() {
return true
}
@@ -319,7 +319,7 @@ func createTestPayload(modelID string) (map[string]any, error) {
return nil, err
}
return map[string]any{
payload := map[string]any{
"model": modelID,
"messages": []map[string]any{
{
@@ -347,10 +347,13 @@ func createTestPayload(modelID string) (map[string]any, error) {
"metadata": map[string]string{
"user_id": sessionID,
},
"max_tokens": 1024,
"temperature": 1,
"stream": true,
}, nil
"max_tokens": 1024,
"stream": true,
}
if !claude.RejectsTemperature(modelID) {
payload["temperature"] = 1
}
return payload, nil
}
// TestAccountConnection tests an account's connection by sending a test request
@@ -739,6 +742,28 @@ func (s *AccountTestService) testClaudeVertexServiceAccountConnection(c *gin.Con
return s.processClaudeStream(c, resp.Body)
}
func buildBedrockTestPayload(modelID string) map[string]any {
payload := map[string]any{
"anthropic_version": "bedrock-2023-05-31",
"messages": []map[string]any{
{
"role": "user",
"content": []map[string]any{
{
"type": "text",
"text": "hi",
},
},
},
},
"max_tokens": 256,
}
if !claude.RejectsTemperature(modelID) {
payload["temperature"] = 1
}
return payload
}
// testBedrockAccountConnection tests a Bedrock (SigV4 or API Key) account using non-streaming invoke
func (s *AccountTestService) testBedrockAccountConnection(c *gin.Context, ctx context.Context, account *Account, testModelID string) error {
region := bedrockRuntimeRegion(account)
@@ -756,23 +781,7 @@ func (s *AccountTestService) testBedrockAccountConnection(c *gin.Context, ctx co
c.Writer.Flush()
// Create a minimal Bedrock-compatible payload (no stream, no cache_control)
bedrockPayload := map[string]any{
"anthropic_version": "bedrock-2023-05-31",
"messages": []map[string]any{
{
"role": "user",
"content": []map[string]any{
{
"type": "text",
"text": "hi",
},
},
},
},
"max_tokens": 256,
"temperature": 1,
}
bedrockBody, _ := json.Marshal(bedrockPayload)
bedrockBody, _ := json.Marshal(buildBedrockTestPayload(testModelID))
// Use non-streaming endpoint (response is standard Claude JSON)
apiURL := BuildBedrockURL(region, testModelID, false)
@@ -0,0 +1,55 @@
//go:build unit
package service
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestCreateTestPayload_Temperature(t *testing.T) {
tests := []struct {
model string
wantTemperature bool
}{
{model: "claude-sonnet-4-6", wantTemperature: true},
{model: "claude-opus-4-6", wantTemperature: true},
{model: "claude-sonnet-5-5", wantTemperature: true},
{model: "claude-haiku-5-5", wantTemperature: true},
{model: "claude-opus-4-7", wantTemperature: false},
{model: "claude-opus-4-8", wantTemperature: false},
{model: "claude-opus-5-5", wantTemperature: false},
{model: "claude-fable-5-2", wantTemperature: false},
{model: "claude-mythos-5-2", wantTemperature: false},
}
for _, tt := range tests {
t.Run(tt.model, func(t *testing.T) {
payload, err := createTestPayload(tt.model)
require.NoError(t, err)
temperature, present := payload["temperature"]
require.Equal(t, tt.wantTemperature, present)
if tt.wantTemperature {
require.Equal(t, 1, temperature)
}
require.Equal(t, tt.model, payload["model"])
})
}
}
func TestBuildBedrockTestPayload_Temperature(t *testing.T) {
tests := []struct {
model string
wantTemperature bool
}{
{model: "us.anthropic.claude-sonnet-4-6", wantTemperature: true},
{model: "us.anthropic.claude-opus-4-8-v1", wantTemperature: false},
}
for _, tt := range tests {
t.Run(tt.model, func(t *testing.T) {
_, present := buildBedrockTestPayload(tt.model)["temperature"]
require.Equal(t, tt.wantTemperature, present)
})
}
}
@@ -39,8 +39,9 @@ func (s *AccountTestService) testTypeSafeAccountConnection(c *gin.Context, accou
if state == "" {
state = typeSafeTestDefaultState
}
model := firstNonEmpty(account.GetMappedModel(typesafe.JevLatestModel), typesafe.JevLatestModel)
payload, err := json.Marshal(map[string]any{
"model": typesafe.JevLatestModel,
"model": model,
"state": state,
"questions": map[string]any{
typeSafeTestQuestionID: map[string]any{
@@ -59,7 +60,7 @@ func (s *AccountTestService) testTypeSafeAccountConnection(c *gin.Context, accou
c.Writer.Header().Set("X-Accel-Buffering", "no")
c.Writer.Flush()
s.sendEvent(c, TestEvent{Type: "test_start", Model: typesafe.JevLatestModel})
s.sendEvent(c, TestEvent{Type: "test_start", Model: model})
req, err := typesafe.NewSystemOneRequest(ctx, baseURL, apiKey, payload)
if err != nil {
@@ -60,6 +60,18 @@ func TestTypeSafeAccountTestSendsNativeSystemOneRequest(t *testing.T) {
require.Zero(t, repo.errorCalls)
}
func TestTypeSafeAccountTestAppliesAccountModelMapping(t *testing.T) {
svc, repo, requests, c, rec := newTypeSafeAccountTestFixture(t, http.StatusOK, `{"answers":{"connection_test":{"type":"noul"}}}`)
repo.account.Credentials["model_mapping"] = map[string]any{"jev-latest": "decision-model-preview"}
require.NoError(t, svc.TestAccountConnection(c, 31, "ignored-client-model", "custom state", AccountTestModeDefault))
require.Len(t, *requests, 1)
body, err := io.ReadAll((*requests)[0].Body)
require.NoError(t, err)
require.JSONEq(t, `{"model":"decision-model-preview","state":"custom state","questions":{"connection_test":{"type":"noul","instructions":"Is this text a connection test?"}}}`, string(body))
require.Contains(t, rec.Body.String(), `"type":"test_start","model":"decision-model-preview"`)
}
func TestTypeSafeAccountTestMarksRejectedKey(t *testing.T) {
for _, status := range []int{http.StatusUnauthorized, http.StatusForbidden} {
t.Run(http.StatusText(status), func(t *testing.T) {
@@ -97,6 +97,13 @@ type apiUsageCache struct {
type windowStatsCache struct {
stats *WindowStats
timestamp time.Time
startTime time.Time
}
// Separate quota windows while keeping at most two cached entries per account.
type windowStatsCacheKey struct {
accountID int64
duration time.Duration
}
// antigravityUsageCache 缓存 Antigravity 额度数据
@@ -119,7 +126,7 @@ const (
// UsageCache 封装账户使用量相关的缓存
type UsageCache struct {
apiCache sync.Map // accountID -> *apiUsageCache
windowStatsCache sync.Map // accountID -> *windowStatsCache
windowStatsCache sync.Map // windowStatsCacheKey -> *windowStatsCache
antigravityCache sync.Map // accountID -> *antigravityUsageCache
apiFlight singleflight.Group // 防止同一账号的并发请求击穿缓存(Anthropic)
antigravityFlight singleflight.Group // 防止同一 Antigravity 账号的并发请求击穿缓存
@@ -1461,50 +1468,61 @@ func enrichUsageWithAccountError(info *UsageInfo, account *Account) {
// addWindowStats 为 usage 数据添加窗口期统计
// 使用独立缓存(1 分钟),与 API 缓存分离
func (s *AccountUsageService) addWindowStats(ctx context.Context, account *Account, usage *UsageInfo) {
// 修复:即使 FiveHour 为 nil,也要尝试获取统计数据
// 因为 SevenDay/SevenDaySonnet/SevenDayFable 可能需要
if usage.FiveHour == nil && usage.SevenDay == nil && usage.SevenDaySonnet == nil && usage.SevenDayFable == nil {
if s.usageLogRepo == nil || usage == nil {
return
}
// 检查窗口统计缓存(1 分钟)
var windowStats *WindowStats
if cached, ok := s.cache.windowStatsCache.Load(account.ID); ok {
if cache, ok := cached.(*windowStatsCache); ok && time.Since(cache.timestamp) < windowStatsCacheTTL {
windowStats = cache.stats
now := time.Now()
for _, window := range []struct {
progress *UsageProgress
duration time.Duration
}{
{usage.FiveHour, 5 * time.Hour},
{usage.SevenDay, 7 * 24 * time.Hour},
} {
if window.progress == nil {
continue
}
}
// 如果没有缓存,从数据库查询
if windowStats == nil {
// 使用统一的窗口开始时间计算逻辑(考虑窗口过期情况)
startTime := account.GetCurrentWindowStartTime()
if supportsAnthropicPassiveUsage(account) {
// Only pair local costs with a known, current upstream quota window.
// A rolling lookback or expired sample would produce a misleading estimate.
if window.progress.ResetsAt == nil || !now.Before(*window.progress.ResetsAt) {
continue
}
startTime = window.progress.ResetsAt.Add(-window.duration)
if startTime.After(now) {
continue
}
} else if window.duration != 5*time.Hour {
continue
}
key := windowStatsCacheKey{accountID: account.ID, duration: window.duration}
if cached, ok := s.cache.windowStatsCache.Load(key); ok {
if cache, ok := cached.(*windowStatsCache); ok && cache.startTime.Equal(startTime) && now.Sub(cache.timestamp) < windowStatsCacheTTL {
window.progress.WindowStats = cache.stats
continue
}
}
stats, err := s.usageLogRepo.GetAccountWindowStats(ctx, account.ID, startTime)
if err != nil {
log.Printf("Failed to get window stats for account %d: %v", account.ID, err)
return
continue
}
windowStats = &WindowStats{
Requests: stats.Requests,
Tokens: stats.Tokens,
Cost: stats.Cost,
StandardCost: stats.StandardCost,
UserCost: stats.UserCost,
if stats == nil {
continue
}
// 缓存窗口统计(1 分钟)
s.cache.windowStatsCache.Store(account.ID, &windowStatsCache{
windowStats := windowStatsFromAccountStats(stats)
window.progress.WindowStats = windowStats
s.cache.windowStatsCache.Store(key, &windowStatsCache{
stats: windowStats,
timestamp: time.Now(),
timestamp: now,
startTime: startTime,
})
}
// 为 FiveHour 添加 WindowStats(5h 窗口统计)
if usage.FiveHour != nil {
usage.FiveHour.WindowStats = windowStats
}
}
// GetTodayStats 获取账号今日统计
@@ -0,0 +1,98 @@
package service
import (
"context"
"errors"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/usagestats"
"github.com/stretchr/testify/require"
)
type windowCostRepo struct {
usageBatchLogRepoStub
starts []time.Time
failStart time.Time
}
func (r *windowCostRepo) GetAccountWindowStats(_ context.Context, _ int64, start time.Time) (*usagestats.AccountStats, error) {
r.starts = append(r.starts, start)
if start.Equal(r.failStart) {
return nil, errors.New("test query failure")
}
return &usagestats.AccountStats{Requests: 1, Tokens: 100, Cost: float64(len(r.starts)), UserCost: 99}, nil
}
func TestAccountUsageService_ClaudeWindowCosts(t *testing.T) {
for _, accountType := range []string{AccountTypeOAuth, AccountTypeSetupToken} {
t.Run(accountType, func(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
fiveReset, weeklyReset := now.Add(time.Hour), now.Add(48*time.Hour)
account := Account{ID: 8510, Platform: PlatformAnthropic, Type: accountType,
SessionWindowEnd: &fiveReset,
Extra: map[string]any{
"session_window_utilization": 0.25,
"passive_usage_7d_utilization": 0.4,
"passive_usage_7d_reset": weeklyReset.Unix(),
},
}
repo := &windowCostRepo{}
svc := &AccountUsageService{accountRepo: &stubOpenAIAccountRepo{accounts: []Account{account}}, usageLogRepo: repo, cache: NewUsageCache()}
usage, err := svc.GetPassiveUsage(t.Context(), account.ID)
require.NoError(t, err)
require.Len(t, repo.starts, 2)
require.True(t, fiveReset.Add(-5*time.Hour).Equal(repo.starts[0]))
require.True(t, weeklyReset.Add(-7*24*time.Hour).Equal(repo.starts[1]))
require.Equal(t, 1.0, usage.FiveHour.WindowStats.Cost)
require.Equal(t, 2.0, usage.SevenDay.WindowStats.Cost)
// Cached costs remain separated, and a changed reset invalidates the weekly entry.
svc.addWindowStats(t.Context(), &account, usage)
require.Len(t, repo.starts, 2)
nextReset := weeklyReset.Add(time.Hour)
usage.SevenDay.ResetsAt = &nextReset
svc.addWindowStats(t.Context(), &account, usage)
require.Len(t, repo.starts, 3)
require.True(t, nextReset.Add(-7*24*time.Hour).Equal(repo.starts[2]))
require.Equal(t, 1.0, usage.FiveHour.WindowStats.Cost)
require.Equal(t, 3.0, usage.SevenDay.WindowStats.Cost)
entries := 0
svc.cache.windowStatsCache.Range(func(_, _ any) bool { entries++; return true })
require.Equal(t, 2, entries)
})
}
}
func TestAccountUsageService_ClaudeWindowCostsMissingOrExpired(t *testing.T) {
now := time.Now()
expired, futureStart := now.Add(-time.Hour), now.Add(8*24*time.Hour)
for name, reset := range map[string]*time.Time{"missing": nil, "expired": &expired, "future_start": &futureStart} {
t.Run(name, func(t *testing.T) {
repo := &windowCostRepo{}
svc := &AccountUsageService{usageLogRepo: repo, cache: NewUsageCache()}
usage := &UsageInfo{SevenDay: &UsageProgress{ResetsAt: reset}}
svc.addWindowStats(t.Context(), &Account{ID: 8511, Platform: PlatformAnthropic, Type: AccountTypeSetupToken}, usage)
require.Empty(t, repo.starts)
require.Nil(t, usage.SevenDay.WindowStats)
})
}
}
func TestAccountUsageService_ClaudeWindowCostsIndependentFailure(t *testing.T) {
now := time.Now().UTC().Truncate(time.Second)
fiveReset, weeklyReset := now.Add(time.Hour), now.Add(48*time.Hour)
repo := &windowCostRepo{failStart: fiveReset.Add(-5 * time.Hour)}
svc := &AccountUsageService{usageLogRepo: repo, cache: NewUsageCache()}
usage := &UsageInfo{
FiveHour: &UsageProgress{ResetsAt: &fiveReset},
SevenDay: &UsageProgress{ResetsAt: &weeklyReset},
SevenDaySonnet: &UsageProgress{ResetsAt: &weeklyReset},
SevenDayFable: &UsageProgress{ResetsAt: &weeklyReset},
}
svc.addWindowStats(t.Context(), &Account{ID: 8512, Platform: PlatformAnthropic, Type: AccountTypeOAuth}, usage)
require.Nil(t, usage.FiveHour.WindowStats)
require.NotNil(t, usage.SevenDay.WindowStats)
require.Nil(t, usage.SevenDaySonnet.WindowStats)
require.Nil(t, usage.SevenDayFable.WindowStats)
}
+4 -1
View File
@@ -723,7 +723,8 @@ type adminServiceImpl struct {
compositeResolver *CompositeRouteResolver
// B2-③ 保存期无价门禁用:ollama_cloud 账号保存时断言可出站模型名全部可定价。
// 生产 wire 注入;直接构造 struct 的单测可为 nil(门禁对 nil 跳过)。
billingService *BillingService
billingService *BillingService
userPlatformQuotaRepo UserPlatformQuotaRepository
// 分组平台变更后用来失效渠道缓存;可为 nil(缓存会在 TTL 到期后自然重建)
channelCacheInvalidator ChannelCacheInvalidator
}
@@ -768,6 +769,7 @@ func NewAdminService(
compositeResolver *CompositeRouteResolver,
channelCacheInvalidator ChannelCacheInvalidator,
billingService *BillingService,
userPlatformQuotaRepo UserPlatformQuotaRepository,
) AdminService {
return &adminServiceImpl{
cfg: cfg,
@@ -799,5 +801,6 @@ func NewAdminService(
billingService: billingService,
channelCacheInvalidator: channelCacheInvalidator,
userPlatformQuotaRepo: userPlatformQuotaRepo,
}
}
@@ -108,7 +108,14 @@ func TestAdminService_CreateUser_EmailExists(t *testing.T) {
func TestAdminService_CreateUser_CreateError(t *testing.T) {
createErr := errors.New("db down")
repo := &userRepoStub{createErr: createErr}
svc := &adminServiceImpl{userRepo: repo}
quotas := &userPlatformQuotaRepoStub{}
svc := &adminServiceImpl{
userRepo: repo,
settingService: NewSettingService(&settingRepoStub{values: map[string]string{
SettingKeyDefaultPlatformQuotas: `{"openai":{"daily":100}}`,
}}, &config.Config{}),
userPlatformQuotaRepo: quotas,
}
_, err := svc.CreateUser(context.Background(), &CreateUserInput{
Email: "user@test.com",
@@ -116,6 +123,7 @@ func TestAdminService_CreateUser_CreateError(t *testing.T) {
})
require.ErrorIs(t, err, createErr)
require.Empty(t, repo.created)
require.Empty(t, quotas.bulkInsertCalls, "failed user creation must not initialize platform quotas")
}
func TestAdminService_CreateUser_AssignsDefaultSubscriptions(t *testing.T) {
@@ -146,3 +154,109 @@ func TestAdminService_CreateUser_AssignsDefaultSubscriptions(t *testing.T) {
require.Equal(t, int64(5), assigner.calls[0].GroupID)
require.Equal(t, 30, assigner.calls[0].ValidityDays)
}
func TestAdminService_CreateUser_SnapshotsDefaultPlatformQuotas(t *testing.T) {
users := &userRepoStub{nextID: 40}
quotas := &userPlatformQuotaRepoStub{}
settings := NewSettingService(&settingRepoStub{values: map[string]string{
SettingKeyDefaultPlatformQuotas: `{
"openai": {"daily": 100, "weekly": 700, "monthly": 3000},
"anthropic": {"daily": 100},
"gemini": {"daily": 500},
"antigravity": {"daily": 500},
"grok": {"daily": 0},
"cline": {},
"deepseek": null
}`,
SettingKeyAuthSourceDefaultEmailGrantOnSignup: "true",
SettingKeyAuthSourcePlatformQuotas("email"): `{"openai":{"daily":3}}`,
}}, &config.Config{})
svc := NewAdminService(nil, users, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, settings, nil, nil, nil, nil, nil, nil, nil, nil, nil, quotas)
user, err := svc.CreateUser(context.Background(), &CreateUserInput{
Email: "quota-defaults@example.test",
Password: "strong-pass",
})
require.NoError(t, err)
require.Equal(t, int64(40), user.ID)
require.Len(t, quotas.bulkInsertCalls, 1, "admin-created users must receive the configured platform quotas")
records := make(map[string]UserPlatformQuotaRecord)
for _, record := range quotas.bulkInsertCalls[0] {
require.Equal(t, user.ID, record.UserID)
records[record.Platform] = record
}
require.Len(t, records, 5, "unconfigured platforms must not receive quota rows")
require.Equal(t, 100.0, *records["openai"].DailyLimitUSD, "admin creation uses system defaults, not email signup overrides")
require.Equal(t, 700.0, *records["openai"].WeeklyLimitUSD)
require.Equal(t, 3000.0, *records["openai"].MonthlyLimitUSD)
require.Equal(t, 100.0, *records["anthropic"].DailyLimitUSD)
require.Equal(t, 500.0, *records["gemini"].DailyLimitUSD)
require.Equal(t, 500.0, *records["antigravity"].DailyLimitUSD)
require.NotNil(t, records["grok"].DailyLimitUSD, "zero is an explicit limit")
require.Zero(t, *records["grok"].DailyLimitUSD)
require.Nil(t, records["anthropic"].WeeklyLimitUSD)
require.Nil(t, records["anthropic"].MonthlyLimitUSD)
}
func TestAdminService_CreateUser_UnlimitedDefaultsDoNotCreateQuotaRows(t *testing.T) {
quotas := &userPlatformQuotaRepoStub{}
svc := &adminServiceImpl{
userRepo: &userRepoStub{nextID: 41},
settingService: NewSettingService(&settingRepoStub{values: map[string]string{
SettingKeyDefaultPlatformQuotas: `{"openai":{"daily":null,"weekly":null,"monthly":null}}`,
}}, &config.Config{}),
userPlatformQuotaRepo: quotas,
}
_, err := svc.CreateUser(context.Background(), &CreateUserInput{
Email: "unlimited@example.test",
Password: "strong-pass",
})
require.NoError(t, err)
require.Empty(t, quotas.bulkInsertCalls)
}
func TestAdminService_CreateUser_AdminSkipsDefaultPlatformQuotas(t *testing.T) {
quotas := &userPlatformQuotaRepoStub{}
svc := &adminServiceImpl{
userRepo: &userRepoStub{nextID: 42},
settingService: NewSettingService(&settingRepoStub{values: map[string]string{
SettingKeyDefaultPlatformQuotas: `{"openai":{"daily":100}}`,
}}, &config.Config{}),
userPlatformQuotaRepo: quotas,
}
user, err := svc.CreateUser(context.Background(), &CreateUserInput{
Email: "admin@example.test",
Password: "strong-pass",
Role: RoleAdmin,
})
require.NoError(t, err)
require.Equal(t, RoleAdmin, user.Role)
require.Empty(t, quotas.bulkInsertCalls)
}
func TestAdminService_CreateUser_QuotaWriteFailureDoesNotFailCreation(t *testing.T) {
users := &userRepoStub{nextID: 43}
quotas := &userPlatformQuotaRepoStub{bulkInsertErr: errors.New("quota insert failed")}
svc := &adminServiceImpl{
userRepo: users,
settingService: NewSettingService(&settingRepoStub{values: map[string]string{
SettingKeyDefaultPlatformQuotas: `{"openai":{"daily":100}}`,
}}, &config.Config{}),
userPlatformQuotaRepo: quotas,
}
user, err := svc.CreateUser(context.Background(), &CreateUserInput{
Email: "quota-failure@example.test",
Password: "strong-pass",
})
require.NoError(t, err)
require.Equal(t, int64(43), user.ID)
require.Len(t, users.created, 1)
require.Len(t, quotas.bulkInsertCalls, 1)
}
+15
View File
@@ -156,9 +156,24 @@ func (s *adminServiceImpl) CreateUser(ctx context.Context, input *CreateUserInpu
input.ActorAdminID, user.ID)
}
s.assignDefaultSubscriptions(ctx, user.ID)
s.assignDefaultPlatformQuotas(ctx, user)
return user, nil
}
func (s *adminServiceImpl) assignDefaultPlatformQuotas(ctx context.Context, user *User) {
if user == nil || user.Role != RoleUser || s.settingService == nil || s.userPlatformQuotaRepo == nil {
return
}
quotas, err := s.settingService.GetDefaultPlatformQuotas(ctx)
if err != nil {
logger.LegacyPrintf("service.admin", "failed to load default platform quotas: user_id=%d err=%v", user.ID, err)
return
}
if err := snapshotUserPlatformQuotaDefaults(ctx, s.userPlatformQuotaRepo, user.ID, quotas); err != nil {
logger.LegacyPrintf("service.admin", "failed to snapshot default platform quotas: user_id=%d err=%v (fail-open)", user.ID, err)
}
}
// ensureNotLastAdmin 降级管理员前确认系统中仍存在其他管理员,防止零 admin 锁死。
// 注:读取与写入之间存在竞态窗口,极端并发下仍可能双双降级;作为后台低频操作
// 的兜底保护足够,彻底防护需依赖数据库层约束。
@@ -0,0 +1,47 @@
package service
import (
"context"
"slices"
"strings"
)
func (s *GatewayService) ExpandAnthropicLongContextModels(ctx context.Context, group *Group, models []string) []string {
var accounts []Account
var err error
if group != nil {
accounts, err = s.accountRepo.ListSchedulableByGroupID(ctx, group.ID)
} else {
accounts, err = s.accountRepo.ListSchedulable(ctx)
}
if err != nil {
return models
}
result := cloneStringSlice(models)
seen := make(map[string]bool, len(models))
for _, model := range models {
seen[strings.ToLower(model)] = true
}
for _, model := range models {
if strings.HasSuffix(strings.ToLower(model), claudeCodeLongContextModelSuffix) || strings.Contains(model, "*") {
continue
}
var routedAccountIDs []int64
if group != nil {
routedAccountIDs = group.GetRoutingAccountIDs(model)
}
for _, account := range accounts {
if !account.IsAnthropic() || !account.IsModelSupported(model) ||
(len(routedAccountIDs) > 0 && !slices.Contains(routedAccountIDs, account.ID)) {
continue
}
metadata, ok := account.GetUpstreamModelMetadata(account.GetMappedModel(model))
variant := model + claudeCodeLongContextModelSuffix
if ok && metadata.ContextWindow >= 900_000 && !seen[strings.ToLower(variant)] {
result = append(result, variant)
seen[strings.ToLower(variant)] = true
}
}
}
return result
}
@@ -0,0 +1,80 @@
//go:build unit
package service
import (
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// 2026-11-19 17:03 UTC: one Codex request (/v1/responses, 2 MB) got the bare 429
// on #2, #7 and #6. The retry loop cooled #2 and logged bare_429_cooldown_skipped
// for #7 and #6, but the compat path then cooled #7 and #6 anyway when it turned
// the 429 into a failover, so the whole pool was down for a minute.
func compatBare429(t *testing.T, svc *AntigravityGatewayService, c *gin.Context, accountID int64) error {
t.Helper()
call := &antigravityCompatUpstreamCall{
prefix: "[test]",
request: antigravityCompatRequest{originalModel: "gemini-4-argon-medium"},
}
resp := &http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{},
Body: io.NopCloser(strings.NewReader(bareAntigravity429Body)),
}
return svc.handleAntigravityCompatHTTPError(context.Background(), c, bare429Account(accountID), call, resp)
}
func cooledAccounts(repo *stubAntigravityAccountRepo) map[int64]bool {
cooled := map[int64]bool{}
for _, call := range repo.modelRateLimitCalls {
cooled[call.accountID] = true
}
for _, call := range repo.rateCalls {
cooled[call.accountID] = true
}
return cooled
}
func TestCompatHTTPError_Bare429_DoesNotCoolASecondAccount(t *testing.T) {
repo := &stubAntigravityAccountRepo{}
svc := &AntigravityGatewayService{accountRepo: repo}
c := newBare429TestContext()
// The retry loop already cooled #2 for this request.
require.True(t, claimBare429Cooldown(c, 2))
for _, id := range []int64{7, 6} {
err := compatBare429(t, svc, c, id)
var failover *UpstreamFailoverError
require.ErrorAs(t, err, &failover, "the request still fails over from account %d", id)
}
require.Empty(t, cooledAccounts(repo), "accounts 7 and 6 must not be cooled by the request that cooled 2")
}
func TestCompatHTTPError_Bare429_FirstAccountIsStillCooled(t *testing.T) {
repo := &stubAntigravityAccountRepo{}
svc := &AntigravityGatewayService{accountRepo: repo}
c := newBare429TestContext()
require.Error(t, compatBare429(t, svc, c, 13))
require.Equal(t, map[int64]bool{13: true}, cooledAccounts(repo))
}
func TestCompatHTTPError_429WithReason_CoolsEveryAccount(t *testing.T) {
repo := &stubAntigravityAccountRepo{}
svc := &AntigravityGatewayService{accountRepo: repo}
c := newBare429TestContext()
require.True(t, claimBare429Cooldown(c, 2))
body := `{"error":{"code":429,"message":"Individual quota reached.","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"QUOTA_EXHAUSTED","metadata":{"quotaResetDelay":"41m15s"}}]}}`
call := &antigravityCompatUpstreamCall{prefix: "[test]", request: antigravityCompatRequest{originalModel: "gemini-4-argon-medium"}}
resp := &http.Response{StatusCode: http.StatusTooManyRequests, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))}
require.Error(t, svc.handleAntigravityCompatHTTPError(context.Background(), c, bare429Account(7), call, resp))
require.True(t, cooledAccounts(repo)[7])
}
@@ -0,0 +1,123 @@
//go:build unit
package service
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
"github.com/Wei-Shaw/sub2api/internal/pkg/tlsfingerprint"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// fixed429Upstream answers every call with one 429 body.
type fixed429Upstream struct {
body string
calls int
}
func (u *fixed429Upstream) Do(req *http.Request, proxyURL string, accountID int64, accountConcurrency int) (*http.Response, error) {
u.calls++
return &http.Response{
StatusCode: http.StatusTooManyRequests,
Header: http.Header{},
Body: io.NopCloser(strings.NewReader(u.body)),
}, nil
}
func (u *fixed429Upstream) DoWithTLS(req *http.Request, proxyURL string, accountID int64, accountConcurrency int, profile *tlsfingerprint.Profile) (*http.Response, error) {
return u.Do(req, proxyURL, accountID, accountConcurrency)
}
// The body Google sent on 2026-11-16 for one 1.8 MB request on every account it
// reached, while the same accounts served other requests: no reason, no delay.
const bareAntigravity429Body = `{"error":{"code":429,"message":"Resource has been exhausted (e.g. check quota).","status":"RESOURCE_EXHAUSTED"}}`
func runBare429Loop(t *testing.T, c *gin.Context, account *Account, body string) (cooled bool) {
t.Helper()
svc := &AntigravityGatewayService{}
result, err := svc.antigravityRetryLoop(antigravityRetryLoopParams{
prefix: "[test]",
ctx: context.Background(),
account: account,
accessToken: "token",
action: "streamGenerateContent",
body: []byte(`{"input":"test"}`),
c: c,
httpUpstream: &fixed429Upstream{body: body},
requestedModel: "gemini-4-argon-high",
handleError: func(ctx context.Context, prefix string, account *Account, statusCode int, headers http.Header, body []byte, requestedModel string, groupID int64, sessionHash string, isStickySession bool) *handleModelRateLimitResult {
cooled = true
return nil
},
})
require.NoError(t, err)
require.NotNil(t, result)
require.NotNil(t, result.resp)
_ = result.resp.Body.Close()
require.Equal(t, http.StatusTooManyRequests, result.resp.StatusCode)
return cooled
}
func setupBare429Test(t *testing.T) {
t.Helper()
t.Setenv(antigravityForwardBaseURLEnv, "")
oldBaseURLs := append([]string(nil), antigravity.BaseURLs...)
oldAvailability := antigravity.DefaultURLAvailability
t.Cleanup(func() {
antigravity.BaseURLs = oldBaseURLs
antigravity.DefaultURLAvailability = oldAvailability
})
antigravity.BaseURLs = []string{"https://ag-1.test"}
antigravity.DefaultURLAvailability = antigravity.NewURLAvailability(time.Minute)
}
func newBare429TestContext() *gin.Context {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", nil)
return c
}
func bare429Account(id int64) *Account {
return &Account{ID: id, Name: "acc", Platform: PlatformAntigravity, Schedulable: true, Status: StatusActive, Concurrency: 1}
}
// One request that gets a bare 429 on every account it reaches must not cool
// them all: it cools the first, and the rest are only skipped for this request.
func TestAntigravityRetryLoop_Bare429_CoolsOnlyTheFirstAccountPerRequest(t *testing.T) {
setupBare429Test(t)
c := newBare429TestContext()
require.True(t, runBare429Loop(t, c, bare429Account(13), bareAntigravity429Body), "first account is cooled")
require.False(t, runBare429Loop(t, c, bare429Account(6), bareAntigravity429Body), "same request on a second account: not cooled")
require.False(t, runBare429Loop(t, c, bare429Account(2), bareAntigravity429Body), "same request on a third account: not cooled")
require.True(t, runBare429Loop(t, c, bare429Account(13), bareAntigravity429Body), "the account it already cooled may be cooled again")
}
// Another request that reaches the second account first still cools it, so an
// account that really is throttled for everyone is still taken out.
func TestAntigravityRetryLoop_Bare429_OtherRequestStillCools(t *testing.T) {
setupBare429Test(t)
require.True(t, runBare429Loop(t, newBare429TestContext(), bare429Account(13), bareAntigravity429Body))
require.True(t, runBare429Loop(t, newBare429TestContext(), bare429Account(6), bareAntigravity429Body))
}
// A 429 that says when it resets is Google's statement about the account and is
// applied on every account, as before.
func TestAntigravityRetryLoop_429WithResetDelay_CoolsEveryAccount(t *testing.T) {
setupBare429Test(t)
c := newBare429TestContext()
body := `{"error":{"code":429,"message":"You have exhausted your capacity on this model. Your quota will reset after 2h.","status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.ErrorInfo","reason":"QUOTA_EXHAUSTED","metadata":{"quotaResetDelay":"2h0m0s"}}]}}`
require.True(t, runBare429Loop(t, c, bare429Account(13), body))
require.True(t, runBare429Loop(t, c, bare429Account(6), body))
}
@@ -0,0 +1,67 @@
package service
import (
"context"
"net/http"
"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
)
// antigravityBare429CooledAccountKey holds, on the request's gin context, the one
// account this request has cooled down for a bare 429.
const antigravityBare429CooledAccountKey = "antigravity_bare429_cooled_account_id"
// isBareAntigravity429 reports a 429 with no reason and no reset time, only
// "Resource has been exhausted". Google sends it for an account that is
// throttled, but also for a single request it will not serve (2026-11-16: one
// 1.8 MB request got it on four accounts in a row while those accounts kept
// serving other requests). A 429 that names a reason or a reset time is
// Google's statement about the account and is not bare.
func isBareAntigravity429(statusCode int, body []byte) bool {
if statusCode != http.StatusTooManyRequests {
return false
}
if gjson.GetBytes(body, "error.details").Exists() {
return false
}
return ParseGeminiRateLimitResetTime(body) == nil
}
// claimBare429Cooldown reports whether this request may cool accountID for a
// bare 429. A request cools at most one account this way: when the same bare
// 429 follows the request to another account, the request is the likely cause,
// and cooling every account it reaches takes a shared pool offline for everyone.
// The request still leaves that account and fails over. An account throttled
// for everyone is cooled by the next request that reaches it first.
func claimBare429Cooldown(c *gin.Context, accountID int64) bool {
if c == nil {
return true
}
if v, ok := c.Get(antigravityBare429CooledAccountKey); ok {
if id, ok := v.(int64); ok && id != accountID {
return false
}
}
c.Set(antigravityBare429CooledAccountKey, accountID)
return true
}
// handleUpstreamErrorAfterRetryLoop applies an error the retry loop handed back
// as a response. A bare 429 there was already decided by the loop: the account
// this request cooled may be cooled again, any other is left alone. Without this
// the compat, Gemini and Claude paths cooled every account the loop had skipped
// (2026-11-19: one 2 MB Codex request cooled #2, #7 and #6 every few minutes).
func (s *AntigravityGatewayService) handleUpstreamErrorAfterRetryLoop(
ctx context.Context, c *gin.Context, prefix string, account *Account,
statusCode int, headers http.Header, body []byte,
requestedModel string,
groupID int64, sessionHash string, isStickySession bool,
) *handleModelRateLimitResult {
if isBareAntigravity429(statusCode, body) && !claimBare429Cooldown(c, account.ID) {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d bare_429_cooldown_skipped account=%d (after retry loop)", prefix, statusCode, account.ID)
return nil
}
return s.handleUpstreamError(ctx, prefix, account, statusCode, headers, body, requestedModel, groupID, sessionHash, isStickySession)
}
@@ -392,7 +392,7 @@ func (s *AntigravityGatewayService) Forward(ctx context.Context, c *gin.Context,
}
}
s.handleUpstreamError(ctx, prefix, account, resp.StatusCode, resp.Header, respBody, originalModel, 0, "", isStickySession)
s.handleUpstreamErrorAfterRetryLoop(ctx, c, prefix, account, resp.StatusCode, resp.Header, respBody, originalModel, 0, "", isStickySession)
// 精确匹配服务端配置类 400 错误,触发同账号重试 + failover
if resp.StatusCode == http.StatusBadRequest {
@@ -499,8 +499,9 @@ func (s *AntigravityGatewayService) handleAntigravityCompatHTTPError(
resp *http.Response,
) error {
body := s.readUpstreamErrorBody(resp)
s.handleUpstreamError(
s.handleUpstreamErrorAfterRetryLoop(
ctx,
c,
call.prefix,
account,
resp.StatusCode,
@@ -355,7 +355,7 @@ func (s *AntigravityGatewayService) ForwardGemini(ctx context.Context, c *gin.Co
if unwrapErr != nil || len(unwrappedForOps) == 0 {
unwrappedForOps = respBody
}
s.handleUpstreamError(ctx, prefix, account, resp.StatusCode, resp.Header, respBody, originalModel, forwardOpts.groupID, forwardOpts.sessionHash, isStickySession)
s.handleUpstreamErrorAfterRetryLoop(ctx, c, prefix, account, resp.StatusCode, resp.Header, respBody, originalModel, forwardOpts.groupID, forwardOpts.sessionHash, isStickySession)
upstreamMsg := strings.TrimSpace(extractAntigravityErrorMessage(unwrappedForOps))
upstreamMsg = sanitizeUpstreamErrorMessage(upstreamMsg)
upstreamDetail := s.getUpstreamErrorDetail(unwrappedForOps)
@@ -642,8 +642,12 @@ urlFallbackLoop:
continue
}
// 重试用尽,标记账户限流
p.handleError(p.ctx, p.prefix, p.account, resp.StatusCode, resp.Header, respBody, p.requestedModel, p.groupID, p.sessionHash, p.isStickySession)
// 重试用尽,标记账户限流(无原因的 429 每个请求最多冷却一个账号)
if isBareAntigravity429(resp.StatusCode, respBody) && !claimBare429Cooldown(p.c, p.account.ID) {
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d bare_429_cooldown_skipped account=%d (this request already cooled another account; the request is the likely cause)", p.prefix, resp.StatusCode, p.account.ID)
} else {
p.handleError(p.ctx, p.prefix, p.account, resp.StatusCode, resp.Header, respBody, p.requestedModel, p.groupID, p.sessionHash, p.isStickySession)
}
logger.LegacyPrintf("service.antigravity_gateway", "%s status=%d rate_limited base_url=%s body=%s", p.prefix, resp.StatusCode, baseURL, truncateForLog(respBody, 200))
resp = &http.Response{
StatusCode: resp.StatusCode,
@@ -1430,6 +1430,37 @@ func TestHandleGeminiStreamingResponse_EventSeparatorIsExactlyOneBlankLine(t *te
}
}
func TestHandleGeminiStreamingResponse_ForwardedCommentFrames(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := newAntigravityTestService(&config.Config{
Gateway: config.GatewayConfig{MaxLineSize: defaultMaxLineSize},
})
const first = `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"first"}]}}]}` + "\n\n"
const second = `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"second"}]}}]}` + "\n\n"
const comment = ": upstream"
const stream = first + comment + "\r\n\r\n" + second
for _, tc := range []struct {
name string
userAgent string
forwardedComment string
}{
{"js-genai", "google-genai-sdk/3.6.0 gl-node/v26.13.1", comment + "\n\n"},
{"go-genai", "google-genai-sdk/1.71.0 gl-go/go1.27.4", ""},
{"python-genai", "google-genai-sdk/1.20.0 gl-python/3.12.4", ""},
} {
t.Run(tc.name, func(t *testing.T) {
c, rec := newAntigravityCompatContext(http.MethodPost, "/v1beta/models/gemini-2.5-flash:streamGenerateContent", nil)
c.Request.Header.Set("User-Agent", tc.userAgent)
resp := &http.Response{StatusCode: http.StatusOK, Body: io.NopCloser(strings.NewReader(stream)), Header: http.Header{}}
_, err := svc.handleGeminiStreamingResponse(c, resp, time.Now())
require.NoError(t, err)
require.Equal(t, first+tc.forwardedComment+second, rec.Body.String())
})
}
}
func TestHandleGeminiStreamingResponse_ThoughtsTokenCount(t *testing.T) {
gin.SetMode(gin.TestMode)
svc := newAntigravityTestService(&config.Config{
@@ -203,9 +203,9 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context
if s.settingService.cfg != nil && s.settingService.cfg.Gateway.StreamKeepaliveInterval > 0 {
keepaliveInterval = time.Duration(s.settingService.cfg.Gateway.StreamKeepaliveInterval) * time.Second
}
// go-genai / python-genai 不会忽略 SSE 注释行,收到 ":\n\n" 会直接把整个流判成
// invalid stream chunk 而中断(Antigravity CLI 在用 go-genai)。对这类客户端宁可不发心跳。
if keepaliveInterval > 0 && downstreamRejectsSSEComments(c) {
// go-genai / python-genai 收到 SSE 注释会中断流。
rejectComments := downstreamRejectsSSEComments(c)
if rejectComments {
keepaliveInterval = 0
}
var keepaliveTicker *time.Ticker
@@ -232,6 +232,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context
flusher.Flush()
}
var needsEventSeparator bool
for {
select {
case ev, ok := <-events:
@@ -260,6 +261,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context
s.observeAntigravityGeminiSSELine(c, line)
trimmed := strings.TrimRight(line, "\r\n")
if strings.HasPrefix(trimmed, "data:") {
needsEventSeparator = false
payload := strings.TrimSpace(strings.TrimPrefix(trimmed, "data:"))
if payload == "" || payload == "[DONE]" {
cw.Fprintf("%s\n", line)
@@ -302,15 +304,20 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context
continue
}
// 上游每个 data 事件后面跟一个空行作为事件分隔。上面已经把 data 行写成
// "data: ...\n\n",若再把这个空行透传出去,事件之间就会变成 "\n\n\n"。
// google-genai 的 Go SDK(Antigravity CLI 在用)按 "\n\n" 切事件,多出的
// "\n" 会粘到下一个事件开头,前缀变成 "\ndata" 而被判成 invalid stream chunk。
// 保留透传帧的空行。重写的 data 帧已带分隔符,重复空行会破坏部分客户端的解析。
if trimmed == "" {
if needsEventSeparator {
cw.Fprintf("\n")
needsEventSeparator = false
}
continue
}
if rejectComments && strings.HasPrefix(trimmed, ":") {
continue
}
cw.Fprintf("%s\n", line)
needsEventSeparator = true
case <-intervalCh:
lastRead := time.Unix(0, atomic.LoadInt64(&lastReadAt))
@@ -337,6 +344,7 @@ func (s *AntigravityGatewayService) handleGeminiStreamingResponse(c *gin.Context
logger.LegacyPrintf("service.antigravity_gateway", "Client disconnected during keepalive ping (antigravity gemini), continuing to drain upstream for billing")
continue
}
needsEventSeparator = false
}
}
}
@@ -57,8 +57,14 @@ func (f *AntigravityQuotaFetcher) FetchQuota(ctx context.Context, account *Accou
return nil, fmt.Errorf("create antigravity client failed: %w", err)
}
// 调用 API 获取配额
modelsResp, modelsRaw, err := client.FetchAvailableModels(ctx, accessToken, projectID, resolveModelsListReadLimit(f.cfg))
baseURL := resolveAntigravityForwardBaseURL(account)
if baseURL == "" {
return nil, errors.New("no antigravity base url configured")
}
// Query the same endpoint that receives forwarded requests for this account (daily for
// paid tiers, prod otherwise), because Google accounts quota separately per endpoint.
modelsResp, modelsRaw, err := client.FetchAvailableModelsFromURL(ctx, baseURL, accessToken, projectID, resolveModelsListReadLimit(f.cfg))
if err != nil {
// 403 Forbidden: 不报错,返回 is_forbidden 标记
var forbiddenErr *antigravity.ForbiddenError
@@ -89,7 +95,7 @@ func (f *AntigravityQuotaFetcher) FetchQuota(ctx context.Context, account *Accou
// The per-group 5-hour and weekly windows. Not on the critical path: without them the
// per-model figures above are shown as before.
if summary, err := client.RetrieveUserQuotaSummary(ctx, accessToken, projectID); err != nil {
if summary, err := client.RetrieveUserQuotaSummaryFromURL(ctx, baseURL, accessToken, projectID); err != nil {
slog.Warn("failed to fetch antigravity quota summary", "account_id", account.ID, "error", err)
} else {
usageInfo.AntigravityQuotaGroups = buildAntigravityQuotaGroups(summary)
@@ -7,6 +7,7 @@ import (
"errors"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
@@ -555,3 +556,156 @@ func TestExtractValidationURL(t *testing.T) {
})
}
}
func TestFetchQuota_QueriesForwardEndpoint(t *testing.T) {
newQuotaServer := func(t *testing.T, remaining float64, hits *[]string) *httptest.Server {
t.Helper()
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*hits = append(*hits, r.URL.Path)
w.Header().Set("Content-Type", "application/json")
remainingText := strconv.FormatFloat(remaining, 'f', -1, 64)
switch r.URL.Path {
case "/v1internal:fetchAvailableModels":
_, _ = w.Write([]byte(`{"models":{"gemini-3-flash":{"quotaInfo":{"remainingFraction":` + remainingText + `,"resetTime":"2026-11-20T09:00:00Z"}}}}`))
case "/v1internal:retrieveUserQuotaSummary":
_, _ = w.Write([]byte(`{"groups":[{"displayName":"Gemini Models","buckets":[{"bucketId":"gemini-5h","window":"5h","remainingFraction":` + remainingText + `,"resetTime":"2026-11-20T09:00:00Z"}]}]}`))
case "/v1internal:loadCodeAssist":
_, _ = w.Write([]byte(`{"paidTier":{"id":"g1-ultra-tier"}}`))
default:
http.NotFound(w, r)
}
}))
}
tests := []struct {
name string
planType string
envOverride string
wantDaily bool
wantUtilization int
wantGroupUtil float64
}{
{
name: "paid Ultra account queries daily endpoint",
planType: "Ultra",
wantDaily: true,
wantUtilization: 75,
wantGroupUtil: 75,
},
{
name: "paid Pro account queries daily endpoint",
planType: "Pro",
wantDaily: true,
wantUtilization: 75,
wantGroupUtil: 75,
},
{
name: "free account queries prod endpoint",
planType: "Free",
wantDaily: false,
wantUtilization: 25,
wantGroupUtil: 25,
},
{
name: "env override daily routes free account to daily",
planType: "Free",
envOverride: "daily",
wantDaily: true,
wantUtilization: 75,
wantGroupUtil: 75,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv(antigravityForwardBaseURLEnv, tt.envOverride)
var prodHits, dailyHits []string
prodServer := newQuotaServer(t, 0.75, &prodHits)
defer prodServer.Close()
dailyServer := newQuotaServer(t, 0.25, &dailyHits)
defer dailyServer.Close()
oldBaseURLs := append([]string(nil), antigravity.BaseURLs...)
oldAvailability := antigravity.DefaultURLAvailability
t.Cleanup(func() {
antigravity.BaseURLs = oldBaseURLs
antigravity.DefaultURLAvailability = oldAvailability
})
antigravity.BaseURLs = []string{prodServer.URL, dailyServer.URL}
antigravity.DefaultURLAvailability = antigravity.NewURLAvailability(time.Minute)
fetcher := NewAntigravityQuotaFetcher(nil, &config.Config{})
res, err := fetcher.FetchQuota(context.Background(), &Account{
ID: 80,
Platform: PlatformAntigravity,
Type: AccountTypeOAuth,
Credentials: map[string]any{
"access_token": "token",
"project_id": "project",
"plan_type": tt.planType,
},
}, "")
require.NoError(t, err)
require.NotNil(t, res)
require.NotNil(t, res.UsageInfo)
require.Equal(t, tt.wantUtilization, res.UsageInfo.AntigravityQuota["gemini-3-flash"].Utilization)
require.Len(t, res.UsageInfo.AntigravityQuotaGroups, 1)
require.InDelta(t, tt.wantGroupUtil, res.UsageInfo.AntigravityQuotaGroups[0].Windows[0].Utilization, 0.001)
if tt.wantDaily {
require.Contains(t, dailyHits, "/v1internal:fetchAvailableModels")
require.Contains(t, dailyHits, "/v1internal:retrieveUserQuotaSummary")
require.NotContains(t, prodHits, "/v1internal:fetchAvailableModels")
require.NotContains(t, prodHits, "/v1internal:retrieveUserQuotaSummary")
} else {
require.Contains(t, prodHits, "/v1internal:fetchAvailableModels")
require.Contains(t, prodHits, "/v1internal:retrieveUserQuotaSummary")
require.NotContains(t, dailyHits, "/v1internal:fetchAvailableModels")
require.NotContains(t, dailyHits, "/v1internal:retrieveUserQuotaSummary")
}
})
}
}
func TestFetchQuota_PaidAccountDoesNotFallbackToProdQuotaOnDailyFailure(t *testing.T) {
t.Setenv(antigravityForwardBaseURLEnv, "")
var prodQuotaHits int
prodServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1internal:fetchAvailableModels" || r.URL.Path == "/v1internal:retrieveUserQuotaSummary" {
prodQuotaHits++
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"models":{"gemini-3-flash":{"quotaInfo":{"remainingFraction":1}}}}`))
}))
defer prodServer.Close()
dailyServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "upstream failure", http.StatusInternalServerError)
}))
defer dailyServer.Close()
oldBaseURLs := append([]string(nil), antigravity.BaseURLs...)
oldAvailability := antigravity.DefaultURLAvailability
t.Cleanup(func() {
antigravity.BaseURLs = oldBaseURLs
antigravity.DefaultURLAvailability = oldAvailability
})
antigravity.BaseURLs = []string{prodServer.URL, dailyServer.URL}
antigravity.DefaultURLAvailability = antigravity.NewURLAvailability(time.Minute)
fetcher := NewAntigravityQuotaFetcher(nil, &config.Config{})
_, err := fetcher.FetchQuota(context.Background(), &Account{
ID: 77,
Platform: PlatformAntigravity,
Type: AccountTypeOAuth,
Credentials: map[string]any{
"access_token": "token",
"project_id": "project",
"plan_type": "Ultra",
},
}, "")
require.Error(t, err)
require.Zero(t, prodQuotaHits, "paid account quota query must not silently fall back to prod")
}
@@ -3,6 +3,7 @@ package service
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/pkg/antigravity"
@@ -75,6 +76,23 @@ func TestAntigravityResponsesParallelToolResultImagesKeepFunctionResponsesContig
{"type":"function_call_output","call_id":"call_cmd_3","output":"done"}
]}`)
wire := toolImageCompatWire(t, raw, model)
if strings.HasPrefix(model, "gemini-") {
// Gemini rejects a turn whose parts continue past the last
// functionResponse ("Requests ending with a model turn are not
// supported."), so tool-result images move to the following user
// turn and each turn keeps its functionResponses contiguous.
frParts := gjson.GetBytes(wire, "request.contents.1.parts").Array()
require.Len(t, frParts, 3)
require.Equal(t, "view_image", frParts[0].Get("functionResponse.name").String())
require.Equal(t, "view_image", frParts[1].Get("functionResponse.name").String())
require.Equal(t, "exec_command", frParts[2].Get("functionResponse.name").String())
imageParts := gjson.GetBytes(wire, "request.contents.2.parts").Array()
require.Len(t, imageParts, 2)
require.Equal(t, "user", gjson.GetBytes(wire, "request.contents.2.role").String())
require.Equal(t, "AQID", imageParts[0].Get("inlineData.data").String())
require.Equal(t, "BAUG", imageParts[1].Get("inlineData.data").String())
return
}
parts := gjson.GetBytes(wire, "request.contents.1.parts").Array()
require.Len(t, parts, 5)
require.Equal(t, "view_image", parts[0].Get("functionResponse.name").String())
+2 -26
View File
@@ -1973,35 +1973,11 @@ func resolvedTokenVersion(user *User) int64 {
// snapshotPlatformQuotaDefaults 把 plan.PlatformQuotas 中至少配置了一档限额的平台以
// BulkInsertInitial 形式写入 user_platform_quotas 表。失败 fail-open(仅 warn log)。
func (s *AuthService) snapshotPlatformQuotaDefaults(ctx context.Context, userID int64, plan *signupGrantPlan) error {
if s.userPlatformQuotaRepo == nil || plan == nil || len(plan.PlatformQuotas) == 0 {
if plan == nil {
return nil
}
// 平台配额快照是 best-effort(fail-open):必须脱离调用方事务执行。
// 否则写入时的任何数据库错误(历史上是新平台尚未加入 user_platform_quotas 的
// CHECK 约束)都会让整个调用方事务被 Postgres 标记 aborted,把"无关紧要的默认
// 配额快照"放大成"整笔注册失败"(OAuth pending 路径曾因此 500 → 清 cookie → 404)。
ctx = dbent.WithoutTx(ctx)
// 仅为至少配置了一档限额的平台建行:user_platform_quotas 中不存在的行等价于不限额,
// 三档全空的记录不携带任何可执行的限额。
records := make([]UserPlatformQuotaRecord, 0, len(plan.PlatformQuotas))
for platform, q := range plan.PlatformQuotas {
if !q.HasAnyLimit() {
continue
}
records = append(records, UserPlatformQuotaRecord{
UserID: userID,
Platform: platform,
DailyLimitUSD: q.DailyLimitUSD,
WeeklyLimitUSD: q.WeeklyLimitUSD,
MonthlyLimitUSD: q.MonthlyLimitUSD,
})
}
if len(records) == 0 {
return nil
}
if err := s.userPlatformQuotaRepo.BulkInsertInitial(ctx, records); err != nil {
if err := snapshotUserPlatformQuotaDefaults(ctx, s.userPlatformQuotaRepo, userID, plan.PlatformQuotas); err != nil {
logger.LegacyPrintf("service.auth", "[Auth] Warning: snapshot platform quota failed user=%d: %v (fail-open)", userID, err)
return nil // fail-open:返回 nil,让调用方继续
}
return nil
}
+1 -8
View File
@@ -765,14 +765,7 @@ func sanitizeBedrockThinking(body []byte, modelID string) []byte {
}
if claude.IsSonnet55(modelID) {
switch thinkingType {
case "enabled":
body, _ = sjson.SetBytes(body, "thinking.type", "adaptive")
body, _ = sjson.DeleteBytes(body, "thinking.budget_tokens")
case "disabled":
body, _ = sjson.SetBytes(body, "thinking.type", "between_tools")
}
return body
return adaptThinkingToClaude55(body, modelID)
}
if isBedrockOpus47OrNewer(modelID) {
@@ -0,0 +1,27 @@
package service
import (
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
// adaptThinkingToClaude55 replaces a thinking mode that a Claude 5.5 model
// rejects with the nearest mode it accepts: enabled becomes adaptive without
// budget_tokens, and on Sonnet 5.5 disabled becomes between_tools. Other modes
// are left for validateClaude55Request to judge.
func adaptThinkingToClaude55(body []byte, model string) []byte {
if !isClaude55SignedThinkingModel(model) {
return body
}
switch gjson.GetBytes(body, "thinking.type").String() {
case "enabled":
body, _ = sjson.SetBytes(body, "thinking.type", "adaptive")
body, _ = sjson.DeleteBytes(body, "thinking.budget_tokens")
case "disabled":
if claude.IsSonnet55(model) {
body, _ = sjson.SetBytes(body, "thinking.type", "between_tools")
}
}
return body
}
@@ -120,6 +120,18 @@ func withCompositeRequiredClaimStrength(ctx context.Context, strength CompositeC
return context.WithValue(ctx, ctxkey.CompositeRequiredClaimStrength, strength)
}
// RewriteCompositeRequestModel puts a composite route's upstream model into the
// request body at modelPath. The client chose its thinking mode for the model
// it asked for, so a mode the upstream model rejects becomes the nearest mode
// it accepts. The body is returned unchanged when it cannot be rewritten.
func RewriteCompositeRequestModel(body []byte, modelPath, upstreamModel string) []byte {
rewritten, err := sjson.SetBytes(body, modelPath, upstreamModel)
if err != nil {
return body
}
return adaptThinkingToClaude55(rewritten, upstreamModel)
}
func ResolvedUpstreamModelFromContext(ctx context.Context) (string, bool) {
if ctx == nil {
return "", false
@@ -0,0 +1,82 @@
//go:build unit
package service
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func forwardCompositeThinkingRequest(t *testing.T, publicModel, upstreamModel, clientBody string) (*httptest.ResponseRecorder, *anthropicHTTPUpstreamRecorder, error) {
t.Helper()
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/messages", nil)
body := []byte(clientBody)
ctx := context.Background()
if upstreamModel != publicModel {
body = RewriteCompositeRequestModel(body, "model", upstreamModel)
ctx = WithCompositeRouteDecision(ctx, CompositeRouteDecision{
Matched: true, Source: CompositeRouteSourceExplicit,
PublicModel: publicModel, TargetPlatform: PlatformAnthropic, UpstreamModel: upstreamModel,
})
}
c.Request = c.Request.WithContext(ctx)
parsed, err := ParseGatewayRequest(NewRequestBodyRef(body), PlatformAnthropic)
require.NoError(t, err)
upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{
StatusCode: http.StatusOK,
Header: http.Header{"Content-Type": []string{"application/json"}},
Body: io.NopCloser(strings.NewReader(`{"id":"msg_1","type":"message","role":"assistant","model":"` + upstreamModel + `","content":[{"type":"text","text":"ok"}],"usage":{"input_tokens":1,"output_tokens":1}}`)),
}}
svc := newForwardPartialUsageServiceForTest(upstream)
_, err = svc.Forward(ctx, c, newAnthropicOAuthAccountForPartialUsageTest(), parsed)
return rec, upstream, err
}
// A composite route that rewrites claude-sonnet-5 to claude-opus-5-5 sends the
// client's budget thinking upstream as adaptive thinking instead of failing
// Opus 5.5 validation.
func TestCompositeRewriteToOpus55SendsEnabledThinkingAsAdaptive(t *testing.T) {
rec, upstream, err := forwardCompositeThinkingRequest(t, "claude-sonnet-5", "claude-opus-5-5",
`{"model":"claude-sonnet-5","max_tokens":64,"stream":false,"thinking":{"type":"enabled","budget_tokens":4096},"messages":[{"role":"user","content":"hi"}]}`)
require.NoError(t, err)
require.NotEqual(t, http.StatusBadRequest, rec.Code)
require.NotNil(t, upstream.lastReq, "request must reach the upstream")
require.Equal(t, "claude-opus-5-5", gjson.GetBytes(upstream.lastBody, "model").String())
require.Equal(t, "adaptive", gjson.GetBytes(upstream.lastBody, "thinking.type").String())
require.False(t, gjson.GetBytes(upstream.lastBody, "thinking.budget_tokens").Exists())
}
func TestCompositeRewriteToSonnet55SendsDisabledThinkingAsBetweenTools(t *testing.T) {
rec, upstream, err := forwardCompositeThinkingRequest(t, "claude-sonnet-5", "claude-sonnet-5-5",
`{"model":"claude-sonnet-5","max_tokens":64,"stream":false,"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"hi"}]}`)
require.NoError(t, err)
require.NotEqual(t, http.StatusBadRequest, rec.Code)
require.NotNil(t, upstream.lastReq, "request must reach the upstream")
require.Equal(t, "between_tools", gjson.GetBytes(upstream.lastBody, "thinking.type").String())
}
// Without a model rewrite the client's own invalid thinking mode is still
// rejected.
func TestDirectOpus55RequestWithEnabledThinkingIsStillRejected(t *testing.T) {
rec, upstream, err := forwardCompositeThinkingRequest(t, "claude-opus-5-5", "claude-opus-5-5",
`{"model":"claude-opus-5-5","max_tokens":64,"stream":false,"thinking":{"type":"enabled","budget_tokens":4096},"messages":[{"role":"user","content":"hi"}]}`)
require.ErrorContains(t, err, "claude-opus-5-5 requires adaptive thinking")
require.Equal(t, http.StatusBadRequest, rec.Code)
require.Nil(t, upstream.lastReq)
}
@@ -68,9 +68,9 @@ func TestAnthropicConverterOutputCacheFields(t *testing.T) {
var err error
switch route {
case "chat buffered":
result, err = service.bufferChatCompletionsAsAnthropic(ctx, response, "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now())
result, err = service.bufferChatCompletionsAsAnthropic(ctx, response, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now())
case "chat terminal", "chat eof":
result, err = service.streamChatCompletionsAsAnthropic(ctx, response, "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now())
result, err = service.streamChatCompletionsAsAnthropic(ctx, response, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", nil, nil, time.Now())
case "responses buffered":
result, err = service.handleAnthropicBufferedStreamingResponse(response, ctx, rawChatCompletionsTestAccount(), "gpt-5.4", "gpt-5.4", "gpt-5.4", time.Now())
default:
@@ -1091,7 +1091,15 @@ func enforceCacheControlLimit(body []byte) []byte {
}
return normalizeCacheControlTTLOrder(body)
}
return normalizeCacheControlTTLOrder(enforceCacheControlBlockLimit(body))
out := enforceCacheControlBlockLimit(body)
// Escaped bodies returned earlier, so a missing "1h" literal here is exact:
// the TTL walk would find no 1h breakpoint and rewrite nothing, yet it still
// costs a full collectCacheControlPaths pass over the body. Deletions above
// only remove cache_control keys, so they cannot introduce a 1h breakpoint.
if !bytes.Contains(body, cacheTTL1hJSONBytes) {
return out
}
return normalizeCacheControlTTLOrder(out)
}
// enforceCacheControlBlockLimit 强制执行 cache_control 块数量限制(最多 4 个)
@@ -1221,10 +1229,57 @@ func normalizeCacheControlTTLOrder(body []byte) []byte {
// injectAnthropicCacheControlTTL1h 将已有 ephemeral cache_control 块的 ttl 强制写为 1h。
// 仅修改已经存在的 cache_control,不新增缓存断点。
//
// Claude Code compaction requests are written at 5m instead: the conversation is
// replaced by the summary afterwards, so nothing reads the extra tokens again,
// and a 5m breakpoint still reads the prefix the main thread wrote at 1h.
func injectAnthropicCacheControlTTL1h(body []byte) []byte {
if isClaudeCodeCompactionRequest(body) {
return forceEphemeralCacheControlTTL(body, cacheTTLTarget5m)
}
return forceEphemeralCacheControlTTL(body, cacheTTLTarget1h)
}
// claudeCodeCompactPreamble opens the compact prompt of Claude Code 2.1.282 in
// its full, partial-from and partial-up-to variants, and no other prompt it sends.
const claudeCodeCompactPreamble = "CRITICAL: Respond with TEXT ONLY. Do NOT call any tools.\n\n"
// isClaudeCodeCompactionRequest reports whether the last user message is a compact
// prompt. When auto-compaction fires during a tool loop the prompt arrives as a text
// block merged into the user message that carries the tool_result.
func isClaudeCodeCompactionRequest(body []byte) bool {
return claudeLastUserTextHasPrefix(body, claudeCodeCompactPreamble)
}
// claudeLastUserTextHasPrefix reports whether a text block (or the string content) of
// the last user message starts with any of prefixes.
func claudeLastUserTextHasPrefix(body []byte, prefixes ...string) bool {
hasPrefix := func(s string) bool {
for _, p := range prefixes {
if strings.HasPrefix(s, p) {
return true
}
}
return false
}
var last gjson.Result
gjson.GetBytes(body, "messages").ForEach(func(_, msg gjson.Result) bool {
if msg.Get("role").String() == "user" {
last = msg.Get("content")
}
return true
})
if last.Type == gjson.String {
return hasPrefix(last.Str)
}
found := false
last.ForEach(func(_, block gjson.Result) bool {
found = block.Get("type").String() == "text" && hasPrefix(block.Get("text").String())
return !found
})
return found
}
func forceEphemeralCacheControlTTL(body []byte, ttl string) []byte {
if len(body) == 0 || ttl == "" {
return body
@@ -0,0 +1,87 @@
package service
import (
"encoding/json"
"fmt"
"testing"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
// Only the preamble is the real marker; the rest of the prompt is placeholder text.
const testCompactPrompt = claudeCodeCompactPreamble + "placeholder compact instructions"
// compactionTestBody builds a request with three breakpoints (two system blocks and
// the assistant message before the last user message) and a trailing role:system
// message. lastUser is the JSON content of the last user message; a non-empty
// cacheTTL is written into every breakpoint.
func compactionTestBody(t *testing.T, lastUser string, cacheTTL string) []byte {
t.Helper()
cc := `{"type":"ephemeral"}`
if cacheTTL != "" {
cc = fmt.Sprintf(`{"type":"ephemeral","ttl":%q}`, cacheTTL)
}
body := fmt.Sprintf(`{"model":"claude-test","messages":[`+
`{"role":"user","content":[{"type":"text","text":"first question"}]},`+
`{"role":"assistant","content":[{"type":"tool_use","id":"toolu_1","name":"Bash","input":{"command":"ls"},"cache_control":%[1]s}]},`+
`{"role":"user","content":%[2]s},`+
`{"role":"system","content":"placeholder trailing system message"}],`+
`"system":[{"type":"text","text":"billing block"},`+
`{"type":"text","text":"system block one","cache_control":%[1]s},`+
`{"type":"text","text":"system block two","cache_control":%[1]s}],`+
`"tools":[{"name":"Bash","input_schema":{}}],"max_tokens":1024,"stream":true}`, cc, lastUser)
require.True(t, json.Valid([]byte(body)))
return []byte(body)
}
func compactionTestJSONString(t *testing.T, s string) string {
t.Helper()
b, err := json.Marshal(s)
require.NoError(t, err)
return string(b)
}
func requireCompactionTestTTLs(t *testing.T, body []byte, want string) {
t.Helper()
for _, path := range []string{"system.1.cache_control", "system.2.cache_control", "messages.1.content.0.cache_control"} {
require.Equal(t, want, gjson.GetBytes(body, path+".ttl").String(), path)
}
}
func TestInjectAnthropicCacheControlTTL1h_CompactionUses5m(t *testing.T) {
prompt := compactionTestJSONString(t, testCompactPrompt)
cases := map[string]string{
"merged_with_tool_result": `[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":` + prompt + `}]`,
"own_message": prompt,
}
for name, lastUser := range cases {
for _, clientTTL := range []string{"", "1h"} {
t.Run(name+"/client_ttl="+clientTTL, func(t *testing.T) {
out := injectAnthropicCacheControlTTL1h(compactionTestBody(t, lastUser, clientTTL))
require.NotContains(t, string(out), `"1h"`)
requireCompactionTestTTLs(t, out, "5m")
})
}
}
}
func TestInjectAnthropicCacheControlTTL1h_NonCompactionStill1h(t *testing.T) {
cases := map[string]string{
"tool_result_and_reminder": `[{"type":"tool_result","tool_use_id":"toolu_1","content":"ok"},{"type":"text","text":"keep going"}]`,
"preamble_not_at_start": compactionTestJSONString(t, "note: "+testCompactPrompt),
}
for name, lastUser := range cases {
t.Run(name, func(t *testing.T) {
out := injectAnthropicCacheControlTTL1h(compactionTestBody(t, lastUser, ""))
requireCompactionTestTTLs(t, out, "1h")
})
}
}
func TestIsClaudeCodeCompactionRequest_OnlyLastUserMessageCounts(t *testing.T) {
earlier := `{"messages":[{"role":"user","content":` + compactionTestJSONString(t, testCompactPrompt) + `},{"role":"assistant","content":"summary"},{"role":"user","content":"next question"}]}`
require.False(t, isClaudeCodeCompactionRequest([]byte(earlier)))
require.False(t, isClaudeCodeCompactionRequest([]byte(`{"messages":[]}`)))
require.False(t, isClaudeCodeCompactionRequest([]byte(`{}`)))
}
+132 -34
View File
@@ -189,29 +189,115 @@ func clearGatewayRequestRanges(parsed *ParsedRequest) {
parsed.inputRange = missingJSONRange()
}
func setGatewayRequestRanges(parsed *ParsedRequest, protocol string, jsonStr string) {
// gatewayRequestRootFields 保存一次根对象遍历取到的原始值视图。全部零拷贝,
// 只在本次解析内使用,body 被改写后必须重新扫描。
//
// 嵌套字段按 gjson.Get 的语义取值:路径的每一段都取「第一个能解析出子键的同名键」,
// 而不是简单取第一个同名键。例如 {"metadata":"x","metadata":{"user_id":"u"}} 在
// gjson.Get("metadata.user_id") 下取到 "u",这里以 Exists() 作为「还没取到」的判据
// 复现该重试行为。
type gatewayRequestRootFields struct {
model gjson.Result
stream gjson.Result
maxTokens gjson.Result
metadataUID gjson.Result
thinkingType gjson.Result
outputEffort gjson.Result
speed gjson.Result
system gjson.Result
messages gjson.Result
input gjson.Result
contents gjson.Result
geminiSysParts gjson.Result
}
// scanGatewayRequestRoot 用一次根对象遍历取出解析需要的全部字段。
//
// 逐字段 gjson.Get 的问题在于「键不存在」也要把整份 body 扫一遍才能返回不存在:
// 1 MiB body 上每个缺失键约 142µs,而一次完整遍历约 220µs——解析一次要做 7 次查找,
// 其中 6 个键(metadata.user_id / thinking.type / output_config.effort / max_tokens /
// system / messages)在典型 Responses 请求里都不存在。
func scanGatewayRequestRoot(body []byte) gatewayRequestRootFields {
var f gatewayRequestRootFields
parseRawJSONView(body).ForEach(func(key, value gjson.Result) bool {
switch key.Str {
case "model":
if !f.model.Exists() {
f.model = value
}
case "stream":
if !f.stream.Exists() {
f.stream = value
}
case "max_tokens":
if !f.maxTokens.Exists() {
f.maxTokens = value
}
case "metadata":
if !f.metadataUID.Exists() {
f.metadataUID = value.Get("user_id")
}
case "thinking":
if !f.thinkingType.Exists() {
f.thinkingType = value.Get("type")
}
case "output_config":
if !f.outputEffort.Exists() {
f.outputEffort = value.Get("effort")
}
case "speed":
if !f.speed.Exists() {
f.speed = value
}
case "system":
if !f.system.Exists() {
f.system = value
}
case "messages":
if !f.messages.Exists() {
f.messages = value
}
case "input":
if !f.input.Exists() {
f.input = value
}
case "contents":
if !f.contents.Exists() {
f.contents = value
}
case "systemInstruction":
if !f.geminiSysParts.Exists() {
f.geminiSysParts = value.Get("parts")
}
}
return true
})
return f
}
func setGatewayRequestRangesFromFields(parsed *ParsedRequest, protocol string, fields gatewayRequestRootFields) {
if parsed == nil {
return
}
switch protocol {
case domain.PlatformGemini:
if sysParts := gjson.Get(jsonStr, "systemInstruction.parts"); sysParts.Exists() && sysParts.IsArray() {
parsed.systemRange = rangeFromResult(sysParts)
if fields.geminiSysParts.Exists() && fields.geminiSysParts.IsArray() {
parsed.systemRange = rangeFromResult(fields.geminiSysParts)
}
if contents := gjson.Get(jsonStr, "contents"); contents.Exists() && contents.IsArray() {
parsed.messagesRange = rangeFromResult(contents)
if fields.contents.Exists() && fields.contents.IsArray() {
parsed.messagesRange = rangeFromResult(fields.contents)
}
default:
if sys := gjson.Get(jsonStr, "system"); sys.Exists() {
if fields.system.Exists() {
parsed.HasSystem = true
parsed.systemRange = rangeFromResult(sys)
parsed.systemRange = rangeFromResult(fields.system)
}
if msgs := gjson.Get(jsonStr, "messages"); msgs.Exists() && msgs.IsArray() {
parsed.messagesRange = rangeFromResult(msgs)
if fields.messages.Exists() && fields.messages.IsArray() {
parsed.messagesRange = rangeFromResult(fields.messages)
}
if protocol == "responses" {
if input := gjson.Get(jsonStr, "input"); input.Exists() {
parsed.inputRange = rangeFromResult(input)
if fields.input.Exists() {
parsed.inputRange = rangeFromResult(fields.input)
}
}
}
@@ -229,31 +315,32 @@ func normalizeClaudeCodeLongContextModel(model string) string {
return model
}
// parseGatewayRequestCurrentBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。
func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) error {
// parseGatewayRequestBody 只做标量和 raw range 轻量解析,不恢复 system/messages 对象图。
// validate 为 false 时要求调用方已经确认 body 是合法 JSON(见 ParseGatewayRequestValidated)。
func parseGatewayRequestBody(parsed *ParsedRequest, protocol string, validate bool) error {
if parsed == nil || parsed.Body == nil {
return fmt.Errorf("empty request body")
}
parsed.Body.parsed = nil
bodyBytes := parsed.Body.Bytes()
if !gjson.ValidBytes(bodyBytes) {
if validate && !gjson.ValidBytes(bodyBytes) {
return DescribeInvalidJSON(bodyBytes)
}
// Zero-copy JSON reads stay local to parsing. Persisted scalar strings must
// own their storage: an unescaped gjson string otherwise retains the complete
// request buffer when copied into queued billing work. Raw ranges stay zero-copy.
jsonStr := *(*string)(unsafe.Pointer(&bodyBytes))
clearGatewayRequestDerivedState(parsed)
parsed.protocol = protocol
modelResult := gjson.Get(jsonStr, "model")
if modelResult.Exists() {
if modelResult.Type != gjson.String {
fields := scanGatewayRequestRoot(bodyBytes)
if fields.model.Exists() {
if fields.model.Type != gjson.String {
return fmt.Errorf("invalid model field type")
}
parsed.Model = strings.Clone(modelResult.String())
parsed.Model = strings.Clone(fields.model.String())
if protocol == domain.PlatformAnthropic {
normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model)
if normalizedModel != parsed.Model {
@@ -263,47 +350,46 @@ func parseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) erro
}
parsed.Body.Replace(normalizedBody)
bodyBytes = normalizedBody
jsonStr = *(*string)(unsafe.Pointer(&bodyBytes))
// 改写后旧的值视图指向已失效的字节,重新遍历一次(仅 [1m] 规范化这条罕见路径)。
fields = scanGatewayRequestRoot(bodyBytes)
parsed.Model = normalizedModel
}
}
}
streamResult := gjson.Get(jsonStr, "stream")
if streamResult.Exists() {
if streamResult.Type != gjson.True && streamResult.Type != gjson.False {
if fields.stream.Exists() {
if fields.stream.Type != gjson.True && fields.stream.Type != gjson.False {
return fmt.Errorf("invalid stream field type")
}
parsed.Stream = streamResult.Bool()
parsed.Stream = fields.stream.Bool()
}
parsed.MetadataUserID = strings.Clone(gjson.Get(jsonStr, "metadata.user_id").String())
parsed.MetadataUserID = strings.Clone(fields.metadataUID.String())
thinkingType := gjson.Get(jsonStr, "thinking.type").String()
thinkingType := fields.thinkingType.String()
parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" ||
(protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model))
parsed.OutputEffort = strings.Clone(strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String()))
parsed.OutputEffort = strings.Clone(strings.TrimSpace(fields.outputEffort.String()))
if protocol == domain.PlatformAnthropic {
parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String())))
parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(fields.speed.String())))
}
maxTokensResult := gjson.Get(jsonStr, "max_tokens")
if maxTokensResult.Exists() && maxTokensResult.Type == gjson.Number {
f := maxTokensResult.Float()
if fields.maxTokens.Exists() && fields.maxTokens.Type == gjson.Number {
f := fields.maxTokens.Float()
if !math.IsNaN(f) && !math.IsInf(f, 0) && f == math.Trunc(f) &&
f <= float64(math.MaxInt) && f >= float64(math.MinInt) {
parsed.MaxTokens = int(f)
}
}
setGatewayRequestRanges(parsed, protocol, jsonStr)
setGatewayRequestRangesFromFields(parsed, protocol, fields)
parsed.saveBodyState()
return nil
}
func refreshGatewayRequestRanges(parsed *ParsedRequest, protocol string) error {
return parseGatewayRequestCurrentBody(parsed, protocol)
return parseGatewayRequestBody(parsed, protocol, true)
}
// DescribeInvalidJSON returns a diagnostic error for a request body that
@@ -410,8 +496,20 @@ func normalizeSessionUserAgentFallback(raw string) string {
// protocol 指定请求协议格式(domain.PlatformAnthropic / domain.PlatformGemini),
// 不同协议使用不同的 system/messages 字段名。
func ParseGatewayRequest(body *RequestBodyRef, protocol string) (*ParsedRequest, error) {
return parseGatewayRequest(body, protocol, true)
}
// ParseGatewayRequestValidated 与 ParseGatewayRequest 结果相同,但要求调用方已经确认
// body 是合法 JSON(例如 handler 已对同一份字节做过 gjson.ValidBytes,且此后的改写只
// 经过 sjson)。它跳过这次全量校验——1 MiB body 上约 510µs,占解析耗时的七成。
// 非法 JSON 的语义与未校验版本不同,只允许在校验过同一份字节的调用点使用。
func ParseGatewayRequestValidated(body *RequestBodyRef, protocol string) (*ParsedRequest, error) {
return parseGatewayRequest(body, protocol, false)
}
func parseGatewayRequest(body *RequestBodyRef, protocol string, validate bool) (*ParsedRequest, error) {
parsed := &ParsedRequest{Body: body}
if err := parseGatewayRequestCurrentBody(parsed, protocol); err != nil {
if err := parseGatewayRequestBody(parsed, protocol, validate); err != nil {
return nil, err
}
return parsed, nil
@@ -10,8 +10,32 @@ import (
// claudeCodeLikeBody builds a ~32KB request shaped like a Claude Code turn:
// 20 tools, a system prompt, and 40 messages with 4 content blocks each.
func claudeCodeLikeBody(cacheControls int, with1h bool) []byte {
return claudeCodeLikeBodyWith(claudeCodeLikeBodyOptions{cacheControls: cacheControls, with1h: with1h})
}
// claudeCodeLikeBodyWithThinking builds the same shape with extended thinking
// enabled: the top-level thinking config plus a thinking block in the last
// assistant turn. Either occurrence makes the byte-level precheck in
// enforceCacheControlLimit inapplicable, so this is the shape that decides
// whether the cache_control walks can be skipped for real Claude Code traffic.
func claudeCodeLikeBodyWithThinking(with1h bool) []byte {
return claudeCodeLikeBodyWith(claudeCodeLikeBodyOptions{cacheControls: 4, with1h: with1h, thinking: true})
}
type claudeCodeLikeBodyOptions struct {
cacheControls int
with1h bool
thinking bool
}
func claudeCodeLikeBodyWith(opts claudeCodeLikeBodyOptions) []byte {
cacheControls := opts.cacheControls
var b strings.Builder
_, _ = b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true,"tools":[`)
_, _ = b.WriteString(`{"model":"claude-sonnet-5-5","max_tokens":32000,"stream":true`)
if opts.thinking {
_, _ = b.WriteString(`,"thinking":{"type":"enabled","budget_tokens":31999}`)
}
_, _ = b.WriteString(`,"tools":[`)
for i := 0; i < 20; i++ {
if i > 0 {
_ = b.WriteByte(',')
@@ -42,10 +66,14 @@ func claudeCodeLikeBody(cacheControls int, with1h bool) []byte {
if c > 0 {
_ = b.WriteByte(',')
}
if opts.thinking && m == 39 && c == 0 {
_, _ = b.WriteString(`{"type":"thinking","thinking":"` + strings.Repeat("t", 80) + `","signature":"` + strings.Repeat("s", 64) + `"}`)
continue
}
fmt.Fprintf(&b, `{"type":"text","text":"%s"`, strings.Repeat("x", 120))
if m >= 38 && c == 3 && cacheControls > 0 {
ttl := ""
if with1h && m == 39 {
if opts.with1h && m == 39 {
ttl = `,"ttl":"1h"`
}
fmt.Fprintf(&b, `,"cache_control":{"type":"ephemeral"%s}`, ttl)
@@ -66,6 +94,8 @@ func BenchmarkEnforceCacheControlLimit(b *testing.B) {
}{
{"common_4cc_no1h", claudeCodeLikeBody(4, false)},
{"with_1h", claudeCodeLikeBody(4, true)},
{"thinking_4cc_no1h", claudeCodeLikeBodyWithThinking(false)},
{"thinking_4cc_1h", claudeCodeLikeBodyWithThinking(true)},
}
for _, tc := range cases {
b.Run(tc.name+"/legacy", func(b *testing.B) {
@@ -0,0 +1,94 @@
package service
import (
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/domain"
)
// buildGatewayRequestBenchmarkBody 生成 Codex / Claude Code 两种形态的大请求体。
func buildGatewayRequestBenchmarkBody(targetBytes int, anthropic bool) []byte {
var sb strings.Builder
sb.Grow(targetBytes + 1024)
// strings.Builder.WriteString 的 error 恒为 nil,errcheck 不接受裸忽略,收口在这里。
write := func(s string) { _, _ = sb.WriteString(s) }
item := `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 4000) + `"}]}`
if anthropic {
write(`{"model":"claude-sonnet-5-5","stream":true,"system":[{"type":"text","text":"`)
write(strings.Repeat("z", targetBytes/8))
write(`"}],"tools":[{"name":"shell","description":"`)
write(strings.Repeat("y", targetBytes/16))
write(`"}],"messages":[`)
msg := `{"role":"user","content":[{"type":"text","text":"` + strings.Repeat("x", 4000) + `"}]}`
for i := 0; sb.Len() < targetBytes; i++ {
if i > 0 {
write(`,`)
}
write(msg)
}
write(`]}`)
return []byte(sb.String())
}
write(`{"model":"gpt-5.5","stream":true,"instructions":"`)
write(strings.Repeat("z", targetBytes/8))
write(`","tools":[{"type":"function","name":"shell","description":"`)
write(strings.Repeat("y", targetBytes/16))
write(`"}],"input":[`)
for i := 0; sb.Len() < targetBytes; i++ {
if i > 0 {
write(`,`)
}
write(item)
}
write(`]}`)
return []byte(sb.String())
}
func BenchmarkParseGatewayRequestScan(b *testing.B) {
cases := []struct {
name string
size int
protocol string
anthropic bool
}{
{"responses_128KiB", 128 << 10, "responses", false},
{"responses_1MiB", 1 << 20, "responses", false},
{"anthropic_1MiB", 1 << 20, domain.PlatformAnthropic, true},
}
for _, tc := range cases {
body := buildGatewayRequestBenchmarkBody(tc.size, tc.anthropic)
b.Run(tc.name+"/legacy", func(b *testing.B) {
b.SetBytes(int64(len(body)))
b.ReportAllocs()
for range b.N {
parsed := &ParsedRequest{Body: NewRequestBodyRef(body)}
if err := legacyParseGatewayRequestCurrentBody(parsed, tc.protocol); err != nil {
b.Fatal(err)
}
}
})
b.Run(tc.name+"/scan", func(b *testing.B) {
b.SetBytes(int64(len(body)))
b.ReportAllocs()
for range b.N {
parsed := &ParsedRequest{Body: NewRequestBodyRef(body)}
if err := parseGatewayRequestBody(parsed, tc.protocol, true); err != nil {
b.Fatal(err)
}
}
})
// 调用方已经校验过同一份字节时(handler 已做 gjson.ValidBytes,且之后只经 sjson 改写)。
b.Run(tc.name+"/scan_validated", func(b *testing.B) {
b.SetBytes(int64(len(body)))
b.ReportAllocs()
for range b.N {
parsed := &ParsedRequest{Body: NewRequestBodyRef(body)}
if err := parseGatewayRequestBody(parsed, tc.protocol, false); err != nil {
b.Fatal(err)
}
}
})
}
}
@@ -0,0 +1,326 @@
package service
import (
"fmt"
"math"
"strings"
"testing"
"unsafe"
"github.com/Wei-Shaw/sub2api/internal/domain"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
// 下面两个函数是重构前的 parseGatewayRequestCurrentBody / setGatewayRequestRanges
// 的逐字副本,作为差分测试的基准。任何一处语义变化都会在下面的对比里暴露。
func legacyParseGatewayRequestCurrentBody(parsed *ParsedRequest, protocol string) error {
if parsed == nil || parsed.Body == nil {
return fmt.Errorf("empty request body")
}
parsed.Body.parsed = nil
bodyBytes := parsed.Body.Bytes()
if !gjson.ValidBytes(bodyBytes) {
return DescribeInvalidJSON(bodyBytes)
}
jsonStr := *(*string)(unsafe.Pointer(&bodyBytes))
clearGatewayRequestDerivedState(parsed)
parsed.protocol = protocol
modelResult := gjson.Get(jsonStr, "model")
if modelResult.Exists() {
if modelResult.Type != gjson.String {
return fmt.Errorf("invalid model field type")
}
parsed.Model = strings.Clone(modelResult.String())
if protocol == domain.PlatformAnthropic {
normalizedModel := normalizeClaudeCodeLongContextModel(parsed.Model)
if normalizedModel != parsed.Model {
normalizedBody, err := sjson.SetBytes(bodyBytes, "model", normalizedModel)
if err != nil {
return fmt.Errorf("normalize model field: %w", err)
}
parsed.Body.Replace(normalizedBody)
bodyBytes = normalizedBody
jsonStr = *(*string)(unsafe.Pointer(&bodyBytes))
parsed.Model = normalizedModel
}
}
}
streamResult := gjson.Get(jsonStr, "stream")
if streamResult.Exists() {
if streamResult.Type != gjson.True && streamResult.Type != gjson.False {
return fmt.Errorf("invalid stream field type")
}
parsed.Stream = streamResult.Bool()
}
parsed.MetadataUserID = strings.Clone(gjson.Get(jsonStr, "metadata.user_id").String())
thinkingType := gjson.Get(jsonStr, "thinking.type").String()
parsed.ThinkingEnabled = thinkingType == "enabled" || thinkingType == "adaptive" || thinkingType == "between_tools" ||
(protocol == domain.PlatformAnthropic && isClaude55SignedThinkingModel(parsed.Model))
parsed.OutputEffort = strings.Clone(strings.TrimSpace(gjson.Get(jsonStr, "output_config.effort").String()))
if protocol == domain.PlatformAnthropic {
parsed.Speed = strings.Clone(strings.ToLower(strings.TrimSpace(gjson.Get(jsonStr, "speed").String())))
}
maxTokensResult := gjson.Get(jsonStr, "max_tokens")
if maxTokensResult.Exists() && maxTokensResult.Type == gjson.Number {
f := maxTokensResult.Float()
if !math.IsNaN(f) && !math.IsInf(f, 0) && f == math.Trunc(f) &&
f <= float64(math.MaxInt) && f >= float64(math.MinInt) {
parsed.MaxTokens = int(f)
}
}
legacySetGatewayRequestRanges(parsed, protocol, jsonStr)
parsed.saveBodyState()
return nil
}
func legacySetGatewayRequestRanges(parsed *ParsedRequest, protocol string, jsonStr string) {
if parsed == nil {
return
}
switch protocol {
case domain.PlatformGemini:
if sysParts := gjson.Get(jsonStr, "systemInstruction.parts"); sysParts.Exists() && sysParts.IsArray() {
parsed.systemRange = rangeFromResult(sysParts)
}
if contents := gjson.Get(jsonStr, "contents"); contents.Exists() && contents.IsArray() {
parsed.messagesRange = rangeFromResult(contents)
}
default:
if sys := gjson.Get(jsonStr, "system"); sys.Exists() {
parsed.HasSystem = true
parsed.systemRange = rangeFromResult(sys)
}
if msgs := gjson.Get(jsonStr, "messages"); msgs.Exists() && msgs.IsArray() {
parsed.messagesRange = rangeFromResult(msgs)
}
if protocol == "responses" {
if input := gjson.Get(jsonStr, "input"); input.Exists() {
parsed.inputRange = rangeFromResult(input)
}
}
}
}
// parsedSnapshot 只记录解析产出的可观测结果,避免比较实现内部的缓存指针。
type parsedSnapshot struct {
err string
model string
stream bool
metadataUserID string
thinkingOn bool
outputEffort string
speed string
maxTokens int
hasSystem bool
systemRange jsonRange
messagesRange jsonRange
inputRange jsonRange
protocol string
bodyAfter string
}
func snapshotOf(parsed *ParsedRequest, err error) parsedSnapshot {
snap := parsedSnapshot{}
if err != nil {
snap.err = err.Error()
}
if parsed == nil {
return snap
}
snap.model = parsed.Model
snap.stream = parsed.Stream
snap.metadataUserID = parsed.MetadataUserID
snap.thinkingOn = parsed.ThinkingEnabled
snap.outputEffort = parsed.OutputEffort
snap.speed = parsed.Speed
snap.maxTokens = parsed.MaxTokens
snap.hasSystem = parsed.HasSystem
snap.systemRange = parsed.systemRange
snap.messagesRange = parsed.messagesRange
snap.inputRange = parsed.inputRange
snap.protocol = parsed.protocol
if parsed.Body != nil {
snap.bodyAfter = string(parsed.Body.Bytes())
}
return snap
}
func parseBoth(t *testing.T, protocol string, body []byte) (parsedSnapshot, parsedSnapshot) {
t.Helper()
legacyBody := NewRequestBodyRef(append([]byte(nil), body...))
legacyParsed := &ParsedRequest{Body: legacyBody}
legacyErr := legacyParseGatewayRequestCurrentBody(legacyParsed, protocol)
// 直接调被重构的这一步:ParseGatewayRequest 在失败时返回 nil,无法比较错误路径上的中间状态。
newBody := NewRequestBodyRef(append([]byte(nil), body...))
newParsed := &ParsedRequest{Body: newBody}
newErr := parseGatewayRequestBody(newParsed, protocol, true)
return snapshotOf(legacyParsed, legacyErr), snapshotOf(newParsed, newErr)
}
func TestParseGatewayRequestMatchesLegacy(t *testing.T) {
escape := string(rune(92))
cases := []struct {
name string
body string
}{
{"typical responses", `{"model":"gpt-5.5","stream":true,"input":[{"type":"message"}]}`},
{"typical anthropic", `{"model":"claude-sonnet-5-5","stream":true,"system":"s","messages":[{"role":"user","content":"hi"}],"max_tokens":1024,"thinking":{"type":"enabled"},"output_config":{"effort":" high "},"speed":"Fast"}`},
{"typical gemini", `{"contents":[{"parts":[{"text":"hi"}]}],"systemInstruction":{"parts":[{"text":"sys"}]},"generationConfig":{"maxOutputTokens":32}}`},
{"empty object", `{}`},
{"empty string", ``},
{"invalid json", `{"model":`},
{"invalid json with image tool", `{"tools":[{"type":"image_generation"}]`},
{"model wrong type", `{"model":123}`},
{"model null", `{"model":null}`},
{"stream wrong type", `{"model":"m","stream":"yes"}`},
{"stream null", `{"model":"m","stream":null}`},
{"stream false", `{"model":"m","stream":false}`},
{"max_tokens float", `{"model":"m","max_tokens":1024.5}`},
{"max_tokens negative", `{"model":"m","max_tokens":-8}`},
{"max_tokens huge", `{"model":"m","max_tokens":1e30}`},
{"max_tokens string", `{"model":"m","max_tokens":"1024"}`},
{"metadata nested", `{"metadata":{"user_id":"u1"}}`},
{"metadata string first", `{"metadata":"x","metadata":{"user_id":"u2"}}`},
{"metadata null child", `{"metadata":{"user_id":null},"metadata":{"user_id":"u3"}}`},
{"metadata wrong shape", `{"metadata":[],"metadata":{"user_id":"u4"}}`},
{"thinking string first", `{"thinking":"x","thinking":{"type":"enabled"}}`},
{"thinking adaptive", `{"thinking":{"type":"adaptive"}}`},
{"thinking between tools", `{"thinking":{"type":"between_tools"}}`},
{"effort with spaces", `{"output_config":{"effort":" medium "}}`},
{"effort first empty", `{"output_config":{"effort":""},"output_config":{"effort":"high"}}`},
{"speed uppercase", `{"speed":" FAST "}`},
{"system string", `{"system":"sys","messages":[{"role":"user"}]}`},
{"system object", `{"system":{"type":"text"},"messages":[]}`},
{"system wrong shape", `{"system":123}`},
{"messages not array", `{"messages":"x"}`},
{"input present", `{"input":[{"a":1}]}`},
{"contents not array", `{"contents":"x"}`},
{"gemini parts not array", `{"systemInstruction":{"parts":"x"}}`},
{"gemini parts retry", `{"systemInstruction":{"parts":"x"},"systemInstruction":{"parts":[{"a":1}]}}`},
{"duplicate model", `{"model":"m1","model":"m2"}`},
{"duplicate stream", `{"stream":true,"stream":false}`},
{"long context suffix", `{"model":"claude-sonnet-5-5[1m]","messages":[]}`},
{"long context suffix duplicated", `{"model":"claude-sonnet-5-5[1m][1m]","messages":[]}`},
{"escaped system key", `{"` + escape + `u0073ystem":"s","messages":[]}`},
{"escaped model key", `{"` + escape + `u006dodel":"m"}`},
{"root array", `[1,2,3]`},
{"root scalar", `"just a string"`},
{"nested nulls", `{"model":"m","system":null,"messages":[{"a":1}],"input":null}`},
{"unicode content", `{"model":"m","messages":[{"content":"中文 😀"}]}`},
}
protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini}
for _, tc := range cases {
for _, protocol := range protocols {
t.Run(tc.name+"/"+protocol, func(t *testing.T) {
want, got := parseBoth(t, protocol, []byte(tc.body))
require.Equal(t, want, got, "body=%s", tc.body)
})
}
}
}
// deterministic 随机组合,覆盖键顺序、重复键、类型混杂的组合空间。
func TestParseGatewayRequestMatchesLegacyRandomized(t *testing.T) {
pieces := []string{
`"model":"m"`, `"model":"claude-x[1m]"`, `"model":null`, `"model":1`,
`"stream":true`, `"stream":"x"`, `"stream":null`,
`"max_tokens":16`, `"max_tokens":16.5`, `"max_tokens":"16"`,
`"metadata":{"user_id":"u"}`, `"metadata":"s"`, `"metadata":null`,
`"thinking":{"type":"enabled"}`, `"thinking":{"type":"adaptive"}`, `"thinking":"x"`,
`"output_config":{"effort":" low "}`, `"output_config":null`,
`"speed":" FAST "`, `"speed":null`,
`"system":"sys"`, `"system":[{"type":"text"}]`, `"system":null`,
`"messages":[]`, `"messages":[{"role":"user"}]`, `"messages":"x"`,
`"input":[]`, `"input":[{"a":1}]`, `"input":null`,
`"contents":[]`, `"contents":"x"`,
`"systemInstruction":{"parts":[]}`, `"systemInstruction":{"parts":"x"}`,
`"unknown":1`, `"unknown":{"nested":true}`,
}
protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini}
seed := uint64(0x9e3779b97f4a7c15)
next := func() uint64 {
seed ^= seed << 13
seed ^= seed >> 7
seed ^= seed << 17
return seed
}
for i := 0; i < 3000; i++ {
n := int(next()%6) + 1
parts := make([]string, 0, n)
for j := 0; j < n; j++ {
parts = append(parts, pieces[int(next()%uint64(len(pieces)))])
}
body := []byte("{" + strings.Join(parts, ",") + "}")
protocol := protocols[int(next()%uint64(len(protocols)))]
want, got := parseBoth(t, protocol, body)
require.Equal(t, want, got, "iteration=%d protocol=%s body=%s", i, protocol, body)
}
}
// 已校验变体只允许在「body 合法」的前提下使用;合法 JSON 上两者必须产出完全相同的结果。
func TestParseGatewayRequestValidatedMatchesValidatingPath(t *testing.T) {
bodies := []string{
`{"model":"gpt-5.5","stream":true,"input":[{"type":"message"}]}`,
`{"model":"claude-x[1m]","messages":[],"system":"s","max_tokens":8}`,
`{"metadata":{"user_id":"u"},"thinking":{"type":"enabled"},"output_config":{"effort":" high "}}`,
`{"contents":[],"systemInstruction":{"parts":[]}}`,
`{}`,
}
protocols := []string{"responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini}
for _, body := range bodies {
for _, protocol := range protocols {
validating := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))}
validatingErr := parseGatewayRequestBody(validating, protocol, true)
trusted := &ParsedRequest{Body: NewRequestBodyRef([]byte(body))}
trustedErr := parseGatewayRequestBody(trusted, protocol, false)
require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr),
"body=%s protocol=%s", body, protocol)
}
}
}
func FuzzParseGatewayRequestMatchesLegacy(f *testing.F) {
f.Add([]byte(`{"model":"m","stream":true,"input":[]}`), "responses")
f.Add([]byte(`{"model":"claude-x[1m]","messages":[],"system":"s"}`), domain.PlatformAnthropic)
f.Add([]byte(`{"metadata":{"user_id":"u"},"thinking":{"type":"enabled"}}`), "chat_completions")
f.Add([]byte(`{"contents":[],"systemInstruction":{"parts":[]}}`), domain.PlatformGemini)
f.Fuzz(func(t *testing.T, body []byte, protocol string) {
switch protocol {
case "responses", "chat_completions", domain.PlatformAnthropic, domain.PlatformGemini:
default:
return
}
want, got := parseBoth(t, protocol, body)
require.Equal(t, want, got, "body=%q protocol=%s", body, protocol)
// 合法 JSON 上,跳过校验不得改变结果。
if gjson.ValidBytes(body) {
validating := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))}
validatingErr := parseGatewayRequestBody(validating, protocol, true)
trusted := &ParsedRequest{Body: NewRequestBodyRef(append([]byte(nil), body...))}
trustedErr := parseGatewayRequestBody(trusted, protocol, false)
require.Equal(t, snapshotOf(validating, validatingErr), snapshotOf(trusted, trustedErr),
"validated path diverged: body=%q protocol=%s", body, protocol)
}
})
}
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff. Show more