Merge pull request #8437 from m11y/fix/error-passthrough-before-body-limit-failover

fix(openai): let error passthrough rules override the built-in body-limit 413
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-11-07 10:53:41 +08:00
commit 1209e71e6d
2 files changed
+209 -21

No files matched your search

@@ -0,0 +1,157 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/Wei-Shaw/sub2api/internal/model"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
// errorPassthroughRepoStub is a minimal service.ErrorPassthroughRepository for
// handler-level rule tests. Rules are returned as-is; the mutating methods are
// never exercised here.
type errorPassthroughRepoStub struct {
rules []*model.ErrorPassthroughRule
}
func (s *errorPassthroughRepoStub) List(context.Context) ([]*model.ErrorPassthroughRule, error) {
return s.rules, nil
}
func (s *errorPassthroughRepoStub) GetByID(context.Context, int64) (*model.ErrorPassthroughRule, error) {
return nil, nil
}
func (s *errorPassthroughRepoStub) Create(_ context.Context, rule *model.ErrorPassthroughRule) (*model.ErrorPassthroughRule, error) {
return rule, nil
}
func (s *errorPassthroughRepoStub) Update(_ context.Context, rule *model.ErrorPassthroughRule) (*model.ErrorPassthroughRule, error) {
return rule, nil
}
func (s *errorPassthroughRepoStub) Delete(context.Context, int64) error { return nil }
func newBodyLimitPassthroughHandler(t *testing.T, rule *model.ErrorPassthroughRule) *OpenAIGatewayHandler {
t.Helper()
repo := &errorPassthroughRepoStub{}
if rule != nil {
repo.rules = []*model.ErrorPassthroughRule{rule}
}
return &OpenAIGatewayHandler{
errorPassthroughService: service.NewErrorPassthroughService(repo, nil),
}
}
func newBodyLimitPassthroughRule(responseCode int, customMessage string) *model.ErrorPassthroughRule {
msg := customMessage
return &model.ErrorPassthroughRule{
ID: 1,
Name: "body limit -> client error",
Enabled: true,
Priority: 1,
ErrorCodes: []int{http.StatusRequestEntityTooLarge},
MatchMode: model.MatchModeAny,
Platforms: []string{model.PlatformOpenAI},
PassthroughCode: false,
ResponseCode: &responseCode,
PassthroughBody: false,
CustomMessage: &msg,
}
}
// A configured 413 rule must win over the built-in body-limit mapping: the
// built-in branch returns 413 before the generic passthrough lookup runs, so a
// rule could otherwise never match on this path.
func TestOpenAIBodyLimitFailoverExhausted_PassthroughRuleOverridesBuiltInMapping(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil))
h := newBodyLimitPassthroughHandler(t, newBodyLimitPassthroughRule(http.StatusBadRequest, "Request body exceeds the upstream limit"))
h.handleFailoverExhausted(c, bodyLimitFailoverTestError(), false)
require.Equal(t, http.StatusBadRequest, rec.Code)
var envelope map[string]any
require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &envelope))
errBody, ok := envelope["error"].(map[string]any)
require.True(t, ok)
require.Equal(t, "upstream_error", errBody["type"])
require.Equal(t, "Request body exceeds the upstream limit", errBody["message"])
require.NotContains(t, rec.Body.String(), "must-not-leak")
}
// The override must also apply once the SSE stream has already started.
func TestOpenAIBodyLimitFailoverExhausted_PassthroughRuleAppliesToStartedStream(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil))
h := newBodyLimitPassthroughHandler(t, newBodyLimitPassthroughRule(http.StatusBadRequest, "Request body exceeds the upstream limit"))
h.handleFailoverExhausted(c, bodyLimitFailoverTestError(), true)
body := rec.Body.String()
require.Contains(t, body, `"message":"Request body exceeds the upstream limit"`)
require.NotContains(t, body, "must-not-leak")
}
// Without a rule the built-in 413 mapping stays in place.
func TestOpenAIBodyLimitFailoverExhausted_NoRuleKeepsBuiltIn413(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil))
h := newBodyLimitPassthroughHandler(t, nil)
h.handleFailoverExhausted(c, bodyLimitFailoverTestError(), false)
require.Equal(t, http.StatusRequestEntityTooLarge, rec.Code)
require.Contains(t, rec.Body.String(), service.OpenAIRequestBodyTooLargeClientMessage)
}
// A rule scoped to a different upstream status must not affect the 413 path.
func TestOpenAIBodyLimitFailoverExhausted_NonMatchingRuleKeepsBuiltIn413(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil))
rule := newBodyLimitPassthroughRule(http.StatusBadRequest, "Request body exceeds the upstream limit")
rule.ErrorCodes = []int{http.StatusServiceUnavailable}
h := newBodyLimitPassthroughHandler(t, rule)
h.handleFailoverExhausted(c, bodyLimitFailoverTestError(), false)
require.Equal(t, http.StatusRequestEntityTooLarge, rec.Code)
require.Contains(t, rec.Body.String(), service.OpenAIRequestBodyTooLargeClientMessage)
}
// skip_monitoring on a matching rule must still be honored on this path.
func TestOpenAIBodyLimitFailoverExhausted_PassthroughRuleSkipMonitoring(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, "/v1/responses", bytes.NewReader(nil))
rule := newBodyLimitPassthroughRule(http.StatusBadRequest, "Request body exceeds the upstream limit")
rule.SkipMonitoring = true
h := newBodyLimitPassthroughHandler(t, rule)
h.handleFailoverExhausted(c, bodyLimitFailoverTestError(), false)
value, exists := c.Get(service.OpsSkipPassthroughKey)
require.True(t, exists)
require.Equal(t, true, value)
}
@@ -3589,6 +3589,17 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE
}
copyFailoverRetryAfter(c, failoverErr.ResponseHeaders)
if failoverErr.IsOpenAIRequestBodyTooLarge() {
// An operator-configured passthrough rule wins over the built-in body
// limit mapping below. Failover on 413 exists because different
// accounts can front proxies with different body limits, so the
// switching itself is left intact; what the rule controls is the
// client-facing response once failover is exhausted. Without this
// check a 413 rule can never match on the native /responses path,
// because the body-limit branch returns before the generic rule
// lookup further down.
if h.applyOpenAIFailoverPassthroughRule(c, failoverErr.StatusCode, failoverErr.ResponseBody, streamStarted) {
return
}
service.SetOpsUpstreamError(c, http.StatusRequestEntityTooLarge, service.OpenAIRequestBodyTooLargeClientMessage, "")
h.handleStreamingAwareError(
c,
@@ -3648,27 +3659,8 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE
}
// 先检查透传规则
if h.errorPassthroughService != nil && len(responseBody) > 0 {
if rule := h.errorPassthroughService.MatchRule("openai", statusCode, responseBody); rule != nil {
// 确定响应状态码
respCode := statusCode
if !rule.PassthroughCode && rule.ResponseCode != nil {
respCode = *rule.ResponseCode
}
// 确定响应消息
msg := service.ExtractUpstreamErrorMessage(responseBody)
if !rule.PassthroughBody && rule.CustomMessage != nil {
msg = *rule.CustomMessage
}
if rule.SkipMonitoring {
c.Set(service.OpsSkipPassthroughKey, true)
}
h.handleStreamingAwareError(c, respCode, "upstream_error", msg, streamStarted)
return
}
if h.applyOpenAIFailoverPassthroughRule(c, statusCode, responseBody, streamStarted) {
return
}
// 记录原始上游状态码,以便 ops 错误日志捕获真实的上游错误
@@ -3680,6 +3672,45 @@ func (h *OpenAIGatewayHandler) handleFailoverExhausted(c *gin.Context, failoverE
h.handleStreamingAwareError(c, status, errType, errMsg, streamStarted)
}
// applyOpenAIFailoverPassthroughRule applies a configured error passthrough
// rule to an exhausted OpenAI failover. It reports whether a rule matched and
// the client response has been written; callers must return when it does.
//
// Rules are operator opt-in overrides, so they take precedence over the
// gateway's built-in mapping for the same upstream status, including the
// body-too-large branch that otherwise returns a fixed 413.
func (h *OpenAIGatewayHandler) applyOpenAIFailoverPassthroughRule(
c *gin.Context,
statusCode int,
responseBody []byte,
streamStarted bool,
) bool {
if h.errorPassthroughService == nil || statusCode <= 0 || len(responseBody) == 0 {
return false
}
rule := h.errorPassthroughService.MatchRule("openai", statusCode, responseBody)
if rule == nil {
return false
}
respCode := statusCode
if !rule.PassthroughCode && rule.ResponseCode != nil {
respCode = *rule.ResponseCode
}
msg := service.ExtractUpstreamErrorMessage(responseBody)
if !rule.PassthroughBody && rule.CustomMessage != nil {
msg = *rule.CustomMessage
}
if rule.SkipMonitoring {
c.Set(service.OpsSkipPassthroughKey, true)
}
h.handleStreamingAwareError(c, respCode, "upstream_error", msg, streamStarted)
return true
}
func credentialFailoverClientResponse(failoverErr *service.UpstreamFailoverError) (int, string) {
if failoverErr != nil && failoverErr.Reason == service.OpenAIUpstreamAccessStateReason && strings.TrimSpace(failoverErr.ClientMessage) != "" {
status := failoverErr.ClientStatusCode