From ee99ee1e23b34e96c3d6d38ebe2cfa59a40bf294 Mon Sep 17 00:00:00 2001 From: Sterbennicht Date: Thu, 22 Oct 2026 23:29:05 +0800 Subject: [PATCH] fix(openai-ws): reject unresolved previous_response_id on HTTP bridge On the http_bridge path, a response.create whose previous_response_id cannot be resolved on this connection was silently stripped of the id and posted as a delta-only request, losing the entire prior context. Fail closed instead: close the socket with 1008 and tell the client to resend the full input without previous_response_id. The bridge tracks the last completed turn's response id; a parent is resolvable only when it matches that id and a non-empty replay history exists. Covers fresh connections, id mismatches, empty replay, missing upstream response ids, and failed parent turns. --- .../service/openai_ws_forwarder_ingress.go | 14 +++ .../service/openai_ws_http_bridge_p2_test.go | 117 ++++++++++++++++++ 2 files changed, 131 insertions(+) create mode 100644 backend/internal/service/openai_ws_http_bridge_p2_test.go diff --git a/backend/internal/service/openai_ws_forwarder_ingress.go b/backend/internal/service/openai_ws_forwarder_ingress.go index e97faa44ed..53467fa67e 100644 --- a/backend/internal/service/openai_ws_forwarder_ingress.go +++ b/backend/internal/service/openai_ws_forwarder_ingress.go @@ -589,6 +589,7 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( grokCacheSeedPayload := firstPayload.payloadRaw var bridgeReplayInput []json.RawMessage bridgeReplayInputExists := false + bridgeLastResponseID := "" var bridgeAccountFailoverInput []json.RawMessage bridgeAccountFailoverInputExists := false for turn := 1; ; turn++ { @@ -597,6 +598,15 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( return err } } + // HTTP cannot resolve an opaque parent; only this connection's replay can. + if parent := currentBridgePayload.previousResponseID; parent != "" && + (parent != bridgeLastResponseID || !bridgeReplayInputExists || len(bridgeReplayInput) == 0) { + return NewOpenAIWSClientCloseError( + coderws.StatusPolicyViolation, + "previous_response_id cannot be resolved on this connection; resend full input without previous_response_id", + nil, + ) + } if hooks != nil && hooks.BeforeTurn != nil { if err := hooks.BeforeTurn(turn); err != nil { return err @@ -754,6 +764,10 @@ func (s *OpenAIGatewayService) ProxyResponsesWebSocketFromClient( turnState = bridgeTurnState } responseID := strings.TrimSpace(result.RequestID) + bridgeLastResponseID = "" + if result.UpstreamTerminalEvent == "response.completed" || result.UpstreamTerminalEvent == "response.done" { + bridgeLastResponseID = responseID + } if responseID != "" && stateStore != nil { ttl := s.openAIWSResponseStickyTTL() logOpenAIWSBindResponseAccountWarn(groupID, account.ID, responseID, stateStore.BindResponseAccount(ctx, groupID, responseID, account.ID, ttl)) diff --git a/backend/internal/service/openai_ws_http_bridge_p2_test.go b/backend/internal/service/openai_ws_http_bridge_p2_test.go new file mode 100644 index 0000000000..c0ed7e58b6 --- /dev/null +++ b/backend/internal/service/openai_ws_http_bridge_p2_test.go @@ -0,0 +1,117 @@ +package service + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/config" + coderws "github.com/coder/websocket" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/require" + "github.com/tidwall/gjson" +) + +func TestOpenAIWSHTTPBridgeRejectsUnresolvedPreviousResponseID(t *testing.T) { + gin.SetMode(gin.TestMode) + + for _, tc := range []struct { + name string + priorPayload string + terminal string + responseID string + }{ + {name: "fresh_connection"}, + {name: "mismatching_parent", priorPayload: `{"input":[{"role":"user","content":"first"}]}`, terminal: "response.completed", responseID: "resp_other"}, + {name: "empty_history", priorPayload: `{}`, terminal: "response.completed", responseID: "resp_parent"}, + {name: "missing_response_id", priorPayload: `{"input":[{"role":"user","content":"first"}]}`, terminal: "response.completed"}, + {name: "failed_parent", priorPayload: `{"input":[{"role":"user","content":"first"}]}`, terminal: "response.failed", responseID: "resp_parent"}, + } { + t.Run(tc.name, func(t *testing.T) { + upstream := &httpUpstreamRecorder{} + if tc.priorPayload != "" { + body := fmt.Sprintf("data: {\"type\":%q,\"response\":{\"id\":%q,\"output\":[]}}\n\n", tc.terminal, tc.responseID) + if tc.terminal == "response.failed" { + body = `data: {"type":"response.failed","response":{"id":"resp_parent","output":[],"error":{"type":"invalid_request_error","code":"invalid_value","message":"invalid input"}}}` + "\n\n" + } + upstream.responses = append(upstream.responses, &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(body))}) + } + upstream.responses = append(upstream.responses, &http.Response{StatusCode: http.StatusOK, Header: http.Header{"Content-Type": []string{"text/event-stream"}}, Body: io.NopCloser(strings.NewReader("data: {\"type\":\"response.completed\",\"response\":{\"id\":\"resp_should_not_post\",\"output\":[]}}\n\n"))}) + cfg := &config.Config{} + cfg.Gateway.OpenAIWS.Enabled = true + cfg.Gateway.OpenAIWS.APIKeyEnabled = true + cfg.Gateway.OpenAIWS.ResponsesWebsocketsV2 = true + cfg.Gateway.OpenAIWS.ModeRouterV2Enabled = true + cfg.Gateway.OpenAIWS.ReadTimeoutSeconds = 3 + cfg.Gateway.OpenAIWS.WriteTimeoutSeconds = 3 + svc := &OpenAIGatewayService{cfg: cfg, httpUpstream: upstream, cache: &stubGatewayCache{}, openaiWSResolver: NewOpenAIWSProtocolResolver(cfg)} + account := &Account{ + ID: 9005, Platform: PlatformOpenAI, Type: AccountTypeAPIKey, + Credentials: map[string]any{"api_key": "sk-test"}, + Extra: map[string]any{"openai_apikey_responses_websockets_v2_mode": OpenAIWSIngressModeHTTPBridge}, + Status: StatusActive, Schedulable: true, Concurrency: 1, + } + errCh := make(chan error, 1) + wsServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + conn, err := coderws.Accept(w, r, nil) + if err != nil { + errCh <- err + return + } + defer func() { _ = conn.CloseNow() }() + readCtx, cancel := context.WithTimeout(r.Context(), 3*time.Second) + _, firstMessage, err := conn.Read(readCtx) + cancel() + if err != nil { + errCh <- err + return + } + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = r.Clone(r.Context()) + proxyErr := svc.ProxyResponsesWebSocketFromClient(r.Context(), c, conn, account, "sk-test", firstMessage, nil) + var closeErr *OpenAIWSClientCloseError + if errors.As(proxyErr, &closeErr) { + _ = conn.Close(closeErr.StatusCode(), closeErr.Reason()) + } + errCh <- proxyErr + })) + defer wsServer.Close() + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + client, _, err := coderws.Dial(ctx, "ws"+strings.TrimPrefix(wsServer.URL, "http"), nil) + require.NoError(t, err) + defer func() { _ = client.CloseNow() }() + priorTurns := 0 + if tc.priorPayload != "" { + priorTurns = 1 + priorFrame := `{"type":"response.create","model":"gpt-6.1-sol",` + strings.TrimPrefix(tc.priorPayload, "{") + if tc.priorPayload == `{}` { + priorFrame = `{"type":"response.create","model":"gpt-6.1-sol"}` + } + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(priorFrame))) + _, event, err := client.Read(ctx) + require.NoError(t, err) + require.Equal(t, tc.terminal, gjson.GetBytes(event, "type").String()) + } + require.NoError(t, client.Write(ctx, coderws.MessageText, []byte(`{"type":"response.create","model":"gpt-6.1-sol","previous_response_id":"resp_parent","input":[{"role":"user","content":"delta needing parent"}]}`))) + _, event, readErr := client.Read(ctx) + require.Equal(t, coderws.StatusPolicyViolation, coderws.CloseStatus(readErr), "unresolved parent must fail closed, received: %s", event) + require.Contains(t, readErr.Error(), "previous_response_id") + require.Contains(t, readErr.Error(), "full input") + select { + case proxyErr := <-errCh: + var closeErr *OpenAIWSClientCloseError + require.ErrorAs(t, proxyErr, &closeErr) + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for websocket bridge rejection") + } + require.Len(t, upstream.bodies, priorTurns, "never POST a delta whose parent cannot be reconstructed") + }) + } +}