diff --git a/backend/internal/handler/openai_gateway_handler.go b/backend/internal/handler/openai_gateway_handler.go index 819b605cf8..0273ddc062 100644 --- a/backend/internal/handler/openai_gateway_handler.go +++ b/backend/internal/handler/openai_gateway_handler.go @@ -2614,11 +2614,12 @@ func (h *OpenAIGatewayHandler) ResponsesWebSocket(c *gin.Context) { 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") + // 帧内重复字段(model、service_tier、reasoning.effort 等,含大小写变体与 + // 嵌套对象)取值不一致时,计费/策略按首个值、上游可能按末值绑定。与 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)) return } // Keep the client model in the frame for admission, response identity and usage. @@ -3099,10 +3100,10 @@ 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 同首帧:帧内模型候选取值不一致时关闭连接,避免计费 - // 模型与上游实际绑定的模型分叉。 - if requestmodel.HasConflictingModels(frameModelCandidates) { - return service.NewOpenAIWSClientCloseError(coderws.StatusPolicyViolation, "websocket request payload declares model more than once with different values", nil) + // 后续 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) } 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_conflict_test.go b/backend/internal/handler/openai_gateway_ws_model_conflict_test.go index 4b8bbd0329..19aa012856 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 = "declares model more than once with different values" +const wsModelConflictCloseReason = "more than once with different values" // 没有开启白名单的分组:首帧里重复 model 键取值不一致(计费按第一个、上游可能 // 按最后一个绑定)必须以 1008 关闭,帧不到达上游。 @@ -73,3 +73,29 @@ func TestOpenAIResponsesWebSocket_IdenticalDuplicateModelKeysAllowedWithoutAllow t.Fatalf("expected two completed events, got %d", len(got.clientEvents)) } } + +// 非 model 字段同样参与计费与策略:首帧 service_tier、后续 turn 嵌套的 +// reasoning.effort 取值不一致都必须关闭连接。 +func TestOpenAIResponsesWebSocket_ConflictingBillingFieldsRejected(t *testing.T) { + for _, mode := range []string{service.OpenAIWSIngressModePassthrough, service.OpenAIWSIngressModeDedicated} { + t.Run(mode+"/first_frame_service_tier", func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4","service_tier":"flex","stream":false,"service_tier":"priority"}`, + group: wsAllowlistGroup(false), + ingressMode: mode, + firstFrameCloseExpected: true, + closeReason: `declares field "service_tier" more than once`, + }) + }) + t.Run(mode+"/subsequent_turn_reasoning_effort", func(t *testing.T) { + runOpenAIResponsesWebSocketUsageLogCase(t, openAIResponsesWSUsageLogCase{ + firstPayload: `{"type":"response.create","model":"gpt-5.4","stream":false}`, + secondPayload: `{"type":"response.create","model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"stream":false}`, + group: wsAllowlistGroup(false), + ingressMode: mode, + secondTurnCloseExpected: true, + closeReason: `declares field "reasoning.effort" more than once`, + }) + }) + } +} diff --git a/backend/internal/pkg/requestmodel/conflict.go b/backend/internal/pkg/requestmodel/conflict.go index d3ee0d58ad..0d55125fb0 100644 --- a/backend/internal/pkg/requestmodel/conflict.go +++ b/backend/internal/pkg/requestmodel/conflict.go @@ -2,6 +2,7 @@ package requestmodel import ( "bytes" + "strconv" "strings" "unicode" "unsafe" @@ -25,8 +26,13 @@ var utf8BOM = []byte{0xEF, 0xBB, 0xBF} // - JSON:顶层成员名在转义解码、大小写折叠后相同,且原始取值不同;顶层 // session 对象(Live 入口的模型所在位置)内部同理,字段名报告为 // session.。 +// - JSON 嵌套对象(任意深度,含数组元素):成员名转义解码后完全相同且原始 +// 取值不同,字段名按路径报告(如 reasoning.effort、messages[0].role)。 +// reasoning.effort 等嵌套字段同样参与计费倍率与分组策略,gjson 读首个、 +// sjson 只改首个、重新编码保留末个的分叉与顶层一致。嵌套层不做大小写 +// 折叠:工具 JSON Schema 等用户数据里 id 与 ID 是合法的不同属性。 // - multipart:model / session 文本字段出现多次且取值不同;session 字段的 -// JSON 值内部同理。 +// JSON 值内部同理(含嵌套)。 // // 取值完全相同的重复字段不算歧义:任何解析器绑定到的值都一样,这与白名单 // 准入对同值重复字段的放行保持一致。不是 JSON 对象也不是 multipart 的请求体 @@ -75,7 +81,155 @@ func jsonConflictingField(body []byte) (string, bool) { } return true }) - return conflict, conflict != "" + if conflict != "" { + return conflict, true + } + return nestedConflictingField(root, "") +} + +// maxConflictDepth 与 encoding/json 的嵌套上限一致:更深的请求体下游解码必然 +// 失败,不再下钻,同时避免恶意深嵌套耗尽栈。 +const maxConflictDepth = 10000 + +// 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) + } + object.ForEach(func(key, value gjson.Result) bool { + if !value.IsObject() && !value.IsArray() { + 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 { + 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 + } + } + 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 + } + } + (*index)[name] = raw + } + return false +} + +// joinConflictPath 把路径段拼成 a.b[0].c;结果是新分配的字符串,不引用请求体。 +func joinConflictPath(path []conflictPathSegment) string { + var b strings.Builder + for i, segment := range path { + if segment.index >= 0 { + b.WriteByte('[') + b.WriteString(strconv.Itoa(segment.index)) + b.WriteByte(']') + continue + } + if i > 0 { + b.WriteByte('.') + } + b.WriteString(segment.name) + } + return b.String() } // conflictingMember 返回对象里第一个与更早的同名成员取值不同的成员名。 @@ -134,6 +288,9 @@ func multipartConflictingField(contentType string, body []byte) (string, bool) { if name, ok := conflictingMember(session); ok { return "session." + name, true } + if name, ok := nestedConflictingField(session, "session"); ok { + return name, true + } } return "", false } diff --git a/backend/internal/pkg/requestmodel/conflict_test.go b/backend/internal/pkg/requestmodel/conflict_test.go index 66def26b23..cae635d907 100644 --- a/backend/internal/pkg/requestmodel/conflict_test.go +++ b/backend/internal/pkg/requestmodel/conflict_test.go @@ -3,7 +3,9 @@ package requestmodel import ( "bytes" "encoding/json" + "fmt" "mime/multipart" + "strings" "testing" "github.com/stretchr/testify/require" @@ -28,6 +30,13 @@ func TestConflictingFieldJSONReportsDisagreeingDuplicates(t *testing.T) { {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: "数组元素里的重复键", 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"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -50,8 +59,10 @@ func TestConflictingFieldJSONAcceptsUnambiguousBodies(t *testing.T) { {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","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\\"}"}`}, } @@ -151,6 +162,71 @@ func TestConflictingFieldMultipart(t *testing.T) { }) } +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) + } + 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) +} + +func BenchmarkConflictingField(b *testing.B) { + var sb strings.Builder + sb.WriteString(`{"model":"claude-sonnet-4-5","max_tokens":4096,"stream":true,"system":[{"type":"text","text":"sys"}],"tools":[`) + for i := 0; i < 40; i++ { + if i > 0 { + sb.WriteString(",") + } + fmt.Fprintf(&sb, `{"name":"tool_%d","description":"%s","input_schema":{"type":"object","properties":{"path":{"type":"string"},"content":{"type":"string"}},"required":["path"]}}`, i, strings.Repeat("d", 200)) + } + sb.WriteString(`],"messages":[`) + for i := 0; i < 200; i++ { + if i > 0 { + sb.WriteString(",") + } + fmt.Fprintf(&sb, `{"role":"user","content":[{"type":"text","text":"%s"}]}`, strings.Repeat("t", 1000)) + } + sb.WriteString(`]}`) + body := []byte(sb.String()) + b.SetBytes(int64(len(body))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + if _, conflict := ConflictingField("application/json", body); conflict { + b.Fatal("unexpected conflict") + } + } +} + func TestHasConflictingModels(t *testing.T) { require.False(t, HasConflictingModels(nil)) require.False(t, HasConflictingModels([]string{"a"})) diff --git a/backend/internal/server/middleware/request_field_conflict.go b/backend/internal/server/middleware/request_field_conflict.go index 2d65ee3a2e..70fc99a449 100644 --- a/backend/internal/server/middleware/request_field_conflict.go +++ b/backend/internal/server/middleware/request_field_conflict.go @@ -26,7 +26,7 @@ import ( // 不是 JSON 对象也不是 multipart 的请求体放行,交给 handler 自己校验。 // - 拒绝:按入口协议格式返回 400,请求不会进入合成路由、调度和计费。 // -// Responses WebSocket 的帧不经过这里,由 ResponsesWebSocket 逐帧检查模型候选。 +// Responses WebSocket 的帧不经过这里,由 ResponsesWebSocket 对每一帧执行同一规则。 func RejectConflictingRequestFields() gin.HandlerFunc { return func(c *gin.Context) { if c.Request == nil || c.Request.Body == nil { diff --git a/backend/internal/server/middleware/request_field_conflict_test.go b/backend/internal/server/middleware/request_field_conflict_test.go index 28909a4762..cc5ac2f72f 100644 --- a/backend/internal/server/middleware/request_field_conflict_test.go +++ b/backend/internal/server/middleware/request_field_conflict_test.go @@ -120,7 +120,7 @@ func TestRejectConflictingRequestFieldsPassesUnambiguousBodiesUnchanged(t *testi 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"}}`, + `{"model":"gpt-5.4","metadata":{"k":"1","k":"1"}}`, `not json`, ``, } { 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 364e83429f..a673e35c8c 100644 --- a/backend/internal/server/routes/gateway_request_field_conflict_test.go +++ b/backend/internal/server/routes/gateway_request_field_conflict_test.go @@ -120,3 +120,31 @@ func TestGatewayRoutesRejectConflictingFieldsAllowsIdenticalDuplicates(t *testin 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()) } + +// 嵌套字段取值不一致(reasoning.effort 参与计费倍率与分组推理强度上限、 +// thinking.type 决定是否清洗 thinking 块)同样在进入 handler 之前拒绝。 +func TestGatewayRoutesRejectConflictingNestedFields(t *testing.T) { + cases := []struct { + platform string + path string + body string + field string + }{ + {service.PlatformOpenAI, "/v1/responses", `{"model":"gpt-5.4","reasoning":{"effort":"low","effort":"xhigh"},"input":"hi"}`, `reasoning.effort`}, + {service.PlatformOpenAI, "/backend-api/codex/responses", `{"model":"gpt-5.4","input":[{"role":"user","content":"a","role":"system"}]}`, `input[0].role`}, + {service.PlatformAnthropic, "/v1/messages", `{"model":"claude-sonnet-4-5","thinking":{"type":"disabled","type":"enabled","budget_tokens":1024},"messages":[]}`, `thinking.type`}, + } + for _, tc := range cases { + t.Run(tc.path, func(t *testing.T) { + router := newGatewayRoutesTestRouterWithGroup(allowlistGroup(tc.platform, false)) + req := httptest.NewRequest(http.MethodPost, tc.path, strings.NewReader(tc.body)) + req.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + router.ServeHTTP(w, req) + + require.Equal(t, http.StatusBadRequest, w.Code, w.Body.String()) + require.Contains(t, w.Body.String(), "invalid_request_error") + require.Contains(t, w.Body.String(), tc.field) + }) + } +}