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 形状,又远小于「一段话」。
|
||||
|
||||
@@ -21,6 +21,8 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -155,12 +157,27 @@ func (c *obHTTPClient) post(ctx context.Context, payload []byte) (*obAPIResponse
|
||||
return nil, fmt.Errorf("qq-obv11: decode http %s response: %w", action, err)
|
||||
}
|
||||
if env.RetCode != 0 || (env.Status != "" && !strings.EqualFold(env.Status, "ok")) {
|
||||
return nil, fmt.Errorf("qq-obv11: http %s failed: retcode=%d status=%q msg=%q",
|
||||
action, env.RetCode, env.Status, env.Msg)
|
||||
return nil, fmt.Errorf("qq-obv11: http %s failed: retcode=%d%s",
|
||||
action, env.RetCode, upstreamStatusSuffix(env.Status))
|
||||
}
|
||||
return &env, nil
|
||||
}
|
||||
|
||||
// upstreamStatusSuffix 渲染 OneBot 信封的 status(协议字段,取值 `ok` / `failed`):它
|
||||
// 过 trace.ErrorToken 的令牌守卫后才出镜,因此上游若在 status 里塞散文,那一段整体
|
||||
// 消失(与 trace.UpstreamError 对 code/type 的守卫同一口径)。
|
||||
//
|
||||
// 🔴 上游的 `msg` / `wording` 是**自由文本面**,一律不进错误也不进日志:NapCat /
|
||||
// go-cqhttp 会把失败的请求内容回显在 msg 里,而请求里就有她要发的话(M50 口径 ——
|
||||
// 默认安全,要带必须显式 opt-in,本适配器不开)。排障真正用得到的是 retcode 与
|
||||
// status,两者恒在。
|
||||
func upstreamStatusSuffix(status string) string {
|
||||
if tok := trace.ErrorToken(status); tok != "" {
|
||||
return fmt.Sprintf(" status=%q", tok)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// actionOf 从已编码的 action 请求里取出 action 名,仅用于日志与错误上下文。
|
||||
func actionOf(payload []byte) string {
|
||||
var head struct {
|
||||
|
||||
@@ -27,6 +27,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/adapter"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -155,7 +156,9 @@ func (a *Adapter) logSendReceipt(ctx context.Context, receipt adapter.SendReceip
|
||||
//
|
||||
// 回执报错**不**改成返回 error:帧已经写出去了,把「已投递」报成失败会让调用方重发。
|
||||
// 但**绝不静默** —— 观察到了一个「发送失败」却一声不吭,正是「数据看到了又丢掉」的
|
||||
// 老毛病(本切片要修的就是它)。只记 retcode / status / msg,不记正文。
|
||||
// 老毛病(本切片要修的就是它)。只记 retcode 与 status(status 过 trace.ErrorToken 的
|
||||
// 令牌守卫):上游的 msg / wording 是自由文本面,会把失败的请求内容回显出来,所以
|
||||
// **不记**(M50 口径,与 http_client.post 的错误文本同一道边界)。
|
||||
func (a *Adapter) logEchoFailure(resp *obAPIResponse) {
|
||||
if resp == nil {
|
||||
return
|
||||
@@ -164,5 +167,5 @@ func (a *Adapter) logEchoFailure(resp *obAPIResponse) {
|
||||
return
|
||||
}
|
||||
a.log.Warn("send_msg echo reports failure",
|
||||
"retcode", resp.RetCode, "status", resp.Status, "msg", resp.Msg)
|
||||
"retcode", resp.RetCode, "status", trace.ErrorToken(resp.Status))
|
||||
}
|
||||
@@ -181,8 +181,8 @@ func parseStatusResponse(resp *obAPIResponse) (obStatusData, error) {
|
||||
return obStatusData{}, errors.New("qq-obv11: get_status response: empty envelope")
|
||||
}
|
||||
if resp.RetCode != 0 || (resp.Status != "" && !strings.EqualFold(resp.Status, "ok")) {
|
||||
return obStatusData{}, fmt.Errorf("qq-obv11: get_status response: retcode=%d status=%q",
|
||||
resp.RetCode, resp.Status)
|
||||
return obStatusData{}, fmt.Errorf("qq-obv11: get_status response: retcode=%d%s",
|
||||
resp.RetCode, upstreamStatusSuffix(resp.Status))
|
||||
}
|
||||
var data *obStatusData
|
||||
if err := json.Unmarshal(resp.Data, &data); err != nil {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
package qq_obv11
|
||||
|
||||
// 本文件钉住 OneBot 信封里**自由文本面**的出镜边界(M50,与 httpclient 的信封
|
||||
// message、Telegram 的 description、iLink 的 x-error-message 同一族):
|
||||
//
|
||||
// - 失败时上游的 `msg` / `wording` **不进错误文本**:NapCat / go-cqhttp 会把失败的
|
||||
// 请求内容回显在 msg 里,而那些内容里就有她要发的话。留下的是 retcode 与 status。
|
||||
// - status 是**协议字段**,但同样只按令牌出镜(trace.ErrorToken):上游若在 status
|
||||
// 里塞散文,那一段整体消失。
|
||||
// - 回执失败的 WARN 日志(logEchoFailure)走同一道边界 —— 否则同一个洞只是换个出口。
|
||||
//
|
||||
// 每条都是「把字段拼回去就变红」的形状,断言的是**错误文本与日志行**。
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// newFailingOneBotAPI 起一个总是回「失败信封」的假 OneBot,body 由调用方给。
|
||||
func newFailingOneBotAPI(t *testing.T, body map[string]any) *httptest.Server {
|
||||
t.Helper()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(body)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// TestHTTPClientDropsUpstreamMsg 失败信封里的 msg / wording 带她的原话 ⇒ 错误与日志里
|
||||
// 都搜不到,而 retcode 与 status 仍在(变异的两个方向各钉一条)。
|
||||
func TestHTTPClientDropsUpstreamMsg(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sentinel = "她刚才说的那句话"
|
||||
srv := newFailingOneBotAPI(t, map[string]any{
|
||||
"status": "failed",
|
||||
"retcode": 1404,
|
||||
"msg": "SEND_MSG_API_ERROR: invalid content: " + sentinel,
|
||||
"wording": "参数错误:" + sentinel,
|
||||
"data": nil,
|
||||
})
|
||||
|
||||
c, err := newOBHTTPClient(srv.URL, "tok")
|
||||
if err != nil {
|
||||
t.Fatalf("newOBHTTPClient: %v", err)
|
||||
}
|
||||
payload, err := buildActionReq("send_msg", map[string]any{"message": sentinel}, "")
|
||||
if err != nil {
|
||||
t.Fatalf("buildActionReq: %v", err)
|
||||
}
|
||||
_, err = c.post(context.Background(), payload)
|
||||
if err == nil {
|
||||
t.Fatal("retcode=1404 却报成功")
|
||||
}
|
||||
|
||||
var logBuf bytes.Buffer
|
||||
slog.New(slog.NewJSONHandler(&logBuf, nil)).Error("onebot action failed", "err", err)
|
||||
for _, surface := range []string{err.Error(), logBuf.String()} {
|
||||
if strings.Contains(surface, sentinel) {
|
||||
t.Fatalf("上游 msg / wording 进了错误或日志:%s", surface)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(err.Error(), "retcode=1404") {
|
||||
t.Fatalf("retcode 丢了(唯一可靠的分类信息):%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), `status="failed"`) {
|
||||
t.Fatalf("status 丢了(它是协议字段,应当仍出镜):%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHTTPClientDropsProseStatus 上游若把散文塞进 status,令牌守卫让它整体消失 ——
|
||||
// status 不是第二条正文通道。
|
||||
func TestHTTPClientDropsProseStatus(t *testing.T) {
|
||||
t.Parallel()
|
||||
srv := newFailingOneBotAPI(t, map[string]any{
|
||||
"status": "failed: 她刚才说的那句话",
|
||||
"retcode": 1404,
|
||||
"data": nil,
|
||||
})
|
||||
|
||||
c, err := newOBHTTPClient(srv.URL, "tok")
|
||||
if err != nil {
|
||||
t.Fatalf("newOBHTTPClient: %v", err)
|
||||
}
|
||||
payload, err := buildActionReq("send_msg", map[string]any{"message": "hi"}, "")
|
||||
if err != nil {
|
||||
t.Fatalf("buildActionReq: %v", err)
|
||||
}
|
||||
_, err = c.post(context.Background(), payload)
|
||||
if err == nil {
|
||||
t.Fatal("retcode=1404 却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), "她刚才说的那句话") || strings.Contains(err.Error(), "status=") {
|
||||
t.Fatalf("散文 status 出镜了(应被令牌守卫丢弃):%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "retcode=1404") {
|
||||
t.Fatalf("retcode 丢了:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLogEchoFailureDropsUpstreamMsg 回执失败的 WARN 是**另一个出口**:它同样只记
|
||||
// retcode 与 status,不记上游 msg(同一个洞换个出口的形态)。
|
||||
func TestLogEchoFailureDropsUpstreamMsg(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sentinel = "她刚才说的那句话"
|
||||
var buf bytes.Buffer
|
||||
a := NewAdapter(Config{}, WithLogger(slog.New(slog.NewJSONHandler(&buf, nil))))
|
||||
|
||||
a.logEchoFailure(&obAPIResponse{
|
||||
Status: "failed",
|
||||
RetCode: 1404,
|
||||
Msg: "SEND_MSG_API_ERROR: invalid content: " + sentinel,
|
||||
Wording: "参数错误:" + sentinel,
|
||||
})
|
||||
line := buf.String()
|
||||
if line == "" {
|
||||
t.Fatal("回执失败一条日志都没有(静默即缺陷)")
|
||||
}
|
||||
if strings.Contains(line, sentinel) {
|
||||
t.Fatalf("上游 msg 进了日志:%s", line)
|
||||
}
|
||||
if !strings.Contains(line, `"retcode":1404`) || !strings.Contains(line, `"status":"failed"`) {
|
||||
t.Fatalf("日志里没有 retcode/status(诊断面):%s", line)
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ type botResponse struct {
|
||||
}
|
||||
|
||||
// maxErrorBodyBytes caps how much of a non-200 reply is read before classifying it.
|
||||
// Only error_code is taken from it (description is dropped — see badResponseError).
|
||||
const maxErrorBodyBytes = 512
|
||||
|
||||
// doJSON posts a JSON payload to a Bot API method and decodes the envelope. The
|
||||
@@ -63,6 +64,13 @@ func (a *Adapter) doJSON(ctx context.Context, method string, payload any) (*botR
|
||||
return nil, fmt.Errorf("telegram: decode %s response: %w", method, err)
|
||||
}
|
||||
if !out.OK {
|
||||
// 200 + `ok:false` 也是失败。这一支没有 status 可报(HTTP 恒 200),于是把
|
||||
// error_code 带上 —— 它是**分类令牌**,不是正文通道,与上面非 200 分支同一口径。
|
||||
// description 在这里同样**默认不带**:Telegram 会在里面回显我们发过去的参数
|
||||
// (M50 口径,见 badResponseError)。
|
||||
if out.ErrorCode != 0 {
|
||||
return nil, fmt.Errorf("telegram: %s: error_code %d: %w", method, out.ErrorCode, ErrBadResponse)
|
||||
}
|
||||
return nil, fmt.Errorf("telegram: %s: %w", method, ErrBadResponse)
|
||||
}
|
||||
return &out, nil
|
||||
@@ -210,12 +218,16 @@ func parseReplyToID(s string) int64 {
|
||||
return n
|
||||
}
|
||||
|
||||
// badResponseError 把一次非 200 的回复收敛成错误:**只**取 error_code 与
|
||||
// description。响应体其余字段(以及 Telegram 回显的请求参数)一个字都不拼 ——
|
||||
// 旧实现把 512B 体原文当 desc 拼进来,等于把上游报文写进调用方的日志。
|
||||
// badResponseError 把一次非 200 的回复收敛成错误:**只**取 status 与 error_code。
|
||||
// 响应体其余字段(以及 Telegram 回显的请求参数)一个字都不拼 —— 旧实现把 512B 体原文
|
||||
// 当 desc 拼进来,等于把上游报文写进调用方的日志。
|
||||
//
|
||||
// description 是上游自由文本(例如 setWebhook 失败时会回显我们给的地址),因此过
|
||||
// trace.RedactText 清洗凭据形状并按 rune 截断后才出镜。
|
||||
// 🔴 description 默认**不带**(M50):它是上游自由文本,Telegram 会回显我们发过去的
|
||||
// 参数,而那些参数里就有她的话(`Bad Request: can't parse entities: <正文>` 是真实
|
||||
// 形状)。口径与 `trace.UpstreamError` 的 message 一致 —— 默认安全,要带必须显式
|
||||
// opt-in;本适配器不开这个开关,因为 status + error_code 已足够分类(400/403/429)。
|
||||
// 将来若真要带,请回到 httpclient 那条单一清洗口径(`trace` 的唯一打码 + 40 rune,
|
||||
// 见 internal/channel/adapter/httpclient/upstream_text.go),不要在这里另写截断。
|
||||
func badResponseError(method string, status int, body []byte) error {
|
||||
var env botResponse
|
||||
_ = json.Unmarshal(body, &env)
|
||||
@@ -223,14 +235,5 @@ func badResponseError(method string, status int, body []byte) error {
|
||||
if env.ErrorCode != 0 {
|
||||
parts = append(parts, fmt.Sprintf("error_code %d", env.ErrorCode))
|
||||
}
|
||||
if desc := boundedDescription(env.Description); desc != "" {
|
||||
parts = append(parts, desc)
|
||||
}
|
||||
return fmt.Errorf("%s: %w", strings.Join(parts, ": "), ErrBadResponse)
|
||||
}
|
||||
|
||||
// boundedDescription 是 Bot API description 进入错误前的唯一处理:压平空白,再交给
|
||||
// trace.RedactText —— 它既清洗凭据形状,也把长度压到 80 rune(超出的带省略号)。
|
||||
func boundedDescription(s string) string {
|
||||
return trace.RedactText(strings.Join(strings.Fields(s), " "))
|
||||
}
|
||||
@@ -1,18 +1,22 @@
|
||||
package telegram
|
||||
|
||||
// 本文件钉住 Bot API 出站调用的两条出镜边界(M41 #12/#13 那一族):
|
||||
// 本文件钉住 Bot API 出站调用的三条出镜边界(M41 #12/#13 那一族,M50 补 description):
|
||||
//
|
||||
// - **非 200 的响应体原文不进错误**:旧实现把 512B 体原文当 description 拼进
|
||||
// error,而 `ReadMessages` 会以 `long poll failed` 落日志 —— 上游在体里回显什么,
|
||||
// 日志里就有什么。现在只解 error_code 与 description(清洗、截断后)。
|
||||
// 日志里就有什么。现在只解 error_code 与 HTTP status。
|
||||
// - **description 默认不带**:它是上游自由文本,Telegram 会回显我们发过去的参数
|
||||
// (里面就有她的话)。要带必须显式 opt-in;本适配器不开。
|
||||
// - **地址里的 bot token 不进错误**:Bot API 的地址是 /bot<token>/<method>,
|
||||
// 传输层失败时 net/http 的 *url.Error 会把整条地址拼进错误串。
|
||||
//
|
||||
// 两条都是「改回去就变红」的形状:断言的是错误文本 —— 也就是真正被写进日志的字符串。
|
||||
// 三条都是「改回去就变红」的形状:断言的是错误文本 —— 也就是真正被写进日志的字符串。
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -28,14 +32,15 @@ func (failingTransport) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
|
||||
// TestDoJSON_StatusErrorDoesNotEchoBodySentinel 4xx 体里放哨兵 ⇒ 错误里搜不到。
|
||||
//
|
||||
// 哨兵刻意放在 description 之外的字段:description 按设计要保留(那是 Telegram 对
|
||||
// 这次请求的说明),而「体里其余字节一个字都不拼」才是要钉住的口径。
|
||||
// 哨兵同时放在 description 之外与 description 之内:description 是上游自由文本面,
|
||||
// **默认不带**(M50),因此两个位置的哨兵都必须搜不到;留下的诊断面是 status 与
|
||||
// error_code。
|
||||
func TestDoJSON_StatusErrorDoesNotEchoBodySentinel(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sentinel = "SENTINEL-TG-BODY"
|
||||
a, _ := newTestAdapter(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"ok":false,"error_code":400,"description":"Bad Request: chat not found",` +
|
||||
_, _ = w.Write([]byte(`{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities: ` + sentinel + `",` +
|
||||
`"echoed_params":{"text":"` + sentinel + `"}}`))
|
||||
}))
|
||||
|
||||
@@ -46,20 +51,26 @@ func TestDoJSON_StatusErrorDoesNotEchoBodySentinel(t *testing.T) {
|
||||
if !errors.Is(err, ErrBadResponse) {
|
||||
t.Fatalf("err = %v, want ErrBadResponse", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), sentinel) {
|
||||
t.Fatalf("响应体其余字段进了错误(会随 long poll failed 落日志):%v", err)
|
||||
var logBuf bytes.Buffer
|
||||
slog.New(slog.NewJSONHandler(&logBuf, nil)).Error("long poll failed", "err", err)
|
||||
for _, surface := range []string{err.Error(), logBuf.String()} {
|
||||
if strings.Contains(surface, sentinel) {
|
||||
t.Fatalf("响应体原文(含 description 回显)进了错误或日志:%s", surface)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(err.Error(), "error_code 400") || !strings.Contains(err.Error(), "chat not found") {
|
||||
t.Fatalf("error_code/description 丢了(诊断面不能一起丢):%v", err)
|
||||
// 变异:把 description 拼回 parts ⇒ 上面那条立刻红。
|
||||
if !strings.Contains(err.Error(), "error_code 400") {
|
||||
t.Fatalf("error_code 丢了(诊断面不能一起丢):%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "status 400") {
|
||||
t.Fatalf("HTTP 状态码丢了:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_StatusErrorRedactsDescriptionSecrets description 是上游自由文本,而
|
||||
// setWebhook 失败时 Telegram 会把我们给的地址回显在里面 —— 地址的 query 常带凭据。
|
||||
// 这类赋值形状必须被清洗。改回原样透传就变红。
|
||||
// TestDoJSON_StatusErrorRedactsDescriptionSecrets 上一族里的凭据形态:description 现在
|
||||
// 整段不带,因此 setWebhook 回显的地址(query 常带凭据)也一并不能出镜。这条与
|
||||
// TestDoJSON_StatusErrorDoesNotEchoBodySentinel 是同一处代码的两个变异方向 —— 一个钉
|
||||
// 「正文不进来」,一个钉「凭据不出去」。
|
||||
func TestDoJSON_StatusErrorRedactsDescriptionSecrets(t *testing.T) {
|
||||
t.Parallel()
|
||||
const secret = "WEBHOOK-SECRET-VALUE"
|
||||
@@ -76,6 +87,9 @@ func TestDoJSON_StatusErrorRedactsDescriptionSecrets(t *testing.T) {
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("description 里的凭据原样进了错误:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "error_code 400") || !strings.Contains(err.Error(), "status 400") {
|
||||
t.Fatalf("剥掉 description 时把分类信息一起丢了:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_TransportErrorOmitsBotToken 传输层失败时,错误里不得出现 bot token ——
|
||||
@@ -130,10 +144,10 @@ func TestDoJSON_BuildErrorOmitsBotToken(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_DescriptionIsBoundedByRedactText 钉住长度口径:description 只有一道
|
||||
// 清洗(trace.RedactText,80 rune + 省略号)。本片曾按 200 rune 自己再截一刀,那层
|
||||
// 永远命中不了 —— 这条用例让「到底哪一层在截」变成可断言的事实。
|
||||
func TestDoJSON_DescriptionIsBoundedByRedactText(t *testing.T) {
|
||||
// TestDoJSON_DescriptionIsDropped 钉住「description 默认不带」:无论它多长、写的是什么,
|
||||
// 错误里都只剩 status + error_code。变异:把 description 拼回 badResponseError 的
|
||||
// parts ⇒ 本用例立刻红(`aaaa…` 会出现)。
|
||||
func TestDoJSON_DescriptionIsDropped(t *testing.T) {
|
||||
t.Parallel()
|
||||
long := strings.Repeat("a", 300)
|
||||
a, _ := newTestAdapter(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -145,10 +159,10 @@ func TestDoJSON_DescriptionIsBoundedByRedactText(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("400 却报成功")
|
||||
}
|
||||
if !strings.Contains(err.Error(), strings.Repeat("a", 80)+"…") {
|
||||
t.Fatalf("description 没有按 80 rune 截断:%v", err)
|
||||
if strings.Contains(err.Error(), "aaaa") {
|
||||
t.Fatalf("description 进了错误(M50 口径是默认不带):%v", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), strings.Repeat("a", 81)) {
|
||||
t.Fatalf("description 超过了 80 rune 上限:%v", err)
|
||||
if !strings.Contains(err.Error(), "status 400") || !strings.Contains(err.Error(), "error_code 400") {
|
||||
t.Fatalf("剥掉 description 时把分类信息一起丢了:%v", err)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ import (
|
||||
"net/url"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// loginPollInterval 是 Connect 轮询二维码确认状态的默认间隔。它是文档记录的约 1s
|
||||
@@ -65,6 +67,19 @@ func (a *Adapter) login(ctx context.Context) error {
|
||||
|
||||
// runLogin 轮询 get_qrcode_status,直到二维码被确认或登录窗口结束,然后把结果记录在
|
||||
// 会话上。它运行在 goroutine 中,所以 StartLogin 能立即返回,而面板轮询 LoginStatus。
|
||||
//
|
||||
// 🔴 出镜口径(M50):`status` 与 `redirect_host` 都是**上游字段**,进日志前一律过
|
||||
// trace.ErrorToken(协议枚举字段的那道守卫,判据见 internal/runtime/trace/errortoken.go):
|
||||
// 真实取值(wait / scaned / confirmed / scaned_but_redirect / idc.weixin.qq.com …)原样
|
||||
// 通过;上游若在枚举位上塞散文,那一栏整体变空串。
|
||||
//
|
||||
// 🔴 **控制流只用原值**:setPhase、下面的 switch、setPollBaseURL 与 confirmingPhase 读
|
||||
// 的都是原始串 —— 渲染口径绝不参与判定。一个图省事的修法是把守卫后的值喂给
|
||||
// setPollBaseURL,那会让带端口的合法重定向主机整体失效(用例
|
||||
// TestStartLogin_ProseRedirectHostNeverReachesLog 钉的就是这个方向)。
|
||||
//
|
||||
// 同一个 status 还有第二个日志出口(复用二维码时那条 INFO 打 currentPhase),在
|
||||
// login_admin.go 里过同一道守卫。
|
||||
func (a *Adapter) runLogin(sess *loginSession, sessCtx context.Context) {
|
||||
timeoutCtx, cancel := context.WithTimeout(sessCtx, a.cfg.LoginTimeout)
|
||||
defer cancel()
|
||||
@@ -84,12 +99,11 @@ func (a *Adapter) runLogin(sess *loginSession, sessCtx context.Context) {
|
||||
}
|
||||
return
|
||||
}
|
||||
// 跟踪线上的原始阶段,便于 StartLogin 保护「已扫描/确认中」的绑定不被重新取码。
|
||||
// 仅在状态变化时打日志以避免噪声,且绝不记录 qrcode 标识符或 token。
|
||||
// status 进日志前过令牌守卫(口径见函数头);控制流仍用原值。
|
||||
sess.setPhase(status.Status)
|
||||
if status.Status != prevStatus {
|
||||
prevStatus = status.Status
|
||||
a.log.Info("weixin_ilink: get_qrcode_status", "status", status.Status)
|
||||
a.log.Info("weixin_ilink: get_qrcode_status", "status", trace.ErrorToken(status.Status))
|
||||
}
|
||||
|
||||
switch status.Status {
|
||||
@@ -115,8 +129,10 @@ func (a *Adapter) runLogin(sess *loginSession, sessCtx context.Context) {
|
||||
a.setLoginState(LoginStatusWaiting, loginScannedDetail)
|
||||
case "scaned_but_redirect":
|
||||
if status.RedirectHost != "" {
|
||||
// 路由用**原值**,日志只留守卫后的形态(口径见函数头)。
|
||||
a.setPollBaseURL(status.RedirectHost)
|
||||
a.log.Info("weixin_ilink: idc redirect, switching polling host", "host", status.RedirectHost)
|
||||
a.log.Info("weixin_ilink: idc redirect, switching polling host",
|
||||
"host", trace.ErrorToken(status.RedirectHost))
|
||||
} else {
|
||||
a.log.Warn("weixin_ilink: scaned_but_redirect without redirect_host, continuing on current host")
|
||||
}
|
||||
@@ -240,7 +256,12 @@ func (a *Adapter) fetchQRCode(ctx context.Context) (qrcodeResp, error) {
|
||||
}
|
||||
// 只记录可渲染的二维码 URL,绝不记录原始 qrcode 标识符(它是回传给
|
||||
// get_qrcode_status 的密钥)。时间戳由 logger 附加。
|
||||
a.log.Info("weixin_ilink: get_bot_qrcode ok", "url", out.QrcodeImgContent)
|
||||
//
|
||||
// 🔴 URL 一律走 trace.MaskQuery(M50 复审补扫):它是**上游给的**串,可能是带签名
|
||||
// 的图片地址,也可能整段是 `data:` 内联图 —— 原样落日志等于把二维码(扫码即绑定)
|
||||
// 抄进一个会被 tail、采集、粘进工单的面。MaskQuery 打码凭据类 query 值并保留路径,
|
||||
// 解析不出 host(data: URI、畸形串)时回空串而**不**回原串。
|
||||
a.log.Info("weixin_ilink: get_bot_qrcode ok", "url", trace.MaskQuery(out.QrcodeImgContent))
|
||||
return out, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// Adapter.LoginStatus 上报的登录状态取值。
|
||||
@@ -119,7 +121,10 @@ func (a *Adapter) StartLogin(ctx context.Context) (LoginQR, error) {
|
||||
// 无条件复用当前二维码加以保护。只有仍未被扫描、且已过那个极小复用窗口的
|
||||
// 二维码才会被重新生成,使显式的「刷新二维码」能拿到全新码。
|
||||
if sess.confirmingPhase() {
|
||||
a.log.Info("weixin_ilink: login in progress, reusing qrcode", "phase", sess.currentPhase())
|
||||
// phase 是**上游字段**(`get_qrcode_status` 的 status 原值经 setPhase 存下),
|
||||
// 因此进日志前过令牌守卫 —— 与 login.go 里那一行同一道(M50 复审:同一字段
|
||||
// 的第二个出口)。`confirmingPhase()` 的判定用的是原值,不受渲染口径影响。
|
||||
a.log.Info("weixin_ilink: login in progress, reusing qrcode", "phase", trace.ErrorToken(sess.currentPhase()))
|
||||
return LoginQR{Qrcode: sess.qrcode, Image: sess.image}, nil
|
||||
}
|
||||
// 码仍然新鲜或已被扫描时都返回同一个码——一律复用、绝不替换,使进行中的
|
||||
@@ -127,7 +132,7 @@ func (a *Adapter) StartLogin(ctx context.Context) (LoginQR, error) {
|
||||
// 用户扫码期间取消会话。只有真正过期(超过服务端 60s TTL)且从未被扫描的码
|
||||
// 才会重新生成。
|
||||
if time.Since(sess.startedAt) < 60*time.Second {
|
||||
a.log.Info("weixin_ilink: login in progress, reusing qrcode", "phase", sess.currentPhase())
|
||||
a.log.Info("weixin_ilink: login in progress, reusing qrcode", "phase", trace.ErrorToken(sess.currentPhase()))
|
||||
return LoginQR{Qrcode: sess.qrcode, Image: sess.image}, nil
|
||||
}
|
||||
// 码已过期(>60s)且从未被扫描:生成新码,并取消旧的那次(已过期、未扫描的)
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
package weixin_ilink
|
||||
|
||||
// 本文件钉住扫码登录期**上游字段进日志**的边界(M50 复审的第五个出口):
|
||||
//
|
||||
// - `get_qrcode_status` 的 `status` 与 `scaned_but_redirect` 的 `redirect_host` 此前
|
||||
// 原样写进 INFO —— 两个都是上游字段,此前不过 `trace.ErrorToken`、不过
|
||||
// `RedactText`、也没有长度上限。现在两者都过令牌守卫后才出镜。
|
||||
// - 🔴 **控制流仍用原值**:状态机读 `status.Status`、路由读 `status.RedirectHost`。
|
||||
// 这条比「日志干净」更容易被修坏 —— 一个图省事的修法是把守卫后的值喂给
|
||||
// `setPollBaseURL`,那会让带端口的合法重定向主机整体失效。
|
||||
//
|
||||
// 两条用例的变异方向各一:把守卫从日志里去掉 ⇒ 哨兵出现(红);把守卫**挪进**控制流
|
||||
// ⇒ 第二条用例的重定向落不到上游给的主机上(红)。
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// loginProse 是一段「像人话、不像协议令牌」的上游字段值:它若出现在日志里,就说明这一栏
|
||||
// 又是一个不受控的正文通道。
|
||||
const loginProse = "她刚才说的那句话"
|
||||
|
||||
// syncBuffer 让后台登录 goroutine 的日志写入与测试的读取不打架(-race 下也成立)。
|
||||
type syncBuffer struct {
|
||||
mu sync.Mutex
|
||||
b bytes.Buffer
|
||||
}
|
||||
|
||||
func (s *syncBuffer) Write(p []byte) (int, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.Write(p)
|
||||
}
|
||||
|
||||
func (s *syncBuffer) String() string {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.b.String()
|
||||
}
|
||||
|
||||
// newLoggingScriptedAdapter 与 newScriptedAdapter 相同,但把日志收进 buf 供断言。
|
||||
func newLoggingScriptedAdapter(t *testing.T, cfg Config, tr http.RoundTripper, buf *syncBuffer) *Adapter {
|
||||
t.Helper()
|
||||
ad, err := New(cfg, &http.Client{Transport: tr}, slog.New(slog.NewJSONHandler(buf, nil)))
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
return ad
|
||||
}
|
||||
|
||||
// TestStartLogin_ProseStatusNeverReachesLog status 喂散文 ⇒ 日志里那一栏是空串,
|
||||
// 哨兵一个字都搜不到;而控制流照旧(散文不匹配任何 case ⇒ 继续轮询,直到窗口结束)。
|
||||
func TestStartLogin_ProseStatusNeverReachesLog(t *testing.T) {
|
||||
t.Parallel()
|
||||
var buf syncBuffer
|
||||
tr := &scriptedTransport{
|
||||
qr: []byte(scriptedQR),
|
||||
statusFn: func(int) []byte { return []byte(`{"status":"` + loginProse + `"}`) },
|
||||
}
|
||||
ad := newLoggingScriptedAdapter(t, Config{
|
||||
BaseURL: scriptedBaseURL, LoginInterval: time.Millisecond, LoginTimeout: 300 * time.Millisecond,
|
||||
}, tr, &buf)
|
||||
|
||||
if _, err := ad.StartLogin(context.Background()); err != nil {
|
||||
t.Fatalf("StartLogin: %v", err)
|
||||
}
|
||||
waitFor(t, func() bool {
|
||||
s, _ := ad.LoginStatus(context.Background())
|
||||
return s == LoginStatusFailed
|
||||
})
|
||||
|
||||
line := buf.String()
|
||||
if line == "" {
|
||||
t.Fatal("扫码轮询一条日志都没有(静默即缺陷)")
|
||||
}
|
||||
if strings.Contains(line, loginProse) {
|
||||
t.Fatalf("上游 status 原文进了日志:%s", line)
|
||||
}
|
||||
// 守卫的实际效果:散文 ⇒ 空串(不是「截断」也不是「保留前几个字」)。
|
||||
if !strings.Contains(line, `"status":""`) {
|
||||
t.Fatalf("散文 status 没有收敛成空串(令牌守卫没生效?):%s", line)
|
||||
}
|
||||
// 控制流不受影响:散文不匹配任何 case ⇒ 一直轮询到窗口结束(≥2 次),而不是
|
||||
// 被当成某个阶段直接失败/确认。
|
||||
if n := len(tr.hosts()); n < 2 {
|
||||
t.Fatalf("status 轮询 %d 次, want >= 2(散文 status 不该改变控制流)", n)
|
||||
}
|
||||
if ad.IsConnected() {
|
||||
t.Fatal("散文 status 被当成了成功(控制流被渲染口径污染)")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartLogin_ProseRedirectHostNeverReachesLog redirect_host 喂散文 ⇒ 日志里没有它,
|
||||
// 而路由**照旧**切到上游给的那个主机(证明守卫只作用于渲染,没有混进控制流)。
|
||||
func TestStartLogin_ProseRedirectHostNeverReachesLog(t *testing.T) {
|
||||
t.Parallel()
|
||||
var buf syncBuffer
|
||||
tr := &scriptedTransport{
|
||||
qr: []byte(scriptedQR),
|
||||
statusFn: func(n int) []byte {
|
||||
if n == 1 {
|
||||
return []byte(`{"status":"scaned_but_redirect","redirect_host":"` + loginProse + `"}`)
|
||||
}
|
||||
return []byte(`{"status":"confirmed","bot_token":"tok-x","ilink_bot_id":"bot-x",` +
|
||||
`"ilink_user_id":"o-1","baseurl":"https://ilinkai.weixin.qq.com"}`)
|
||||
},
|
||||
}
|
||||
ad := newLoggingScriptedAdapter(t, Config{
|
||||
BaseURL: scriptedBaseURL, LoginInterval: time.Millisecond, LoginTimeout: 5 * time.Second,
|
||||
}, tr, &buf)
|
||||
|
||||
if _, err := ad.StartLogin(context.Background()); err != nil {
|
||||
t.Fatalf("StartLogin: %v", err)
|
||||
}
|
||||
waitFor(t, func() bool {
|
||||
s, _ := ad.LoginStatus(context.Background())
|
||||
return s == LoginStatusConfirmed
|
||||
})
|
||||
|
||||
line := buf.String()
|
||||
if strings.Contains(line, loginProse) {
|
||||
t.Fatalf("上游 redirect_host 原文进了日志:%s", line)
|
||||
}
|
||||
if !strings.Contains(line, `"host":""`) {
|
||||
t.Fatalf("散文 redirect_host 没有收敛成空串(令牌守卫没生效?):%s", line)
|
||||
}
|
||||
// 🔴 控制流仍用原值:第二次轮询必须落在上游给的那个主机上。
|
||||
hosts := tr.hosts()
|
||||
if len(hosts) < 2 {
|
||||
t.Fatalf("status 轮询 %d 次, want >= 2", len(hosts))
|
||||
}
|
||||
if hosts[1] != loginProse {
|
||||
t.Fatalf("第二次轮询的主机 = %q, want 上游给的 redirect_host 原值(控制流被守卫污染)", hosts[1])
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartLogin_ProsePhaseNeverReachesLog 同一个上游 status 还有**第二个日志出口**:
|
||||
// 复用二维码时那条 INFO 打的是 `sess.currentPhase()`(setPhase 存下的上游原值)。它现在
|
||||
// 过同一道令牌守卫。变异:把守卫从这一行去掉 ⇒ 本用例红。
|
||||
func TestStartLogin_ProsePhaseNeverReachesLog(t *testing.T) {
|
||||
t.Parallel()
|
||||
var buf syncBuffer
|
||||
tr := &scriptedTransport{
|
||||
qr: []byte(scriptedQR),
|
||||
statusFn: func(int) []byte { return []byte(`{"status":"` + loginProse + `"}`) },
|
||||
}
|
||||
ad := newLoggingScriptedAdapter(t, Config{
|
||||
BaseURL: scriptedBaseURL, LoginInterval: time.Millisecond, LoginTimeout: 300 * time.Millisecond,
|
||||
}, tr, &buf)
|
||||
|
||||
if _, err := ad.StartLogin(context.Background()); err != nil {
|
||||
t.Fatalf("StartLogin: %v", err)
|
||||
}
|
||||
// 等后台轮询把 phase 填成上游原值,再点第二次「扫码登录」走复用分支。
|
||||
waitFor(t, func() bool { return len(tr.hosts()) >= 1 })
|
||||
if _, err := ad.StartLogin(context.Background()); err != nil {
|
||||
t.Fatalf("StartLogin (reuse): %v", err)
|
||||
}
|
||||
waitFor(t, func() bool {
|
||||
s, _ := ad.LoginStatus(context.Background())
|
||||
return s == LoginStatusFailed
|
||||
})
|
||||
|
||||
line := buf.String()
|
||||
if strings.Contains(line, loginProse) {
|
||||
t.Fatalf("上游 status 经 currentPhase() 进了第二条日志:%s", line)
|
||||
}
|
||||
if !strings.Contains(line, `"phase":""`) {
|
||||
t.Fatalf("复用二维码那条 INFO 的 phase 没有过令牌守卫:%s", line)
|
||||
}
|
||||
// 控制流不受影响:散文 phase 不满足 confirmingPhase,复用走的是「码仍新鲜」那一支,
|
||||
// 返回的仍是同一个码。
|
||||
if qr := ad.loginSession; qr != nil && qr.qrcode != "qr-r" {
|
||||
t.Fatalf("复用分支返回的 qrcode = %q, want qr-r", qr.qrcode)
|
||||
}
|
||||
}
|
||||
|
||||
// TestStartLogin_QrcodeURLLogIsMasked get_bot_qrcode 的 `qrcode_img_content` 也是
|
||||
// **上游给的串**(可能是带签名的图片地址,也可能整段是 data: 内联图)。它进日志前走
|
||||
// trace.MaskQuery:凭据类 query 值打码、路径保留;解析不出 host 时回空串(data: URI
|
||||
// 就是这么被整体挡掉的)。变异:改回原串 ⇒ 本用例立刻红。
|
||||
func TestStartLogin_QrcodeURLLogIsMasked(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sig = "SIG-SECRET-123"
|
||||
var buf syncBuffer
|
||||
tr := &scriptedTransport{
|
||||
qr: []byte(`{"qrcode":"qr-1","qrcode_img_content":"https://img.example/qr.png?sig=` + sig + `&size=200"}`),
|
||||
statusFn: func(int) []byte {
|
||||
return []byte(`{"status":"confirmed","bot_token":"tok-x","ilink_bot_id":"bot-x","ilink_user_id":"o-1"}`)
|
||||
},
|
||||
}
|
||||
ad := newLoggingScriptedAdapter(t, Config{
|
||||
BaseURL: scriptedBaseURL, LoginInterval: time.Millisecond, LoginTimeout: 5 * time.Second,
|
||||
}, tr, &buf)
|
||||
|
||||
if _, err := ad.StartLogin(context.Background()); err != nil {
|
||||
t.Fatalf("StartLogin: %v", err)
|
||||
}
|
||||
waitFor(t, func() bool {
|
||||
s, _ := ad.LoginStatus(context.Background())
|
||||
return s == LoginStatusConfirmed
|
||||
})
|
||||
|
||||
line := buf.String()
|
||||
if strings.Contains(line, sig) {
|
||||
t.Fatalf("二维码图片地址的签名参数原样进了日志:%s", line)
|
||||
}
|
||||
if !strings.Contains(line, "https://img.example/qr.png") || !strings.Contains(line, "sig=***") {
|
||||
t.Fatalf("打码后把可读的路径也丢了(诊断面):%s", line)
|
||||
}
|
||||
}
|
||||
@@ -54,8 +54,6 @@ const (
|
||||
// uploadMaxAttempts 是 CDN 上传的最大尝试次数(官方 cdn-upload.ts:7 的
|
||||
// UPLOAD_MAX_RETRIES=3,无退避重试)。
|
||||
uploadMaxAttempts = 3
|
||||
// uploadErrMaxChars 是进日志/错误的服务端错误说明的字符上限。
|
||||
uploadErrMaxChars = 200
|
||||
|
||||
// encryptTypePacked 是 CDNMedia.encrypt_type 的取值:1 = 打包了缩略图/中图等信息
|
||||
// (官方 src/api/types.ts:95 的注释)。官方出站三种媒体都固定填 1
|
||||
@@ -199,7 +197,8 @@ func (a *Adapter) uploadURLFromParam(param, fileKey string) string {
|
||||
// - `src/cdn/cdn-upload.ts:61`:下载凭据在**响应头 `x-encrypted-param`** 里,拿到后
|
||||
// 填进 item 的 `media.encrypt_query_param`(`src/cdn/upload.ts:17` 的注释写明);
|
||||
// 响应体本身不是凭据来源 —— 这正是旧实现「PUT 上去就当成功」丢掉的那一环;
|
||||
// - `src/cdn/cdn-upload.ts:40-83`:4xx 立即放弃(附服务端 `x-error-message`),
|
||||
// - `src/cdn/cdn-upload.ts:40-83`:4xx 立即放弃(官方附服务端 `x-error-message`;
|
||||
// 本项目**不把它拼进错误** —— 上游自由文本面一律默认不带,见 uploadOnce),
|
||||
// 其余失败最多重试 3 次(无退避);
|
||||
// - `src/cdn/cdn-upload.ts:62-65`:200 但没有该响应头同样是失败(不得当成成功)。
|
||||
//
|
||||
@@ -243,10 +242,12 @@ func (a *Adapter) uploadOnce(ctx context.Context, uploadURL string, data []byte)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
|
||||
// 服务端把原因放在 x-error-message 头里(官方 cdn-upload.ts:48);它是对我们
|
||||
// 这次请求的说明,不是凭据,可以进错误与日志(截断,避免服务端回显灌爆日志)。
|
||||
return "", false, fmt.Errorf("weixin_ilink: upload media: status %d: %s",
|
||||
resp.StatusCode, truncateForLog(resp.Header.Get("x-error-message"), uploadErrMaxChars))
|
||||
// 服务端把原因放在 x-error-message 头里(官方 cdn-upload.ts:48)。它是**上游自由
|
||||
// 文本面**(与信封 message / Bot API description / OneBot msg 同族),因此
|
||||
// **默认不进**错误与日志(M50 口径):上游可以在里面回显我们上传的东西,而同一道
|
||||
// 边界在别处才刚收紧过。status 已经足以分类(4xx = 请求本身不对,立即放弃),
|
||||
// 所以这里只留 status。
|
||||
return "", false, fmt.Errorf("weixin_ilink: upload media: status %d", resp.StatusCode)
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", true, fmt.Errorf("weixin_ilink: upload media: status %d", resp.StatusCode)
|
||||
@@ -316,17 +317,6 @@ func encodeMediaAesKey(key []byte) string {
|
||||
return base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(key)))
|
||||
}
|
||||
|
||||
// truncateForLog 按 rune 截断一段外来文本,用于把服务端的错误说明放进日志/错误而不
|
||||
// 让它撑爆日志行。它只被喂给「服务端对我们这次请求的说明」,不是凭据。
|
||||
func truncateForLog(s string, max int) string {
|
||||
trimmed := strings.TrimSpace(s)
|
||||
runes := []rune(trimmed)
|
||||
if len(runes) <= max {
|
||||
return trimmed
|
||||
}
|
||||
return string(runes[:max]) + "…"
|
||||
}
|
||||
|
||||
// uploadMediaTypeFor 把归一化的 MediaKind 映射到 getuploadurl 的 media_type 码。
|
||||
func uploadMediaTypeFor(kind adapter.MediaKind) int {
|
||||
switch kind {
|
||||
|
||||
@@ -264,14 +264,16 @@ func TestOutboundMedia_UploadWithoutParamHeaderIsHonest(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestOutboundMedia_UploadClientErrorIsNotRetried 覆盖 ④-b:4xx 是客户端错误,重试徒劳
|
||||
// (官方 cdn-upload.ts:47-52 立即抛出),且服务端的 `x-error-message` 必须进错误信息 ——
|
||||
// 失败要可诊断。
|
||||
// (官方 cdn-upload.ts:47-52 立即抛出)。且服务端的 `x-error-message` **不进错误**
|
||||
// (M50 口径:它是上游自由文本面,与信封 message / Bot API description / OneBot msg
|
||||
// 同族;4xx 这个 status 已足够分类)—— 变异:把它拼回错误 ⇒ 本用例后半段立刻红。
|
||||
func TestOutboundMedia_UploadClientErrorIsNotRetried(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sentinel = "invalid content: 她刚才说的那句话"
|
||||
s := newUploadCaptureServer(t, handlerResult{
|
||||
status: http.StatusBadRequest,
|
||||
body: []byte("ignored"),
|
||||
headers: map[string]string{"x-error-message": "bad filekey"},
|
||||
headers: map[string]string{"x-error-message": sentinel},
|
||||
})
|
||||
ad := newConnectedAdapter(t, Config{BaseURL: s.srv.URL, CDNBaseURL: s.srv.URL, BotToken: "tok"}, s.srv)
|
||||
ad.recordInbound("tok-1", adapter.UnifiedMessage{SenderID: "u-1", Timestamp: ad.clock()})
|
||||
@@ -285,8 +287,11 @@ func TestOutboundMedia_UploadClientErrorIsNotRetried(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("4xx 上传失败却报成功")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "bad filekey") {
|
||||
t.Fatalf("错误里没有服务端说明:%v", err)
|
||||
if strings.Contains(err.Error(), "她刚才说的那句话") {
|
||||
t.Fatalf("服务端的 x-error-message 进了错误:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "status 400") {
|
||||
t.Fatalf("剥掉服务端说明时把 status 一起丢了:%v", err)
|
||||
}
|
||||
if s.attempts != 1 {
|
||||
t.Fatalf("4xx 被重试了:上传尝试 %d 次, want 1", s.attempts)
|
||||
|
||||
Reference in new issue
Block a user