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
3 changes: 3 additions & 0 deletions .github/scripts/upstream-v0222-red-fixtures.txt
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,9 @@ backend/internal/service/oauth_degradation_429_test.go
backend/internal/service/oauth_degradation_validation_test.go
backend/internal/service/oauth_degradation_candy_test.go

# Ciallo quality questions were introduced after the WS residual RED baseline.
backend/internal/service/ciallo_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
5 changes: 3 additions & 2 deletions .github/workflows/ws-http-bridge-warmup.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ on:
- 'backend/internal/service/openai_gateway_service.go'
- 'backend/internal/handler/openai_gateway_handler.go'
- 'backend/internal/handler/openai_http_bridge_warmup_test.go'
- 'backend/internal/handler/openai_ws_tool_result_bridge_test.go'
- '.github/workflows/ws-http-bridge-warmup.yml'
permissions:
contents: read
Expand Down Expand Up @@ -51,12 +52,12 @@ jobs:
- name: Candidate warmup, full-history tool loop and refusal controls
run: |
set -euo pipefail
(cd backend && go test -race -json -tags=unit,bridgewarmup ./internal/handler ./internal/service -run '^Test(HTTPBridgeWarmup|HTTPBridgeAcceptedHistory|OpenAIWSHTTPBridgeAPIKeyReusesClientToolMappingWhenFollowupOmitsTools|PrepareOpenAIWSHTTPBridgeBody)' -count=1 -timeout=3m) | tee "$RUNNER_TEMP/http-warmup-head.jsonl"
(cd backend && go test -race -json -tags=unit,bridgewarmup ./internal/handler ./internal/service -run '^Test(HTTPBridgeLargeHistoryToolResult|HTTPBridgeWarmup|HTTPBridgeAcceptedHistory|OpenAIWSHTTPBridgeAPIKeyReusesClientToolMappingWhenFollowupOmitsTools|PrepareOpenAIWSHTTPBridgeBody)' -count=1 -timeout=3m) | tee "$RUNNER_TEMP/http-warmup-head.jsonl"
python3 - "$RUNNER_TEMP/http-warmup-head.jsonl" <<'PY'
import json,sys
rows=[json.loads(line) for line in open(sys.argv[1]) if line.startswith('{')]
assert not any(r.get('Action') in ('build-fail','fail','skip') for r in rows)
for name in ('TestHTTPBridgeWarmupThenToolContinuation','TestHTTPBridgeWarmupGuards','TestHTTPBridgeWarmupDefaultsAndForeignPointer','TestHTTPBridgeWarmupWithPriorCompletedToolHistory','TestHTTPBridgeAcceptedHistoryRequiresCompletedDelivery'):
for name in ('TestHTTPBridgeLargeHistoryToolResult/api_key_large','TestHTTPBridgeLargeHistoryToolResult/oauth_large','TestHTTPBridgeLargeHistoryToolResult/oauth_wrong_response','TestHTTPBridgeLargeHistoryToolResult/oauth_unobserved_call','TestHTTPBridgeLargeHistoryToolResult/oauth_old_call','TestHTTPBridgeWarmupThenToolContinuation','TestHTTPBridgeWarmupGuards','TestHTTPBridgeWarmupDefaultsAndForeignPointer','TestHTTPBridgeWarmupWithPriorCompletedToolHistory','TestHTTPBridgeAcceptedHistoryRequiresCompletedDelivery'):
assert any(r.get('Test')==name and r.get('Action')=='pass' for r in rows),name
PY
- uses: actions/upload-artifact@v7
Expand Down
102 changes: 102 additions & 0 deletions backend/internal/handler/openai_ws_tool_result_bridge_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
//go:build unit && bridgewarmup

package handler

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"

"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/Wei-Shaw/sub2api/internal/testutil"
ws "github.com/coder/websocket"
"github.com/stretchr/testify/require"
"github.com/tidwall/gjson"
)

func TestHTTPBridgeLargeHistoryToolResult(t *testing.T) {
for _, tc := range []struct {
name, account, previous, call string
size int
accept bool
}{
{"api_key_large", service.AccountTypeAPIKey, "resp_one", "turn_one", (8 << 20) + 1024, true},
{"oauth_large", service.AccountTypeOAuth, "resp_one", "turn_one", (16 << 20) + 1024, true},
{"oauth_wrong_response", service.AccountTypeOAuth, "resp_foreign", "turn_one", 256, false},
{"oauth_unobserved_call", service.AccountTypeOAuth, "resp_one", "never_delivered", 256, false},
{"oauth_old_call", service.AccountTypeOAuth, "resp_one", "prior", 256, false},
} {
t.Run(tc.name, func(t *testing.T) {
var calls atomic.Int32
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
t.Error(err)
return
}
n := calls.Add(1)
w.Header().Set("Content-Type", "text/event-stream")
if n == 1 {
fmt.Fprint(w, `data: {"type":"response.completed","response":{"id":"resp_one","status":"completed","output":[{"type":"function_call","name":"lookup","call_id":"turn_one","arguments":"{}","status":"completed"}],"usage":{"input_tokens":1,"output_tokens":1}}}`+"\n\n")
return
}
if !tc.accept || n != 2 || gjson.GetBytes(body, "previous_response_id").Exists() ||
gjson.GetBytes(body, `input.#(call_id=="turn_one")#.type`).Raw != `["function_call","function_call_output"]` ||
gjson.GetBytes(body, `input.#(call_id=="prior")#.type`).Raw != `["function_call","function_call_output"]` ||
gjson.GetBytes(body, `input.#(type=="function_call_output")#.output`).Raw != `["old receipt","new receipt"]` {
t.Error("unexpected bridge payload or repeated dispatch")
}
fmt.Fprint(w, `data: {"type":"response.completed","response":{"id":"resp_two","status":"completed","output":[],"usage":{"input_tokens":1,"output_tokens":1}}}`+"\n\n")
}))
defer upstream.Close()
h := newOpenAIWSPassthroughHandlerHarnessWithKey(t, upstream.URL, http.Header{"Session-Id": {"fixture-tool-result"}}, map[string]string{service.SettingKeyCyberSessionBlockEnabled: "false", service.SettingKeyOpenAI409OmitEncryptedHistoryEnabled: "true"}, nil, func(k *service.APIKey) { k.AllowLongContext = true }, func(a *service.Account, cfg *config.Config, transport *service.HTTPUpstream, _ *service.AccountRepository) {
a.Extra["openai_apikey_responses_websockets_v2_mode"] = service.OpenAIWSIngressModeHTTPBridge
if tc.account == service.AccountTypeOAuth {
a.Type = tc.account
a.Credentials = map[string]any{"access_token": "fixture-token", "chatgpt_account_id": "fixture-account"}
a.Extra["openai_oauth_responses_websockets_v2_enabled"] = true
a.Extra["openai_oauth_responses_websockets_v2_mode"] = service.OpenAIWSIngressModeCtxPool
cfg.Gateway.OpenAIWS.OAuthEnabled = true
cfg.Gateway.OpenAIWS.HTTPBridgeEnabled = true
cfg.Gateway.OpenAIWS.HTTPBridgeThresholdBytes = 128
target, err := url.Parse(upstream.URL)
require.NoError(t, err)
*transport = &httpRebuildTransport{HTTPUpstream: testutil.NewRealHTTPUpstream(cfg), target: target}
}
})
defer h.clientConn.CloseNow()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
first := `{"type":"response.create","model":"gpt-5.1","store":false,"input":[{"role":"user","content":"` + strings.Repeat("x", tc.size) + `"},{"type":"function_call","name":"lookup","call_id":"prior","arguments":"{}","status":"completed"},{"type":"function_call_output","call_id":"prior","output":"old receipt"}]}`
require.NoError(t, h.clientConn.Write(ctx, ws.MessageText, []byte(first)))
_, raw, err := h.clientConn.Read(ctx)
require.NoError(t, err)
require.Equal(t, "resp_one", gjson.GetBytes(raw, "response.id").String())
next := fmt.Sprintf(`{"type":"response.create","model":"gpt-5.1","store":false,"previous_response_id":%q,"input":[{"type":"function_call_output","call_id":%q,"output":"new receipt"}]}`, tc.previous, tc.call)
require.NoError(t, h.clientConn.Write(ctx, ws.MessageText, []byte(next)))
_, raw, err = h.clientConn.Read(ctx)
if tc.accept {
require.NoError(t, err, "BRIDGE_TOOL_RESULT_REFUSED")
require.Equal(t, "resp_two", gjson.GetBytes(raw, "response.id").String(), "BRIDGE_TOOL_RESULT_REFUSED")
require.EqualValues(t, 2, calls.Load())
return
}
if err == nil {
require.True(t, json.Valid(raw))
require.Equal(t, "error", gjson.GetBytes(raw, "type").String())
} else {
require.NotEqual(t, ws.StatusCode(-1), ws.CloseStatus(err))
}
require.EqualValues(t, 1, calls.Load())
})
}
}
25 changes: 20 additions & 5 deletions backend/internal/service/openai_tool_provenance.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ import (
"strings"
"time"

"github.com/Wei-Shaw/sub2api/internal/pkg/logger"
"github.com/tidwall/gjson"
"go.uber.org/zap"
)

// Only hashes and delivery/route metadata; never tool arguments/results. A
Expand Down Expand Up @@ -480,6 +482,13 @@ func (s *OpenAIGatewayService) verifyOpenAIToolInputs(ctx context.Context, r *op
return s.verifyOpenAIToolInputProofs(ctx, r, body, false)
}

// The externally visible refusal stays stable. Only fixed classifications go
// to the journal; call IDs, proof bytes and tool contents stay private.
func openAIToolProvenanceRefusal(ctx context.Context, r *openAIAgentRecoveryRequest, detail string) error {
logger.FromContext(ctx).Warn("openai.tool_provenance_refused", zap.String("check", detail))
return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r)
}

func (s *OpenAIGatewayService) verifyOpenAIToolInputProofs(ctx context.Context, r *openAIAgentRecoveryRequest, body []byte, discoveryOnly bool) error {
if discoveryOnly {
hasDiscovery := false
Expand Down Expand Up @@ -513,7 +522,7 @@ func (s *OpenAIGatewayService) verifyOpenAIToolInputProofs(ctx context.Context,
}
fingerprint, ok := openAIToolFingerprint(item)
if !ok || r.userID <= 0 {
return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r)
return openAIToolProvenanceRefusal(ctx, r, "invalid_call_or_principal")
}
key := r.toolKey(item.Get("call_id").String())
raw, err := s.toolProofGet(ctx, key)
Expand All @@ -522,23 +531,29 @@ func (s *OpenAIGatewayService) verifyOpenAIToolInputProofs(ctx context.Context,
select {
case <-ctx.Done():
timer.Stop()
return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r)
return openAIToolProvenanceRefusal(ctx, r, "pending_interrupted")
case <-timer.C:
}
raw, err = s.toolProofGet(ctx, key)
// Once a pending proof was observed, exhausting this wait is the
// same ownership refusal whether the timer or GET sees the deadline.
// An independent backend timeout/error remains a store failure.
if ctx.Err() == context.DeadlineExceeded && errors.Is(err, context.DeadlineExceeded) {
return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r)
return openAIToolProvenanceRefusal(ctx, r, "pending_timeout")
}
}
if err != nil {
return openAIRecoveryDiagnosticError("store_unavailable", "tool_provenance_unavailable", r)
}
var proof openAIToolProof
if len(raw) > OpenAIToolProvenanceMaxBytes || json.Unmarshal([]byte(raw), &proof) != nil || proof.Call != fingerprint {
return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r)
if raw == "" {
return openAIToolProvenanceRefusal(ctx, r, "record_missing")
}
if len(raw) > OpenAIToolProvenanceMaxBytes || json.Unmarshal([]byte(raw), &proof) != nil {
return openAIToolProvenanceRefusal(ctx, r, "record_unusable")
}
if proof.Call != fingerprint {
return openAIToolProvenanceRefusal(ctx, r, "fingerprint_mismatch")
}
handoffValid := false
if h, ok := ctx.Value(openAIWSDiscoveryHandoffKey{}).(*openAIWSDiscoveryHandoff); ok && h != nil && kind == "tool_search_call" {
Expand Down
69 changes: 64 additions & 5 deletions backend/internal/service/openai_ws_agent_recovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ type openAIWSAgentRecovery struct {
pendingHistoryTools map[string]openAIWSAcceptedToolHistory
historicalToolIDs map[[32]byte]struct{}
historicalToolIDsExhausted bool
completedTurnTools map[string]openAIWSDeliveredTool
deliveredTools map[string]openAIWSDeliveredTool
pendingTools map[string]openAIWSDeliveredTool
localHistory openAIWSLocalHistory
Expand Down Expand Up @@ -360,7 +361,7 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte,
previous := gjson.GetBytes(source, "previous_response_id").String()
projected := false
if proof, ok := req.Context().Value(openAIWSPlaintextProjectionKey{}).(*openAIWSPlaintextProjection); ok {
if proof == nil || mode != "http_bridge" || !account.IsOpenAIApiKey() || proof.accountID != account.ID ||
if proof == nil || mode != "http_bridge" || !openAIWSPlaintextBridgeAccount(account) || proof.accountID != account.ID ||
proof.anchor.response == "" || proof.anchor != r.completedBridge || proof.anchor != openAIWSBridgeAnchor(r.request, account, previous) ||
r.request.owner != nil || len(r.request.items) != 0 || r.request.preservesHistory() ||
proof.previous != previous || r.request.previousResponseID != previous ||
Expand All @@ -369,6 +370,13 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte,
proof.controls != openAI409ControlsDigest(payload) {
return openAIWSWireRefusal(ctx, "ws_projection_integrity", source, payload)
}
if account.IsOpenAIOAuth() && (r.request.disallowLearning || r.request.userID <= 0 || r.request.keyID <= 0 ||
!oauthBridgeDeliveredResults(source, r.request.model, previous, r.completedTurnTools) ||
openAIWSHasOpaqueField(gjson.GetBytes(proof.history, "input"), 0) ||
openAIAgentRecoveryInputDigest(proof.history) != proof.input ||
openAI409ControlsDigest(proof.history) != proof.controls) {
return openAIWSWireRefusal(ctx, "ws_projection_integrity", source, payload)
}
// Recheck the original pointer on the actual selected account before
// allowing its HTTP representation to omit that pointer.
if err := r.service.checkOpenAIAgentRecoveryAccount(ctx, account); err != nil {
Expand All @@ -383,15 +391,18 @@ func (r *openAIWSAgentRecovery) begin(account *Account, source, payload []byte,
continue
}
if r.historicalToolIDsExhausted {
return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r.request)
return openAIToolProvenanceRefusal(ctx, r.request, "bridge_identity_limit")
}
fingerprint, valid := openAIToolFingerprint(item)
observed, found := r.deliveredTools[r.request.model+"\x00"+item.Get("call_id").String()]
if !found && acceptsPriorToolPair(r.acceptedHistoryTools, account, r.request.model, item, proof.history) {
continue
}
if !valid || !found || observed.conflicted || observed.fingerprint != fingerprint || observed.accountID != account.ID || observed.config != openAIAgentRecoveryConfig(account, r.request.model) {
return openAIRecoveryDiagnosticError("owner_conflict", "tool_provenance_unknown", r.request)
if !found {
return openAIToolProvenanceRefusal(ctx, r.request, "bridge_delivery_missing")
}
if !valid || observed.conflicted || observed.fingerprint != fingerprint || observed.accountID != account.ID || observed.config != openAIAgentRecoveryConfig(account, r.request.model) {
return openAIToolProvenanceRefusal(ctx, r.request, "bridge_delivery_mismatch")
}
}
handoff := &openAIWSDiscoveryHandoff{scope: *r.request, input: openAIAgentRecoveryInputDigest(proof.history), controls: openAI409ControlsDigest(proof.history), proofs: make(map[string]openAIToolProofSnapshot)}
Expand Down Expand Up @@ -577,13 +588,15 @@ func (r *openAIWSAgentRecovery) write(payload []byte, write func() error) error
}
r.acceptedHistoryTools = r.pendingHistoryTools
}
r.completedTurnTools = r.pendingTools
r.completedResponse, r.completedAccount, r.completedModel = responseID, request.delivery.binding.accountID, request.model
r.completedBridge = openAIWSBridgeResponseAnchor{response: responseID, model: request.model, session: request.session,
account: request.delivery.binding.accountID, key: request.keyID, user: request.userID, group: request.groupID, config: request.delivery.binding.config}
if r.deliveredTools == nil {
r.deliveredTools = make(map[string]openAIWSDeliveredTool)
}
for key, observed := range r.pendingTools {

// Reuse the delivery's terminal verdict for this manager-local
// proof. Shared persisted proofs additionally require encrypted
// anchors, which an ordinary plaintext call does not have.
Expand Down Expand Up @@ -1349,11 +1362,37 @@ func openAIWSToolResultDigest(item gjson.Result) [32]byte {
}

func acceptedOpenAIWSToolHistory(source []byte, account *Account, model string) map[string]openAIWSAcceptedToolHistory {
if account == nil || !account.IsOpenAIApiKey() || len(source) > 8<<20 ||
if !openAIWSPlaintextBridgeAccount(account) || int64(len(source)) > openAIWSClientReadLimitBytesDefault ||
gjson.GetBytes(source, "previous_response_id").String() != "" || gjson.GetBytes(source, "conversation").Exists() ||
len(openAIAgentRecoveryItemDigests(source)) != 0 || !openAIEncryptedJSONUnambiguous(source) {
return nil
}
// Large frames can carry images or long messages unrelated to tool history.
// Bound the tool data we normalize and fingerprint, after validating the
// entire original frame (including ambiguous keys and encrypted items).
if len(source) > 8<<20 {
const prefix = `{"input":[`
tools := []byte(prefix)
fits := true
gjson.GetBytes(source, "input").ForEach(func(_, item gjson.Result) bool {
switch item.Get("type").String() {
case "function_call", "custom_tool_call", "tool_search_call", "function_call_output", "custom_tool_call_output", "tool_search_output":
if len(tools)+len(item.Raw)+3 > 8<<20 {
fits = false
return false
}
if len(tools) > len(prefix) {
tools = append(tools, ',')
}
tools = append(tools, item.Raw...)
}
return true
})
if !fits {
return nil
}
source = append(tools, ']', '}')
}
if _, reason := inspectOpenAIWSCompletedTools(source); reason != "" {
return nil
}
Expand Down Expand Up @@ -1397,3 +1436,23 @@ func acceptsPriorToolPair(acceptedTools map[string]openAIWSAcceptedToolHistory,
}
return false
}

// An OAuth HTTP bridge may consume results of the immediately preceding
// delivered response. Reconnects and independent tasks have a different anchor.
func oauthBridgeDeliveredResults(source []byte, model, previous string, delivered map[string]openAIWSDeliveredTool) bool {
input := gjson.GetBytes(source, "input")
if !input.IsArray() || previous == "" {
return false
}
count := 0
ok := true
input.ForEach(func(_, item gjson.Result) bool {
count++
kind := item.Get("type").String()
record, found := delivered[model+"\x00"+item.Get("call_id").String()]
ok = (kind == "function_call_output" || kind == "custom_tool_call_output") &&
found && !record.conflicted
return ok
})
return count > 0 && ok
}
2 changes: 1 addition & 1 deletion backend/internal/service/openai_ws_http_bridge.go
Original file line number Diff line number Diff line change
Expand Up @@ -575,7 +575,7 @@ func (s *OpenAIGatewayService) proxyOpenAIWSHTTPBridgeTurn(
// store=false cannot carry a provider-side response pointer over HTTP.
// The ingress has reconstructed this same bridge's history; retain an immutable
// proof before request construction, rather than trusting final wire bytes.
if !s.openAILegacyCompatibility() && account.IsOpenAIApiKey() && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) {
if !s.openAILegacyCompatibility() && openAIWSPlaintextBridgeAccount(account) && s.settingService != nil && s.settingService.IsOpenAI409OmitEncryptedHistoryEnabled(ctx) {
source, _ := ctx.Value(openAIWSAgentSourceKey{}).([]byte)
previous := gjson.GetBytes(source, "previous_response_id").String()
// The ingress has already stripped invalid item IDs. Derive that one
Expand Down
8 changes: 8 additions & 0 deletions backend/internal/service/openai_ws_http_bridge_account.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package service

func openAIWSPlaintextBridgeAccount(account *Account) bool {
return account != nil && (account.IsOpenAIApiKey() || (account.IsOpenAIOAuth() &&
!account.HasManagedOpenAIConnections() && account.AuthConnectionID == "" &&
!account.IsSIWCEnabled() && !account.IsCopilotSDKEnabled() && !account.IsExcelOAuth() &&
!account.IsOpenAIPassthroughEnabled()))
}
Loading