fix(gateway): reject request bodies whose duplicate fields disagree

A body such as {"model":"cheap",...,"model":"expensive"} was scheduled and
billed under the first model, while paths that decode and re-encode the
body forwarded the last one. gjson returns the first member with a name;
encoding/json keeps the last and matches struct fields case-insensitively.
The group allowlist already validates every model candidate, but billing
did not, and groups without an allowlist had no check at all.

RejectConflictingRequestFields runs on every gateway chain after the
allowlist and before the composite rewrite. It answers 400 when a
top-level JSON member, a member of the session object, or a multipart
model/session field is declared more than once with different values.
Repeated fields with identical values still pass, as they do in the
allowlist. Responses WebSocket frames apply the same rule to their model
candidates on the first frame and on later turns.

The source-level chain assertion in gateway_model_allowlist_test.go is
updated for the new middleware position.

Not covered: repeated non-model members inside WebSocket frames (an
existing test accepts a repeated previous_response_id there), and nested
objects other than session.

Refs: GHSA-p3r4-jcm3-2hph

Co-Authored-By: claude-mythos-5-2 <noreply@anthropic.com>
This commit is contained in:
AIBIN GEandclaude-mythos-5-2 committed 2026-11-20 04:00:28 +09:00
1 parent 2af3f1e15c
commit 2b67d1ede2
9 files changed
+827 -6

No files matched your search

@@ -2607,12 +2607,20 @@ 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 键/大小写变体取值不一致时,计费按首个值、上游可能按末值
// 绑定。与 HTTP 入口(RejectConflictingRequestFields)一致,对所有分组直接
// 拒绝;取值相同的重复键放行。放在白名单之后,白名单的拒绝原因保持不变。
if requestmodel.HasConflictingModels(firstModelCandidates) {
closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, "response.create payload declares model more than once with different values")
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
@@ -3084,12 +3092,18 @@ 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 requestmodel.HasConflictingModels(frameModelCandidates) {
return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "websocket request payload declares model more than once with different values", 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)
@@ -0,0 +1,75 @@
package handler
import (
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
)
const wsModelConflictCloseReason = "declares model more than once with different values"
// 没有开启白名单的分组:首帧里重复 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,
})
})
}
}
// 取值相同的重复 model 键不受影响,两个 turn 正常完成。
func TestOpenAIResponsesWebSocket_IdenticalDuplicateModelKeysAllowedWithoutAllowlist(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","model":"gpt-5.4","stream":false}`,
group: wsAllowlistGroup(false),
})
if len(got.clientEvents) != 2 {
t.Fatalf("expected two completed events, got %d", len(got.clientEvents))
}
}
@@ -0,0 +1,139 @@
package requestmodel
import (
"bytes"
"strings"
"unicode"
"unsafe"
"github.com/tidwall/gjson"
)
// utf8BOM 是部分客户端写在 JSON 文档前的 UTF-8 字节序标记。宽容读取会跳过它
// 再解析对象,歧义检查也要看同一个对象。
var utf8BOM = []byte{0xEF, 0xBB, 0xBF}
// ConflictingField 返回请求体里第一个「重复声明且取值不一致」的字段名。
//
// 网关读取 model、service_tier 等字段用的是 gjson(重复键取第一个、大小写
// 敏感),而改写并转发请求体的路径会经过 encoding/json(重复键取最后一个,
// 结构体绑定不区分大小写)。同名字段取值不一致时,准入、计费看到的值和上游
// 实际收到的值会分叉:{"model":"便宜模型",...,"model":"贵模型"} 按便宜模型
// 计费,转发的却是贵模型。调用方应在任何解析器读取字段之前拒绝这类请求。
//
// 判定范围:
// - JSON:顶层成员名在转义解码、大小写折叠后相同,且原始取值不同;顶层
// session 对象(Live 入口的模型所在位置)内部同理,字段名报告为
// session.<name>。
// - multipart:model / session 文本字段出现多次且取值不同;session 字段的
// JSON 值内部同理。
//
// 取值完全相同的重复字段不算歧义:任何解析器绑定到的值都一样,这与白名单
// 准入对同值重复字段的放行保持一致。不是 JSON 对象也不是 multipart 的请求体
// 返回 false,其合法性由各入口自己的解析器判断。
func ConflictingField(contentType string, body []byte) (string, bool) {
if isMultipartContentType(contentType) {
return multipartConflictingField(contentType, body)
}
return jsonConflictingField(body)
}
// HasConflictingModels 判断模型候选集(见 FromBodyCandidates)里是否存在不同的
// 取值。候选集覆盖重复键与大小写变体,取值不一致说明不同解析器会绑定到不同
// 模型。
func HasConflictingModels(candidates []string) bool {
for i := 1; i < len(candidates); i++ {
if candidates[i] != candidates[0] {
return true
}
}
return false
}
// jsonConflictingField 检查 JSON 对象的顶层成员,以及顶层 session 对象的成员。
func jsonConflictingField(body []byte) (string, bool) {
body = bytes.TrimPrefix(body, utf8BOM)
if len(body) == 0 {
return "", false
}
// 零拷贝视图只在本次检查内使用;返回的字段名会单独复制。
root := gjson.Parse(*(*string)(unsafe.Pointer(&body)))
if !root.IsObject() {
return "", false
}
if name, ok := conflictingMember(root); ok {
return name, true
}
conflict := ""
root.ForEach(func(key, value gjson.Result) bool {
if !strings.EqualFold(key.String(), "session") || !value.IsObject() {
return true
}
if name, ok := conflictingMember(value); ok {
conflict = "session." + name
return false
}
return true
})
return conflict, conflict != ""
}
// conflictingMember 返回对象里第一个与更早的同名成员取值不同的成员名。
// 成员名按 encoding/json 结构体绑定的规则比较:先解码转义,再做 Unicode
// 简单大小写折叠,所以 model、MODEL 和 "\u006dodel" 是同一个名字。取值按原始
// JSON 文本比较,写法不同的等价值(如 1 和 1.0)按不一致处理。
func conflictingMember(object gjson.Result) (string, bool) {
seen := make(map[string]string)
conflict := ""
object.ForEach(func(key, value gjson.Result) bool {
folded := strings.Map(foldRune, key.String())
first, repeated := seen[folded]
if !repeated {
seen[folded] = value.Raw
return true
}
if first != value.Raw {
conflict = strings.Clone(key.String())
return false
}
return true
})
return conflict, conflict != ""
}
// foldRune 返回 r 所在大小写折叠轨道上的固定代表,只有大小写不同的字符映射到
// 同一个值。拉丁字母取小写,常见的小写字段名无需改写。
func foldRune(r rune) rune {
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
}
// multipartConflictingField 检查 multipart 表单:model / session 文本字段多次
// 出现且取值不同,或某个 session 字段的 JSON 值内部存在取值不一致的重复成员。
func multipartConflictingField(contentType string, body []byte) (string, bool) {
models, sessions := multipartModelCandidates(contentType, body)
if HasConflictingModels(models) {
return "model", true
}
if HasConflictingModels(sessions) {
return "session", true
}
for _, raw := range sessions {
session := gjson.Parse(raw)
if !session.IsObject() {
continue
}
if name, ok := conflictingMember(session); ok {
return "session." + name, true
}
}
return "", false
}
@@ -0,0 +1,160 @@
package requestmodel
import (
"bytes"
"encoding/json"
"mime/multipart"
"testing"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)
func TestConflictingFieldJSONReportsDisagreeingDuplicates(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":"a","model":"a","model":"b"}`, want: "model"},
{name: "大小写变体", body: `{"model":"gpt-5.4-nano","MODEL":"gpt-5.4"}`, want: "MODEL"},
{name: "转义写法", body: `{"model":"cheap","\u006dodel":"expensive"}`, want: "model"},
{name: "长 s 折叠为 s", body: "{\"service_tier\":\"flex\",\"\u017Fervice_tier\":\"priority\"}", want: "\u017Fervice_tier"},
{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: `{"n":1,"n":1.0}`, want: "n"},
{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"},
}
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: "取值相同的重复 model", body: `{"model":"gpt-5.4","input":"hi","model":"gpt-5.4"}`},
{name: "取值相同的大小写变体", body: `{"model":"gpt-5.4","Model":"gpt-5.4"}`},
{name: "session 内取值相同的重复 model", body: `{"session":{"model":"a","model":"a"}}`},
{name: "只有嵌套对象里有不一致的重复键", body: `{"model":"a","metadata":{"user_id":"1","user_id":"2"}}`},
{name: "数组元素里的重复键", body: `{"messages":[{"role":"user","role":"assistant"}]}`},
{name: "顶层数组", body: `[{"model":"a"},{"model":"b"}]`},
{name: "字符串值里出现字段名", body: `{"model":"a","input":"{\\"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)
require.Empty(t, got)
})
}
}
// 检查规则和它要防的解析器行为绑在一起:未报告冲突的请求体,gjson(首个、
// 大小写敏感)和 encoding/json 结构体绑定(末值、大小写不敏感)读到的 model
// 必须一致;parsersDisagree 标出两者确实读到不同值的请求体,它们都必须被报告。
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},
// gjson 精确匹配到第二个键,这里两类解析器恰好一致;规则按保守处理仍然拒绝。
{body: `{"MODEL":"first","model":"last"}`, conflict: true},
{body: `{"model":"same","Model":"same"}`},
{body: `{"model":"same","x":1,"model":"same"}`},
{body: `{"model":"only"}`},
}
for _, tt := range tests {
t.Run(tt.body, func(t *testing.T) {
var decoded struct {
Model string `json:"model"`
}
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)
}
})
}
}
func TestConflictingFieldReturnsIndependentCopy(t *testing.T) {
body := []byte(`{"model":"a","model":"b"}`)
got, conflict := ConflictingField("application/json", body)
require.True(t, conflict)
for i := range body {
body[i] = 'x'
}
require.Equal(t, "model", got)
}
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) {
t.Run("model 字段取值不同", func(t *testing.T) {
contentType, body := multipartBody(t, [2]string{"model", "gpt-image-1"}, [2]string{"prompt", "cat"}, [2]string{"model", "gpt-image-1.5"})
got, conflict := ConflictingField(contentType, body)
require.True(t, conflict)
require.Equal(t, "model", got)
})
t.Run("model 字段取值相同", func(t *testing.T) {
contentType, body := multipartBody(t, [2]string{"model", "gpt-image-1"}, [2]string{"model", "gpt-image-1"})
_, conflict := ConflictingField(contentType, body)
require.False(t, conflict)
})
t.Run("session 字段取值不同", func(t *testing.T) {
contentType, body := multipartBody(t, [2]string{"sdp", "v=0"}, [2]string{"session", `{"model":"a"}`}, [2]string{"session", `{"model":"b"}`})
got, conflict := ConflictingField(contentType, body)
require.True(t, conflict)
require.Equal(t, "session", got)
})
t.Run("session JSON 内的 model 取值不同", func(t *testing.T) {
contentType, body := multipartBody(t, [2]string{"sdp", "v=0"}, [2]string{"session", `{"model":"a","instructions":"hi","model":"b"}`})
got, conflict := ConflictingField(contentType, body)
require.True(t, conflict)
require.Equal(t, "session.model", got)
})
t.Run("普通表单", func(t *testing.T) {
contentType, body := multipartBody(t, [2]string{"model", "gpt-image-1"}, [2]string{"prompt", `{"model":"a","model":"b"}`})
_, conflict := ConflictingField(contentType, body)
require.False(t, conflict)
})
}
func TestHasConflictingModels(t *testing.T) {
require.False(t, HasConflictingModels(nil))
require.False(t, HasConflictingModels([]string{"a"}))
require.False(t, HasConflictingModels([]string{"a", "a", "a"}))
require.True(t, HasConflictingModels([]string{"a", "b"}))
require.True(t, HasConflictingModels([]string{"a", "a", "b"}))
}
@@ -0,0 +1,86 @@
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 等同样按首个值做策略判断的字段也是如此。
//
// 行为:
// - 只检查带请求体的方法(POST/PUT/PATCH)。读体后用 PrereadBody 回填,
// 下游中间件和 handler 零拷贝重读。
// - 判定规则见 requestmodel.ConflictingField:取值相同的重复字段放行,
// 不是 JSON 对象也不是 multipart 的请求体放行,交给 handler 自己校验。
// - 拒绝:按入口协议格式返回 400,请求不会进入合成路由、调度和计费。
//
// Responses WebSocket 的帧不经过这里,由 ResponsesWebSocket 逐帧检查模型候选。
func RejectConflictingRequestFields() gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request == nil || c.Request.Body == nil {
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
}
requestmodel.ResetRequestBody(c.Request, body)
field, conflict := requestmodel.ConflictingField(c.GetHeader("Content-Type"), body)
if !conflict {
c.Next()
return
}
// 字段名来自客户端请求体,回显时加引号并限制在 64 个字符以内。
message := fmt.Sprintf("Request body declares field %.64q more than once with different values", field)
writeRequestFieldConflictError(c, message)
c.Abort()
}
}
// writeRequestFieldConflictError 按入口协议输出 400 invalid_request_error。
// 协议划分与 groupModelAllowlistErrorWriter 相同;这里不复用它,是因为现有的
// Anthropic / OpenAI 写入器把非 404/403 的状态写成 api_error / model_not_found。
func writeRequestFieldConflictError(c *gin.Context, message string) {
path := ""
if c.Request.URL != nil {
path = c.Request.URL.Path
}
switch {
case strings.HasPrefix(path, "/v1beta") || strings.HasPrefix(path, "/antigravity/v1beta"):
GoogleErrorWriter(c, http.StatusBadRequest, message)
case strings.Contains(path, "/messages"):
c.JSON(http.StatusBadRequest, gin.H{
"type": "error",
"error": gin.H{"type": "invalid_request_error", "message": message},
})
default:
c.JSON(http.StatusBadRequest, gin.H{
"error": gin.H{"type": "invalid_request_error", "message": message},
})
}
}
@@ -0,0 +1,216 @@
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","input":"hi","model":"gpt-5.4"}`,
`{"model":"gpt-5.4","metadata":{"k":"1","k":"2"}}`,
`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.StatusOK {
t.Fatalf("identical multipart model fields should pass, 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())
}
if len(*handlerBodies) != 0 {
t.Fatalf("expected handler not to run, got %v", *handlerBodies)
}
}
+11 -2
View File
@@ -46,6 +46,11 @@ func RegisterGatewayRoutes(
// 保证校验发生在合成路由改写与调度之前,且只看客户端书写的模型名。
groupModelAllowlist := middleware.GroupModelAllowlist()
// 请求体字段歧义拒绝:同名字段重复且取值不一致(如两个不同的 model)时,
// 计费读到的值和实际转发的值会分叉。对所有分组生效,紧跟在白名单准入之后、
// 合成路由改写之前,白名单的拒绝响应保持不变。
rejectConflictingFields := middleware.RejectConflictingRequestFields()
isOpenAIResponsesCompatibleGatewayPlatform := func(c *gin.Context) bool {
// openai、grok 与多协议 API Key 供应商经 OpenAI 网关转发(平台清单)。
return domain.UsesOpenAIGateway(getGroupPlatform(c))
@@ -185,6 +190,7 @@ func RegisterGatewayRoutes(
gateway.Use(gin.HandlerFunc(apiKeyAuth))
gateway.GET("/sub2api/billing", h.Gateway.KeyBillingInfo)
gateway.Use(groupModelAllowlist)
gateway.Use(rejectConflictingFields)
gateway.Use(compositeTarget)
gateway.Use(requireGroupAnthropic)
{
@@ -342,6 +348,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)
{
@@ -368,7 +375,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)
@@ -385,7 +392,7 @@ 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(bodyLimit, clientRequestID, opsErrorLogger, endpointNorm, gin.HandlerFunc(apiKeyAuth), groupModelAllowlist, rejectConflictingFields, compositeTarget, requireGroupAnthropic)
{
codexDirect.POST("/realtime/calls", h.OpenAIGateway.Live)
codexDirect.GET("/:call_id", h.OpenAIGateway.LiveSideband)
@@ -499,6 +506,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)
@@ -515,6 +523,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)
@@ -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(bodyLimit, 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,122 @@
package routes
import (
"net/http"
"net/http/httptest"
"os"
"regexp"
"strings"
"testing"
"github.com/Wei-Shaw/sub2api/internal/service"
"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 with different values", "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 with different values")
}
// 取值相同的重复 model 不算歧义,不会被这层拒绝。
func TestGatewayRoutesRejectConflictingFieldsAllowsIdenticalDuplicates(t *testing.T) {
router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(service.PlatformOpenAI, false))
req := httptest.NewRequest(http.MethodPost, "/v1/responses", strings.NewReader(`{"model":"gpt-5.4","input":"hi","model":"gpt-5.4"}`))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
require.NotContains(t, w.Body.String(), "more than once with different values",
"identical duplicates must pass the conflict check, got %d: %s", w.Code, w.Body.String())
}