From 2b71d868e989ecbc9b8063a020f5c8ddd3c799d3 Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 20 Nov 2026 16:08:18 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20=E5=AF=B9=E9=BD=90=20OAuth=20?= =?UTF-8?q?=E5=8E=86=E5=8F=B2=E9=87=8D=E5=BB=BA=E7=9A=84=E5=B7=A5=E5=85=B7?= =?UTF-8?q?=E5=A3=B0=E6=98=8E=E4=B8=8E=E9=80=89=E6=8B=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../http-recovery-native-controls.yml | 2 +- .../openai_409_native_controls_test.go | 54 ++++++++++++ .../openai_409_controls_diagnostics_test.go | 84 ++++++++++++++++++- .../service/openai_409_omit_history.go | 45 +++++++++- .../service/openai_codex_transform.go | 31 +------ .../openai_oauth_web_search_history.go | 9 ++ .../openai_responses_ingress_compat.go | 28 +++++++ 7 files changed, 219 insertions(+), 34 deletions(-) diff --git a/.github/workflows/http-recovery-native-controls.yml b/.github/workflows/http-recovery-native-controls.yml index 2aa372b03c68..a5495f5fe4b1 100644 --- a/.github/workflows/http-recovery-native-controls.yml +++ b/.github/workflows/http-recovery-native-controls.yml @@ -68,7 +68,7 @@ jobs: - name: Trusted source and late mutation guards if: matrix.phase == 'GREEN' working-directory: backend - run: go test -race -tags=unit,httpprojection ./internal/service -run '^TestOpenAI409NativeControlsIntegrity$' -count=1 -v -timeout=3m + run: go test -race -tags=unit,httpprojection ./internal/service ./internal/handler -run '^TestOpenAI409(NativeControlsIntegrity|NativeControlsOAuthToolHistory|OAuthReplayDiagnosesWebSearchHistoryProjection|OAuthReplayToolPolicies)$' -count=1 -v -timeout=5m - uses: actions/upload-artifact@v7 if: always() with: diff --git a/backend/internal/handler/openai_409_native_controls_test.go b/backend/internal/handler/openai_409_native_controls_test.go index 5812c43f7eb9..1eafa4f27abc 100644 --- a/backend/internal/handler/openai_409_native_controls_test.go +++ b/backend/internal/handler/openai_409_native_controls_test.go @@ -3,6 +3,7 @@ package handler import ( + "encoding/json" "fmt" "net/http" "testing" @@ -13,6 +14,59 @@ import ( "github.com/tidwall/sjson" ) +func TestOpenAI409NativeControlsOAuthToolHistory(t *testing.T) { + t.Run("legacy_named_function", func(t *testing.T) { + option := httpRebuildFixtureOptions{ + request: func(body map[string]any, _ bool) { + if body["previous_response_id"] != "resp_rebuild_A" { + return + } + functions := httpRebuildToolDefinitions() + for _, f := range functions { + delete(f.(map[string]any), "type") + } + delete(body, "tools") + body["functions"] = functions + body["function_call"] = map[string]any{"name": "run_tests"} + }, + provider: func(t *testing.T, body []byte, _ http.Header, n int) { + if n == 2 { + require.Equal(t, "run_tests", gjson.GetBytes(body, "tool_choice.name").String()) + require.False(t, gjson.GetBytes(body, "functions").Exists()) + require.False(t, gjson.GetBytes(body, "function_call").Exists()) + } + }, + } + runHTTPRebuildFixture(t, service.AccountTypeOAuth, false, "previous", "completed", "issue854_auth", "", option) + }) + t.Run("historical_search_only", func(t *testing.T) { + option := httpRebuildFixtureOptions{ + request: func(body map[string]any, _ bool) { + if body["previous_response_id"] != "resp_rebuild_A" { + return + } + body["tools"] = []any{} + var input []json.RawMessage + require.NoError(t, json.Unmarshal(body["input"].(json.RawMessage), &input)) + body["input"] = append(input, json.RawMessage(`{"type":"web_search_call","id":"ws_fixture","status":"completed"}`)) + }, + toolsAvailable: func(body []byte) bool { + return httpRebuildToolsAvailable(body) || (gjson.GetBytes(body, "tools.#").Int() == 1 && + gjson.GetBytes(body, "tools.0.type").String() == "web_search" && gjson.GetBytes(body, "tool_choice").String() == "none") + }, + provider: func(t *testing.T, body []byte, _ http.Header, n int) { + if n == 2 { + require.Equal(t, "none", gjson.GetBytes(body, "tool_choice").String()) + require.Equal(t, "web_search", gjson.GetBytes(body, "tools.0.type").String()) + } + }, + } + // The provider rejects B after recording the physical request. The + // fixture asserts one B send and no subsequent generation or retry. + runHTTPRebuildFixture(t, service.AccountTypeOAuth, false, "previous", "rejected", "issue854_auth", "", option) + }) +} + // Real authentication, scheduler, native builders, Redis delivery fences and // a loopback provider. A emits a patch once, becomes unavailable, then B must // reuse the result, verify once and finish the same client task. diff --git a/backend/internal/service/openai_409_controls_diagnostics_test.go b/backend/internal/service/openai_409_controls_diagnostics_test.go index e7ed2b861141..0e4019ff1124 100644 --- a/backend/internal/service/openai_409_controls_diagnostics_test.go +++ b/backend/internal/service/openai_409_controls_diagnostics_test.go @@ -9,6 +9,7 @@ import ( "github.com/Wei-Shaw/sub2api/internal/config" "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" ) func TestOpenAI409OAuthReplayDiagnosesWebSearchHistoryProjection(t *testing.T) { @@ -34,12 +35,24 @@ func TestOpenAI409OAuthReplayDiagnosesWebSearchHistoryProjection(t *testing.T) { }) require.NoError(t, transformed.Error) require.Len(t, decoded["tools"], 1, "the normal Codex transform declares the historical web_search call") + require.Equal(t, "none", decoded["tool_choice"]) wire, err := json.Marshal(decoded) require.NoError(t, err) req, err := http.NewRequest(http.MethodPost, "https://chatgpt.com/backend-api/codex/responses", bytes.NewReader(wire)) require.NoError(t, err) - _, err = svc.prepareOpenAIAgentRecoveryAttempt(ctx, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth}, req) + account := &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth} + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(ctx, account, req) + require.NoError(t, err) + finish(false) + + decoded["tools"] = []any{map[string]any{"type": "function", "name": "unexpected"}} + decoded["tool_choice"] = "auto" + wire, err = json.Marshal(decoded) + require.NoError(t, err) + req, err = http.NewRequest(http.MethodPost, req.URL.String(), bytes.NewReader(wire)) + require.NoError(t, err) + _, err = svc.prepareOpenAIAgentRecoveryAttempt(ctx, account, req) var recovery *OpenAIAgentRecoveryError require.ErrorAs(t, err, &recovery) require.Equal(t, "controls_integrity", recovery.InternalSubreason()) @@ -57,6 +70,75 @@ func TestOpenAI409OAuthReplayDiagnosesWebSearchHistoryProjection(t *testing.T) { require.NotContains(t, string(encoded), "continue from recorded search results") } +func TestOpenAI409OAuthReplayToolPolicies(t *testing.T) { + for _, tc := range []struct { + name, fields, path string + lite, refuse bool + }{ + {name: "legacy", fields: `"functions":[{"name":"lookup"}],"function_call":{"name":"lookup"}`}, + {name: "changed_legacy_source", fields: `"functions":[{"name":"lookup"}]`, refuse: true}, + {name: "mixed_alias", fields: `"functions":[],"tools":[{"type":"function","name":"lookup"}]`, refuse: true}, + {name: "missing_forced_function", fields: `"functions":[],"function_call":{"name":"lookup"}`, refuse: true}, + {name: "search_lite", fields: `"tools":[]`, lite: true}, + {name: "search_compact", fields: `"tools":[]`, path: "/v1/responses/compact"}, + {name: "search_with_other_tools", fields: `"tools":[{"type":"function","name":"lookup"}],"tool_choice":"auto"`, refuse: true}, + } { + t.Run(tc.name, func(t *testing.T) { + c, _ := newTurnStateTestContext(t, 715, "fixture-session") + if tc.path != "" { + c.Request.URL.Path = tc.path + } + if tc.lite { + c.Request.Header.Set(responsesLiteHeader, "true") + } + input := `[{"role":"user","content":"continue"}]` + if tc.name == "search_lite" || tc.name == "search_compact" || tc.name == "search_with_other_tools" { + input = `[{"type":"web_search_call","id":"ws_1"}]` + } + body := []byte(`{"model":"gpt-6-astra","input":` + input + `,` + tc.fields + `}`) + r := &openAIAgentRecoveryRequest{omittedHistory: true, keyID: 715, session: "fixture-session", model: "gpt-6-astra", inputDigest: openAIAgentRecoveryInputDigest(body), replayControlsDigest: openAI409ControlsDigest(body)} + ctx := context.WithValue(context.Background(), openAIAgentRecoveryContextKey{}, r) + var decoded map[string]any + require.NoError(t, decodeOpenAIJSONUseNumber(body, &decoded)) + if tc.name == "changed_legacy_source" { + decoded["functions"] = []any{map[string]any{"name": "other"}} + } + err := prepareOpenAI409OAuthReplay(ctx, c, decoded) + if tc.refuse && tc.name != "search_with_other_tools" { + require.Error(t, err) + return + } + require.NoError(t, err) + result := applyCodexOAuthTransformWithOptions(decoded, codexOAuthTransformOptions{ResponsesLite: tc.lite, IsCompact: tc.path != "", PreserveReadableReplay: true, SkipDefaultInstructions: true}) + require.NoError(t, result.Error) + wire, err := json.Marshal(decoded) + require.NoError(t, err) + req, err := http.NewRequest(http.MethodPost, "https://chatgpt.com/backend-api/codex/responses", bytes.NewReader(wire)) + require.NoError(t, err) + svc := &OpenAIGatewayService{cfg: &config.Config{}} + finish, err := svc.prepareOpenAIAgentRecoveryAttempt(ctx, &Account{ID: 2, Platform: PlatformOpenAI, Type: AccountTypeOAuth}, req) + if tc.refuse { + require.Error(t, err) + return + } + require.NoError(t, err) + finish(false) + switch tc.name { + case "legacy": + require.Equal(t, "lookup", gjson.GetBytes(wire, "tool_choice.name").String()) + require.Equal(t, "lookup", gjson.GetBytes(wire, "tools.0.name").String()) + case "search_lite": + require.Len(t, decoded["tools"], 0) + require.Equal(t, "web_search", gjson.GetBytes(wire, `input.#(type=="additional_tools").tools.0.type`).String()) + require.Equal(t, "none", decoded["tool_choice"]) + case "search_compact": + require.Len(t, decoded["tools"], 0) + require.NotContains(t, decoded, "tool_choice") + } + }) + } +} + func TestOpenAI409ControlDiagnosticReportsEachControlAndSessionMarker(t *testing.T) { base := []byte(`{"tools":[],"tool_choice":"auto","parallel_tool_calls":true,"instructions":"private instruction"}`) expected := openAI409FingerprintControls(base) diff --git a/backend/internal/service/openai_409_omit_history.go b/backend/internal/service/openai_409_omit_history.go index 5017cf41e09d..982d92330936 100644 --- a/backend/internal/service/openai_409_omit_history.go +++ b/backend/internal/service/openai_409_omit_history.go @@ -6,6 +6,7 @@ import ( "crypto/sha256" "encoding/json" "errors" + "net/http" "strings" "sync/atomic" "time" @@ -561,12 +562,16 @@ func prepareOpenAI409KnownReadableReplay(raw []byte) ([]byte, error) { // Protect the caller's available tools/schema and task instructions as well as // input. Model mappings and transport flags are independently account-specific. func openAI409ControlsDigest(raw []byte) [32]byte { - fields := []string{"tools", "tool_choice", "parallel_tool_calls", "instructions"} + fields := []string{"tools", "tool_choice", "parallel_tool_calls", "instructions", "functions", "function_call"} selected := make(map[string]any, len(fields)) + // Bind legacy inputs to the same immutable source before converting them. + // Keep the digest of requests without aliases byte-for-byte compatible. for _, field := range fields { value := gjson.GetBytes(raw, field) if !value.Exists() { - selected[field] = nil + if field != "functions" && field != "function_call" { + selected[field] = nil + } continue } decoder := json.NewDecoder(strings.NewReader(value.Raw)) @@ -685,6 +690,31 @@ func prepareOpenAI409OAuthReplay(ctx context.Context, c *gin.Context, body map[s body["instructions"] = defaultCodexSynthInstructions(firstNonEmptyString(body["model"])) } extractSystemMessagesFromInput(body, false) + httpReplay := c != nil && c.Request != nil && c.Request.Method == http.MethodPost && GetOpenAIClientTransport(c) != OpenAIClientTransportWS + legacyCall, hasLegacyCall := body["function_call"] + if httpReplay { + _, functions := body["functions"] + _, tools := body["tools"] + _, choice := body["tool_choice"] + if (functions && tools) || (hasLegacyCall && choice) { + return openAIRecoveryWireRefusal(ctx, "oauth_projection_source") + } + if hasLegacyCall { + switch value := legacyCall.(type) { + case string: + if value != "none" && value != "auto" { + return openAIRecoveryWireRefusal(ctx, "oauth_projection_source") + } + case map[string]any: + if len(value) != 1 || strings.TrimSpace(firstNonEmptyString(value["name"])) == "" { + return openAIRecoveryWireRefusal(ctx, "oauth_projection_source") + } + default: + return openAIRecoveryWireRefusal(ctx, "oauth_projection_source") + } + } + convertCodexLegacyFunctionControls(body) + } normalizeCodexTools(body) reverse, _, err := aliasOpenAIOAuthReservedToolNames(body) if err != nil { @@ -692,6 +722,17 @@ func prepareOpenAI409OAuthReplay(ctx context.Context, c *gin.Context, body map[s } setCodexToolNameReverse(c, reverse) normalizeCodexToolChoice(body) + if httpReplay { + // A forced legacy function must not fall back to auto during flattening. + if _, forced := legacyCall.(map[string]any); forced { + if choice, ok := body["tool_choice"].(map[string]any); !ok || choice["type"] != "function" { + return openAIRecoveryWireRefusal(ctx, "oauth_projection_source") + } + } + if !isOpenAIResponsesCompactPath(c) { + declareOpenAIWebSearchHistoryTool(body, isOpenAIResponsesLiteHeader(c.GetHeader(responsesLiteHeader)), true) + } + } prepared, err := json.Marshal(body) if err != nil { return err diff --git a/backend/internal/service/openai_codex_transform.go b/backend/internal/service/openai_codex_transform.go index 86d0d4dda763..c0b1ee842bc2 100644 --- a/backend/internal/service/openai_codex_transform.go +++ b/backend/internal/service/openai_codex_transform.go @@ -242,36 +242,7 @@ func applyCodexOAuthTransformWithOptions(reqBody map[string]any, opts codexOAuth result.Modified = true } - // 兼容遗留的 functions 和 function_call,转换为 tools 和 tool_choice - if functionsRaw, ok := reqBody["functions"]; ok { - if functions, k := functionsRaw.([]any); k { - tools := make([]any, 0, len(functions)) - for _, f := range functions { - tools = append(tools, map[string]any{ - "type": "function", - "function": f, - }) - } - reqBody["tools"] = tools - } - delete(reqBody, "functions") - result.Modified = true - } - - if fcRaw, ok := reqBody["function_call"]; ok { - if fcStr, ok := fcRaw.(string); ok { - // e.g. "auto", "none" - reqBody["tool_choice"] = fcStr - } else if fcObj, ok := fcRaw.(map[string]any); ok { - // e.g. {"name": "my_func"} - if name, ok := fcObj["name"].(string); ok && strings.TrimSpace(name) != "" { - reqBody["tool_choice"] = map[string]any{ - "type": "function", - "name": name, - } - } - } - delete(reqBody, "function_call") + if convertCodexLegacyFunctionControls(reqBody) { result.Modified = true } diff --git a/backend/internal/service/openai_oauth_web_search_history.go b/backend/internal/service/openai_oauth_web_search_history.go index 5ca936143e77..a48dc5815469 100644 --- a/backend/internal/service/openai_oauth_web_search_history.go +++ b/backend/internal/service/openai_oauth_web_search_history.go @@ -78,6 +78,10 @@ func openAIAdditionalToolsInsertIndex(itemTypes []string) int { // ensureOpenAIOAuthWebSearchToolForHistory is the map variant used by the // Codex OAuth transform. func ensureOpenAIOAuthWebSearchToolForHistory(reqBody map[string]any, responsesLite bool) bool { + return declareOpenAIWebSearchHistoryTool(reqBody, responsesLite, false) +} + +func declareOpenAIWebSearchHistoryTool(reqBody map[string]any, responsesLite, requireDisabled bool) bool { if reqBody == nil { return false } @@ -115,6 +119,11 @@ func ensureOpenAIOAuthWebSearchToolForHistory(reqBody map[string]any, responsesL } tools, _ := reqBody["tools"].([]any) callerDeclaredTools = callerDeclaredTools || len(tools) > 0 + // A replay may add a historical declaration only when the resulting + // choice prohibits calling it. Keep the caller's other tools available. + if requireDisabled && reqBody["tool_choice"] != "none" && (callerDeclaredTools || !shouldPinOpenAIWebSearchHistoryToolChoice(reqBody["tool_choice"])) { + return false + } switch { case !responsesLite: diff --git a/backend/internal/service/openai_responses_ingress_compat.go b/backend/internal/service/openai_responses_ingress_compat.go index d7a2adafb853..7c2ea046ffe6 100644 --- a/backend/internal/service/openai_responses_ingress_compat.go +++ b/backend/internal/service/openai_responses_ingress_compat.go @@ -95,6 +95,34 @@ func normalizeOpenAIResponsesLegacyIngressWithConfig(cfg *config.Config, body [] return normalized, true, nil } +// Both ordinary Codex requests and verified OAuth replays use this projection. +func convertCodexLegacyFunctionControls(body map[string]any) bool { + functions, hasFunctions := body["functions"] + call, hasCall := body["function_call"] + if hasFunctions { + if declarations, ok := functions.([]any); ok { + tools := make([]any, 0, len(declarations)) + for _, declaration := range declarations { + tools = append(tools, map[string]any{"type": "function", "function": declaration}) + } + body["tools"] = tools + } + delete(body, "functions") + } + if hasCall { + switch choice := call.(type) { + case string: + body["tool_choice"] = choice + case map[string]any: + if name, ok := choice["name"].(string); ok && strings.TrimSpace(name) != "" { + body["tool_choice"] = map[string]any{"type": "function", "name": name} + } + } + delete(body, "function_call") + } + return hasFunctions || hasCall +} + type convertedLegacyResponsesMessages struct { input any instructions string From 802fca4cc06274a5bcb8336994555512f9dcdafc Mon Sep 17 00:00:00 2001 From: ranxi2001 Date: Fri, 20 Nov 2026 16:35:50 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(ci):=20=E5=AF=B9=E9=BD=90=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=20RED=20=E7=9A=84=20OAuth=20=E9=99=8D=E7=BA=A7?= =?UTF-8?q?=E5=A4=B9=E5=85=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The residual ws-ticket RED compiles unrelated service tests against baseline 94bb4a53e9e5057990cd851ab0620d99b116ad41. The raw job 136166449283 log reports seven compile diagnostics for Candy APIs absent from that production overlay. Use the existing candidate-content-checked shared manifest to restore the baseline 429 and validation fixtures and omit the baseline-absent Candy fixture. These tests cover degradation policy, not the selected WS residual/ticket oracles. The shared helper remains their sole owner and handles repeat invocations idempotently. Production bytes, selected assertions, candidate GREEN and contamination validation are unchanged. Validation: static source/log inspection and git diff --check only. No local tests, installs, lint, typecheck or build; dynamic gates remain remote CI. Agent: Codex; scope: diagnosis and fixture manifest repair. Model: GPT-6; exact model ID and reasoning effort unknown because metadata is not exposed. No subagents used for this repair. --- .github/scripts/upstream-v0222-red-fixtures.txt | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index 53da2b4cd724..41f9232cbb00 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -178,6 +178,13 @@ backend/internal/service/grok_rate_limit_history_test.go backend/internal/service/new_api_cost_test.go backend/internal/service/new_api_wallet_test.go +# Later OAuth degradation/Candy tests require APIs absent from older overlays. +# Restore existing 429/validation fixtures; omit Candy only when baseline-absent. +# This manifest is their sole owner across the HTTP2 and replay helper chains. +backend/internal/service/oauth_degradation_429_test.go +backend/internal/service/oauth_degradation_validation_test.go +backend/internal/service/oauth_degradation_candy_test.go + # Controls diagnostics require the newer recovery APIs, not historical RED sources. backend/internal/service/openai_409_controls_diagnostics_test.go backend/internal/handler/openai_owner_conflict_diagnostics_test.go