fix(openai): let error passthrough rules override the built-in body-limit 413

handleFailoverExhausted returned a fixed 413 for
IsOpenAIRequestBodyTooLarge() before reaching the generic error-passthrough
rule lookup further down, so a rule configured with error_codes [413] could
never match on this path. The service layer already returns the same
failover sentinel ahead of applyErrorPassthroughRule, so both layers
short-circuit and the rule vocabulary silently excludes 413.

Extract the existing rule application into
applyOpenAIFailoverPassthroughRule and call it first inside the body-limit
branch (and reuse it for the generic branch). Failover on 413 is left
intact: different accounts can front proxies with different body limits, so
switching may still succeed. The rule only decides the client-facing
response once failover is exhausted.

This matters for clients that treat 413 as retryable. Codex CLI maps a
non-2xx HTTP status to CodexErr::UnexpectedStatus, whose is_retryable()
returns true, and retries the sampling request up to stream_max_retries
(default 5) times. When the payload can never fit, every retry is wasted
work, and an operator has no supported way to signal "do not retry". Mapping
the same upstream 413 to 400 makes Codex map it to InvalidRequest, which is
not retryable, so it fails fast.

Tests cover the override on both unary and started-stream paths, the
unchanged built-in 413 when no rule matches, and skip_monitoring.
This commit is contained in:
wangjunwei committed 2026-10-30 15:19:54 +08:00
1 parent d851a38477
commit fa6f06510b
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)
}
@@ -3538,6 +3538,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,
@@ -3597,27 +3608,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 错误日志捕获真实的上游错误
@@ -3629,6 +3621,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