Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .github/scripts/upstream-v0222-red-fixtures.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion .github/workflows/http-recovery-native-controls.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
54 changes: 54 additions & 0 deletions backend/internal/handler/openai_409_native_controls_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package handler

import (
"encoding/json"
"fmt"
"net/http"
"testing"
Expand All @@ -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.
Expand Down
84 changes: 83 additions & 1 deletion backend/internal/service/openai_409_controls_diagnostics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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())
Expand All @@ -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)
Expand Down
45 changes: 43 additions & 2 deletions backend/internal/service/openai_409_omit_history.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"crypto/sha256"
"encoding/json"
"errors"
"net/http"
"strings"
"sync/atomic"
"time"
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -685,13 +690,49 @@ 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 {
return err
}
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
Expand Down
31 changes: 1 addition & 30 deletions backend/internal/service/openai_codex_transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
9 changes: 9 additions & 0 deletions backend/internal/service/openai_oauth_web_search_history.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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:
Expand Down
28 changes: 28 additions & 0 deletions backend/internal/service/openai_responses_ingress_compat.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading