Merge pull request #8255 from wucm667/fix/issue-8248-cloudflare-json-403

fix(ratelimit): avoid penalizing Cloudflare 1010 blocks
This commit is contained in:
Wesley Liddick authored and GitHub committed 2026-10-21 20:09:19 +08:00
commit aa48a8bbd8
2 files changed
+128 -15

No files matched your search

+65 -13
View File
@@ -1003,10 +1003,19 @@ func buildForbiddenErrorMessage(prefix string, upstreamMsg string, responseBody
return prefix + fallback
}
// handle403 处理 403 Forbidden 错误
// Antigravity 平台区分 validation/violation/generic 三种类型,均 SetError 永久禁用;
// 其他平台保持原有 SetError 行为。
// handle403 处理 403 Forbidden 错误。Cloudflare 1010 是请求/边缘级拦截,
// 不应将其视为账号级故障;其他真实 403 继续按平台策略处理。
func (s *RateLimitService) handle403(ctx context.Context, account *Account, upstreamMsg string, responseBody []byte) (shouldDisable bool) {
if isCloudflareBotBlockResponse(responseBody) {
slog.Warn(
"403_cloudflare_bot_block_skips_account_penalty",
"account_id", account.ID,
"platform", account.Platform,
"upstream_message", upstreamMsg,
)
return false
}
if account.Platform == PlatformAntigravity {
return s.handleAntigravity403(ctx, account, upstreamMsg, responseBody)
}
@@ -1064,16 +1073,6 @@ func (s *RateLimitService) handleOpenAI403(ctx context.Context, account *Account
)
return false
}
if isCloudflareBotBlockResponse(responseBody) {
slog.Warn(
"openai_403_cloudflare_bot_block_skips_account_penalty",
"account_id", account.ID,
"platform", account.Platform,
"upstream_message", upstreamMsg,
)
return false
}
msg := buildForbiddenErrorMessage(
"Access forbidden (403):",
upstreamMsg,
@@ -1123,9 +1122,62 @@ func (s *RateLimitService) handleOpenAI403(ctx context.Context, account *Account
// request/edge-level failure and must not consume the account 403 strike budget.
func isCloudflareBotBlockResponse(body []byte) bool {
normalized := strings.ToLower(strings.TrimSpace(string(body)))
var payload any
if json.Unmarshal(body, &payload) == nil {
return containsCloudflareBotBlockCode(payload)
}
return strings.Contains(normalized, "error code: 1010")
}
func containsCloudflareBotBlockCode(value any) bool {
switch node := value.(type) {
case map[string]any:
cloudflareError := false
for key, child := range node {
if strings.EqualFold(key, "cloudflare_error") {
if is, ok := child.(bool); ok && is {
cloudflareError = true
}
}
}
for key, child := range node {
if strings.EqualFold(key, "error_name") {
if name, ok := child.(string); ok && strings.EqualFold(strings.TrimSpace(name), "browser_signature_banned") {
return true
}
}
if cloudflareError && (strings.EqualFold(key, "code") || strings.EqualFold(key, "error_code")) {
if isCloudflareBotBlockCode(child) {
return true
}
}
if containsCloudflareBotBlockCode(child) {
return true
}
}
case []any:
for _, child := range node {
if containsCloudflareBotBlockCode(child) {
return true
}
}
}
return false
}
func isCloudflareBotBlockCode(value any) bool {
switch code := value.(type) {
case float64:
return code == 1010
case json.Number:
return code == "1010"
case string:
return strings.TrimSpace(code) == "1010"
default:
return false
}
}
// handleAntigravity403 处理 Antigravity 平台的 403 错误
// validation(需要验证)→ 永久 SetError(需人工去 Google 验证后恢复)
// violation(违规封号)→ 永久 SetError(需人工处理)
@@ -104,8 +104,8 @@ func TestHandleUpstreamError_OpenAIHTML403RepeatedNeverEscalates(t *testing.T) {
h.requireNoAccountPenalty(t)
}
func TestHandleUpstreamError_OpenAICloudflare1010DoesNotPenalizeAccount(t *testing.T) {
for _, platform := range []string{PlatformOpenAI, PlatformOpenCodeGo} {
func TestHandleUpstreamError_Cloudflare1010DoesNotPenalizeAccount(t *testing.T) {
for _, platform := range []string{PlatformOpenAI, PlatformOpenCodeGo, PlatformAnthropic, PlatformGemini, PlatformAntigravity} {
t.Run(platform, func(t *testing.T) {
repo := &rateLimitAccountRepoStub{}
counter := &countingOpenAI403CounterCache{
@@ -130,6 +130,67 @@ func TestHandleUpstreamError_OpenAICloudflare1010DoesNotPenalizeAccount(t *testi
}
}
func TestHandleUpstreamError_Cloudflare1010JSONDoesNotPenalizeAccount(t *testing.T) {
for _, body := range []string{
`{"cloudflare_error":true,"error_code":1010,"error_name":"browser_signature_banned","detail":"blocked"}`,
`{"error_name":"browser_signature_banned","detail":"blocked by Cloudflare"}`,
} {
t.Run(body, func(t *testing.T) {
repo := &rateLimitAccountRepoStub{}
counter := &countingOpenAI403CounterCache{
openAI403CounterCacheStub: openAI403CounterCacheStub{counts: []int64{openAI403DisableThreshold}},
}
svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
svc.SetOpenAI403CounterCache(counter)
account := &Account{ID: 602, Platform: PlatformAnthropic, Type: AccountTypeAPIKey}
require.False(t, svc.HandleUpstreamError(
context.Background(), account, http.StatusForbidden, http.Header{}, []byte(body),
))
require.Equal(t, 0, counter.increments)
require.Equal(t, 0, repo.setErrorCalls)
require.Equal(t, 0, repo.tempCalls)
})
}
}
func TestIsCloudflareBotBlockResponseOnlyMatches1010(t *testing.T) {
cases := []struct {
name string
body string
want bool
}{
{"plain text", "error code: 1010", true},
{"root numeric JSON code", `{"cloudflare_error":true,"code":1010}`, true},
{"nested string JSON code", `{"errors":[{"cloudflare_error":true,"code":"1010"}]}`, true},
{"cloudflare error code", `{"cloudflare_error":true,"error_code":1010}`, true},
{"browser signature name", `{"error_name":"browser_signature_banned"}`, true},
{"different JSON code", `{"code":403,"message":"forbidden"}`, false},
{"unrelated code 1010", `{"error":{"code":1010,"message":"account banned"}}`, false},
{"message mentions 1010", `{"message":"error code: 1010"}`, false},
{"malformed JSON", `{"code":1010`, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.want, isCloudflareBotBlockResponse([]byte(tc.body)))
})
}
}
func TestHandleUpstreamError_AnthropicGenuine403StillPenalizes(t *testing.T) {
repo := &rateLimitAccountRepoStub{}
svc := NewRateLimitService(repo, nil, &config.Config{}, nil, nil)
account := &Account{ID: 603, Platform: PlatformAnthropic, Type: AccountTypeAPIKey}
require.True(t, svc.HandleUpstreamError(
context.Background(), account, http.StatusForbidden, http.Header{},
[]byte(`{"error":{"type":"permission_error","message":"invalid API key"}}`),
))
require.Equal(t, 1, repo.setErrorCalls)
require.Contains(t, repo.lastErrorMsg, "invalid API key")
}
// 对照不变式:真正的结构化 JSON 403 是账号级证据,处罚链路必须原样保留。
// 缺了这组断言,上面的跳过逻辑一旦写宽就会把真实的封号 403 也放过去。
func TestHandleUpstreamError_OpenAIStructured403StillPenalizes(t *testing.T) {