Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(datasource): 语雀/Notion/IMA/飞书连接器 API 响应体补体积上限 (#3985)
yetugea75e8e9ac0ac
diff --git a/internal/datasource/connector/feishu/core/client.go b/internal/datasource/connector/feishu/core/client.goindex f6484c217..3fb3dbcfb 100644--- a/internal/datasource/connector/feishu/core/client.go+++ b/internal/datasource/connector/feishu/core/client.go@@ -4,6 +4,7 @@ import ("bytes""context""encoding/json"+ "errors""fmt""io""net/http"@@ -27,6 +28,9 @@ type Client struct {location *time.LocationhttpClient *http.Client+ // jsonLimit caps each API response body; a field so tests can lower it+ // without materialising the production limit.+ jsonLimit int64// Token cache (thread-safe)tokenMu sync.Mutex@@ -34,6 +38,32 @@ type Client struct {tokenExpAt time.Time}+// maxJSONResponseBytes bounds every API response body. Document and wiki+// payloads are small; a larger body means a broken or hostile server.+const maxJSONResponseBytes = 16 << 20++// errResponseTooLarge marks a body over the cap. It is deterministic: the same+// request returns the same oversized body, so callers must not retry it.+var errResponseTooLarge = errors.New("response exceeds maximum size")++// readCapped reads a response body, refusing anything larger than limit instead+// of buffering it. Oversized payloads are reported as an error: a truncated+// body would be indexed as if it were the whole document. A non-positive limit+// (e.g. a zero-value client built in tests) falls back to maxJSONResponseBytes.+func readCapped(body io.Reader, limit int64) ([]byte, error) {+ if limit <= 0 {+ limit = maxJSONResponseBytes+ }+ data, err := io.ReadAll(io.LimitReader(body, limit+1))+ if err != nil {+ return nil, err+ }+ if int64(len(data)) > limit {+ return nil, fmt.Errorf("%w (%d bytes)", errResponseTooLarge, limit)+ }+ return data, nil+}+type WikiNodeListFailure struct {Node WikiNodeErr error@@ -71,6 +101,7 @@ func NewClient(config *Config) *Client {appSecret: config.AppSecret,location: resolveLocation(config.Timezone),httpClient: datasource.NewConnectorHTTPClient(30 * time.Second),+ jsonLimit: maxJSONResponseBytes,}}@@ -102,8 +133,12 @@ func (c *Client) GetTenantAccessToken(ctx context.Context) (string, error) {}defer resp.Body.Close()+ respBody, err := readCapped(resp.Body, c.jsonLimit)+ if err != nil {+ return "", fmt.Errorf("read token response: %w", err)+ }var result TokenResponse- if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {+ if err := json.Unmarshal(respBody, &result); err != nil {return "", fmt.Errorf("decode token response: %w", err)}if result.Code != 0 {@@ -139,6 +174,10 @@ const (feishuRetry5xxDelay = 2 * time.Second)+// maxFeishuErrorPreviewBytes bounds how much of a failed download's body is+// read for diagnostics; only the first 500 bytes are ever logged.+const maxFeishuErrorPreviewBytes = 4 << 10+// maxFeishuDownloadBytes bounds a single file download to protect the sync// worker from adversarial or pathological oversized responses.const maxFeishuDownloadBytes = 512 * 1024 * 1024 // 512 MB@@ -205,11 +244,11 @@ func (c *Client) DoRequest(ctx context.Context, method, path string, body interfreturn lastErr}- respBody, readErr := io.ReadAll(resp.Body)+ respBody, readErr := readCapped(resp.Body, c.jsonLimit)resp.Body.Close()if readErr != nil {lastErr = fmt.Errorf("read response body: %w", readErr)- if attempt < maxRetries {+ if attempt < maxRetries && !errors.Is(readErr, errResponseTooLarge) {if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil {return sErr}@@ -722,7 +761,7 @@ func (c *Client) downloadRawBytes(ctx context.Context, path string) ([]byte, err}if resp.StatusCode == http.StatusTooManyRequests {- body, _ := io.ReadAll(resp.Body)+ body, _ := io.ReadAll(io.LimitReader(resp.Body, maxFeishuErrorPreviewBytes))resp.Body.Close()wait := parseRetryAfter(resp.Header.Get("Retry-After"), feishuRetryBackoff[min(attempt, len(feishuRetryBackoff)-1)])lastErr = fmt.Errorf("download rate limited: status=429 body=%s", truncate(string(body), 500))@@ -736,7 +775,7 @@ func (c *Client) downloadRawBytes(ctx context.Context, path string) ([]byte, err}if resp.StatusCode >= 500 && resp.StatusCode < 600 {- body, _ := io.ReadAll(resp.Body)+ body, _ := io.ReadAll(io.LimitReader(resp.Body, maxFeishuErrorPreviewBytes))resp.Body.Close()lastErr = fmt.Errorf("download server error: status=%d body=%s", resp.StatusCode, truncate(string(body), 500))if attempt < feishuMax5xxRetries {@@ -749,10 +788,10 @@ func (c *Client) downloadRawBytes(ctx context.Context, path string) ([]byte, err}if resp.StatusCode != http.StatusOK {- body, _ := io.ReadAll(resp.Body)+ body, _ := io.ReadAll(io.LimitReader(resp.Body, maxFeishuErrorPreviewBytes))resp.Body.Close()logger.Errorf(ctx, "[Feishu] download GET %s → status=%d body=%s", path, resp.StatusCode, truncate(string(body), 500))- return nil, fmt.Errorf("download failed: status=%d body=%s", resp.StatusCode, string(body))+ return nil, fmt.Errorf("download failed: status=%d body=%s", resp.StatusCode, truncate(string(body), 500))}data, readErr := io.ReadAll(io.LimitReader(resp.Body, maxFeishuDownloadBytes+1))diff --git a/internal/datasource/connector/feishu/core/client_retry_test.go b/internal/datasource/connector/feishu/core/client_retry_test.goindex 0e9444918..54baef727 100644--- a/internal/datasource/connector/feishu/core/client_retry_test.go+++ b/internal/datasource/connector/feishu/core/client_retry_test.go@@ -1,10 +1,13 @@package coreimport (+ "bytes""context""io""net/http""net/http/httptest"+ "strings"+ "sync/atomic""testing""time")@@ -171,3 +174,116 @@ func TestParseRetryAfter(t *testing.T) {}}}++func TestDoRequest_RejectsOversizedResponse(t *testing.T) {+ var hits atomic.Int32+ ts, cfg := retryTestServer("/open-apis/docx/v1/documents", func(w http.ResponseWriter, _ *http.Request) {+ hits.Add(1)+ _, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20+1))+ })+ defer ts.Close()++ c := NewClient(cfg)+ c.jsonLimit = 1 << 20+ err := c.DoRequest(context.Background(), http.MethodGet, "/open-apis/docx/v1/documents", nil, &map[string]any{})+ if err == nil {+ t.Fatal("DoRequest accepted a response larger than the cap, want error")+ }+ if !strings.Contains(err.Error(), "exceeds maximum size") {+ t.Fatalf("error = %v, want an explicit over-limit error", err)+ }+ // The same document is just as large on every attempt; retrying only burns+ // the rate-limit budget and re-reads the full cap each time.+ if got := hits.Load(); got != 1 {+ t.Fatalf("server hit %d times, want 1 (oversized responses must not be retried)", got)+ }+}++// The token response is decoded under tokenMu on every refresh and Ping, so it+// must honour the same cap as every other API response.+func TestGetTenantAccessToken_RejectsOversizedResponse(t *testing.T) {+ mux := http.NewServeMux()+ mux.HandleFunc("/open-apis/auth/v3/tenant_access_token/internal", func(w http.ResponseWriter, _ *http.Request) {+ // Valid JSON, so only the size cap can reject it.+ _, _ = io.WriteString(w, `{"code":0,"tenant_access_token":"fake-token","expire":7200,"pad":"`)+ _, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20))+ _, _ = io.WriteString(w, `"}`)+ })+ ts := httptest.NewServer(mux)+ defer ts.Close()++ c := NewClient(&Config{AppID: "a", AppSecret: "b", BaseURL: ts.URL})+ c.jsonLimit = 1 << 20+ _, err := c.GetTenantAccessToken(context.Background())+ if err == nil {+ t.Fatal("GetTenantAccessToken accepted a response larger than the cap, want error")+ }+ if !strings.Contains(err.Error(), "exceeds maximum size") {+ t.Fatalf("error = %v, want an explicit over-limit error", err)+ }+}++// countingBody records how much of a response body the client consumed.+type countingBody struct {+ io.ReadCloser+ n *atomic.Int64+}++func (b countingBody) Read(p []byte) (int, error) {+ n, err := b.ReadCloser.Read(p)+ b.n.Add(int64(n))+ return n, err+}++type countingTransport struct {+ base http.RoundTripper+ n *atomic.Int64+}++func (t countingTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ resp, err := t.base.RoundTrip(req)+ if err == nil && strings.Contains(req.URL.Path, "/download") {+ resp.Body = countingBody{ReadCloser: resp.Body, n: t.n}+ }+ return resp, err+}++// Download error bodies are only a diagnostic preview: they must be read with a+// small bound and never copied whole into the returned error.+func TestDownloadRawBytes_BoundsErrorBodies(t *testing.T) {+ const bodySize = 1 << 20+ for _, status := range []int{http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusForbidden} {+ t.Run(http.StatusText(status), func(t *testing.T) {+ handler := func(w http.ResponseWriter, _ *http.Request) {+ if status == http.StatusTooManyRequests {+ w.Header().Set("Retry-After", "0")+ }+ w.WriteHeader(status)+ _, _ = w.Write(bytes.Repeat([]byte("a"), bodySize))+ }+ ts, cfg := retryTestServer("/open-apis/drive/v1/files/f/download", handler)+ defer ts.Close()++ c := NewClient(cfg)+ var read atomic.Int64+ hc := *c.httpClient+ base := hc.Transport+ if base == nil {+ base = http.DefaultTransport+ }+ hc.Transport = countingTransport{base: base, n: &read}+ c.httpClient = &hc++ _, err := c.DownloadDriveFile(context.Background(), "f")+ if err == nil {+ t.Fatalf("status %d: want error", status)+ }+ if len(err.Error()) > 1024 {+ t.Fatalf("error carries %d bytes of response body, want a short preview", len(err.Error()))+ }+ if got := read.Load(); got >= bodySize {+ t.Fatalf("read %d bytes of error bodies, want a bounded preview per response", got)+ }+ })+ }+}diff --git a/internal/datasource/connector/ima/client.go b/internal/datasource/connector/ima/client.goindex 743dadf04..e5d713f7a 100644--- a/internal/datasource/connector/ima/client.go+++ b/internal/datasource/connector/ima/client.go@@ -7,6 +7,7 @@ import ("bytes""context""encoding/json"+ "errors""fmt""io""net/http"@@ -31,6 +32,10 @@ const (// Max body we accept from get_media_info-URLs. 200MB matches IMA's largestmaxDownloadBytes = 200 * 1024 * 1024++ // maxJSONResponseBytes bounds every API response body. Listings and document+ // payloads are small; a larger body means a broken or hostile server.+ maxJSONResponseBytes = 16 << 20)// client wraps the IMA OpenAPI. It is safe for concurrent use.@@ -39,6 +44,9 @@ type client struct {clientID stringapiKey stringhttpClient *http.Client+ // jsonLimit caps each API response body; a field so tests can lower it+ // without materialising the production limit.+ jsonLimit int64// downloadClient is a separate client with a longer timeout for pulling// media bodies from COS/CDN URLs returned by get_media_info.downloadClient *http.Client@@ -53,9 +61,32 @@ func newClient(cfg *Config) *client {apiKey: cfg.APIKey,httpClient: datasource.NewConnectorHTTPClient(defaultTimeout),downloadClient: datasource.NewConnectorHTTPClient(downloadTimeout),+ jsonLimit: maxJSONResponseBytes,}}+// errResponseTooLarge marks a body over the cap. It is deterministic: the same+// request returns the same oversized body, so callers must not retry it.+var errResponseTooLarge = errors.New("response exceeds maximum size")++// readCapped reads a response body, refusing anything larger than limit instead+// of buffering it. Oversized payloads are reported as an error: a truncated+// body would be indexed as if it were the whole document. A non-positive limit+// (e.g. a zero-value client built in tests) falls back to maxJSONResponseBytes.+func readCapped(body io.Reader, limit int64) ([]byte, error) {+ if limit <= 0 {+ limit = maxJSONResponseBytes+ }+ data, err := io.ReadAll(io.LimitReader(body, limit+1))+ if err != nil {+ return nil, err+ }+ if int64(len(data)) > limit {+ return nil, fmt.Errorf("%w (%d bytes)", errResponseTooLarge, limit)+ }+ return data, nil+}+// callAPI executes an authenticated POST to /openapi/wiki/v1/<action>.func (c *client) callAPI(ctx context.Context, action string, req interface{}, result interface{}) error {return c.callAPIAt(ctx, apiBasePath, action, req, result)@@ -128,11 +159,11 @@ func (c *client) callAPIAt(return lastErr}- respBody, readErr := io.ReadAll(resp.Body)+ respBody, readErr := readCapped(resp.Body, c.jsonLimit)_ = resp.Body.Close()if readErr != nil {lastErr = fmt.Errorf("read response: %w", readErr)- if attempt < maxRetries {+ if attempt < maxRetries && !errors.Is(readErr, errResponseTooLarge) {if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil {return sErr}diff --git a/internal/datasource/connector/ima/client_cap_test.go b/internal/datasource/connector/ima/client_cap_test.gonew file mode 100644index 000000000..4a9a5c7ed--- /dev/null+++ b/internal/datasource/connector/ima/client_cap_test.go@@ -0,0 +1,33 @@+package ima++import (+ "bytes"+ "context"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+)++func TestCallAPI_RejectsOversizedResponse(t *testing.T) {+ var hits atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ hits.Add(1)+ _, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20+1))+ }))+ defer server.Close()++ c := newClient(&Config{ClientID: "cid", APIKey: "cak", BaseURL: server.URL})+ c.jsonLimit = 1 << 20+ err := c.callAPI(context.Background(), "get_knowledge_list", map[string]any{}, &map[string]any{})+ if err == nil {+ t.Fatal("callAPI accepted a response larger than the cap, want error")+ }+ if !strings.Contains(err.Error(), "exceeds maximum size") {+ t.Fatalf("error = %v, want an explicit over-limit error", err)+ }+ if got := hits.Load(); got != 1 {+ t.Fatalf("server hit %d times, want 1 (oversized responses must not be retried)", got)+ }+}diff --git a/internal/datasource/connector/notion/client.go b/internal/datasource/connector/notion/client.goindex ae4befee3..86c16819a 100644--- a/internal/datasource/connector/notion/client.go+++ b/internal/datasource/connector/notion/client.go@@ -25,6 +25,35 @@ type notionClient struct {httpClient *http.Clientlimiter *rate.LimiterbaseURL string+ // jsonLimit caps each API response body; a field so tests can lower it+ // without materialising the production limit.+ jsonLimit int64+}++// maxJSONResponseBytes bounds every API response body. Page and block payloads+// are small; a larger body means a broken or hostile server.+const maxJSONResponseBytes = 16 << 20++// errResponseTooLarge marks a body over the cap. It is deterministic: the same+// request returns the same oversized body, so callers must not retry it.+var errResponseTooLarge = errors.New("response exceeds maximum size")++// readCapped reads a response body, refusing anything larger than limit instead+// of buffering it. Oversized payloads are reported as an error: a truncated+// body would be indexed as if it were the whole document. A non-positive limit+// (e.g. a zero-value client built in tests) falls back to maxJSONResponseBytes.+func readCapped(body io.Reader, limit int64) ([]byte, error) {+ if limit <= 0 {+ limit = maxJSONResponseBytes+ }+ data, err := io.ReadAll(io.LimitReader(body, limit+1))+ if err != nil {+ return nil, err+ }+ if int64(len(data)) > limit {+ return nil, fmt.Errorf("%w (%d bytes)", errResponseTooLarge, limit)+ }+ return data, nil}// newClient creates a new Notion API client.@@ -40,6 +69,7 @@ func newClient(token, baseURL string) (*notionClient, error) {httpClient: datasource.NewConnectorHTTPClient(30 * time.Second),limiter: rate.NewLimiter(rate.Limit(3), 3),baseURL: baseURL,+ jsonLimit: maxJSONResponseBytes,}, nil}@@ -101,7 +131,7 @@ func (c *notionClient) doRequest(ctx context.Context, method, path string, bodybreak}- respBody, err := io.ReadAll(resp.Body)+ respBody, err := readCapped(resp.Body, c.jsonLimit)resp.Body.Close()if err != nil {return nil, fmt.Errorf("read response: %w", err)diff --git a/internal/datasource/connector/notion/client_test.go b/internal/datasource/connector/notion/client_test.goindex 5e6848adf..73370a35b 100644--- a/internal/datasource/connector/notion/client_test.go+++ b/internal/datasource/connector/notion/client_test.go@@ -1,10 +1,13 @@package notionimport (+ "bytes""context""encoding/json""net/http""net/http/httptest"+ "strings"+ "sync/atomic""testing""time"@@ -361,3 +364,25 @@ func TestDownloadFile_RejectsLoopbackURL(t *testing.T) {t.Fatal("expected loopback attachment URL to be rejected")}}++func TestDoRequest_RejectsOversizedResponse(t *testing.T) {+ var hits atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ hits.Add(1)+ _, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20+1))+ }))+ defer server.Close()++ c := mustTestClient(t, "token", server.URL)+ c.jsonLimit = 1 << 20+ _, err := c.doRequest(context.Background(), http.MethodGet, "/v1/users/me", nil)+ if err == nil {+ t.Fatal("doRequest accepted a response larger than the cap, want error")+ }+ if !strings.Contains(err.Error(), "exceeds maximum size") {+ t.Fatalf("error = %v, want an explicit over-limit error", err)+ }+ if got := hits.Load(); got != 1 {+ t.Fatalf("server hit %d times, want 1 (oversized responses must not be retried)", got)+ }+}diff --git a/internal/datasource/connector/yuque/client.go b/internal/datasource/connector/yuque/client.goindex e7a9cab79..7fb517074 100644--- a/internal/datasource/connector/yuque/client.go+++ b/internal/datasource/connector/yuque/client.go@@ -3,6 +3,7 @@ package yuqueimport ("context""encoding/json"+ "errors""fmt""io""net/http"@@ -18,6 +19,10 @@ const (defaultTimeout = 30 * time.SeconddefaultPageSize = 100userAgent = "WeKnora-Yuque-Connector/1.0"++ // maxJSONResponseBytes bounds every API response body. Listings and document+ // payloads are small; a larger body means a broken or hostile server.+ maxJSONResponseBytes = 16 << 20)// client wraps the Yuque Open API.@@ -25,6 +30,9 @@ type client struct {baseURL stringtoken stringhttpClient *http.Client+ // jsonLimit caps each API response body; a field so tests can lower it+ // without materialising the production limit.+ jsonLimit int64// logTokenOnce ensures the redacted token identity is logged at most once// per client lifetime (first real request), rather than on every call.@@ -37,9 +45,32 @@ func newClient(cfg *Config) *client {baseURL: cfg.GetBaseURL(),token: cfg.APIToken,httpClient: datasource.NewConnectorHTTPClient(defaultTimeout),+ jsonLimit: maxJSONResponseBytes,}}+// errResponseTooLarge marks a body over the cap. It is deterministic: the same+// request returns the same oversized body, so callers must not retry it.+var errResponseTooLarge = errors.New("response exceeds maximum size")++// readCapped reads a response body, refusing anything larger than limit instead+// of buffering it. Oversized payloads are reported as an error: a truncated+// body would be indexed as if it were the whole document. A non-positive limit+// (e.g. a zero-value client built in tests) falls back to maxJSONResponseBytes.+func readCapped(body io.Reader, limit int64) ([]byte, error) {+ if limit <= 0 {+ limit = maxJSONResponseBytes+ }+ data, err := io.ReadAll(io.LimitReader(body, limit+1))+ if err != nil {+ return nil, err+ }+ if int64(len(data)) > limit {+ return nil, fmt.Errorf("%w (%d bytes)", errResponseTooLarge, limit)+ }+ return data, nil+}+// doRequest executes an authenticated request and decodes JSON, with retry logic// for transient errors (429, 5xx, transport failures).// The raw X-Auth-Token is never logged; only a redacted form is emitted once per@@ -85,11 +116,11 @@ func (c *client) doRequest(ctx context.Context, method, path string, result intereturn lastErr}- body, readErr := io.ReadAll(resp.Body)+ body, readErr := readCapped(resp.Body, c.jsonLimit)resp.Body.Close()if readErr != nil {lastErr = fmt.Errorf("read response body: %w", readErr)- if attempt < maxRetries {+ if attempt < maxRetries && !errors.Is(readErr, errResponseTooLarge) {if sErr := sleepCtx(ctx, backoff[attempt]); sErr != nil {return sErr}diff --git a/internal/datasource/connector/yuque/client_test.go b/internal/datasource/connector/yuque/client_test.goindex 60fb06a00..8a78214c1 100644--- a/internal/datasource/connector/yuque/client_test.go+++ b/internal/datasource/connector/yuque/client_test.go@@ -11,6 +11,7 @@ import ("net/http/httptest""os""strings"+ "sync/atomic""testing""time"@@ -420,3 +421,31 @@ func TestClient_GetDocDetail(t *testing.T) {t.Errorf("Body = %q", d.Body)}}++func TestClient_DoRequest_RejectsOversizedResponse(t *testing.T) {+ f := newFakeYuque()+ defer f.Close()++ var hits atomic.Int32+ f.mux = http.NewServeMux()+ f.mux.HandleFunc("/api/v2/user", func(w http.ResponseWriter, _ *http.Request) {+ hits.Add(1)+ _, _ = w.Write(bytes.Repeat([]byte("a"), 1<<20+1))+ })+ f.server.Config.Handler = f.mux++ c := newClient(f.cfg())+ c.jsonLimit = 1 << 20+ err := c.Ping(context.Background())+ if err == nil {+ t.Fatal("Ping accepted a response larger than the cap, want error")+ }+ if !strings.Contains(err.Error(), "exceeds maximum size") {+ t.Fatalf("error = %v, want an explicit over-limit error", err)+ }+ // The same document is just as large on every attempt; retrying only burns+ // the rate-limit budget and re-reads the full cap each time.+ if got := hits.Load(); got != 1 {+ t.Fatalf("server hit %d times, want 1 (oversized responses must not be retried)", got)+ }+}