fix(datasource): 语雀/Notion/IMA/飞书连接器 API 响应体补体积上限 (#3985)
* fix(datasource): 语雀/Notion/IMA/飞书 API 响应体补体积上限 #3887 给 GitLab 客户端补了 readCapped 上限;语雀、Notion、IMA、飞书四个 连接器的 API 读取仍是裸 io.ReadAll,破损或恶意端点可让同步进程缓冲无界 响应体。各连接器比照 GitLab 同步同一上限(16 MiB)与显式超限报错,limit 做成字段以便测试下调。飞书 429/5xx 错误路径的 best-effort 读取刻意不动。 * fix(datasource): 响应体上限为零值时回退到默认 16 MiB 测试里直接用字面量构造的 Client 不经过 NewClient,jsonLimit 为 0, readCapped 会拒绝任何响应,导致 feishu/core 11 个现有测试失败。 readCapped 遇到非正数 limit 时改用 maxJSONResponseBytes。 * fix(datasource): 响应体超限不再重试;补齐飞书 token 与下载错误分支的读取上限 - yuque/ima/feishu/notion 的 readCapped 改用哨兵错误 errResponseTooLarge, 文案不变;yuque doRequest、ima callAPIAt、feishu DoRequest 遇到超限直接返回, 不再按退避重试 3 次(同一请求必然再次超限,只会白耗限流额度)。 - 飞书 GetTenantAccessToken 改为 readCapped + json.Unmarshal,和其他 API 响应同一上限。 - 飞书 downloadRawBytes 的 429/5xx/非 200 错误预览只读 4 KiB, download failed 错误不再携带完整响应体。 --------- Co-authored-by: wizardchen <wizardchen@tencent.com>main
parent
9a2cd20063
commit
a75e8e9ac0
|
|
@ -4,6 +4,7 @@ import (
|
|||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
|
@ -27,6 +28,9 @@ type Client struct {
|
|||
location *time.Location
|
||||
|
||||
httpClient *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 WikiNode
|
||||
Err 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 interf
|
|||
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 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))
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
package core
|
||||
|
||||
import (
|
||||
"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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 largest
|
||||
maxDownloadBytes = 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 string
|
||||
apiKey string
|
||||
httpClient *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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
@ -25,6 +25,35 @@ type notionClient struct {
|
|||
httpClient *http.Client
|
||||
limiter *rate.Limiter
|
||||
baseURL 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, body
|
|||
break
|
||||
}
|
||||
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
package notion
|
||||
|
||||
import (
|
||||
"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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package yuque
|
|||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
|
@ -18,6 +19,10 @@ const (
|
|||
defaultTimeout = 30 * time.Second
|
||||
defaultPageSize = 100
|
||||
userAgent = "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 string
|
||||
token string
|
||||
httpClient *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 inte
|
|||
return 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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue