Merge branch 'feat/m42-logchannel-channel-and-tool-url-plus' into dev
This commit is contained in:
commit
f37fe05aee
11 files changed
+885
-30
No files matched your search
@@ -23,6 +23,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// ErrAPI is the sentinel returned when the remote API reports a non-zero code or
|
||||
@@ -129,7 +130,13 @@ func (c *Client) resolve(path string) string {
|
||||
}
|
||||
|
||||
// do performs the request, injecting auth and decoding the envelope.
|
||||
//
|
||||
// 地址在这一层只以来源形态出镜:target 由调用方给(GetJSON 的 query 可能带凭据、
|
||||
// 绝对 path 可能带 user:pass@),完整串既不进错误也不进日志。响应体原文同理 ——
|
||||
// 上游可能把被拒的输入回显在体里,因此 4xx/5xx 只收敛成状态码 + 信封的
|
||||
// code/message(清洗并截断),其余字节一概不留。
|
||||
func (c *Client) do(ctx context.Context, method, target string, body any) (json.RawMessage, error) {
|
||||
host := trace.HostOf(target)
|
||||
var buf bytes.Buffer
|
||||
if body != nil {
|
||||
if err := json.NewEncoder(&buf).Encode(body); err != nil {
|
||||
@@ -138,7 +145,7 @@ func (c *Client) do(ctx context.Context, method, target string, body any) (json.
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, target, &buf)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("httpclient: build %s %s request: %w", method, target, err)
|
||||
return nil, fmt.Errorf("httpclient: build %s %s request: %w", method, host, transportCause(err))
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
@@ -152,16 +159,16 @@ func (c *Client) do(ctx context.Context, method, target string, body any) (json.
|
||||
|
||||
resp, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("httpclient: %s %s: %w", method, target, err)
|
||||
return nil, fmt.Errorf("httpclient: %s %s: %w", method, host, transportCause(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(resp.Body, maxBodyBytes))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("httpclient: read %s %s response: %w", method, target, err)
|
||||
return nil, fmt.Errorf("httpclient: read %s %s response: %w", method, host, transportCause(err))
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("httpclient: %s %s: status %d: %s: %w", method, target, resp.StatusCode, truncate(raw), ErrAPI)
|
||||
return nil, apiFailure(method, host, resp, raw)
|
||||
}
|
||||
|
||||
var envelope APIEnvelope
|
||||
@@ -169,15 +176,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, target, envelope.Code, envelope.Message, ErrAPI)
|
||||
return nil, fmt.Errorf("httpclient: %s %s: code %d: %s: %w",
|
||||
method, host, envelope.Code, envelopeMessage(envelope.Message), ErrAPI)
|
||||
}
|
||||
return envelope.Data, nil
|
||||
}
|
||||
|
||||
// truncate caps a byte slice to 512 bytes for inclusion in an error message.
|
||||
func truncate(b []byte) string {
|
||||
if len(b) > 512 {
|
||||
return strings.TrimSpace(string(b[:512])) + "…"
|
||||
// apiFailure 把一次非 2xx 响应收敛成一条不携带响应体原文的错误:来源主机 + 状态码,
|
||||
// 外加(当体确实是 `{code,message}` 信封时)清洗并截断过的 code/message。其余字节只
|
||||
// 经 trace.UpstreamError 留下体积与 sha256 前缀,供「是不是同一份报文」这类相关性判断。
|
||||
func 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)
|
||||
switch {
|
||||
case envelope.Code != 0 && message != "":
|
||||
return fmt.Errorf("httpclient: %s %s: code %d: %s: %w: %w",
|
||||
method, host, envelope.Code, message, 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)
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(string(b))
|
||||
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), " "))
|
||||
}
|
||||
|
||||
// transportCause 剥掉 net/http 的 *url.Error 外壳:它会把**完整请求地址**拼进错误串
|
||||
// (query 里的凭据、user:pass@ 都会跟着走)。剥壳保留内层哨兵链
|
||||
// (context.DeadlineExceeded 等仍可 errors.Is),因此只丢地址、不丢原因。
|
||||
// 与 internal/channel/mediafetch 的 sanitizeErr 同一口径 —— 那份未导出,且服务于入站
|
||||
// 取回路径,本包不能反向依赖它。
|
||||
func transportCause(err error) error {
|
||||
var uerr *url.Error
|
||||
if errors.As(err, &uerr) && uerr.Err != nil {
|
||||
return uerr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package httpclient
|
||||
|
||||
// 本文件钉住本客户端的两条出镜边界(M41 #10/#11 那一族):
|
||||
//
|
||||
// - **非 2xx 的响应体原文不进错误**:旧实现把体截到 512B 拼进 error,而调用方
|
||||
// (KOOK 适配器)会把这条 error 直接落日志 —— 上游在体里回显什么,日志里就有
|
||||
// 什么。现在只留状态码、来源主机,以及信封的 code/message(已清洗、已截断)。
|
||||
// - **请求地址的凭据不进错误**:target 可能带 `?access_token=…` 或 `user:pass@`,
|
||||
// 而 net/http 的 *url.Error 会把整条地址拼进错误串。
|
||||
//
|
||||
// 每条用例都是「把它改回去就变红」的形状:断言的是**错误文本**,也就是调用方实际
|
||||
// 打进日志的那段字符串。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// failingTransport 让 http.Client.Do 以传输层错误收场。选定它而不是拨一个真端口,
|
||||
// 是因为只有传输层失败才会让 net/http 包出 **带完整地址** 的 *url.Error ——
|
||||
// 那正是要钉住的泄漏形态。
|
||||
type failingTransport struct{}
|
||||
|
||||
func (failingTransport) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
return nil, errors.New("dial tcp: connection refused")
|
||||
}
|
||||
|
||||
// TestDoJSON_StatusErrorDoesNotEchoBodySentinel 4xx 体里放哨兵 ⇒ 错误里搜不到。
|
||||
//
|
||||
// 用非信封体(代理返回的 HTML 错误页就是这样):信封类的体按设计会保留
|
||||
// code/message,非信封体则一个字节都不留。
|
||||
func TestDoJSON_StatusErrorDoesNotEchoBodySentinel(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sentinel = "SENTINEL-4XX-BODY"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadGateway)
|
||||
_, _ = w.Write([]byte("<html><body>bad gateway " + sentinel + "</body></html>"))
|
||||
}))
|
||||
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{"a": 1})
|
||||
if err == nil {
|
||||
t.Fatal("502 却报成功")
|
||||
}
|
||||
if !errors.Is(err, ErrAPI) {
|
||||
t.Fatalf("err = %v, want ErrAPI", err)
|
||||
}
|
||||
if strings.Contains(err.Error(), sentinel) {
|
||||
t.Fatalf("响应体原文进了错误(会随调用方落日志):%v", err)
|
||||
}
|
||||
// 可诊断性不能一起丢:来源主机与状态码必须还在,且带得出「体有多大」。
|
||||
host, _, ok := strings.Cut(strings.TrimPrefix(srv.URL, "http://"), ":")
|
||||
if !ok || !strings.Contains(err.Error(), host) {
|
||||
t.Fatalf("错误里没有来源主机 %q:%v", host, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "status=502") {
|
||||
t.Fatalf("错误里没有状态码:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "body_bytes=") {
|
||||
t.Fatalf("错误里没有响应体体积(相关性判断要用):%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_StatusErrorKeepsEnvelopeCode 信封体仍要给出 code/message:这是本客户端
|
||||
// 唯一认识的诊断面,替换掉体原文之后不能连它一起丢。
|
||||
func TestDoJSON_StatusErrorKeepsEnvelopeCode(t *testing.T) {
|
||||
t.Parallel()
|
||||
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}`))
|
||||
}))
|
||||
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(), "code 40101") || !strings.Contains(err.Error(), "invalid token") {
|
||||
t.Fatalf("信封的 code/message 丢了:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_NonZeroCodeRedactsMessageSecrets 信封 message 是上游自由文本面:里面的
|
||||
// 凭据形状必须被清洗掉,长度必须被截断。改回原样透传就变红。
|
||||
func TestDoJSON_NonZeroCodeRedactsMessageSecrets(t *testing.T) {
|
||||
t.Parallel()
|
||||
const secret = "big-secret-value-123456"
|
||||
body := `{"code":40101,"message":"invalid 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))
|
||||
_, 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)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetJSON_TransportErrorOmitsTargetCredentials 传输层失败时,错误里不得出现目标
|
||||
// 地址(含 query 里的凭据)—— net/http 会把整条 URL 放在 *url.Error 里。
|
||||
func TestGetJSON_TransportErrorOmitsTargetCredentials(t *testing.T) {
|
||||
t.Parallel()
|
||||
const secret = "QUERY-SECRET-VALUE"
|
||||
c := New(
|
||||
WithBaseURL("http://api.example.com"),
|
||||
WithHTTPClient(&http.Client{Transport: failingTransport{}}),
|
||||
WithLogger(discardLogger()),
|
||||
)
|
||||
_, err := c.GetJSON(context.Background(), "/gateway/index", url.Values{"access_token": {secret}})
|
||||
if err == nil {
|
||||
t.Fatal("传输层失败却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("目标地址的凭据进了错误:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "api.example.com") || !strings.Contains(err.Error(), "connection refused") {
|
||||
t.Fatalf("剥掉地址时把来源或原因一起丢了:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGetJSON_UserinfoNeverEntersError 绝对地址带 user:pass@ 时同样不得出镜。
|
||||
func TestGetJSON_UserinfoNeverEntersError(t *testing.T) {
|
||||
t.Parallel()
|
||||
c := New(
|
||||
WithHTTPClient(&http.Client{Transport: failingTransport{}}),
|
||||
WithLogger(discardLogger()),
|
||||
)
|
||||
_, err := c.GetJSON(context.Background(), "https://user:pass@api.example.com/x", nil)
|
||||
if err == nil {
|
||||
t.Fatal("传输层失败却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), "user:pass") {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,8 @@ import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// errClientConfig 是 client 模式配置缺失(remote_url 为空)的错误哨兵:重试治不好
|
||||
@@ -61,7 +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)
|
||||
a.log.Info("connected to onebot ws (client mode)", "url", 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
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
package qq_obv11
|
||||
|
||||
// 本文件钉住 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"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 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 {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
for {
|
||||
if _, _, err := conn.ReadMessage(); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv
|
||||
}
|
||||
|
||||
// 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(%q): %v", remote, err)
|
||||
}
|
||||
t.Cleanup(func() { _ = a.Disconnect(context.Background()) })
|
||||
logged := logs.text()
|
||||
if !strings.Contains(logged, "connected to onebot ws") {
|
||||
t.Fatalf("没有连接成功日志,测试没覆盖到目标路径:\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,
|
||||
},
|
||||
}
|
||||
|
||||
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 ""
|
||||
}
|
||||
@@ -4,11 +4,15 @@ import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// botResponse is the shared envelope Telegram returns for every method: ok plus
|
||||
@@ -20,6 +24,9 @@ type botResponse struct {
|
||||
ErrorCode int `json:"error_code"`
|
||||
}
|
||||
|
||||
// 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
|
||||
// ErrBadResponse wrapped with the API description.
|
||||
@@ -32,24 +39,25 @@ 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<token>/… 地址),因此与
|
||||
// 下面的传输层分支同形处理:只留来源,地址由 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")
|
||||
|
||||
resp, err := a.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("telegram: %s call: %w", method, err)
|
||||
// 只留来源:Bot API 把 token 写在地址路径里(/bot<token>/<method>),而
|
||||
// *url.Error 会把整条地址拼进错误串 —— 原样 `%w` 等于把 bot token 写进日志。
|
||||
return nil, fmt.Errorf("telegram: %s call %s: %w", method, trace.HostOf(a.endpoint(method)), callCause(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
|
||||
desc := strings.TrimSpace(string(body))
|
||||
if desc != "" {
|
||||
return nil, fmt.Errorf("telegram: %s: status %d: %s: %w", method, resp.StatusCode, desc, ErrBadResponse)
|
||||
}
|
||||
return nil, fmt.Errorf("telegram: %s: status %d: %w", method, resp.StatusCode, ErrBadResponse)
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodyBytes))
|
||||
return nil, badResponseError(method, resp.StatusCode, body)
|
||||
}
|
||||
|
||||
var out botResponse
|
||||
@@ -203,3 +211,39 @@ func parseReplyToID(s string) int64 {
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// badResponseError 把一次非 200 的回复收敛成错误:**只**取 error_code 与
|
||||
// description。响应体其余字段(以及 Telegram 回显的请求参数)一个字都不拼 ——
|
||||
// 旧实现把 512B 体原文当 desc 拼进来,等于把上游报文写进调用方的日志。
|
||||
//
|
||||
// description 是上游自由文本(例如 setWebhook 失败时会回显我们给的地址),因此过
|
||||
// trace.RedactText 清洗凭据形状并按 rune 截断后才出镜。
|
||||
func badResponseError(method string, status int, body []byte) error {
|
||||
var env botResponse
|
||||
_ = json.Unmarshal(body, &env)
|
||||
parts := []string{fmt.Sprintf("telegram: %s: status %d", method, status)}
|
||||
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), " "))
|
||||
}
|
||||
|
||||
// callCause 剥掉 net/http 的 *url.Error 外壳:它会把完整地址拼进错误串,而 Bot API
|
||||
// 的地址路径里就写着 bot token。剥壳只丢地址,内层哨兵链(context 取消等)原样保留。
|
||||
// 与 internal/channel/mediafetch 的 sanitizeErr 同一口径(那份未导出,且在别包里)。
|
||||
func callCause(err error) error {
|
||||
var uerr *url.Error
|
||||
if errors.As(err, &uerr) && uerr.Err != nil {
|
||||
return uerr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package telegram
|
||||
|
||||
// 本文件钉住 Bot API 出站调用的两条出镜边界(M41 #12/#13 那一族):
|
||||
//
|
||||
// - **非 200 的响应体原文不进错误**:旧实现把 512B 体原文当 description 拼进
|
||||
// error,而 `ReadMessages` 会以 `long poll failed` 落日志 —— 上游在体里回显什么,
|
||||
// 日志里就有什么。现在只解 error_code 与 description(清洗、截断后)。
|
||||
// - **地址里的 bot token 不进错误**:Bot API 的地址是 /bot<token>/<method>,
|
||||
// 传输层失败时 net/http 的 *url.Error 会把整条地址拼进错误串。
|
||||
//
|
||||
// 两条都是「改回去就变红」的形状:断言的是错误文本 —— 也就是真正被写进日志的字符串。
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// failingTransport 让 a.client.Do 以传输层错误收场(只有它会让 net/http 包出带完整
|
||||
// 地址的 *url.Error,那正是要钉住的泄漏形态)。
|
||||
type failingTransport struct{}
|
||||
|
||||
func (failingTransport) RoundTrip(*http.Request) (*http.Response, error) {
|
||||
return nil, errors.New("dial tcp: connection refused")
|
||||
}
|
||||
|
||||
// TestDoJSON_StatusErrorDoesNotEchoBodySentinel 4xx 体里放哨兵 ⇒ 错误里搜不到。
|
||||
//
|
||||
// 哨兵刻意放在 description 之外的字段:description 按设计要保留(那是 Telegram 对
|
||||
// 这次请求的说明),而「体里其余字节一个字都不拼」才是要钉住的口径。
|
||||
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",` +
|
||||
`"echoed_params":{"text":"` + sentinel + `"}}`))
|
||||
}))
|
||||
|
||||
_, err := a.doJSON(context.Background(), "sendMessage", map[string]any{"chat_id": "999"})
|
||||
if err == nil {
|
||||
t.Fatal("400 却报成功")
|
||||
}
|
||||
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)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "error_code 400") || !strings.Contains(err.Error(), "chat not found") {
|
||||
t.Fatalf("error_code/description 丢了(诊断面不能一起丢):%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "status 400") {
|
||||
t.Fatalf("HTTP 状态码丢了:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_StatusErrorRedactsDescriptionSecrets description 是上游自由文本,而
|
||||
// setWebhook 失败时 Telegram 会把我们给的地址回显在里面 —— 地址的 query 常带凭据。
|
||||
// 这类赋值形状必须被清洗。改回原样透传就变红。
|
||||
func TestDoJSON_StatusErrorRedactsDescriptionSecrets(t *testing.T) {
|
||||
t.Parallel()
|
||||
const secret = "WEBHOOK-SECRET-VALUE"
|
||||
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 webhook ` +
|
||||
`https://example.com/hook?access_token=` + secret + `"}`))
|
||||
}))
|
||||
|
||||
_, err := a.doJSON(context.Background(), "setWebhook", map[string]any{"url": "https://x"})
|
||||
if err == nil {
|
||||
t.Fatal("400 却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("description 里的凭据原样进了错误:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_TransportErrorOmitsBotToken 传输层失败时,错误里不得出现 bot token ——
|
||||
// 它就写在 Bot API 的地址路径里。
|
||||
func TestDoJSON_TransportErrorOmitsBotToken(t *testing.T) {
|
||||
t.Parallel()
|
||||
const token = "123456:AAH-SECRET-BOT-TOKEN"
|
||||
a := New(
|
||||
Config{BotToken: token},
|
||||
WithBaseURL("http://api.example.com"),
|
||||
WithHTTPClient(&http.Client{Transport: failingTransport{}}),
|
||||
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(), "api.example.com") || !strings.Contains(err.Error(), "connection refused") {
|
||||
t.Fatalf("剥掉地址时把来源或原因一起丢了:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_BuildErrorOmitsBotToken 请求**构造**失败也是同一族:地址解析失败的
|
||||
// err 同样是 *url.Error,里面就是整条 /bot<token>/… 地址,而 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)
|
||||
}
|
||||
}
|
||||
@@ -10,17 +10,25 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/mediafetch"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
)
|
||||
|
||||
// ilinkAuthType 是 iLink 请求头 `AuthorizationType` 的协议定值,仅此一处定义。
|
||||
const ilinkAuthType = "ilink_bot_token"
|
||||
|
||||
// maxErrorBodyBytes 是 iLink 非 2xx 响应里被读取的字节上限:只用来数体积与取
|
||||
// sha256 前缀(trace.UpstreamError 的口径),正文不进错误。
|
||||
const maxErrorBodyBytes = 4096
|
||||
|
||||
// authorizationHeader 为 req 装上 iLink 通用请求头:JSON 内容类型、bearer
|
||||
// token、认证类型、每次新生成的随机 X-WECHAT-UIN 防重放值,以及 App 标识头。
|
||||
func (a *Adapter) authorizationHeader(req *http.Request) {
|
||||
@@ -61,34 +69,55 @@ func randomUIN() string {
|
||||
|
||||
// doJSON 发起一次 HTTP 请求并把 JSON 响应解码进 out。它关闭响应体,并用 %w
|
||||
// 包裹网络/解码错误。out 为 nil 时跳过解码(用于响应体是不透明字节的 PUT)。
|
||||
//
|
||||
// 地址只以来源形态出镜(mediafetch.HostOf):rawURL 由 base+path 拼成,而 pollBase
|
||||
// 可能是对端重定向给的主机,完整串没有进日志的必要。非 2xx 的响应体同样不拼 ——
|
||||
// iLink 会在 errmsg 里回显请求内容,这里只经 trace.UpstreamError 留下
|
||||
// 状态码/体积/sha256 前缀(同 M40 口径)。
|
||||
func (a *Adapter) doJSON(ctx context.Context, method, rawURL string, body io.Reader, out any) error {
|
||||
host := mediafetch.HostOf(rawURL)
|
||||
req, err := http.NewRequestWithContext(ctx, method, rawURL, body)
|
||||
if err != nil {
|
||||
return fmt.Errorf("weixin_ilink: build %s %s: %w", method, rawURL, err)
|
||||
return fmt.Errorf("weixin_ilink: build %s %s: %w", method, host, urlFreeCause(err))
|
||||
}
|
||||
a.authorizationHeader(req)
|
||||
resp, err := a.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("weixin_ilink: %s %s: %w", method, rawURL, err)
|
||||
return fmt.Errorf("weixin_ilink: %s %s: %w", method, host, urlFreeCause(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
|
||||
return fmt.Errorf("weixin_ilink: %s %s: status %d: %s",
|
||||
method, rawURL, resp.StatusCode, strings.TrimSpace(string(msg)))
|
||||
msg, _ := io.ReadAll(io.LimitReader(resp.Body, maxErrorBodyBytes))
|
||||
return fmt.Errorf("weixin_ilink: %s %s: %w", method, host,
|
||||
trace.UpstreamError(host, resp.StatusCode, resp.Header.Get("Content-Type"), msg))
|
||||
}
|
||||
if out == nil {
|
||||
if _, err := io.Copy(io.Discard, resp.Body); err != nil {
|
||||
return fmt.Errorf("weixin_ilink: drain %s %s: %w", method, rawURL, err)
|
||||
return fmt.Errorf("weixin_ilink: drain %s %s: %w", method, host, urlFreeCause(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
|
||||
return fmt.Errorf("weixin_ilink: decode %s %s: %w", method, rawURL, err)
|
||||
return fmt.Errorf("weixin_ilink: decode %s %s: %w", method, host, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// urlFreeCause 剥掉 net/http 的 *url.Error 外壳:它会把**整条地址**拼进错误串 ——
|
||||
// doJSON 的地址、uploadCiphertext 的预签名上传地址(`encrypted_query_param` 就是下载
|
||||
// 凭据)都会跟着进错误与日志。剥壳只丢地址,内层哨兵链(context 取消、*net.DNSError
|
||||
// 等)原样保留,因此 fetchErrCategory 的归类不受影响。
|
||||
//
|
||||
// 与 internal/channel/mediafetch 的 sanitizeErr 同一口径:那份是未导出符号,且只服务
|
||||
// 于入站取回路径(mediafetch 不感知本包的发送侧),因此这里保留一份同形的三行实现。
|
||||
func urlFreeCause(err error) error {
|
||||
var uerr *url.Error
|
||||
if errors.As(err, &uerr) && uerr.Err != nil {
|
||||
return uerr.Err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// apiURL 把路径与已配置的基础 URL 拼接起来。
|
||||
func (a *Adapter) apiURL(path string) string {
|
||||
return joinURL(a.cfg.BaseURL, path)
|
||||
|
||||
@@ -31,6 +31,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/adapter"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/channel/mediafetch"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -200,6 +201,9 @@ func (a *Adapter) uploadURLFromParam(param, fileKey string) string {
|
||||
// - `src/cdn/cdn-upload.ts:40-83`:4xx 立即放弃(附服务端 `x-error-message`),
|
||||
// 其余失败最多重试 3 次(无退避);
|
||||
// - `src/cdn/cdn-upload.ts:62-65`:200 但没有该响应头同样是失败(不得当成成功)。
|
||||
//
|
||||
// 日志只带**来源主机**:uploadURL 是服务端签发的预签名地址(`encrypted_query_param`
|
||||
// 就是下载凭据),整条写进日志等于把凭据写进日志。
|
||||
func (a *Adapter) uploadCiphertext(ctx context.Context, uploadURL string, data []byte) (string, error) {
|
||||
var lastErr error
|
||||
for attempt := 1; attempt <= uploadMaxAttempts; attempt++ {
|
||||
@@ -212,22 +216,28 @@ func (a *Adapter) uploadCiphertext(ctx context.Context, uploadURL string, data [
|
||||
return "", lastErr
|
||||
}
|
||||
a.log.Warn("cdn upload attempt failed, retrying",
|
||||
"attempt", attempt, "of", uploadMaxAttempts, "err", err)
|
||||
"attempt", attempt, "of", uploadMaxAttempts,
|
||||
"host", mediafetch.HostOf(uploadURL), "err", err)
|
||||
}
|
||||
return "", fmt.Errorf("weixin_ilink: upload media: %d 次尝试均失败: %w", uploadMaxAttempts, lastErr)
|
||||
}
|
||||
|
||||
// uploadOnce 做一次上传尝试,返回下载凭据。retryable 报告这次失败是否值得重试:
|
||||
// 4xx 是客户端错误(请求本身不对),重试只是徒劳;网络/5xx/缺头都可能瞬时。
|
||||
//
|
||||
// 错误里只留来源主机:上传地址是服务端签发的预签名 URL,而 `*url.Error` 会把整条
|
||||
// 地址(含 `encrypted_query_param`)拼进错误串 —— 这条错误还要经 send.go 的
|
||||
// `outbound media item skipped` 落日志,因此必须在**产生错误的那一步**剥掉。
|
||||
func (a *Adapter) uploadOnce(ctx context.Context, uploadURL string, data []byte) (string, bool, error) {
|
||||
host := mediafetch.HostOf(uploadURL)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, uploadURL, bytes.NewReader(data))
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("weixin_ilink: build upload: %w", err)
|
||||
return "", false, fmt.Errorf("weixin_ilink: build upload to %s: %w", host, urlFreeCause(err))
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
resp, err := a.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return "", true, fmt.Errorf("weixin_ilink: upload media: %w", err)
|
||||
return "", true, fmt.Errorf("weixin_ilink: upload media to %s: %w", host, urlFreeCause(err))
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package weixin_ilink
|
||||
|
||||
// 本文件钉住 iLink 出站侧的两条出镜边界(M41 #10/#11 那一族):
|
||||
//
|
||||
// - **预签名上传地址不进日志与错误**:uploadURL 由 getuploadurl 签发,
|
||||
// `encrypted_query_param` 就是下载凭据;而 net/http 的 *url.Error 会把整条地址
|
||||
// 拼进错误串,那条错误要经 `cdn upload attempt failed, retrying` 与 send.go 的
|
||||
// `outbound media item skipped` 两处落日志。
|
||||
// - **非 2xx 的响应体原文不进错误**:iLink 在 errmsg 里回显请求内容,旧实现把 4096B
|
||||
// 体原文拼进 error。
|
||||
//
|
||||
// 两条都是「改回去就变红」的形状:断言的是错误文本与日志文本本身。
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
|
||||
)
|
||||
|
||||
// closedLoopbackAddr 返回一个**刚被关掉**的 127.0.0.1 端口地址。用它而不是拨一个
|
||||
// 域名:这里要的是「连接被拒」这条确定的传输层失败 —— 只有传输层失败才会让
|
||||
// net/http 包出带完整地址的 *url.Error,那正是要钉住的泄漏形态(不需要 DNS、不需要
|
||||
// 外网、失败是立刻的)。
|
||||
func closedLoopbackAddr(t *testing.T) string {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen: %v", err)
|
||||
}
|
||||
addr := ln.Addr().String()
|
||||
if cerr := ln.Close(); cerr != nil {
|
||||
t.Fatalf("close listener: %v", cerr)
|
||||
}
|
||||
return addr
|
||||
}
|
||||
|
||||
// newLeakTestAdapter 构造一个只用来发起出站调用的适配器:日志写进返回的 buffer,
|
||||
// 便于断言「日志里搜不到哨兵」。
|
||||
func newLeakTestAdapter(t *testing.T) (*Adapter, *bytes.Buffer) {
|
||||
t.Helper()
|
||||
buf := &bytes.Buffer{}
|
||||
ad, err := New(
|
||||
Config{BaseURL: "http://127.0.0.1:9/", BotToken: "tok"},
|
||||
nil,
|
||||
logger.New(logger.Options{Out: buf, Level: "debug"}),
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
return ad, buf
|
||||
}
|
||||
|
||||
// TestUploadCiphertext_PresignedURLStaysOutOfLogs 重试日志与最终错误里都不得出现
|
||||
// 预签名地址的签名参数。
|
||||
func TestUploadCiphertext_PresignedURLStaysOutOfLogs(t *testing.T) {
|
||||
t.Parallel()
|
||||
const secret = "PRESIGNED-ENCRYPTED-PARAM-SECRET"
|
||||
ad, logs := newLeakTestAdapter(t)
|
||||
|
||||
uploadURL := "http://" + closedLoopbackAddr(t) + "/upload?encrypted_query_param=" + secret + "&filekey=abc"
|
||||
_, err := ad.uploadCiphertext(context.Background(), uploadURL, []byte("cipher"))
|
||||
if err == nil {
|
||||
t.Fatal("连接被拒却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("预签名地址进了错误(会被 send.go 落日志):%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "dial tcp") {
|
||||
t.Fatalf("剥掉地址时把原因一起丢了:%v", err)
|
||||
}
|
||||
logged := logs.String()
|
||||
if strings.Contains(logged, secret) {
|
||||
t.Fatalf("预签名地址进了日志:\n%s", logged)
|
||||
}
|
||||
// 日志确实被写到了(否则上面的断言是空跑):重试行必须出现,且带来源主机。
|
||||
if !strings.Contains(logged, "cdn upload attempt failed") {
|
||||
t.Fatalf("没有重试日志,测试没覆盖到目标路径:\n%s", logged)
|
||||
}
|
||||
if !strings.Contains(logged, "host=http://127.0.0.1") {
|
||||
t.Fatalf("重试日志缺少来源主机(诊断面不能一起丢):\n%s", logged)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_StatusErrorDoesNotEchoBodySentinel 非 2xx 的体原文不得进错误。
|
||||
func TestDoJSON_StatusErrorDoesNotEchoBodySentinel(t *testing.T) {
|
||||
t.Parallel()
|
||||
const sentinel = "SENTINEL-ILINK-4XX"
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = w.Write([]byte(`{"ret":-1,"errcode":-14,"errmsg":"` + sentinel + `"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
ad, _ := New(Config{BaseURL: srv.URL, BotToken: "tok"}, srv.Client(),
|
||||
logger.New(logger.Options{Out: &bytes.Buffer{}, Level: "debug"}))
|
||||
var out map[string]any
|
||||
err := ad.doJSON(context.Background(), http.MethodPost, ad.apiURL("/ilink/bot/getupdates"), nil, &out)
|
||||
if err == nil {
|
||||
t.Fatal("500 却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), sentinel) {
|
||||
t.Fatalf("响应体原文进了错误:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "status=500") || !strings.Contains(err.Error(), "body_bytes=") {
|
||||
t.Fatalf("状态码/体积丢了(诊断面不能一起丢):%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "127.0.0.1") {
|
||||
t.Fatalf("错误里没有来源主机:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDoJSON_TransportErrorOmitsRequestURL 传输层失败时,错误里不得出现请求地址。
|
||||
func TestDoJSON_TransportErrorOmitsRequestURL(t *testing.T) {
|
||||
t.Parallel()
|
||||
const secret = "QUERY-ENCRYPTED-PARAM-SECRET"
|
||||
ad, _ := newLeakTestAdapter(t)
|
||||
|
||||
rawURL := "http://" + closedLoopbackAddr(t) + "/ilink/bot/getupdates?encrypted_query_param=" + secret
|
||||
err := ad.doJSON(context.Background(), http.MethodPost, rawURL, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("连接被拒却报成功")
|
||||
}
|
||||
if strings.Contains(err.Error(), secret) {
|
||||
t.Fatalf("请求地址的签名参数进了错误:%v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "dial tcp") {
|
||||
t.Fatalf("剥掉地址时把原因一起丢了:%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUploadCiphertext_LogLevelIsWarn 钉住级别:重试行是 WARN(默认 INFO 级别下可见),
|
||||
// 不是只有 debug 才看得到的取证行 —— 这条线要在生产默认级别下就安全。
|
||||
func TestUploadCiphertext_RetryLogIsWarnAndCarriesHost(t *testing.T) {
|
||||
t.Parallel()
|
||||
const secret = "PRESIGNED-SECRET-2"
|
||||
buf := &bytes.Buffer{}
|
||||
ad, err := New(Config{BaseURL: "http://127.0.0.1:9/", BotToken: "tok"}, nil,
|
||||
logger.New(logger.Options{Out: buf, Level: "info"}))
|
||||
if err != nil {
|
||||
t.Fatalf("New: %v", err)
|
||||
}
|
||||
uploadURL := "http://" + closedLoopbackAddr(t) + "/upload?encrypted_query_param=" + secret
|
||||
if _, uerr := ad.uploadCiphertext(context.Background(), uploadURL, []byte("x")); uerr == nil {
|
||||
t.Fatal("连接被拒却报成功")
|
||||
}
|
||||
logged := buf.String()
|
||||
if !strings.Contains(logged, "level=WARN") {
|
||||
t.Fatalf("重试行不是 WARN 级(默认 INFO 下会看不见):\n%s", logged)
|
||||
}
|
||||
if strings.Contains(logged, secret) {
|
||||
t.Fatalf("预签名地址进了日志:\n%s", logged)
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package io
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
stdio "io"
|
||||
"log/slog"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/trace"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/pkg/plugins/sdk"
|
||||
)
|
||||
|
||||
@@ -58,6 +60,18 @@ func (h *httpTool) Parameters() (map[string]any, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// blockReason 把一次拦截归类成稳定原因码,供审计日志使用。日志只记这个码与来源主机:
|
||||
// 拦截原因的具体文本(哪个 scheme、解析失败原话)会经错误返回给调用方,而错误文本本身
|
||||
// 可能带着原 URL —— 那是**不进日志**的那一侧。
|
||||
func blockReason(err error) string {
|
||||
switch {
|
||||
case errors.Is(err, ErrSSRF):
|
||||
return "ssrf_blocked"
|
||||
default:
|
||||
return "url_rejected"
|
||||
}
|
||||
}
|
||||
|
||||
// Execute implements sdk.Tool.
|
||||
func (h *httpTool) Execute(ctx context.Context, args any) (any, error) {
|
||||
m, ok := args.(map[string]any)
|
||||
@@ -77,7 +91,11 @@ func (h *httpTool) Execute(ctx context.Context, args any) (any, error) {
|
||||
}
|
||||
u, err := validateRequestURL(ctx, rawURL, h.allowedHosts)
|
||||
if err != nil {
|
||||
h.log.Warn("io http: blocked request", "url", rawURL, "err", err)
|
||||
// 只记来源与原因码:rawURL 由模型/用户给,可能带 user:pass@ 或 ?api_key=,
|
||||
// 而日志会被采集与转贴;错误原文也不进日志 —— 解析失败时它包着 *url.Error,
|
||||
// 里面就是整条原串。
|
||||
h.log.Warn("io http: blocked request",
|
||||
"host", trace.HostOf(rawURL), "reason", blockReason(err))
|
||||
return nil, err
|
||||
}
|
||||
body := argString(m, "body")
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package io
|
||||
|
||||
// 本文件钉住 http 工具的**拦截日志**(M41 #16):rawURL 由模型/用户给,可能带
|
||||
// `user:pass@` 或 `?api_key=`,而拦截日志是审计面、会被采集与转贴。旧实现把 rawURL
|
||||
// 原样记进 WARN,等于把凭据写进日志。
|
||||
//
|
||||
// 现在只记来源主机与原因码;错误原文也不进日志 —— 解析失败时它包着 *url.Error,
|
||||
// 里面就是整条原串。
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/logger"
|
||||
)
|
||||
|
||||
// blockedLog 返回一个把日志写进 buffer 的 http 工具。
|
||||
func blockedLog(t *testing.T) (*httpTool, *bytes.Buffer) {
|
||||
t.Helper()
|
||||
buf := &bytes.Buffer{}
|
||||
return httpToolForTest(t, WithLogger(logger.New(logger.Options{Out: buf, Level: "debug"}))), buf
|
||||
}
|
||||
|
||||
// TestHTTPTool_BlockedLogHidesURLCredentials SSRF 拦截时日志只留来源与原因码。
|
||||
func TestHTTPTool_BlockedLogHidesURLCredentials(t *testing.T) {
|
||||
t.Parallel()
|
||||
ht, logs := blockedLog(t)
|
||||
|
||||
_, err := ht.Execute(context.Background(), map[string]any{"url": "https://user:pass@127.0.0.1/x"})
|
||||
if !errors.Is(err, ErrSSRF) {
|
||||
t.Fatalf("err = %v, want ErrSSRF", err)
|
||||
}
|
||||
logged := logs.String()
|
||||
if !strings.Contains(logged, "io http: blocked request") {
|
||||
t.Fatalf("没有拦截日志,测试没覆盖到目标路径:\n%s", logged)
|
||||
}
|
||||
if strings.Contains(logged, "user:pass") || strings.Contains(logged, "pass@") {
|
||||
t.Fatalf("user:pass@ 进了拦截日志:\n%s", logged)
|
||||
}
|
||||
if !strings.Contains(logged, "reason=ssrf_blocked") {
|
||||
t.Fatalf("拦截日志缺原因码:\n%s", logged)
|
||||
}
|
||||
if !strings.Contains(logged, "[redacted]@127.0.0.1") {
|
||||
t.Fatalf("拦截日志缺来源主机(诊断面不能一起丢):\n%s", logged)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHTTPTool_BlockedLogHidesQueryCredentials 非 SSRF 的拒绝(这里是不支持的 scheme)
|
||||
// 同样不得带出 query 里的凭据。
|
||||
func TestHTTPTool_BlockedLogHidesQueryCredentials(t *testing.T) {
|
||||
t.Parallel()
|
||||
ht, logs := blockedLog(t)
|
||||
|
||||
_, err := ht.Execute(context.Background(), map[string]any{"url": "ftp://user:pass@files.example.com/x?api_key=QUERY-SECRET"})
|
||||
if err == nil {
|
||||
t.Fatal("不支持的 scheme 却报成功")
|
||||
}
|
||||
logged := logs.String()
|
||||
if !strings.Contains(logged, "io http: blocked request") {
|
||||
t.Fatalf("没有拦截日志,测试没覆盖到目标路径:\n%s", logged)
|
||||
}
|
||||
if strings.Contains(logged, "QUERY-SECRET") || strings.Contains(logged, "user:pass") {
|
||||
t.Fatalf("拦截日志带出了原串里的凭据:\n%s", logged)
|
||||
}
|
||||
if !strings.Contains(logged, "reason=url_rejected") {
|
||||
t.Fatalf("拦截日志缺原因码:\n%s", logged)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user