diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 0273ddc062..5d20fd3f85 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -2615,11 +2615,13 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { return } // 帧内重复字段(model、service_tier、reasoning.effort 等,含大小写变体与 - // 嵌套对象)取值不一致时,计费/策略按首个值、上游可能按末值绑定。与 HTTP - // 入口(RejectConflictingRequestFields)同一规则,对所有分组直接拒绝;取值 - // 相同的重复键放行。放在白名单之后,白名单的拒绝原因保持不变。 + // 嵌套对象)会让计费/策略读到的首个值与上游实际绑定的值分叉;取值相同也不 + // 放行,因为网关的 sjson 改写只动首个(GHSA-p3r4-jcm3-2hph)。与 HTTP 入口 + // (RejectConflictingRequestFields)同一规则,对所有分组生效。放在白名单 + // 之后,白名单的拒绝原因保持不变。 if field, conflict := requestmodel.ConflictingField("application/json", firstMessage); conflict { - closeOpenAIClientWS(wsConn, coderws.StatusPolicyViolation, fmt.Sprintf("response.create payload declares field %.64q more than once with different values", field)) + 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. @@ -3100,10 +3102,11 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { middleware2.MarkIngressRejected(c, middleware2.IngressRejectModelNotAllowed) return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("Model %q is not available for this group", blocked), nil) } - // 后续 turn 同首帧:帧内重复字段取值不一致时关闭连接,避免计费/ - // 策略读到的值与上游实际绑定的值分叉。 + // 后续 turn 同首帧:帧内有重复字段即关闭连接,避免计费/策略读到的 + // 值与上游实际绑定的值分叉。 if field, conflict := requestmodel.ConflictingField("application/json", payload); conflict { - return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, fmt.Sprintf("websocket request payload declares field %.64q more than once with different values", field), nil) + 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) diff --git a/backend/internal/handler/openai_gateway_ws_model_allowlist_test.go b/backend/internal/handler/openai_gateway_ws_model_allowlist_test.go index bf70d4ce9d..230fc1dcc5 100644 --- a/backend/internal/handler/openai_gateway_ws_model_allowlist_test.go +++ b/backend/internal/handler/openai_gateway_ws_model_allowlist_test.go @@ -139,16 +139,15 @@ func TestOpenAIResponsesWebSocket_SubsequentTurnDuplicateModelKeysRejected(t *te } } -// 重复但同值的 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 把会话 diff --git a/backend/internal/handler/openai_gateway_ws_model_conflict_test.go b/backend/internal/handler/openai_gateway_ws_model_conflict_test.go index 19aa012856..e0c7c4a1f2 100644 --- a/backend/internal/handler/openai_gateway_ws_model_conflict_test.go +++ b/backend/internal/handler/openai_gateway_ws_model_conflict_test.go @@ -6,7 +6,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/service" ) -const wsModelConflictCloseReason = "more than once with different values" +const wsModelConflictCloseReason = "more than once" // 没有开启白名单的分组:首帧里重复 model 键取值不一致(计费按第一个、上游可能 // 按最后一个绑定)必须以 1008 关闭,帧不到达上游。 @@ -62,15 +62,29 @@ func TestOpenAIResponsesWebSocket_SubsequentTurnConflictingModelKeysRejectedWith } } -// 取值相同的重复 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)) +// 取值相同的重复键同样拒绝:网关的 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`, + }) + }) } } diff --git a/backend/internal/handler/request_body_limit.go b/backend/internal/handler/request_body_limit.go index a52bb0bfb4..2da6d10092 100644 --- a/backend/internal/handler/request_body_limit.go +++ b/backend/internal/handler/request_body_limit.go @@ -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)) } diff --git a/backend/internal/handler/request_body_limit_test.go b/backend/internal/handler/request_body_limit_test.go index bbb3d2a070..d857a7e0ff 100644 --- a/backend/internal/handler/request_body_limit_test.go +++ b/backend/internal/handler/request_body_limit_test.go @@ -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) { diff --git a/backend/internal/handler/request_body_read_log.go b/backend/internal/handler/request_body_read_log.go index 0068c79212..7be40b3bb3 100644 --- a/backend/internal/handler/request_body_read_log.go +++ b/backend/internal/handler/request_body_read_log.go @@ -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) { diff --git a/backend/internal/handler/request_body_read_log_test.go b/backend/internal/handler/request_body_read_log_test.go index f9eef560a4..881aa8c922 100644 --- a/backend/internal/handler/request_body_read_log_test.go +++ b/backend/internal/handler/request_body_read_log_test.go @@ -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()) } diff --git a/backend/internal/pkg/httputil/body_read_error.go b/backend/internal/pkg/httputil/body_read_error.go index 5acaa741db..07b106faef 100644 --- a/backend/internal/pkg/httputil/body_read_error.go +++ b/backend/internal/pkg/httputil/body_read_error.go @@ -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 { diff --git a/backend/internal/pkg/requestmodel/conflict.go b/backend/internal/pkg/requestmodel/conflict.go index 0d55125fb0..debfcf7fa9 100644 --- a/backend/internal/pkg/requestmodel/conflict.go +++ b/backend/internal/pkg/requestmodel/conflict.go @@ -2,262 +2,348 @@ package requestmodel import ( "bytes" + "hash/maphash" + "io" + "mime" + "mime/multipart" "strconv" "strings" "unicode" - "unsafe" - - "github.com/tidwall/gjson" + "unicode/utf16" + "unicode/utf8" ) -// utf8BOM 是部分客户端写在 JSON 文档前的 UTF-8 字节序标记。宽容读取会跳过它 -// 再解析对象,歧义检查也要看同一个对象。 +// utf8BOM 是部分客户端写在 JSON 文档前的 UTF-8 字节序标记。网关 handler 的宽容 +// 读取(httputil.ReadLenientJSONRequestBodyWithPrealloc)会先剥掉它再解析, +// 准入与歧义检查必须看同一份字节。 var utf8BOM = []byte{0xEF, 0xBB, 0xBF} -// ConflictingField 返回请求体里第一个「重复声明且取值不一致」的字段名。 +// TrimUTF8BOM 去掉请求体开头的 UTF-8 BOM(与宽容读取的规则一致),否则原样返回。 +func TrimUTF8BOM(body []byte) []byte { + return bytes.TrimPrefix(body, utf8BOM) +} + +// LooksLikeJSON 判断(已去 BOM 的)请求体首个非空白字节是否为 JSON 对象或数组。 // -// 网关读取 model、service_tier 等字段用的是 gjson(重复键取第一个、大小写 -// 敏感),而改写并转发请求体的路径会经过 encoding/json(重复键取最后一个, -// 结构体绑定不区分大小写)。同名字段取值不一致时,准入、计费看到的值和上游 -// 实际收到的值会分叉:{"model":"便宜模型",...,"model":"贵模型"} 按便宜模型 -// 计费,转发的却是贵模型。调用方应在任何解析器读取字段之前拒绝这类请求。 +// 是否按 JSON 检查只看内容、不看 Content-Type:JSON handler 从不校验请求头, +// 把 JSON 请求体标成 multipart/form-data 不能绕过检查。真正的 multipart 请求体 +// 以 "--boundary" 开头,不会被误判。 +func LooksLikeJSON(body []byte) bool { + for _, c := range body { + switch c { + case ' ', '\t', '\r', '\n': + continue + case '{', '[': + return true + default: + return false + } + } + return false +} + +// ConflictingField 返回请求体中第一个重复声明的字段路径。 +// +// 网关读取 model、service_tier、reasoning.effort 等字段用的是 gjson(重复键取 +// 第一个、大小写敏感),sjson 改写(模型映射、推理强度降级、fast policy 删除 +// service_tier)也只改第一个;而改写并转发请求体的路径会经过 encoding/json +// (解码到 map 时重复键取最后一个,绑定到结构体时键名大小写不敏感、取最后一个), +// 上游解析器也可能取最后一个。同名字段一旦重复,准入、计费、策略看到的值和上游 +// 实际收到的值就可能分叉,例如 {"model":"便宜模型",...,"model":"贵模型"} 按便宜 +// 模型计费、转发贵模型。取值相同的重复同样拒绝:网关自己的 sjson 改写只动第一个, +// 改写后两者就不再相同。调用方应在任何解析器读取字段之前拒绝这类请求。 // // 判定范围: -// - JSON:顶层成员名在转义解码、大小写折叠后相同,且原始取值不同;顶层 -// session 对象(Live 入口的模型所在位置)内部同理,字段名报告为 -// session.。 -// - JSON 嵌套对象(任意深度,含数组元素):成员名转义解码后完全相同且原始 -// 取值不同,字段名按路径报告(如 reasoning.effort、messages[0].role)。 -// reasoning.effort 等嵌套字段同样参与计费倍率与分组策略,gjson 读首个、 -// sjson 只改首个、重新编码保留末个的分叉与顶层一致。嵌套层不做大小写 -// 折叠:工具 JSON Schema 等用户数据里 id 与 ID 是合法的不同属性。 -// - multipart:model / session 文本字段出现多次且取值不同;session 字段的 -// JSON 值内部同理(含嵌套)。 +// - JSON(按内容识别,见 LooksLikeJSON):任意深度的对象(含数组元素)内, +// 成员名经转义解码(无效 UTF-8 与孤立代理项按 encoding/json 替换为 U+FFFD) +// 后按 encoding/json 结构体绑定的大小写折叠规则相同。用户自定义键空间 +// (JSON Schema 的 properties/$defs、工具调用参数、metadata 等,见 +// isFreeformMember)内只比较精确名字,因为 id 与 ID 在那里是合法的不同键。 +// 字段路径形如 reasoning.effort、messages[1].role。 +// - multipart:同名非文件标量字段出现多次(列表字段见 +// isRepeatableMultipartField);session 字段的 JSON 值内部按 JSON 规则检查。 // -// 取值完全相同的重复字段不算歧义:任何解析器绑定到的值都一样,这与白名单 -// 准入对同值重复字段的放行保持一致。不是 JSON 对象也不是 multipart 的请求体 -// 返回 false,其合法性由各入口自己的解析器判断。 +// 扫描是一次线性遍历,键名以带随机种子的 64 位哈希判重,CPU 与内存都与请求体 +// 大小成线性关系;嵌套超过 maxConflictDepth 的部分只计括号不检查(encoding/json +// 本身拒绝这种深度),其后的同层成员仍继续检查。 func ConflictingField(contentType string, body []byte) (string, bool) { + if doc := TrimUTF8BOM(body); LooksLikeJSON(doc) { + return scanDuplicateMember(doc) + } if isMultipartContentType(contentType) { return multipartConflictingField(contentType, body) } - return jsonConflictingField(body) + return "", false } -// 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 - }) - if conflict != "" { - return conflict, true - } - return nestedConflictingField(root, "") -} - -// maxConflictDepth 与 encoding/json 的嵌套上限一致:更深的请求体下游解码必然 -// 失败,不再下钻,同时避免恶意深嵌套耗尽栈。 +// maxConflictDepth 与 encoding/json 的嵌套上限一致。 const maxConflictDepth = 10000 -// conflictLinearScanLimit 以内的对象线性扫描判重,避免为每个小对象分配 map。 +// conflictLinearScanLimit 以内的对象线性比较哈希,超过后改用 map。 const conflictLinearScanLimit = 16 -// nestedConflictingField 检查 object 各成员值内部(不含 object 自身这一层)的 -// 所有嵌套对象,返回第一个取值不一致的重复成员路径;prefix 为路径前缀。 -func nestedConflictingField(object gjson.Result, prefix string) (string, bool) { - w := conflictWalker{} - if prefix != "" { - w.push(prefix) +// 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 +} + +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] + } + 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++ + } } - object.ForEach(func(key, value gjson.Result) bool { - if !value.IsObject() && !value.IsArray() { + 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 && isFreeformMember(s.body[parent.keyStart:parent.keyEnd], n > 1) { + fold = false + } + } + 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 } - w.push(key.String()) - found := w.walk(value, 1) - w.pop() - return !found - }) - return w.conflict, w.conflict != "" -} - -type conflictMember struct { - name string - raw string -} - -// conflictPathSegment 是成员名或数组下标(index >= 0);只在报告冲突时拼接成字符串。 -type conflictPathSegment struct { - name string - index int -} - -type conflictWalker struct { - path []conflictPathSegment - members []conflictMember - conflict string -} - -func (w *conflictWalker) push(name string) { - w.path = append(w.path, conflictPathSegment{name: name, index: -1}) -} -func (w *conflictWalker) pushIndex(index int) { - w.path = append(w.path, conflictPathSegment{index: index}) -} -func (w *conflictWalker) pop() { w.path = w.path[:len(w.path)-1] } - -// walk 遍历 v;发现冲突时写入 w.conflict 并返回 true。 -func (w *conflictWalker) walk(v gjson.Result, depth int) bool { - if depth >= maxConflictDepth { + top.seen[sum] = struct{}{} return false } - if v.IsArray() { - index := 0 - found := false - v.ForEach(func(_, item gjson.Result) bool { - if item.IsObject() || item.IsArray() { - w.pushIndex(index) - found = w.walk(item, depth+1) - w.pop() - } - index++ - return !found - }) - return found - } - if !v.IsObject() { - return false - } - - start := len(w.members) - defer func() { w.members = w.members[:start] }() - var index map[string]string - found := false - v.ForEach(func(key, item gjson.Result) bool { - name := key.String() - if w.repeatsWithDifferentValue(start, &index, name, item.Raw) { - w.push(name) - w.conflict = joinConflictPath(w.path) - w.pop() - found = true - return false - } - // 子对象在返回前会把 w.members 截回原长度,本对象的成员保持连续。 - w.members = append(w.members, conflictMember{name: name, raw: item.Raw}) - if item.IsObject() || item.IsArray() { - w.push(name) - found = w.walk(item, depth+1) - w.pop() - } - return !found - }) - return found -} - -// repeatsWithDifferentValue 判断 name 是否与本对象(w.members[start:])中更早 -// 的同名成员取值不同;成员较多时改用 map 索引。 -func (w *conflictWalker) repeatsWithDifferentValue(start int, index *map[string]string, name, raw string) bool { - if *index != nil { - first, repeated := (*index)[name] - if !repeated { - (*index)[name] = raw - return false - } - return first != raw - } - for _, seen := range w.members[start:] { - if seen.name == name { - return seen.raw != raw + for _, seen := range s.hashes[top.hashStart:] { + if seen == sum { + return true } } - if len(w.members)-start >= conflictLinearScanLimit { - *index = make(map[string]string, 2*conflictLinearScanLimit) - for _, seen := range w.members[start:] { - if _, ok := (*index)[seen.name]; !ok { - (*index)[seen.name] = seen.raw - } + 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{}{} } - (*index)[name] = raw + s.hashes = s.hashes[:top.hashStart] } return false } -// joinConflictPath 把路径段拼成 a.b[0].c;结果是新分配的字符串,不引用请求体。 -func joinConflictPath(path []conflictPathSegment) string { +// path 把当前栈拼成 a.b[0].c;结果是新分配的字符串,不引用请求体。 +func (s *duplicateScanner) path() string { var b strings.Builder - for i, segment := range path { - if segment.index >= 0 { + for _, frame := range s.stack { + if !frame.object { b.WriteByte('[') - b.WriteString(strconv.Itoa(segment.index)) + b.WriteString(strconv.Itoa(frame.index)) b.WriteByte(']') continue } - if i > 0 { + if b.Len() > 0 { b.WriteByte('.') } - b.WriteString(segment.name) + b.Write(appendMemberName(nil, s.body[frame.keyStart:frame.keyEnd], frame.keyEscaped, false)) } return b.String() } -// 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 +// freeformMembers 的值是用户自定义键空间:JSON Schema 的属性表与取值、工具调用 +// 参数、metadata。这些子树内的成员名只做精确比较。它们都不在网关计费/策略读取的 +// 字段路径上;input / response 只在非顶层时算(顶层 input 是 Responses 的输入 +// 列表,顶层 response 是 realtime response.create 的参数)。 +var freeformMembers = []string{ + "properties", "patternProperties", "$defs", "definitions", "dependentSchemas", + "default", "const", "examples", "enum", + "metadata", "args", "arguments", +} + +func isFreeformMember(name []byte, nested bool) bool { + for _, candidate := range freeformMembers { + if bytes.EqualFold(name, []byte(candidate)) { return true } - if first != value.Raw { - conflict = strings.Clone(key.String()) - return false + } + 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 } - return true - }) - return conflict, conflict != "" + backslash := bytes.IndexByte(b[i:i+quote], '\\') + if backslash < 0 { + return i + quote, escaped + } + escaped = true + i += backslash + 2 + } + 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 { @@ -270,27 +356,51 @@ func foldRune(r rune) rune { return folded } -// multipartConflictingField 检查 multipart 表单:model / session 文本字段多次 -// 出现且取值不同,或某个 session 字段的 JSON 值内部存在取值不一致的重复成员。 +// 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 表单:同名非文件标量字段出现多次 +// (见 isRepeatableMultipartField),或 session 字段的 JSON 值内部有重复成员。 func multipartConflictingField(contentType string, body []byte) (string, bool) { - models, sessions := multipartModelCandidates(contentType, body) - if HasConflictingModels(models) { - return "model", true + _, params, err := mime.ParseMediaType(strings.TrimSpace(contentType)) + if err != nil { + return "", false } - if HasConflictingModels(sessions) { - return "session", true + boundary := strings.TrimSpace(params["boundary"]) + if boundary == "" { + return "", false } - for _, raw := range sessions { - session := gjson.Parse(raw) - if !session.IsObject() { + reader := multipart.NewReader(bytes.NewReader(body), boundary) + seen := make(map[string]struct{}) + for { + part, err := reader.NextPart() + if err != nil { + return "", false + } + name := strings.TrimSpace(part.FormName()) + if part.FileName() != "" || name == "" || isRepeatableMultipartField(name) { continue } - if name, ok := conflictingMember(session); ok { - return "session." + name, true - } - if name, ok := nestedConflictingField(session, "session"); ok { + if _, dup := seen[name]; dup { return name, true } + seen[name] = struct{}{} + if name != "session" { + continue + } + data, err := io.ReadAll(part) + if err != nil { + continue + } + if doc := TrimUTF8BOM(bytes.TrimSpace(data)); LooksLikeJSON(doc) { + if field, conflict := scanDuplicateMember(doc); conflict { + return "session." + field, true + } + } } - return "", false } diff --git a/backend/internal/pkg/requestmodel/conflict_test.go b/backend/internal/pkg/requestmodel/conflict_test.go index cae635d907..5456991427 100644 --- a/backend/internal/pkg/requestmodel/conflict_test.go +++ b/backend/internal/pkg/requestmodel/conflict_test.go @@ -5,38 +5,50 @@ import ( "encoding/json" "fmt" "mime/multipart" + "runtime" "strings" "testing" + "time" "github.com/stretchr/testify/require" "github.com/tidwall/gjson" ) -func TestConflictingFieldJSONReportsDisagreeingDuplicates(t *testing.T) { +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: `{"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"}, {name: "嵌套 reasoning.effort 取值不同", body: `{"model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"input":"hi"}`, want: "reasoning.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: "嵌套 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: "顶层 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) { @@ -56,28 +68,38 @@ func TestConflictingFieldJSONAcceptsUnambiguousBodies(t *testing.T) { {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":"1"}}`}, - {name: "嵌套层大小写不同的键是不同属性", body: `{"tools":[{"input_schema":{"properties":{"id":{"type":"string"},"ID":{"type":"integer"}}}}]}`}, {name: "兄弟对象里的同名键", body: `{"a":{"x":1},"b":{"x":2},"c":[{"x":1},{"x":2}]}`}, {name: "父子对象同名键", body: `{"model":"m","metadata":{"model":"other"}}`}, - {name: "顶层数组", body: `[{"model":"a"},{"model":"b"}]`}, - {name: "字符串值里出现字段名", body: `{"model":"a","input":"{\\"model\\":\\"b\\"}"}`}, + {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: "metadata 大小写不同", body: `{"metadata":{"user_id":"1","USER_ID":"2"}}`}, + {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) + require.False(t, conflict, got) require.Empty(t, got) }) } } -// 检查规则和它要防的解析器行为绑在一起:未报告冲突的请求体,gjson(首个、 -// 大小写敏感)和 encoding/json 结构体绑定(末值、大小写不敏感)读到的 model -// 必须一致;parsersDisagree 标出两者确实读到不同值的请求体,它们都必须被报告。 +// 回归: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 @@ -86,16 +108,18 @@ func TestConflictingFieldMatchesParserDisagreement(t *testing.T) { }{ {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"}`}, + {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"` + 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() @@ -105,19 +129,74 @@ func TestConflictingFieldMatchesParserDisagreement(t *testing.T) { 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(`{"model":"a","model":"b"}`) + 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, "model", got) + 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))) } func multipartBody(t *testing.T, fields ...[2]string) (string, []byte) { @@ -132,71 +211,43 @@ func multipartBody(t *testing.T, fields ...[2]string) (string, []byte) { } 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 TestConflictingFieldManyNestedMembersUsesIndex(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) + 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) + }) } - body := b.String() - got, conflict := ConflictingField("application/json", []byte(body+`"k3":0}}`)) - require.True(t, conflict) - require.Equal(t, "tool.k3", got) - - _, conflict = ConflictingField("application/json", []byte(body+`"k3":3}}`)) - require.False(t, conflict, "identical duplicate past the linear-scan limit must pass") - - _, conflict = ConflictingField("application/json", []byte(body+`"k100":0}}`)) - require.False(t, conflict) -} - -func TestConflictingFieldDeepNestingDoesNotOverflow(t *testing.T) { - depth := maxConflictDepth + 50 - objects := `{"a":` + strings.Repeat(`{"a":`, depth) + "1" + strings.Repeat("}", depth) + `}` - _, conflict := ConflictingField("application/json", []byte(objects)) - require.False(t, conflict) - - arrays := `{"a":` + strings.Repeat("[", depth) + strings.Repeat("]", depth) + `}` - _, conflict = ConflictingField("application/json", []byte(arrays)) - require.False(t, conflict) -} - -func TestConflictingFieldMultipartNestedSession(t *testing.T) { - contentType, body := multipartBody(t, [2]string{"sdp", "v=0"}, [2]string{"session", `{"model":"a","audio":{"voice":"x","voice":"y"}}`}) - got, conflict := ConflictingField(contentType, body) - require.True(t, conflict) - require.Equal(t, "session.audio.voice", 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) { @@ -226,11 +277,3 @@ func BenchmarkConflictingField(b *testing.B) { } } } - -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"})) -} diff --git a/backend/internal/pkg/requestmodel/requestmodel.go b/backend/internal/pkg/requestmodel/requestmodel.go index ead8e1e274..99c9f00a72 100644 --- a/backend/internal/pkg/requestmodel/requestmodel.go +++ b/backend/internal/pkg/requestmodel/requestmodel.go @@ -44,15 +44,17 @@ func IsLiveRequestRoute(routePath string) bool { // (为空回落 session 候选)。候选包含重复键、大小写变体的全部出现。 func FromBodyCandidates(routePath, contentType string, body []byte) []string { var topLevel, session []string - if isMultipartContentType(contentType) { - // 声明为 multipart 的请求体只做 multipart 解析——gjson 的部分扫描 + if doc := TrimUTF8BOM(body); LooksLikeJSON(doc) { + // 按内容识别 JSON,不看 Content-Type:JSON handler 不校验请求头,且宽容 + // 读取会剥掉 BOM,两者都不能成为绕过准入的手段。 + topLevel = jsonModelCandidates(doc) + session = jsonSessionModelCandidates(doc) + } else if isMultipartContentType(contentType) { + // 真正的 multipart 请求体只做 multipart 解析——gjson 的部分扫描 // 会在 multipart 字节流里误匹配 session JSON 内的 model 字段。 models, sessions := multipartModelCandidates(contentType, body) topLevel = models session = sessionModelCandidates(sessions) - } else { - topLevel = jsonModelCandidates(body) - session = jsonSessionModelCandidates(body) } if IsLiveRequestRoute(routePath) { diff --git a/backend/internal/pkg/requestmodel/requestmodel_test.go b/backend/internal/pkg/requestmodel/requestmodel_test.go index 5d59a0d343..6416607918 100644 --- a/backend/internal/pkg/requestmodel/requestmodel_test.go +++ b/backend/internal/pkg/requestmodel/requestmodel_test.go @@ -255,3 +255,30 @@ 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) + } + }) + } +} diff --git a/backend/internal/server/middleware/group_model_allowlist_test.go b/backend/internal/server/middleware/group_model_allowlist_test.go index 4015dbc822..b830707835 100644 --- a/backend/internal/server/middleware/group_model_allowlist_test.go +++ b/backend/internal/server/middleware/group_model_allowlist_test.go @@ -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) diff --git a/backend/internal/server/middleware/ingress_reject.go b/backend/internal/server/middleware/ingress_reject.go index 7c7af027a5..15c0b36f14 100644 --- a/backend/internal/server/middleware/ingress_reject.go +++ b/backend/internal/server/middleware/ingress_reject.go @@ -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" diff --git a/backend/internal/server/middleware/request_body_read_failure.go b/backend/internal/server/middleware/request_body_read_failure.go index a41430a62f..32adbdb2de 100644 --- a/backend/internal/server/middleware/request_body_read_failure.go +++ b/backend/internal/server/middleware/request_body_read_failure.go @@ -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) { diff --git a/backend/internal/server/middleware/request_field_conflict.go b/backend/internal/server/middleware/request_field_conflict.go index 70fc99a449..912933163e 100644 --- a/backend/internal/server/middleware/request_field_conflict.go +++ b/backend/internal/server/middleware/request_field_conflict.go @@ -11,25 +11,29 @@ import ( "github.com/gin-gonic/gin" ) -// RejectConflictingRequestFields 拒绝「同名字段重复声明且取值不一致」的网关请求。 +// RejectConflictingRequestFields 拒绝「同名字段重复声明」的网关请求。 // // 挂载位置:每条网关链的 GroupModelAllowlist 之后、compositeTarget 之前, // 白名单对不在名单内的模型仍按原有格式拒绝。与白名单准入不同,这里对所有分组 // 生效:重复 model 键让计费模型(gjson 取第一个)和实际转发的模型 // (encoding/json 重新序列化后取最后一个)分叉,和分组是否开启白名单无关; -// service_tier 等同样按首个值做策略判断的字段也是如此。 +// service_tier、reasoning.effort 等按首个值做计费/策略判断、由 sjson 只改首个的 +// 字段也是如此(GHSA-p3r4-jcm3-2hph)。 // // 行为: -// - 只检查带请求体的方法(POST/PUT/PATCH)。读体后用 PrereadBody 回填, -// 下游中间件和 handler 零拷贝重读。 -// - 判定规则见 requestmodel.ConflictingField:取值相同的重复字段放行, -// 不是 JSON 对象也不是 multipart 的请求体放行,交给 handler 自己校验。 -// - 拒绝:按入口协议格式返回 400,请求不会进入合成路由、调度和计费。 +// - 只检查带请求体的方法(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 { + if c.Request == nil || c.Request.Body == nil || c.Request.Body == http.NoBody { c.Next() return } @@ -48,6 +52,9 @@ func RejectConflictingRequestFields() gin.HandlerFunc { 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) @@ -55,31 +62,33 @@ func RejectConflictingRequestFields() gin.HandlerFunc { c.Next() return } + MarkIngressRejected(c, IngressRejectConflictingRequestFields) // 字段名来自客户端请求体,回显时加引号并限制在 64 个字符以内。 - message := fmt.Sprintf("Request body declares field %.64q more than once with different values", field) - writeRequestFieldConflictError(c, message) + writeGatewayInvalidRequest(c, http.StatusBadRequest, fmt.Sprintf("Request body declares field %.64q more than once", field)) c.Abort() } } -// writeRequestFieldConflictError 按入口协议输出 400 invalid_request_error。 -// 协议划分与 groupModelAllowlistErrorWriter 相同;这里不复用它,是因为现有的 -// Anthropic / OpenAI 写入器把非 404/403 的状态写成 api_error / model_not_found。 -func writeRequestFieldConflictError(c *gin.Context, message string) { +// 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.URL != nil { + 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, http.StatusBadRequest, message) + GoogleErrorWriter(c, status, message) case strings.Contains(path, "/messages"): - c.JSON(http.StatusBadRequest, gin.H{ + c.JSON(status, gin.H{ "type": "error", "error": gin.H{"type": "invalid_request_error", "message": message}, }) default: - c.JSON(http.StatusBadRequest, gin.H{ + c.JSON(status, gin.H{ "error": gin.H{"type": "invalid_request_error", "message": message}, }) } diff --git a/backend/internal/server/middleware/request_field_conflict_test.go b/backend/internal/server/middleware/request_field_conflict_test.go index cc5ac2f72f..a668100543 100644 --- a/backend/internal/server/middleware/request_field_conflict_test.go +++ b/backend/internal/server/middleware/request_field_conflict_test.go @@ -114,13 +114,11 @@ func TestRejectConflictingRequestFieldsErrorFormats(t *testing.T) { } } -// 取值相同的重复字段、普通请求体和非对象请求体都放行,handler 读到的请求体 -// 与客户端发送的完全一致。 +// 普通请求体和非对象请求体都放行,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":"1"}}`, + `{"model":"gpt-5.4","metadata":{"k":"1","K":"1"}}`, `not json`, ``, } { @@ -155,8 +153,8 @@ func TestRejectConflictingRequestFieldsMultipart(t *testing.T) { 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", "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()) @@ -210,7 +208,75 @@ func TestRejectConflictingRequestFieldsRequestBodyTooLargePassesThrough413(t *te 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) + } +} diff --git a/backend/internal/server/routes/gateway.go b/backend/internal/server/routes/gateway.go index f3fdfa014b..cdc8e0fdf9 100644 --- a/backend/internal/server/routes/gateway.go +++ b/backend/internal/server/routes/gateway.go @@ -32,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() @@ -183,7 +198,7 @@ func RegisterGatewayRoutes( // API网关(Claude API兼容) gateway := r.Group("/v1") - gateway.Use(bodyLimit) + gateway.Use(groupBodyLimit) gateway.Use(clientRequestID) gateway.Use(opsErrorLogger) gateway.Use(endpointNorm) @@ -202,8 +217,8 @@ func RegisterGatewayRoutes( } h.Gateway.Messages(c) }) - // 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) @@ -231,7 +246,7 @@ func RegisterGatewayRoutes( } h.Gateway.Responses(c) })) - 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) }) @@ -243,7 +258,7 @@ func RegisterGatewayRoutes( } h.Gateway.ChatCompletions(c) }) - 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{ @@ -392,13 +407,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, rejectConflictingFields, 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) }) diff --git a/backend/internal/server/routes/gateway_model_allowlist_test.go b/backend/internal/server/routes/gateway_model_allowlist_test.go index e300469922..8c8bc359dd 100644 --- a/backend/internal/server/routes/gateway_model_allowlist_test.go +++ b/backend/internal/server/routes/gateway_model_allowlist_test.go @@ -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, rejectConflictingFields, 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,避免漏挂。 diff --git a/backend/internal/server/routes/gateway_request_field_conflict_test.go b/backend/internal/server/routes/gateway_request_field_conflict_test.go index a673e35c8c..724e802e65 100644 --- a/backend/internal/server/routes/gateway_request_field_conflict_test.go +++ b/backend/internal/server/routes/gateway_request_field_conflict_test.go @@ -8,7 +8,11 @@ import ( "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" ) @@ -82,7 +86,7 @@ func TestGatewayRoutesRejectConflictingFieldsCoversGatewayRoutes(t *testing.T) { 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) + require.Contains(t, w.Body.String(), "more than once", "POST %s", tc.path) } } @@ -105,20 +109,80 @@ func TestGatewayRoutesRejectConflictingFieldsKeepsAllowlistResponse(t *testing.T 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") + require.Contains(t, bothAllowed.Body.String(), "more than once") } -// 取值相同的重复 model 不算歧义,不会被这层拒绝。 -func TestGatewayRoutesRejectConflictingFieldsAllowsIdenticalDuplicates(t *testing.T) { +// 取值相同的重复字段同样拒绝:网关的 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","model":"gpt-5.4"}`)) + 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.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()) + 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 参与计费倍率与分组推理强度上限、