Merge branch 'feat/m50-envelopesafe-drop-envelope-message-o' into dev
This commit is contained in:
commit
604f9ebaa9
15 files changed
+705
-140
No files matched your search
@@ -5,9 +5,16 @@
|
||||
// future platforms; existing adapters (Telegram, OneBot) that already carry
|
||||
// their own transport are left untouched.
|
||||
//
|
||||
// It depends only on the standard library and internal/logger. The auth token is
|
||||
// never logged or surfaced in errors. The Authorization scheme is configurable
|
||||
// (default "Bearer" for OAuth2-style tokens; KOOK robots use "Bot").
|
||||
// It depends only on the standard library, internal/logger and internal/runtime/trace.
|
||||
// The auth token is never logged or surfaced in errors. The Authorization scheme is
|
||||
// configurable (default "Bearer" for OAuth2-style tokens; KOOK robots use "Bot").
|
||||
//
|
||||
// The envelope's message is an upstream free-text channel: upstreams echo the rejected
|
||||
// request body into it, and that body holds what she said. It is therefore **not**
|
||||
// carried in errors by default (see WithEnvelopeMessage); code and HTTP status are. The
|
||||
// same rule — code/status stay, free text goes — applies to every channel adapter's own
|
||||
// envelope handling (Telegram description, OneBot msg, iLink CDN x-error-message); see
|
||||
// upstream_text.go.
|
||||
package httpclient
|
||||
|
||||
import (
|
||||
@@ -40,6 +47,9 @@ type Client struct {
|
||||
token string
|
||||
authScheme string
|
||||
log *slog.Logger
|
||||
// keepEnvelopeMessage 是**默认关闭**的开关:信封 message 只有显式 opt-in
|
||||
// (WithEnvelopeMessage)才会进错误文本。零值 = 安全,见该函数的注释。
|
||||
keepEnvelopeMessage bool
|
||||
}
|
||||
|
||||
// Option customizes a Client at construction time.
|
||||
@@ -81,6 +91,23 @@ func WithLogger(l *slog.Logger) Option {
|
||||
}
|
||||
}
|
||||
|
||||
// WithEnvelopeMessage 显式要求把信封的 message 保留在错误文本里。**默认不带**。
|
||||
//
|
||||
// 🔴 默认不带是刻意的,理由与 trace.UpstreamError 的 message 同源:上游会把被拒的输入
|
||||
// 回显在 message 里(KOOK 实测 `invalid content: <她原话>`),于是那句话会随错误进
|
||||
// 调用方的日志。排障真正用得到的分类信息是 `code` 与 `status`,两者**恒在**;message
|
||||
// 只是人话提示。宁可少一条提示,也不让她的原话进日志。
|
||||
//
|
||||
// 只有在你**确认该上游不回显用户内容**时才打开。打开后 message 仍会压平空白、清洗
|
||||
// 凭据形状并截到 maxUpstreamTextRunes(40 rune)—— 上限不像 trace 的 128,是这层没有
|
||||
// 「一屏摘要」的诉求,短到装不下一句正文。
|
||||
//
|
||||
// 函数式选项的形状让最常用的 `New(...)` 天然就是最安全的那个:想放宽必须在这里显式
|
||||
// 写出来,代码评审时一眼可见(与 trace.WithUpstreamMessage 同一个范式)。
|
||||
func WithEnvelopeMessage() Option {
|
||||
return func(c *Client) { c.keepEnvelopeMessage = true }
|
||||
}
|
||||
|
||||
// New builds a Client. With no base URL the caller must pass absolute URLs (via
|
||||
// the Do/Get helpers' path being an absolute URL).
|
||||
func New(opts ...Option) *Client {
|
||||
@@ -133,8 +160,8 @@ func (c *Client) resolve(path string) string {
|
||||
//
|
||||
// 地址在这一层只以来源形态出镜:target 由调用方给(GetJSON 的 query 可能带凭据、
|
||||
// 绝对 path 可能带 user:pass@),完整串既不进错误也不进日志。响应体原文同理 ——
|
||||
// 上游可能把被拒的输入回显在体里,因此 4xx/5xx 只收敛成状态码 + 信封的
|
||||
// code/message(清洗并截断),其余字节一概不留。
|
||||
// 上游可能把被拒的输入回显在体里,因此 4xx/5xx 只收敛成状态码 + 信封的 code
|
||||
// (message 默认不带,见 WithEnvelopeMessage),其余字节一概不留。
|
||||
func (c *Client) do(ctx context.Context, method, target string, body any) (json.RawMessage, error) {
|
||||
host := trace.HostOf(target)
|
||||
var buf bytes.Buffer
|
||||
@@ -168,7 +195,7 @@ func (c *Client) do(ctx context.Context, method, target string, body any) (json.
|
||||
return nil, fmt.Errorf("httpclient: read %s %s response: %w", method, host, trace.URLCause(err))
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, apiFailure(method, host, resp, raw)
|
||||
return nil, c.apiFailure(method, host, resp, raw)
|
||||
}
|
||||
|
||||
var envelope APIEnvelope
|
||||
@@ -176,36 +203,49 @@ func (c *Client) do(ctx context.Context, method, target string, body any) (json.
|
||||
return raw, nil
|
||||
}
|
||||
if envelope.Code != 0 {
|
||||
return nil, fmt.Errorf("httpclient: %s %s: code %d: %s: %w",
|
||||
method, host, envelope.Code, envelopeMessage(envelope.Message), ErrAPI)
|
||||
if detail := c.envelopeDetail(envelope.Message); detail != "" {
|
||||
return nil, fmt.Errorf("httpclient: %s %s: code %d: %s: %w",
|
||||
method, host, envelope.Code, detail, ErrAPI)
|
||||
}
|
||||
return nil, fmt.Errorf("httpclient: %s %s: code %d: %w", method, host, envelope.Code, ErrAPI)
|
||||
}
|
||||
return envelope.Data, nil
|
||||
}
|
||||
|
||||
// apiFailure 把一次非 2xx 响应收敛成一条不携带响应体原文的错误:来源主机 + 状态码,
|
||||
// 外加(当体确实是 `{code,message}` 信封时)清洗并截断过的 code/message。其余字节只
|
||||
// 经 trace.UpstreamError 留下体积与 sha256 前缀,供「是不是同一份报文」这类相关性判断。
|
||||
func apiFailure(method, host string, resp *http.Response, raw []byte) error {
|
||||
// 外加(当体确实是 `{code,message}` 信封时)code —— message 同样只在显式 opt-in 时
|
||||
// 才出现。其余字节只经 trace.UpstreamError 留下体积与 sha256 前缀,供「是不是同一份
|
||||
// 报文」这类相关性判断。
|
||||
func (c *Client) apiFailure(method, host string, resp *http.Response, raw []byte) error {
|
||||
upstream := trace.UpstreamError(host, resp.StatusCode, resp.Header.Get("Content-Type"), raw)
|
||||
var envelope APIEnvelope
|
||||
if err := json.Unmarshal(raw, &envelope); err == nil {
|
||||
message := envelopeMessage(envelope.Message)
|
||||
detail := c.envelopeDetail(envelope.Message)
|
||||
switch {
|
||||
case envelope.Code != 0 && message != "":
|
||||
case envelope.Code != 0 && detail != "":
|
||||
return fmt.Errorf("httpclient: %s %s: code %d: %s: %w: %w",
|
||||
method, host, envelope.Code, message, upstream, ErrAPI)
|
||||
method, host, envelope.Code, detail, upstream, ErrAPI)
|
||||
case envelope.Code != 0:
|
||||
return fmt.Errorf("httpclient: %s %s: code %d: %w: %w", method, host, envelope.Code, upstream, ErrAPI)
|
||||
case message != "":
|
||||
return fmt.Errorf("httpclient: %s %s: %s: %w: %w", method, host, message, upstream, ErrAPI)
|
||||
case detail != "":
|
||||
return fmt.Errorf("httpclient: %s %s: %s: %w: %w", method, host, detail, upstream, ErrAPI)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("httpclient: %s: %w: %w", method, upstream, ErrAPI)
|
||||
}
|
||||
|
||||
// envelopeMessage 是信封 message 进入错误前的唯一处理:压平空白,再交给
|
||||
// trace.RedactText —— 它既清洗凭据形状,也把长度压到 80 rune(超出的带省略号)。
|
||||
// 上游常把被拒的输入回显在 message 里,因此这一层不是可选的。
|
||||
func envelopeMessage(s string) string {
|
||||
return trace.RedactText(strings.Join(strings.Fields(s), " "))
|
||||
// envelopeDetail 返回**允许进错误文本**的信封 message:默认空串(不带)。
|
||||
//
|
||||
// 为什么默认不带(这条取舍是实测得出的):上游会把被拒的请求正文回显在 message 里,
|
||||
// 而那条正文就是她的话。M49 复审的探针在隔离副本里拿到的实际文本是
|
||||
// `... code 1: invalid content: 她刚才说的那句话: ...: status=400` —— 她的原话既进了
|
||||
// 错误也进了调用方的日志。排障需要的是 code 与 status(两者恒在),不是那句话。
|
||||
//
|
||||
// 只有 WithEnvelopeMessage() 显式打开后,这里才返回 upstreamText(压平空白 + 凭据打码
|
||||
// + 截到 40 rune)。
|
||||
func (c *Client) envelopeDetail(message string) string {
|
||||
if !c.keepEnvelopeMessage {
|
||||
return ""
|
||||
}
|
||||
return upstreamText(message)
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
package httpclient
|
||||
|
||||
// 本文件钉住本客户端的两条出镜边界(M41 #10/#11 那一族):
|
||||
// 本文件钉住本客户端的出镜边界(M41 #10/#11 那一族,M50 补信封 message):
|
||||
//
|
||||
// - **非 2xx 的响应体原文不进错误**:旧实现把体截到 512B 拼进 error,而调用方
|
||||
// (KOOK 适配器)会把这条 error 直接落日志 —— 上游在体里回显什么,日志里就有
|
||||
// 什么。现在只留状态码、来源主机,以及信封的 code/message(已清洗、已截断)。
|
||||
// 什么。现在只留状态码、来源主机,以及信封的 code(message 默认不带)。
|
||||
// - **信封 message 默认不带**:上游会用它在被拒时回显请求正文(也就是她的话)。
|
||||
// 要带必须显式 WithEnvelopeMessage(),那时仍过 upstreamText(凭据打码 + 40 rune)。
|
||||
// - **请求地址的凭据不进错误**:target 可能带 `?access_token=…` 或 `user:pass@`,
|
||||
// 而 net/http 的 *url.Error 会把整条地址拼进错误串。
|
||||
//
|
||||
@@ -12,13 +14,17 @@ package httpclient
|
||||
// 打进日志的那段字符串。
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// failingTransport 让 http.Client.Do 以传输层错误收场。选定它而不是拨一个真端口,
|
||||
@@ -32,8 +38,8 @@ func (failingTransport) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
|
||||
// TestDoJSON_StatusErrorDoesNotEchoBodySentinel 4xx 体里放哨兵 ⇒ 错误里搜不到。
|
||||
//
|
||||
// 用非信封体(代理返回的 HTML 错误页就是这样):信封类的体按设计会保留
|
||||
// code/message,非信封体则一个字节都不留。
|
||||
// 用非信封体(代理返回的 HTML 错误页就是这样):信封类的体按设计会保留 code(message
|
||||
// 默认不带),非信封体则一个字节都不留。
|
||||
func TestDoJSON_StatusErrorDoesNotEchoBodySentinel(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sentinel = "SENTINEL-4XX-BODY"
|
||||
@@ -67,44 +73,117 @@ func TestDoJSON_StatusErrorDoesNotEchoBodySentinel(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_StatusErrorKeepsEnvelopeCode 信封体仍要给出 code/message:这是本客户端
|
||||
// 唯一认识的诊断面,替换掉体原文之后不能连它一起丢。
|
||||
// TestDoJSON_StatusErrorKeepsEnvelopeCode 非 2xx 的信封体仍要给出 code:这是本客户端
|
||||
// 唯一认识的诊断面,替换掉体原文之后不能连它一起丢。而 message 是上游自由文本面,
|
||||
// **默认不带**(M50 口径)—— 上游会用它在被拒时回显她的话。
|
||||
func TestDoJSON_StatusErrorKeepsEnvelopeCode(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sentinel = "invalid content: 她刚才说的那句话"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"code":40101,"message":"invalid token","data":null}`))
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"code":40101,"message":"` + sentinel + `","data":null}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(WithBaseURL(srv.URL), WithHTTPClient(srv.Client()), WithLogger(discardLogger()))
|
||||
_, err := c.DoJSON(context.Background(), http.MethodGet, "/gateway/index", nil)
|
||||
if err == nil {
|
||||
t.Fatal("401 却报成功")
|
||||
t.Fatal("400 却报成功")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "code 40101") || !strings.Contains(err.Error(), "invalid token") {
|
||||
t.Fatalf("信封的 code/message 丢了:%v", err)
|
||||
if !strings.Contains(err.Error(), "code 40101") || !strings.Contains(err.Error(), "status=400") {
|
||||
t.Fatalf("信封的 code / 上游 status 丢了:%v", err)
|
||||
}
|
||||
// 哨兵出现在 message 里 ⇒ 错误与日志都不得带它(变异:把 envelopeDetail 改回
|
||||
// 无条件 upstreamText(message) ⇒ 本断言立刻红)。
|
||||
var logBuf bytes.Buffer
|
||||
slog.New(slog.NewJSONHandler(&logBuf, nil)).Error("send failed", "err", err)
|
||||
for _, surface := range []string{err.Error(), logBuf.String()} {
|
||||
if strings.Contains(surface, "她刚才说的那句话") {
|
||||
t.Fatalf("信封 message(上游回显的她的原话)进了错误或日志:%s", surface)
|
||||
}
|
||||
}
|
||||
// 哨兵链不变:分类靠 errors.Is,不靠文本。
|
||||
if !errors.Is(err, ErrAPI) || !errors.Is(err, trace.ErrUpstream) {
|
||||
t.Fatalf("err = %v, want both ErrAPI and trace.ErrUpstream", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_NonZeroCodeRedactsMessageSecrets 信封 message 是上游自由文本面:里面的
|
||||
// 凭据形状必须被清洗掉,长度必须被截断。改回原样透传就变红。
|
||||
func TestDoJSON_NonZeroCodeRedactsMessageSecrets(t *testing.T) {
|
||||
// TestDoJSON_NonZeroCodeDropsEnvelopeMessage 是 2xx + `code != 0` 这**另一个分支**:
|
||||
// 它此前把 message 直接拼进错误(M49 探针复现的原文里 `code 1: invalid content: …`
|
||||
// 走的就是跨过 apiFailure 的这一支)。code 必须留下,message 必须不带。
|
||||
func TestDoJSON_NonZeroCodeDropsEnvelopeMessage(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sentinel = "invalid content: 她刚才说的那句话"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// 200 + 非零 code:KOOK 一类平台的「业务失败也 200」形态。
|
||||
_, _ = w.Write([]byte(`{"code":1,"message":"` + sentinel + `","data":null}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(WithBaseURL(srv.URL), WithHTTPClient(srv.Client()), WithLogger(discardLogger()))
|
||||
_, err := c.DoJSON(context.Background(), http.MethodPost, "/message/create", map[string]any{"content": "她刚才说的那句话"})
|
||||
if err == nil {
|
||||
t.Fatal("非零 code 却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), "她刚才说的那句话") {
|
||||
t.Fatalf("200 + code!=0 分支仍把 message 拼进错误:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "code 1") {
|
||||
t.Fatalf("2xx 分支的 code 丢了(那一条没别的分类信息):%v", err)
|
||||
}
|
||||
if !errors.Is(err, ErrAPI) {
|
||||
t.Fatalf("err = %v, want ErrAPI", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_EnvelopeMessageOptInRedactsMessageSecrets opt-in(WithEnvelopeMessage)是
|
||||
// 唯一能带 message 的通道:带上的那一刻仍必须清洗凭据形状。
|
||||
func TestDoJSON_EnvelopeMessageOptInRedactsMessageSecrets(t *testing.T) {
|
||||
t.Parallel()
|
||||
const secret = "big-secret-value-123456"
|
||||
body := `{"code":40101,"message":"invalid access_token=` + secret + `","data":null}`
|
||||
body := `{"code":40101,"message":"access_token=` + secret + `","data":null}`
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(WithBaseURL(srv.URL), WithHTTPClient(srv.Client()), WithLogger(discardLogger()), WithToken(secret))
|
||||
c := New(WithBaseURL(srv.URL), WithHTTPClient(srv.Client()),
|
||||
WithLogger(discardLogger()), WithToken(secret), WithEnvelopeMessage())
|
||||
_, err := c.DoJSON(context.Background(), http.MethodGet, "/gateway/index", nil)
|
||||
if err == nil {
|
||||
t.Fatal("非零 code 却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("信封 message 里的凭据原样进了错误:%v", err)
|
||||
t.Fatalf("opt-in 的信封 message 没有清洗凭据形状:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "[redacted]") {
|
||||
t.Fatalf("opt-in 生效后错误里没有 message(无法证明这条通道还活着):%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_EnvelopeMessageOptInIsBounded 钉住 opt-in 下 message 的长度口径:40 rune
|
||||
// (maxUpstreamTextRunes)+ 省略号。这条让「到底哪一层在截、截到多少」变成可断言的事实 ——
|
||||
// 上界刻意比 trace.RedactText 的 80 更短(错误里那句话是提示,不是摘要)。
|
||||
func TestDoJSON_EnvelopeMessageOptInIsBounded(t *testing.T) {
|
||||
t.Parallel()
|
||||
long := strings.Repeat("a", 300)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"code":40101,"message":"` + long + `","data":null}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(WithBaseURL(srv.URL), WithHTTPClient(srv.Client()),
|
||||
WithLogger(discardLogger()), WithEnvelopeMessage())
|
||||
_, err := c.DoJSON(context.Background(), http.MethodGet, "/gateway/index", nil)
|
||||
if err == nil {
|
||||
t.Fatal("401 却报成功")
|
||||
}
|
||||
if !strings.Contains(err.Error(), strings.Repeat("a", maxUpstreamTextRunes)+"…") {
|
||||
t.Fatalf("信封 message 没有按 %d rune 截断:%v", maxUpstreamTextRunes, err)
|
||||
}
|
||||
if strings.Contains(err.Error(), strings.Repeat("a", maxUpstreamTextRunes+1)) {
|
||||
t.Fatalf("信封 message 超过了 %d rune 上限:%v", maxUpstreamTextRunes, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -153,28 +232,3 @@ func TestGetJSON_UserinfoNeverEntersError(t *testing.T) {
|
||||
t.Fatalf("剥掉地址时把来源一起丢了:%v", msg)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_EnvelopeMessageIsBoundedByRedactText 钉住长度口径:信封 message 只有一道
|
||||
// 清洗(trace.RedactText,80 rune + 省略号)。本片曾按 200 rune 自己再截一刀,那层
|
||||
// 永远命中不了 —— 这条用例让「到底哪一层在截」变成可断言的事实。
|
||||
func TestDoJSON_EnvelopeMessageIsBoundedByRedactText(t *testing.T) {
|
||||
t.Parallel()
|
||||
long := strings.Repeat("a", 300)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"code":40101,"message":"` + long + `","data":null}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
c := New(WithBaseURL(srv.URL), WithHTTPClient(srv.Client()), WithLogger(discardLogger()))
|
||||
_, err := c.DoJSON(context.Background(), http.MethodGet, "/gateway/index", nil)
|
||||
if err == nil {
|
||||
t.Fatal("401 却报成功")
|
||||
}
|
||||
if !strings.Contains(err.Error(), strings.Repeat("a", 80)+"…") {
|
||||
t.Fatalf("信封 message 没有按 80 rune 截断:%v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), strings.Repeat("a", 81)) {
|
||||
t.Fatalf("信封 message 超过了 80 rune 上限:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package httpclient
|
||||
|
||||
// 本文件是**渠道侧上游自由文本的唯一清洗入口**(M50)。它管的是同一件事在四个出口上
|
||||
// 的形态:KOOK 一类 `{code,message}` 信封的 `message`、Telegram Bot API 的
|
||||
// `description`、OneBot v11 信封的 `msg` / `wording`、iLink CDN 的 `x-error-message`
|
||||
// 头。四者都是上游给的**人话**,都可能把被拒的请求内容回显出来 —— 而请求内容里就有
|
||||
// 她的原话。
|
||||
//
|
||||
// 🔴 契约(改本文件前先读):
|
||||
// - 上层口径是 **默认不带**:这些字段默认不进 error、不进日志(见 client.go 的
|
||||
// WithEnvelopeMessage 与各渠道调用点的注释)。本文件的函数**只在调用方已经显式
|
||||
// 选择保留**时才被调用 —— 它是「保留时的上限」,不是「可以带」的许可。
|
||||
// - 清洗只有一份:`trace.RedactTextLimited`(凭据形状打码 + rune 截断)。本包**不**
|
||||
// 另写一套正则或截断,另写一套必然漂移,而漂移的方向总是「其中一条出口开始原样
|
||||
// 吐凭据」。
|
||||
// - 压平空白也是必需的一步:一条诊断只许占一行,否则上游可以用换行伪造日志行
|
||||
// (log injection)。
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// maxUpstreamTextRunes 是上游自由文本允许保留的 rune 上限:**40**。
|
||||
//
|
||||
// 为什么比 `trace.RedactText` 的 80 更短:那一档服务的是**摘要素材**(出图、工具结果
|
||||
// 摘要),读者只看这一条;本文件的产物进的是**错误链与日志**,同一条信息还会被调用方
|
||||
// 再落一次,长度预算没有理由按摘要给。而 40 rune 已足够装下渠道侧真正有用的那类说明
|
||||
// (`invalid token`、`参数错误`、`缺少 code`、`FLOOD_WAIT_30`),又短到装不下一句她
|
||||
// 说的话 —— 上游回显 `invalid content: <正文>` 时,前半句就吃掉大半预算。
|
||||
const maxUpstreamTextRunes = 40
|
||||
|
||||
// upstreamText 把一段上游自由文本收敛成可以出镜的短诊断:压平空白,再交给
|
||||
// `trace.RedactTextLimited` 打码凭据形状并截到 maxUpstreamTextRunes(超出的带省略号)。
|
||||
//
|
||||
// 空串进 ⇒ 空串出;调用方据此判断「这一段有没有东西可显示」。
|
||||
//
|
||||
// 🔴 它**不**决定该不该带(默认不带)。把它的结果无条件拼进 error 仍然是把她的原话
|
||||
// 送上日志 —— 调用点必须自己持有那个显式的开关(本包只有 WithEnvelopeMessage 一处)。
|
||||
// 渠道插件当前**不带**任何自由文本,因此没有第二个调用点;将来若真要开,也要回到
|
||||
// 这一条(`trace` 的唯一清洗 + 40 rune),不要在插件里另写一套截断。
|
||||
func upstreamText(s string) string {
|
||||
if s == "" {
|
||||
return ""
|
||||
}
|
||||
return trace.RedactTextLimited(strings.Join(strings.Fields(s), " "), maxUpstreamTextRunes)
|
||||
}
|
||||
@@ -2,10 +2,10 @@ package trace
|
||||
|
||||
import "strings"
|
||||
|
||||
// 本文件是「上游错误信封里的自由文本字段能不能出镜」的唯一守卫。
|
||||
// 本文件是「上游错误字段能不能出镜」的唯一守卫。
|
||||
//
|
||||
// 背景:UpstreamErrorInfo 只解析 error.code / error.type 两个字段,而它们是**自由
|
||||
// 文本面** —— 主流上游里它们确实是枚举(invalid_request_error、overloaded_error、
|
||||
// 背景:UpstreamErrorInfo 只解析 error.code / error.type 两个字段,而它们**可能**是
|
||||
// 自由文本面 —— 主流上游里它们确实是枚举(invalid_request_error、overloaded_error、
|
||||
// Throttling.RateQuota …),但网关、代理与兼容层可以往里面塞任何东西,包括回显的
|
||||
// 用户原文。因此这两个字段出镜前必须像令牌:短、只含标识符字符。
|
||||
//
|
||||
@@ -15,9 +15,25 @@ import "strings"
|
||||
//
|
||||
// 🔴 M49 收口:守卫的**应用点**同样收进本包 —— UpstreamError 构造时对 error.code /
|
||||
// error.type 各调一次(构造即安全,调用点不必也不该再守),构造后的注入走
|
||||
// UpstreamErrorInfo.SetCode / SetType(同一道守卫)。因此本包之外的 Go 代码里
|
||||
// **不应出现 ErrorToken 调用**:出现了就意味着又回到「调用方逐点补」的漂移形态
|
||||
// (M48 复审的 finding 正是这么漏的:httpclient / vision / embedding / weixin 四处)。
|
||||
// UpstreamErrorInfo.SetCode / SetType(同一道守卫)。
|
||||
//
|
||||
// 🔴 M50 修正口径(**取代**原先「本包之外的 Go 代码里不应出现 ErrorToken 调用」的说法;
|
||||
// 那条已被证伪:M50 之后本包外确有正当调用点)。判据是**字段的类别**,不是调用点的位置:
|
||||
//
|
||||
// - **协议枚举字段**(信封的 status / code / type、DashScope 的 request_id 这类
|
||||
// 「一格一个值」的字段)**可以**在渲染点调用本守卫后再出镜。真实取值是短令牌 ⇒
|
||||
// 原样通过;上游若在枚举位上塞散文 ⇒ 整体变空串。现行调用点:
|
||||
// `plugins/channels/qq_obv11`(信封 status,两处)、`plugins/channels/weixin_ilink`
|
||||
// (扫码 status 与 redirect_host)、`runtime/multimodal/voice/dashscope_error.go`
|
||||
// (request_id —— M50 之前就存在的正当例外)。
|
||||
// - **自由文本字段**(message / description / msg / wording / 服务端错误说明头 …)
|
||||
// **不得**靠本守卫出镜。它们的问题不是形状(短的人话照样像令牌),而是取值的
|
||||
// 控制权:上游想写什么就写什么,而它写的常常是被拒的请求正文 —— 也就是她的话。
|
||||
// 这类字段的口径是**默认不带**;要带必须显式 opt-in,并在保留时过 RedactText
|
||||
// (见 trace.UpstreamError 的 WithUpstreamMessage 与
|
||||
// internal/channel/adapter/httpclient 的 WithEnvelopeMessage)。
|
||||
//
|
||||
// 简言之:本守卫回答「这个令牌形状的枚举值能不能露」,不回答「这段人话能不能露」。
|
||||
|
||||
// maxErrorTokenBytes 是 error.code / error.type / request_id 允许出镜的长度上限。
|
||||
// 64 字节足够容纳任何真实的枚举与 UUID 形状,又远小于「一段话」。
|
||||
|
||||
Reference in new issue
Block a user