diff --git a/internal/runtime/model/upstream.go b/internal/runtime/model/upstream.go index f272561..87cc5e4 100644 --- a/internal/runtime/model/upstream.go +++ b/internal/runtime/model/upstream.go @@ -4,7 +4,6 @@ import ( "fmt" "io" "net/http" - "strings" "git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace" ) @@ -24,10 +23,6 @@ import ( // 错误体是攻击面,不是数据面。 const errBodyCap = 512 -// maxErrorTokenBytes 是 error.code / error.type 允许出镜的长度上限(见 -// safeErrorToken)。 -const maxErrorTokenBytes = 64 - // upstreamLabel 报「这次调用实际打到哪」:优先主机(自建网关 / 代理下才看得出 // 真实去向),取不到主机时退回 provider 名(代码里写死的短名)。两种形态都不含 // 路径、查询串与凭据 —— 契约在 trace.HostOf。 @@ -45,12 +40,21 @@ func upstreamLabel(name, baseURL string) string { // 而这类 error 会被 `chat run` / `loop step` 打日志。截断到 512 字节只是把 // 「整段泄漏」变成「前 512 字节泄漏」,不是修复。 // +// error.code 也要过令牌守卫(trace.ErrorToken):它在主流上游是枚举,但网关、代理与 +// 兼容层可以往里面塞任何东西 —— 包括回显的输入。不像令牌的 code 一律变空串,代价只是 +// 少一条分类提示;status / body 摘要等诊断面不受影响。 +// // 双 %w:既保持 errors.Is(err, ErrUpstream)(降级链按它分类,主 → 备 → 本地), // 也让 errors.Is(err, trace.ErrUpstream) 成立(调用方按上游失败分类)。 func providerUpstreamError(name, baseURL string, resp *http.Response) error { body, _ := io.ReadAll(io.LimitReader(resp.Body, errBodyCap)) - info := trace.UpstreamError(upstreamLabel(name, baseURL), resp.StatusCode, - resp.Header.Get("Content-Type"), body) + info, ok := trace.UpstreamError(upstreamLabel(name, baseURL), resp.StatusCode, + resp.Header.Get("Content-Type"), body).(*trace.UpstreamErrorInfo) + if !ok { + // helper 的构造是固定的,走不到这里;真走到也只少一条诊断,不破安全口径。 + return fmt.Errorf("model: %w: status %d", ErrUpstream, resp.StatusCode) + } + info.Code = trace.ErrorToken(info.Code) return fmt.Errorf("model: %w: %w", ErrUpstream, info) } @@ -67,26 +71,6 @@ func streamEventError(upstream string, evt *anthropicStreamError) error { // helper 的构造是固定的,走不到这里;真走到也只少一条诊断,不破安全口径。 return fmt.Errorf("model: %w: anthropic stream error event", ErrUpstream) } - info.Type = safeErrorToken(evt.Type) + info.Type = trace.ErrorToken(evt.Type) return fmt.Errorf("model: %w: %w", ErrUpstream, info) } - -// safeErrorToken 只放行「像协议令牌」的短串(字母、数字与 `_ . -`),其余一律 -// 丢弃。error.code / error.type 在主流上游是枚举,但它们是**自由文本面**:网关、 -// 代理与兼容层可以往里面塞任何东西。丢弃它的代价只是少一条分类提示,保留一个 -// 不受控字段的代价是她的话进日志。 -func safeErrorToken(s string) string { - s = strings.TrimSpace(s) - if s == "" || len(s) > maxErrorTokenBytes { - return "" - } - for _, r := range s { - switch { - case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': - case r == '_' || r == '.' || r == '-': - default: - return "" - } - } - return s -} diff --git a/internal/runtime/model/upstream_test.go b/internal/runtime/model/upstream_test.go new file mode 100644 index 0000000..8fe5d02 --- /dev/null +++ b/internal/runtime/model/upstream_test.go @@ -0,0 +1,94 @@ +package model + +// 本文件钉住 providerUpstreamError 的两条出镜边界: +// +// - **error.code 是自由文本面**:它在主流上游是枚举,但网关、代理与兼容层可以往 +// 里面塞任何东西(包括回显的输入)。只有像令牌才出镜,其余变空串 —— 而 status / +// type / 体积摘要这些诊断面不受影响。 +// - **响应体正文一个字节都不进错误**:这是 providerUpstreamError 存在的理由 +// (旧实现把体截到 512B 拼进 error,而 `chat run` / `loop step` 会把它落日志)。 +// +// 每条用例都是「把它放宽就变红」的形状:断言的是错误的文本,也就是真正进日志的字符串。 + +import ( + "errors" + "io" + "net/http" + "strings" + "testing" + + "git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace" +) + +// upstreamErrResp 造一条非 2xx 响应:只带状态码、Content-Type 与体,够 +// providerUpstreamError 走完整条收敛路径。 +func upstreamErrResp(status int, body string) *http.Response { + return &http.Response{ + StatusCode: status, + Header: http.Header{"Content-Type": []string{"application/json; charset=utf-8"}}, + Body: io.NopCloser(strings.NewReader(body)), + } +} + +// TestProviderUpstreamErrorDropsFreeTextCode code 里是回显的用户原文 ⇒ 该字段整体消失 +// (连 `code=` 这个键都不出现),而 status / type 仍在。去掉令牌守卫就变红。 +func TestProviderUpstreamErrorDropsFreeTextCode(t *testing.T) { + t.Parallel() + const echoed = "Invalid value: '她刚才说的那句话'" + body := `{"error":{"code":"` + echoed + `","type":"invalid_request_error"}}` + + err := providerUpstreamError("openai", "https://api.example.com/v1/chat/completions", upstreamErrResp(http.StatusBadRequest, body)) + if err == nil { + t.Fatal("非 2xx 却报成功") + } + msg := err.Error() + if strings.Contains(msg, echoed) { + t.Fatalf("code 里的用户原文进了错误(会随 chat run 落日志):%v", msg) + } + if strings.Contains(msg, "code=") { + t.Fatalf("非令牌形状的 code 没有被丢弃:%v", msg) + } + // 诊断面不能一起丢:状态、协议枚举的 type、体积摘要都还在。 + for _, want := range []string{"status=400", "type=invalid_request_error", "body_bytes=", "api.example.com"} { + if !strings.Contains(msg, want) { + t.Fatalf("错误里缺少 %q(诊断面不能一起丢):%v", want, msg) + } + } + if !errors.Is(err, ErrUpstream) || !errors.Is(err, trace.ErrUpstream) { + t.Fatalf("降级链的哨兵断了:%v", err) + } +} + +// TestProviderUpstreamErrorKeepsTokenShapedCode 真实枚举原样出镜:丢掉它只是少一条 +// 分类提示,但既然它像令牌就该留下。 +func TestProviderUpstreamErrorKeepsTokenShapedCode(t *testing.T) { + t.Parallel() + body := `{"error":{"code":"Arrearage","type":"invalid_request_error"}}` + + err := providerUpstreamError("deepseek", "https://api.deepseek.com/v1/chat/completions", + upstreamErrResp(http.StatusPaymentRequired, body)) + if err == nil { + t.Fatal("非 2xx 却报成功") + } + if msg := err.Error(); !strings.Contains(msg, "code=Arrearage") { + t.Fatalf("令牌形状的 code 被误杀:%v", msg) + } +} + +// TestProviderUpstreamErrorDropsBodyText 体里除了 code/type 之外的字节一个都不进错误: +// 上游把用户的提问回显在 error.message 里是真实写法。 +func TestProviderUpstreamErrorDropsBodyText(t *testing.T) { + t.Parallel() + const prompt = "她的原始提问:帮我看看这段代码" + body := `{"error":{"code":"invalid_request_error","type":"invalid_request_error",` + + `"message":"Invalid value: '` + prompt + `'"}}` + + err := providerUpstreamError("openai", "https://api.example.com/v1/chat/completions", + upstreamErrResp(http.StatusBadRequest, body)) + if err == nil { + t.Fatal("非 2xx 却报成功") + } + if strings.Contains(err.Error(), prompt) { + t.Fatalf("error.message 的回显进了错误:%v", err) + } +} diff --git a/internal/runtime/trace/errortoken.go b/internal/runtime/trace/errortoken.go new file mode 100644 index 0000000..f6e37a9 --- /dev/null +++ b/internal/runtime/trace/errortoken.go @@ -0,0 +1,37 @@ +package trace + +import "strings" + +// 本文件是「上游错误信封里的自由文本字段能不能出镜」的唯一守卫。 +// +// 背景:UpstreamErrorInfo 只解析 error.code / error.type 两个字段,而它们是**自由 +// 文本面** —— 主流上游里它们确实是枚举(invalid_request_error、overloaded_error、 +// Throttling.RateQuota …),但网关、代理与兼容层可以往里面塞任何东西,包括回显的 +// 用户原文。因此这两个字段出镜前必须像令牌:短、只含标识符字符。 +// +// 丢弃的代价只是少一条分类提示;保留一个不受控字段的代价是她的话进日志。这道守卫 +// 原先在 runtime/model(safeErrorToken)与 runtime/multimodal/voice +// (dashscopeErrorToken)各有一份逐字同形的实现,M46 把同一份收敛到这里。 + +// maxErrorTokenBytes 是 error.code / error.type / request_id 允许出镜的长度上限。 +// 64 字节足够容纳任何真实的枚举与 UUID 形状,又远小于「一段话」。 +const maxErrorTokenBytes = 64 + +// ErrorToken 只放行「像协议令牌」的短串(字母、数字与 `_ . -`),其余一律丢弃并返回 +// 空串 —— 包括带空格、标点、引号的散文,以及超长串。调用方据此决定「这个字段出不 +// 出镜」,而不是先出镜再清洗。 +func ErrorToken(s string) string { + s = strings.TrimSpace(s) + if s == "" || len(s) > maxErrorTokenBytes { + return "" + } + for _, r := range s { + switch { + case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9': + case r == '_' || r == '.' || r == '-': + default: + return "" + } + } + return s +} diff --git a/internal/runtime/trace/errortoken_test.go b/internal/runtime/trace/errortoken_test.go new file mode 100644 index 0000000..4fdedb0 --- /dev/null +++ b/internal/runtime/trace/errortoken_test.go @@ -0,0 +1,63 @@ +package trace + +// 本文件钉住 ErrorToken 的唯一职责:error.code / error.type 这类**自由文本面**只有 +// 「像协议令牌」才允许出镜。它们在上游里是枚举,但网关、代理与兼容层可以往里面塞任何 +// 东西 —— 包括回显的用户原文。 +// +// 每条用例都是「把它放宽就变红」的形状。 + +import ( + "strings" + "testing" +) + +// TestErrorTokenKeepsProtocolTokens 真实枚举必须原样通过:丢掉它们的代价是少一条 +// 分类提示(重试 / 降级 / 熔断的口径)。 +func TestErrorTokenKeepsProtocolTokens(t *testing.T) { + t.Parallel() + for _, token := range []string{ + "invalid_request_error", + "overloaded_error", + "Throttling.RateQuota", + "rate-limit", + "429", + " sparse_error ", + } { + if got := ErrorToken(token); got != strings.TrimSpace(token) { + t.Fatalf("ErrorToken(%q) = %q, want 令牌原值(去首尾空白)", token, got) + } + } +} + +// TestErrorTokenDropsFreeText 只有像令牌才出镜:带空格、标点、引号的散文一律空串 —— +// 那正是「上游把用户原文回显进 code」的形态。 +func TestErrorTokenDropsFreeText(t *testing.T) { + t.Parallel() + for _, text := range []string{ + "Invalid value: '她刚才说的那句话'", + "prompt is too long", + "```json\n{\"a\":1}\n```", + "bad,code", + "code=1", + "", + " ", + "line\nbreak", + "emoji🙂", + } { + if got := ErrorToken(text); got != "" { + t.Fatalf("ErrorToken(%q) = %q, want 空串", text, got) + } + } +} + +// TestErrorTokenRejectsOverlong 超长串不是令牌(边界 64 字节),否则「话」可以靠长度 +// 混进来。 +func TestErrorTokenRejectsOverlong(t *testing.T) { + t.Parallel() + if got := ErrorToken(strings.Repeat("a", 64)); got == "" { + t.Fatal("64 字节的令牌被误杀(边界应含)") + } + if got := ErrorToken(strings.Repeat("a", 65)); got != "" { + t.Fatalf("超长串被放行:%q", got) + } +}