From 0c3be9b258e5fd2b3dff05c639de5306ed19ca72 Mon Sep 17 00:00:00 2001 From: guyu233 Date: Fri, 4 Dec 2026 15:17:10 +0800 Subject: [PATCH] fix(gateway): report the OpenAI error.type for classified failures Classified failures previously all surfaced as api_error even though clients branch on error.type. Map recognized upstream types first, then Kind, then Status, and use the same mapping for the SSE structured error frame. Retroactively correct: invalid request, auth, permission, quota, rate limit, and model-not-found cases. --- .../unreleased/openai-error-type-mapping.md | 7 + internal/gateway/http.go | 70 ++++++- internal/gateway/http_error_type_test.go | 192 ++++++++++++++++++ internal/gateway/openai_stream.go | 2 +- internal/gateway/usage.go | 2 +- internal/server/http.go | 8 +- internal/server/http_error_type_test.go | 45 ++++ 7 files changed, 322 insertions(+), 4 deletions(-) create mode 100644 changelog/unreleased/openai-error-type-mapping.md create mode 100644 internal/gateway/http_error_type_test.go create mode 100644 internal/server/http_error_type_test.go diff --git a/changelog/unreleased/openai-error-type-mapping.md b/changelog/unreleased/openai-error-type-mapping.md new file mode 100644 index 000000000..52629c6ba --- /dev/null +++ b/changelog/unreleased/openai-error-type-mapping.md @@ -0,0 +1,7 @@ +### English + +- OpenAI-compatible error responses now report the correct `error.type` (`invalid_request_error`, `authentication_error`, `permission_error`, `rate_limit_error`, `insufficient_quota`, `model_not_found`, or `api_error`) instead of a generic `api_error`, so clients that branch on error type classify quota, auth, and rate-limit failures correctly. The classifier's kind decides first, so its generic `api_error` placeholder never wins; status only supplies the fallback, and a bare 404 no longer claims `model_not_found`. The API-key and console-key middleware envelopes use the same vocabulary, so a missing or wrong key reports `authentication_error` instead of `api_error`. + +### 中文 + +- OpenAI 兼容接口的错误响应现在返回正确的 `error.type`(`invalid_request_error`、`authentication_error`、`permission_error`、`rate_limit_error`、`insufficient_quota`、`model_not_found`、`api_error`),不再统一写成泛化的 `api_error`,客户端可按错误类型正确区分额度不足、鉴权失败和限流。映射先由分类结果的 kind 决定,分类器默认填充的 `api_error` 不再抢先返回;只有 kind 无法判断时才按 HTTP 状态兜底,普通 404 不再被标成 `model_not_found`。API Key 与控制台密钥的中间件错误也改用同一套取值,密钥缺失或错误会报成 `authentication_error`。 diff --git a/internal/gateway/http.go b/internal/gateway/http.go index 3521b0fd9..b015415f9 100644 --- a/internal/gateway/http.go +++ b/internal/gateway/http.go @@ -4,6 +4,9 @@ import ( "encoding/json" "net/http" "strings" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/executor" ) func writeJSON(w http.ResponseWriter, status int, v any) { @@ -12,16 +15,81 @@ func writeJSON(w http.ResponseWriter, status int, v any) { _ = json.NewEncoder(w).Encode(v) } +// writeErr builds a plain OpenAI-style error envelope. The error type follows +// the HTTP status so a bare status-only failure still carries a meaningful +// type; callers holding a Classified use writeTypedErr with openaiErrorType. func writeErr(w http.ResponseWriter, status int, code, msg string) { + writeTypedErr(w, status, openaiErrorTypeForStatus(status), code, msg) +} + +func writeTypedErr(w http.ResponseWriter, status int, errType, code, msg string) { writeJSON(w, status, map[string]any{ "error": map[string]any{ "message": msg, - "type": "api_error", + "type": errType, "code": code, }, }) } +// openaiErrorType maps a classified failure onto the OpenAI error.type +// vocabulary. Kind is authoritative because Classify derives it from the +// upstream status, body and nested kind; Type is only a hint, and it defaults +// to generic values ("api_error", "invalid_request_error") that would hide a +// rate-limit, auth or model-availability rejection. When Kind says nothing +// specific, a recognized upstream Type wins, then Status supplies the fallback. +func openaiErrorType(classified executor.Classified) string { + switch classified.Kind { + case accounts.KindModelNotAvailable: + return "model_not_found" + case accounts.KindInvalidRequest: + return "invalid_request_error" + case accounts.KindAuth: + if classified.Status == http.StatusForbidden { + return "permission_error" + } + return "authentication_error" + case accounts.KindQuota: + return "insufficient_quota" + case accounts.KindRateLimit: + return "rate_limit_error" + } + switch typ := strings.TrimSpace(classified.Type); typ { + case "invalid_request_error", "authentication_error", "permission_error", + "rate_limit_error", "insufficient_quota", "model_not_found": + return typ + } + return openaiErrorTypeForStatus(classified.Status) +} + +// openaiErrorTypeForStatus is the status-only fallback. 404 stays a generic +// invalid_request_error: only a classified model-availability failure earns +// model_not_found, so an unrelated missing route is not mislabelled as a +// model problem. +func openaiErrorTypeForStatus(status int) string { + switch { + case status == http.StatusUnauthorized: + return "authentication_error" + case status == http.StatusForbidden: + return "permission_error" + case status == http.StatusTooManyRequests: + return "rate_limit_error" + case status == http.StatusBadRequest || status == http.StatusNotFound || + status == http.StatusUnprocessableEntity || + status == http.StatusRequestEntityTooLarge: + return "invalid_request_error" + default: + return "api_error" + } +} + +// OpenAIErrorTypeForStatus exposes the status-only mapping so the server +// middleware (API-key auth, console guard) writes the same error.type +// vocabulary as the public gateway instead of a hard-coded api_error. +func OpenAIErrorTypeForStatus(status int) string { + return openaiErrorTypeForStatus(status) +} + func firstNonEmpty(vals ...string) string { for _, v := range vals { if s := strings.TrimSpace(v); s != "" { diff --git a/internal/gateway/http_error_type_test.go b/internal/gateway/http_error_type_test.go new file mode 100644 index 000000000..f9e0ac5f5 --- /dev/null +++ b/internal/gateway/http_error_type_test.go @@ -0,0 +1,192 @@ +package gateway + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/caigee-cmd/cli2api/internal/accounts" + "github.com/caigee-cmd/cli2api/internal/executor" +) + +func TestOpenAIErrorTypeMapping(t *testing.T) { + cases := []struct { + name string + kind string + status int + typ string + wantType string + }{ + {"quota maps to insufficient_quota", accounts.KindQuota, http.StatusTooManyRequests, "", "insufficient_quota"}, + {"auth 401 maps to authentication_error", accounts.KindAuth, http.StatusUnauthorized, "", "authentication_error"}, + {"auth 403 maps to permission_error", accounts.KindAuth, http.StatusForbidden, "", "permission_error"}, + {"rate limit maps to rate_limit_error", accounts.KindRateLimit, http.StatusTooManyRequests, "", "rate_limit_error"}, + {"invalid request maps to invalid_request_error", accounts.KindInvalidRequest, http.StatusBadRequest, "", "invalid_request_error"}, + {"model not available maps to model_not_found", accounts.KindModelNotAvailable, http.StatusBadRequest, "", "model_not_found"}, + {"unavailable 502 maps to api_error", accounts.KindUnavailable, http.StatusBadGateway, "", "api_error"}, + {"recognized upstream type is ignored when kind is specific", accounts.KindQuota, http.StatusTooManyRequests, "rate_limit_error", "insufficient_quota"}, + {"generic api_error must not win", accounts.KindRateLimit, http.StatusTooManyRequests, "api_error", "rate_limit_error"}, + {"generic api_error on auth falls back to kind", accounts.KindAuth, http.StatusUnauthorized, "api_error", "authentication_error"}, + {"specific upstream type used for unknown kind", accounts.KindUnavailable, http.StatusBadGateway, "permission_error", "permission_error"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + classified := executor.Classified{Kind: tc.kind, Status: tc.status, Type: tc.typ} + if got := openaiErrorType(classified); got != tc.wantType { + t.Fatalf("openaiErrorType(%+v) = %q, want %q", classified, got, tc.wantType) + } + }) + } +} + +func TestOpenAIErrorTypeForStatus(t *testing.T) { + cases := map[int]string{ + http.StatusUnauthorized: "authentication_error", + http.StatusForbidden: "permission_error", + http.StatusNotFound: "invalid_request_error", + http.StatusTooManyRequests: "rate_limit_error", + http.StatusBadRequest: "invalid_request_error", + http.StatusUnprocessableEntity: "invalid_request_error", + http.StatusRequestEntityTooLarge: "invalid_request_error", + http.StatusBadGateway: "api_error", + http.StatusInternalServerError: "api_error", + } + for status, want := range cases { + if got := openaiErrorTypeForStatus(status); got != want { + t.Fatalf("openaiErrorTypeForStatus(%d) = %q, want %q", status, got, want) + } + } +} + +func TestWriteClassifiedErrEnvelopeCarriesTypeAndRetryAfter(t *testing.T) { + classified := executor.Classified{ + Kind: accounts.KindQuota, + Status: http.StatusTooManyRequests, + Code: "insufficient_quota", + Message: "upstream diagnostic that must not reach the client", + RetryAfter: 45 * time.Second, + } + err := executor.NewExecutionError(classified, nil) + + w := httptest.NewRecorder() + WriteClassifiedErr(w, err) + + if w.Code != http.StatusTooManyRequests { + t.Fatalf("status = %d, want %d", w.Code, http.StatusTooManyRequests) + } + if got := w.Header().Get("Retry-After"); got != "45" { + t.Fatalf("Retry-After = %q, want 45", got) + } + + var body struct { + Error struct { + Type string `json:"type"` + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode error envelope: %v", err) + } + if body.Error.Type != "insufficient_quota" { + t.Fatalf("error.type = %q, want insufficient_quota", body.Error.Type) + } + if body.Error.Code != "insufficient_quota" { + t.Fatalf("error.code = %q, want insufficient_quota", body.Error.Code) + } +} + +func TestWriteClassifiedErrUsesRealClassifierOutput(t *testing.T) { + // These cases go through executor.Classify, not a hand-built Classified, so + // the default Type: "api_error" the classifier stamps on generic failures is + // part of the input. That default must not beat the Kind/Status mapping. + cases := []struct { + name string + upstream int + body string + wantType string + wantStatus int + }{ + {"429 rate limit", http.StatusTooManyRequests, `{"error":{"message":"too many requests","code":"rate_limit_exceeded"}}`, "rate_limit_error", http.StatusTooManyRequests}, + {"401 auth", http.StatusUnauthorized, `{"error":{"message":"unauthorized"}}`, "authentication_error", http.StatusUnauthorized}, + {"403 auth", http.StatusForbidden, `{"error":{"message":"forbidden"}}`, "permission_error", http.StatusForbidden}, + {"429 quota", http.StatusTooManyRequests, `{"error":{"message":"insufficient_quota","code":"insufficient_quota"}}`, "insufficient_quota", http.StatusTooManyRequests}, + {"model not available", http.StatusNotFound, `{"error":{"message":"model_not_available","code":"model_not_available"}}`, "model_not_found", http.StatusBadRequest}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + classified := executor.Classify(tc.upstream, tc.body, "", "", "") + err := executor.NewExecutionError(classified, nil) + + w := httptest.NewRecorder() + WriteClassifiedErr(w, err) + if w.Code != tc.wantStatus { + t.Fatalf("status = %d, want %d (classified=%+v)", w.Code, tc.wantStatus, classified) + } + var body struct { + Error struct { + Type string `json:"type"` + } `json:"error"` + } + if jerr := json.Unmarshal(w.Body.Bytes(), &body); jerr != nil { + t.Fatalf("decode envelope: %v", jerr) + } + if body.Error.Type != tc.wantType { + t.Fatalf("error.type = %q, want %q (classified.Type=%q kind=%q)", body.Error.Type, tc.wantType, classified.Type, classified.Kind) + } + }) + } +} + +func TestStructuredStreamErrorCarriesMappedType(t *testing.T) { + cases := []struct { + name string + kind string + status int + wantType string + }{ + {name: "quota", kind: accounts.KindQuota, status: http.StatusTooManyRequests, wantType: "insufficient_quota"}, + {name: "rate limit", kind: accounts.KindRateLimit, status: http.StatusTooManyRequests, wantType: "rate_limit_error"}, + {name: "auth", kind: accounts.KindAuth, status: http.StatusUnauthorized, wantType: "authentication_error"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + classified := executor.Classified{ + Kind: tc.kind, + Status: tc.status, + Code: "test_code", + } + err := executor.NewExecutionError(classified, nil) + var buf bytes.Buffer + if werr := writeStructuredStreamError(&buf, err); werr != nil { + t.Fatalf("writeStructuredStreamError: %v", werr) + } + var dataLine string + for _, line := range strings.Split(buf.String(), "\n") { + if strings.HasPrefix(line, "data:") { + dataLine = strings.TrimSpace(strings.TrimPrefix(line, "data:")) + } + } + var envelope struct { + Error struct { + Type string `json:"type"` + Code string `json:"code"` + Kind string `json:"kind"` + } `json:"error"` + } + if jerr := json.Unmarshal([]byte(dataLine), &envelope); jerr != nil { + t.Fatalf("decode stream error payload: %v", jerr) + } + if envelope.Error.Type != tc.wantType { + t.Fatalf("error.type = %q, want %q", envelope.Error.Type, tc.wantType) + } + if envelope.Error.Kind != tc.kind { + t.Fatalf("error.kind = %q, want %q", envelope.Error.Kind, tc.kind) + } + }) + } +} diff --git a/internal/gateway/openai_stream.go b/internal/gateway/openai_stream.go index 8071cc2ff..91adbf03f 100644 --- a/internal/gateway/openai_stream.go +++ b/internal/gateway/openai_stream.go @@ -259,7 +259,7 @@ func writeStructuredStreamError(writer io.Writer, err error) error { status = http.StatusBadGateway } code := firstNonEmpty(classified.Code, "upstream_error") - typ := firstNonEmpty(classified.Type, "api_error") + typ := openaiErrorType(classified) message := firstNonEmpty(classified.Message, code) errorPayload := map[string]any{ "message": message, diff --git a/internal/gateway/usage.go b/internal/gateway/usage.go index 00496f2b1..d0e406932 100644 --- a/internal/gateway/usage.go +++ b/internal/gateway/usage.go @@ -59,5 +59,5 @@ func WriteClassifiedErr(w http.ResponseWriter, err error) { } else { w.Header().Set("X-Qoder-Failover", "0") } - writeErr(w, classified.Status, classified.Code, classified.Message) + writeTypedErr(w, classified.Status, openaiErrorType(classified), classified.Code, classified.Message) } diff --git a/internal/server/http.go b/internal/server/http.go index 3416fd5ae..99dba824d 100644 --- a/internal/server/http.go +++ b/internal/server/http.go @@ -3,6 +3,8 @@ package server import ( "encoding/json" "net/http" + + "github.com/caigee-cmd/cli2api/internal/gateway" ) func writeJSON(w http.ResponseWriter, status int, v any) { @@ -11,11 +13,15 @@ func writeJSON(w http.ResponseWriter, status int, v any) { _ = json.NewEncoder(w).Encode(v) } +// writeErr keeps the middleware envelopes (API-key auth, console guard, +// update-in-progress) on the same OpenAI error.type vocabulary as the public +// gateway. A hard-coded api_error here made the most common client failures — +// a missing or invalid key — look like generic server errors. func writeErr(w http.ResponseWriter, status int, code, msg string) { writeJSON(w, status, map[string]any{ "error": map[string]any{ "message": msg, - "type": "api_error", + "type": gateway.OpenAIErrorTypeForStatus(status), "code": code, }, }) diff --git a/internal/server/http_error_type_test.go b/internal/server/http_error_type_test.go new file mode 100644 index 000000000..a31462235 --- /dev/null +++ b/internal/server/http_error_type_test.go @@ -0,0 +1,45 @@ +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +// The middleware envelopes are the first error a client sees for the two most +// common failures (a missing key and a console-only key), so they must carry +// the same OpenAI error.type vocabulary as the public gateway. +func TestWriteErrCarriesOpenAIErrorType(t *testing.T) { + cases := []struct { + status int + code string + wantType string + }{ + {http.StatusUnauthorized, "invalid_api_key", "authentication_error"}, + {http.StatusForbidden, "console_key_required", "permission_error"}, + {http.StatusServiceUnavailable, "service_updating", "api_error"}, + } + for _, tc := range cases { + w := httptest.NewRecorder() + writeErr(w, tc.status, tc.code, "message") + if w.Code != tc.status { + t.Fatalf("status = %d, want %d", w.Code, tc.status) + } + var body struct { + Error struct { + Type string `json:"type"` + Code string `json:"code"` + } `json:"error"` + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil { + t.Fatalf("decode envelope: %v", err) + } + if body.Error.Type != tc.wantType { + t.Fatalf("error.type = %q, want %q (code=%q)", body.Error.Type, tc.wantType, tc.code) + } + if body.Error.Code != tc.code { + t.Fatalf("error.code = %q, want %q", body.Error.Code, tc.code) + } + } +}