fix(gateway): map non-failover upstream errors in compat paths

Root cause: PR #8385 applied the account error policy to the Chat
Completions and Responses compatibility paths, but statuses outside the
failover whitelist (for example 410 Gone from a migrated upstream base
URL) still fell through to writeGatewayCCError/writeResponsesError with
the upstream status and raw message. Global passthrough rules were not
consulted either, so the client saw a bare 410 and the upstream
migration hint.

Change:
- Apply applyErrorPassthroughRule before writing the non-failover error,
  so configured rules can remap status and message.
- Record the original upstream status plus an http_error Ops event, then
  collapse unknown 4xx statuses (notably 410) into a generic 502
  "Upstream request failed", matching /v1/messages and avoiding exposure
  of upstream migration hints. 400/404/413/422 keep their request-level
  status and sanitized message.
- Leave 410 out of shouldFailoverUpstreamError to avoid changing retry
  semantics.

Tests: extend the compat account policy regression to assert 410 -> 502
without the upstream message, request-level 4xx passthrough and Ops
bookkeeping; add a passthrough-rule remap case for both entrypoints.

Validation:
- go build ./...
- go test -tags=unit ./internal/service -count=1
- go test -tags=unit ./internal/service -run 'TestAnthropicCompat(AccountErrorPolicy|NonFailoverErrorAppliesPassthroughRule)$' -count=1
This commit is contained in:
debug-zhang committed 2026-12-02 10:24:12 +08:00
1 parent f53641e53c
commit ebc32f90fb
3 files changed
+154 -6

No files matched your search

@@ -12,6 +12,7 @@ import (
"testing"
"github.com/Wei-Shaw/sub2api/internal/config"
"github.com/Wei-Shaw/sub2api/internal/model"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
@@ -24,6 +25,11 @@ func TestAnthropicCompatAccountErrorPolicy(t *testing.T) {
wantError int
wantTemp int
wantFailover bool
// Non-failover client-facing expectations. Zero values default to
// tc.status and the sanitized upstream message ("Service moved").
wantClientStatus int
wantClientBody string
rejectClientBody string
}{
{
name: "custom gone", status: http.StatusGone,
@@ -58,15 +64,26 @@ func TestAnthropicCompatAccountErrorPolicy(t *testing.T) {
},
wantTemp: 1, wantFailover: true,
},
{name: "unconfigured gone", status: http.StatusGone},
{
name: "unconfigured gone", status: http.StatusGone,
wantClientStatus: http.StatusBadGateway,
wantClientBody: "Upstream request failed",
rejectClientBody: "Service moved",
},
{
name: "excluded custom code", status: http.StatusGone,
credentials: map[string]any{
"custom_error_codes_enabled": true,
"custom_error_codes": []any{float64(http.StatusNotFound)},
},
wantClientStatus: http.StatusBadGateway,
wantClientBody: "Upstream request failed",
rejectClientBody: "Service moved",
},
{name: "request error", status: http.StatusBadRequest},
{name: "not found keeps request-level status", status: http.StatusNotFound},
{name: "payload too large keeps request-level status", status: http.StatusRequestEntityTooLarge},
{name: "unprocessable keeps request-level status", status: http.StatusUnprocessableEntity},
{name: "default server failover", status: http.StatusInternalServerError, wantFailover: true},
} {
for _, chat := range []bool{false, true} {
@@ -114,11 +131,76 @@ func TestAnthropicCompatAccountErrorPolicy(t *testing.T) {
require.Empty(t, rec.Body.String())
} else {
require.NotErrorAs(t, err, &failoverErr)
require.Equal(t, tc.status, rec.Code)
require.Contains(t, rec.Body.String(), "Service moved")
wantStatus := tc.wantClientStatus
if wantStatus == 0 {
wantStatus = tc.status
}
wantBody := tc.wantClientBody
if wantBody == "" {
wantBody = "Service moved"
}
require.Equal(t, wantStatus, rec.Code)
require.Contains(t, rec.Body.String(), wantBody)
if tc.rejectClientBody != "" {
require.NotContains(t, rec.Body.String(), tc.rejectClientBody)
}
require.Equal(t, tc.status, c.GetInt(OpsUpstreamStatusCodeKey),
"ops must keep the original upstream status")
events, ok := c.Get(OpsUpstreamErrorsKey)
require.True(t, ok)
opsEvents, ok := events.([]*OpsUpstreamErrorEvent)
require.True(t, ok)
require.NotEmpty(t, opsEvents)
require.Equal(t, "http_error", opsEvents[len(opsEvents)-1].Kind)
require.Equal(t, tc.status, opsEvents[len(opsEvents)-1].UpstreamStatusCode)
}
})
}
}
}
}
func TestAnthropicCompatNonFailoverErrorAppliesPassthroughRule(t *testing.T) {
gin.SetMode(gin.TestMode)
for _, chat := range []bool{false, true} {
name := "responses"
path := "/v1/responses"
body := `{"model":"claude-sonnet-4-5","input":"hello"}`
if chat {
name = "chat_completions"
path = "/v1/chat/completions"
body = `{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hello"}]}`
}
t.Run(name, func(t *testing.T) {
account := &Account{ID: 1, Platform: PlatformAnthropic, Type: AccountTypeAPIKey,
Credentials: map[string]any{"api_key": "fixture-key"}}
upstream := &anthropicHTTPUpstreamRecorder{resp: &http.Response{
StatusCode: http.StatusGone, Header: http.Header{},
Body: io.NopCloser(strings.NewReader(`{"type":"error","error":{"type":"invalid_request_error","message":"Service moved to https://migrated.example"}}`)),
}}
svc := &GatewayService{
cfg: &config.Config{}, httpUpstream: upstream,
rateLimitService: NewRateLimitService(&rateLimitAccountRepoStub{}, nil, &config.Config{}, nil, nil),
}
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = httptest.NewRequest(http.MethodPost, path, strings.NewReader(body))
rules := &ErrorPassthroughService{}
rules.setLocalCache([]*model.ErrorPassthroughRule{
newNonFailoverPassthroughRule(http.StatusGone, "Service moved", http.StatusServiceUnavailable, "Upstream account retired"),
})
BindErrorPassthroughService(c, rules)
var err error
if chat {
_, err = svc.ForwardAsChatCompletions(context.Background(), c, account, []byte(body), nil)
} else {
_, err = svc.ForwardAsResponses(context.Background(), c, account, []byte(body), nil)
}
require.Error(t, err)
require.Equal(t, http.StatusServiceUnavailable, rec.Code)
require.Contains(t, rec.Body.String(), "Upstream account retired")
require.NotContains(t, rec.Body.String(), "migrated.example")
})
}
}
@@ -196,7 +196,31 @@ func (s *GatewayService) ForwardAsChatCompletions(
}
}
writeGatewayCCError(c, mapUpstreamStatusCode(resp.StatusCode), "server_error", upstreamMsg)
// Non-failover error: keep the upstream status in Ops, but do not leak
// upstream-only statuses or messages (for example 410 Gone from a
// migrated base URL) to the client. Configured passthrough rules win.
setOpsUpstreamError(c, resp.StatusCode, upstreamMsg, "")
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
Platform: account.Platform,
AccountID: account.ID,
AccountName: account.Name,
UpstreamStatusCode: resp.StatusCode,
UpstreamRequestID: resp.Header.Get("x-request-id"),
Kind: "http_error",
Message: upstreamMsg,
})
if status, errType, errMsg, matched := applyErrorPassthroughRule(
c, account.Platform, resp.StatusCode, respBody,
http.StatusBadGateway, "server_error", "Upstream request failed",
); matched {
writeGatewayCCError(c, status, errType, errMsg)
return nil, fmt.Errorf("upstream error: %d (passthrough rule matched)", resp.StatusCode)
}
statusCode, message := mapCompatClientError(resp.StatusCode, upstreamMsg)
writeGatewayCCError(c, statusCode, "server_error", message)
return nil, fmt.Errorf("upstream error: %d %s", resp.StatusCode, upstreamMsg)
}
@@ -203,8 +203,31 @@ func (s *GatewayService) ForwardAsResponses(
}
}
// Non-failover error: return Responses-formatted error to client
writeResponsesError(c, mapUpstreamStatusCode(resp.StatusCode), "server_error", upstreamMsg)
// Non-failover error: keep the upstream status in Ops, but do not leak
// upstream-only statuses or messages (for example 410 Gone from a
// migrated base URL) to the client. Configured passthrough rules win.
setOpsUpstreamError(c, resp.StatusCode, upstreamMsg, "")
appendOpsUpstreamError(c, OpsUpstreamErrorEvent{
ProxyID: opsUpstreamProxyID(account),
ProxyName: opsUpstreamProxyName(account),
Platform: account.Platform,
AccountID: account.ID,
AccountName: account.Name,
UpstreamStatusCode: resp.StatusCode,
UpstreamRequestID: resp.Header.Get("x-request-id"),
Kind: "http_error",
Message: upstreamMsg,
})
if status, errType, errMsg, matched := applyErrorPassthroughRule(
c, account.Platform, resp.StatusCode, respBody,
http.StatusBadGateway, "server_error", "Upstream request failed",
); matched {
writeResponsesError(c, status, errType, errMsg)
return nil, fmt.Errorf("upstream error: %d (passthrough rule matched)", resp.StatusCode)
}
statusCode, message := mapCompatClientError(resp.StatusCode, upstreamMsg)
writeResponsesError(c, statusCode, "server_error", message)
return nil, fmt.Errorf("upstream error: %d %s", resp.StatusCode, upstreamMsg)
}
@@ -840,3 +863,22 @@ func mapUpstreamStatusCode(code int) int {
}
return code
}
// mapCompatClientError maps a non-failover upstream error to the client-facing
// status and message for the Chat Completions and Responses compatibility
// entrypoints.
//
// Statuses that describe the caller's own request (400/404/413/422) keep their
// status and sanitized upstream message. Every other status - notably 410 Gone
// from a migrated upstream base URL - is an account/upstream-level condition:
// it is collapsed into a generic 502 so these entrypoints match /v1/messages
// and do not expose upstream migration hints.
func mapCompatClientError(statusCode int, upstreamMessage string) (int, string) {
switch statusCode {
case http.StatusBadRequest, http.StatusNotFound,
http.StatusRequestEntityTooLarge, http.StatusUnprocessableEntity:
return statusCode, upstreamMessage
default:
return http.StatusBadGateway, "Upstream request failed"
}
}