diff --git a/internal/channel/adapter/httpclient/client.go b/internal/channel/adapter/httpclient/client.go index 1e14d50..392e067 100644 --- a/internal/channel/adapter/httpclient/client.go +++ b/internal/channel/adapter/httpclient/client.go @@ -33,11 +33,6 @@ var ErrAPI = errors.New("httpclient: api error") // maxBodyBytes caps how large a response body the client will read. const maxBodyBytes = 1 << 20 // 1 MiB -// maxEnvelopeMessageRunes caps the envelope `message` field once it enters an -// error. It is upstream free text: whatever was rejected may be echoed there, so -// it is cleaned and bounded rather than passed through at the upstream's length. -const maxEnvelopeMessageRunes = 200 - // Client is a token-auth JSON HTTP client bound to a base URL. type Client struct { http *http.Client @@ -208,15 +203,11 @@ func apiFailure(method, host string, resp *http.Response, raw []byte) error { return fmt.Errorf("httpclient: %s: %w: %w", method, upstream, ErrAPI) } -// envelopeMessage 是信封 message 进入错误前的唯一处理:压平空白、清洗凭据形状,再按 -// rune 截断。message 是上游自由文本面,被拒的输入常被回显在这里。 +// envelopeMessage 是信封 message 进入错误前的唯一处理:压平空白,再交给 +// trace.RedactText —— 它既清洗凭据形状,也把长度压到 80 rune(超出的带省略号)。 +// 上游常把被拒的输入回显在 message 里,因此这一层不是可选的。 func envelopeMessage(s string) string { - flat := strings.Join(strings.Fields(s), " ") - flat = trace.RedactText(flat) - if r := []rune(flat); len(r) > maxEnvelopeMessageRunes { - return string(r[:maxEnvelopeMessageRunes]) + "…" - } - return flat + return trace.RedactText(strings.Join(strings.Fields(s), " ")) } // transportCause 剥掉 net/http 的 *url.Error 外壳:它会把**完整请求地址**拼进错误串 diff --git a/internal/channel/adapter/httpclient/leak_test.go b/internal/channel/adapter/httpclient/leak_test.go index ef13b9b..6b9760e 100644 --- a/internal/channel/adapter/httpclient/leak_test.go +++ b/internal/channel/adapter/httpclient/leak_test.go @@ -145,3 +145,28 @@ func TestGetJSON_UserinfoNeverEntersError(t *testing.T) { t.Fatalf("user:pass@ 进了错误:%v", err) } } + +// 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) + } +} diff --git a/plugins/channels/qq_obv11/ws_client.go b/plugins/channels/qq_obv11/ws_client.go index 1ca5444..79fddef 100644 --- a/plugins/channels/qq_obv11/ws_client.go +++ b/plugins/channels/qq_obv11/ws_client.go @@ -14,6 +14,8 @@ import ( "fmt" "net/url" "strings" + + "git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace" ) // errClientConfig 是 client 模式配置缺失(remote_url 为空)的错误哨兵:重试治不好 @@ -61,11 +63,11 @@ func (a *Adapter) connectClient(ctx context.Context) error { return fmt.Errorf("qq-obv11: dial onebot ws %s: %w", a.cfg.RemoteURL, cerr) } a.setConn(conn) - // remote_url 按 OneBot 惯例可以直接写着 `?access_token=…`,原样 INFO 就是把凭据 - // 写进日志。这里复用同包已有的第二层脱敏(connect_outcome.go 的 - // maskAccessTokenQuery)——不另写一套,也不用 sanitizeConnectReason 的 80 rune - // 上限,否则地址的路径会被切掉、失去「连到了哪」的诊断价值。 - a.log.Info("connected to onebot ws (client mode)", "url", maskAccessTokenQuery(a.cfg.RemoteURL)) + // remote_url 按 OneBot 惯例可以直接写着 `?access_token=…`,也可能是把凭据塞进 + // `user:pass@` 或别的键名(`token` / `api_key` / 签名参数)。原样 INFO 就是把凭据 + // 写进日志,因此只打 trace.MaskQuery 的形态:凭据类 query/fragment 值与 userinfo + // 一律打码,路径原样保留(「连到了哪个端点」是这条 INFO 的全部诊断价值)。 + a.log.Info("connected to onebot ws (client mode)", "url", trace.MaskQuery(a.cfg.RemoteURL)) return nil } diff --git a/plugins/channels/qq_obv11/ws_client_log_test.go b/plugins/channels/qq_obv11/ws_client_log_test.go index 7a7e783..413ecc7 100644 --- a/plugins/channels/qq_obv11/ws_client_log_test.go +++ b/plugins/channels/qq_obv11/ws_client_log_test.go @@ -1,8 +1,13 @@ package qq_obv11 -// 本文件钉住 ws+client 连接成功那条 INFO 的出镜边界(M41 #15): -// remote_url 按 OneBot 惯例可以直接写着 `?access_token=…`,原样 INFO 就是把凭据写进 -// 日志。同包 connect_outcome.go 早就有三层脱敏,这里钉的是「连接成功路径也走它」。 +// 本文件钉住 ws+client 连接成功那条 INFO 的出镜边界(M41 #15):remote_url 可以带 +// 凭据 —— OneBot 惯例是 `?access_token=`,但真实配置里也见过 `?token=`、`?api_key=`、 +// 签名参数,以及 `user:pass@`。原样 INFO 就是把凭据写进日志。 +// +// 打码走 trace.MaskQuery(同包 maskAccessTokenQuery 只认 access_token 一个键名,复审 +// 形态矩阵里 `access%5Ftoken` / `token` / `api_key` / 签名 / userinfo 五种形态都不认)。 +// 这条 INFO 的全部诊断价值是「连到了哪个端点」,因此路径必须原样可读 —— 每个用例都 +// 反向断言这一点。 import ( "context" @@ -12,12 +17,10 @@ import ( "testing" ) -// TestConnectClientInfoLogMasksAccessToken 远端 URL 带 access_token 时,成功日志里 -// 不得出现 token 明文;把脱敏改回原样传参就变红。 -func TestConnectClientInfoLogMasksAccessToken(t *testing.T) { - t.Parallel() - - const secret = "ONEBOT-ACCESS-TOKEN-SECRET" +// wsServerForLogTest 起一个只说「握手 + 保持连接」的假 OneBot 服务端。它不解析路径与 +// 查询串,因此下面每条形态都能连得上,测的纯粹是日志字段。 +func wsServerForLogTest(t *testing.T) *httptest.Server { + t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := upgradeWS(w, r) if err != nil { @@ -30,25 +33,119 @@ func TestConnectClientInfoLogMasksAccessToken(t *testing.T) { } } })) - defer srv.Close() + t.Cleanup(srv.Close) + return srv +} - remote := "ws://" + strings.TrimPrefix(srv.URL, "http://") + "/?access_token=" + secret +// connectAndLog 用给定的远端 URL 连一次,返回这段时间的全部日志文本。 +func connectAndLog(t *testing.T, remote string) string { + t.Helper() logs, logger := logCaptureSync() a := NewAdapter(Config{Mode: "client", RemoteURL: remote}, WithLogger(logger)) if err := a.Connect(context.Background()); err != nil { - t.Fatalf("Connect: %v", err) + t.Fatalf("Connect(%q): %v", remote, err) } - defer func() { _ = a.Disconnect(context.Background()) }() - + t.Cleanup(func() { _ = a.Disconnect(context.Background()) }) logged := logs.text() if !strings.Contains(logged, "connected to onebot ws") { t.Fatalf("没有连接成功日志,测试没覆盖到目标路径:\n%s", logged) } - if strings.Contains(logged, secret) { - t.Fatalf("access_token 明文进了 INFO 日志:\n%s", logged) + return logged +} + +// TestConnectClientInfoLogMasksCredentials 是「凭据形态 × 打码」的矩阵:每种形态都要求 +// 凭据搜不到、打码标记在场、路径仍可读。 +func TestConnectClientInfoLogMasksCredentials(t *testing.T) { + srv := wsServerForLogTest(t) + hostport := strings.TrimPrefix(srv.URL, "http://") + const secret = "SECRET-VALUE-1234" + const path = "/onebot/v11/ws" + + cases := []struct { + name string + url string + // leaked 是**不得出现**的子串(明文凭据的形态)。 + leaked string + // masked 是**必须出现**的打码结果片段,兼作「这条日志确实带了该字段」的反向断言。 + masked string + }{ + { + name: "access_token_query", + url: "ws://" + hostport + path + "?access_token=" + secret, + leaked: secret, + masked: "?access_token=***", + }, + { + name: "access_token_after_other_query", + url: "ws://" + hostport + path + "?compress=0&access_token=" + secret, + leaked: secret, + masked: "&access_token=***", + }, + { + name: "percent_encoded_key", + url: "ws://" + hostport + path + "?access%5Ftoken=" + secret, + leaked: secret, + masked: "?access%5Ftoken=***", + }, + { + name: "generic_token_key", + url: "ws://" + hostport + path + "?token=" + secret, + leaked: secret, + masked: "?token=***", + }, + { + name: "api_key_key", + url: "ws://" + hostport + path + "?api_key=" + secret, + leaked: secret, + masked: "?api_key=***", + }, + { + name: "signature_key", + url: "ws://" + hostport + path + "?X-Signature=" + secret, + leaked: secret, + masked: "?X-Signature=***", + }, + { + name: "fragment_token", + url: "ws://" + hostport + path + "#access_token=" + secret, + leaked: secret, + masked: "#access_token=***", + }, + { + name: "userinfo", + url: "ws://apiuser:" + secret + "@" + hostport + path, + leaked: secret, + masked: "ws://[redacted]@" + hostport + path, + }, } - // 反向断言:确实打了脱敏占位符,而不是「这条日志压根没带 url 字段」。 - if !strings.Contains(logged, "access_token="+maskedCredential) { - t.Fatalf("日志里既没有明文也没有脱敏占位符,脱敏可能被绕过了:\n%s", logged) + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + logged := connectAndLog(t, tc.url) + t.Logf("before=%q after=%s", tc.url, urlField(logged)) + if strings.Contains(logged, tc.leaked) { + t.Fatalf("凭据明文进了 INFO 日志:\n%s", logged) + } + if !strings.Contains(logged, tc.masked) { + t.Fatalf("日志里没有打码结果 %q:\n%s", tc.masked, logged) + } + // 反向断言:路径必须还在 —— 否则「连到了哪个端点」这条诊断就没了。 + if !strings.Contains(logged, path) { + t.Fatalf("日志丢了路径 %q:\n%s", path, logged) + } + }) } } + +// urlField 摘出日志里 `url=…` 字段的值(渲染后可能带引号),只用于测试输出。 +func urlField(logged string) string { + for _, line := range strings.Split(logged, "\n") { + if !strings.Contains(line, "connected to onebot ws") { + continue + } + if i := strings.Index(line, " url="); i >= 0 { + return line[i+1:] + } + } + return "" +} diff --git a/plugins/channels/telegram/botapi.go b/plugins/channels/telegram/botapi.go index 2774b43..caeacf1 100644 --- a/plugins/channels/telegram/botapi.go +++ b/plugins/channels/telegram/botapi.go @@ -24,14 +24,8 @@ type botResponse struct { ErrorCode int `json:"error_code"` } -const ( - // maxErrorBodyBytes caps how much of a non-200 reply is read before classifying it. - maxErrorBodyBytes = 512 - // maxDescriptionRunes caps the description once it enters an error. Telegram's - // description is upstream free text (it can echo the parameter we sent), so it - // is cleaned and bounded instead of being passed through verbatim. - maxDescriptionRunes = 200 -) +// maxErrorBodyBytes caps how much of a non-200 reply is read before classifying it. +const maxErrorBodyBytes = 512 // doJSON posts a JSON payload to a Bot API method and decodes the envelope. The // caller is responsible for decoding Result; a non-OK reply is returned as @@ -45,7 +39,10 @@ func (a *Adapter) doJSON(ctx context.Context, method string, payload any) (*botR } req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.endpoint(method), &buf) if err != nil { - return nil, fmt.Errorf("telegram: build %s request: %w", method, err) + // 解析失败的 err 同样是 *url.Error(里面是整条 /bot/… 地址),因此与 + // 下面的传输层分支同形处理:只留来源,地址由 callCause 剥掉。 + return nil, fmt.Errorf("telegram: build %s request %s: %w", + method, trace.HostOf(a.endpoint(method)), callCause(err)) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept", "application/json") @@ -234,15 +231,10 @@ func badResponseError(method string, status int, body []byte) error { return fmt.Errorf("%s: %w", strings.Join(parts, ": "), ErrBadResponse) } -// boundedDescription 是 Bot API description 进入错误前的唯一处理:压平空白、清洗 -// 凭据形状,再按 rune 截断(宁可丢细节,不可把一段回显整段带出来)。 +// boundedDescription 是 Bot API description 进入错误前的唯一处理:压平空白,再交给 +// trace.RedactText —— 它既清洗凭据形状,也把长度压到 80 rune(超出的带省略号)。 func boundedDescription(s string) string { - flat := strings.Join(strings.Fields(s), " ") - flat = trace.RedactText(flat) - if r := []rune(flat); len(r) > maxDescriptionRunes { - return string(r[:maxDescriptionRunes]) + "…" - } - return flat + return trace.RedactText(strings.Join(strings.Fields(s), " ")) } // callCause 剥掉 net/http 的 *url.Error 外壳:它会把完整地址拼进错误串,而 Bot API diff --git a/plugins/channels/telegram/botapi_leak_test.go b/plugins/channels/telegram/botapi_leak_test.go index 0e6844b..0ae7033 100644 --- a/plugins/channels/telegram/botapi_leak_test.go +++ b/plugins/channels/telegram/botapi_leak_test.go @@ -101,3 +101,54 @@ func TestDoJSON_TransportErrorOmitsBotToken(t *testing.T) { t.Fatalf("剥掉地址时把来源或原因一起丢了:%v", err) } } + +// TestDoJSON_BuildErrorOmitsBotToken 请求**构造**失败也是同一族:地址解析失败的 +// err 同样是 *url.Error,里面就是整条 /bot/… 地址,而 poll.go 会原样落日志。 +// 与传输层分支同形:只留来源,原因保留。 +func TestDoJSON_BuildErrorOmitsBotToken(t *testing.T) { + t.Parallel() + const token = "424242:PROBE-BUILD-TOKEN" + a := New( + Config{BotToken: token}, + // 控制字符让 url.Parse 失败 —— 这是「构造请求」分支唯一现实的触发方式。 + WithBaseURL("http://api.example.com/\x7f"), + WithLogger(discardLogger()), + ) + + _, err := a.doJSON(context.Background(), "getUpdates", nil) + if err == nil { + t.Fatal("构造失败却报成功") + } + if strings.Contains(err.Error(), token) { + t.Fatalf("bot token 随地址进了错误(会随 long poll failed 落日志):%v", err) + } + if !strings.Contains(err.Error(), "build getUpdates request") { + t.Fatalf("错误没说是哪个方法的构造失败:%v", err) + } + if !strings.Contains(err.Error(), "net/url") && !strings.Contains(err.Error(), "invalid") { + t.Fatalf("剥掉地址时把原因一起丢了:%v", err) + } +} + +// TestDoJSON_DescriptionIsBoundedByRedactText 钉住长度口径:description 只有一道 +// 清洗(trace.RedactText,80 rune + 省略号)。本片曾按 200 rune 自己再截一刀,那层 +// 永远命中不了 —— 这条用例让「到底哪一层在截」变成可断言的事实。 +func TestDoJSON_DescriptionIsBoundedByRedactText(t *testing.T) { + t.Parallel() + long := strings.Repeat("a", 300) + 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":"` + long + `"}`)) + })) + + _, err := a.doJSON(context.Background(), "getMe", nil) + 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(), strings.Repeat("a", 81)) { + t.Fatalf("description 超过了 80 rune 上限:%v", err) + } +}