fix(httpclient): 信封 message 默认不进错误,渠道上游自由文本一并收口
信封路径(非 2xx + 信封体、2xx + code!=0)此前把上游 message 经 RedactText 拼进 error,而上游会在 message 里回显被拒的请求正文 —— 她的原话因此进了错误 与调用方日志(M49 探针实测:code 1: invalid content: 她刚才说的那句话 ...)。 - envelope message 改为**默认不带**(新 opt-in WithEnvelopeMessage(),与 trace.UpstreamError 的 message 同一口径);code 与上游 status 保留, errors.Is 的 ErrAPI / trace.ErrUpstream 链不变。 - opt-in 下统一走单一清洗 upstreamText:压平空白 + trace.RedactTextLimited, 上限 40 rune(比 trace 的 128 短:错误里那句话是提示,不是摘要)。 - plugins/channels 同族出口一并收口(扫过全部,命中 4 处): telegram description、qq_obv11 msg(错误 + logEchoFailure 日志)、 weixin_ilink CDN x-error-message;qq 的 status 字段改走 trace.ErrorToken 令牌守卫。被剥掉的一律由 status / error_code / retcode 承担分类。 每条新增/改写用例都做过变异验证(把字段拼回去即变红)。
This commit is contained in:
1 parent
3a0cc64160
commit
996201c4ed
11 files changed
+432
-127
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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