Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(client): cap SDK error response bodies at 1 MiB (#4721)

ordinary being3e6e3bb137e9
diff --git a/client/agent.go b/client/agent.go
index 8c103a007..7abeed635 100644
--- a/client/agent.go
+++ b/client/agent.go
@@ -115,8 +115,7 @@ func (c *Client) AgentQAStreamWithRequest(ctx context.Context,
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- body, _ := io.ReadAll(resp.Body)
- return newAPIError(resp.StatusCode, body)
+ return newAPIError(resp.StatusCode, readErrorBody(resp.Body))
}
// Process SSE stream
diff --git a/client/client.go b/client/client.go
index 02d8182b6..d1fd2f921 100644
--- a/client/client.go
+++ b/client/client.go
@@ -269,6 +269,28 @@ func newAPIError(status int, body []byte) *APIError {
return &APIError{StatusCode: status, Body: string(body), Code: extractServerCode(body)}
}
+// maxErrorBodyBytes caps how much of a failed response body the SDK reads.
+//
+// A non-2xx body is copied verbatim into APIError.Body and interpolated into
+// APIError.Error(), which callers log or print. A misconfigured server, a
+// hostile origin, or a proxy serving an HTML error page can make that body
+// arbitrarily large, so the SDK would both hold it in memory and hand the caller
+// an unbounded error string. 1 MiB matches the cap internal/models/api applies
+// to its own error bodies and sits far above any structured error the server
+// emits.
+const maxErrorBodyBytes = 1 << 20
+
+// readErrorBody reads the diagnostic body of a failed response, bounded by
+// maxErrorBodyBytes.
+//
+// Truncating here costs nothing: callers branch on the status code and on
+// APIError.Code, and the body exists only to explain the failure. The read error
+// is dropped, as before, so a broken connection cannot mask the HTTP status.
+func readErrorBody(r io.Reader) []byte {
+ body, _ := io.ReadAll(io.LimitReader(r, maxErrorBodyBytes))
+ return body
+}
+
// extractServerCode pulls the server's structured error code from a JSON error
// body ({"code":1003,...}). Returns 0 when the body isn't JSON or carries no code.
func extractServerCode(body []byte) int {
@@ -286,8 +308,7 @@ func parseResponse(resp *http.Response, target interface{}) error {
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- body, _ := io.ReadAll(resp.Body)
- return newAPIError(resp.StatusCode, body)
+ return newAPIError(resp.StatusCode, readErrorBody(resp.Body))
}
if target == nil {
diff --git a/client/knowledge.go b/client/knowledge.go
index a551818fa..555481abf 100644
--- a/client/knowledge.go
+++ b/client/knowledge.go
@@ -546,7 +546,7 @@ func (c *Client) OpenKnowledgeFile(ctx context.Context, knowledgeID string) (str
return "", nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- body, _ := io.ReadAll(resp.Body)
+ body := readErrorBody(resp.Body)
_ = resp.Body.Close()
return "", nil, newAPIError(resp.StatusCode, body)
}
@@ -592,7 +592,7 @@ func (c *Client) OpenKnowledgeFilesArchive(ctx context.Context, knowledgeBaseID
return "", nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- body, _ := io.ReadAll(resp.Body)
+ body := readErrorBody(resp.Body)
_ = resp.Body.Close()
return "", nil, newAPIError(resp.StatusCode, body)
}
diff --git a/client/response_limit_test.go b/client/response_limit_test.go
new file mode 100644
index 000000000..a52bf83cd
--- /dev/null
+++ b/client/response_limit_test.go
@@ -0,0 +1,101 @@
+package client
+
+import (
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+ "testing"
+)
+
+// fillerReader streams n bytes without allocating them, so a test can hand the
+// SDK a response body far larger than the cap without spending memory itself.
+type fillerReader struct {
+ remaining int64
+}
+
+func (f *fillerReader) Read(p []byte) (int, error) {
+ if f.remaining <= 0 {
+ return 0, io.EOF
+ }
+ if int64(len(p)) > f.remaining {
+ p = p[:f.remaining]
+ }
+ for i := range p {
+ p[i] = 'x'
+ }
+ f.remaining -= int64(len(p))
+ return len(p), nil
+}
+
+func newTestResponse(status int, body io.Reader) *http.Response {
+ return &http.Response{StatusCode: status, Body: io.NopCloser(body)}
+}
+
+// A non-2xx body is copied into APIError.Body and interpolated into
+// APIError.Error(), so it must not be able to grow without bound.
+func TestParseResponseCapsErrorBody(t *testing.T) {
+ t.Run("oversized body is truncated to the cap", func(t *testing.T) {
+ const oversized = maxErrorBodyBytes * 4
+
+ err := parseResponse(newTestResponse(http.StatusBadGateway, &fillerReader{remaining: oversized}), nil)
+
+ var apiErr *APIError
+ if !errors.As(err, &apiErr) {
+ t.Fatalf("parseResponse() = %v, want *APIError", err)
+ }
+ if got := len(apiErr.Body); got != maxErrorBodyBytes {
+ t.Errorf("len(APIError.Body) = %d, want the %d byte cap", got, maxErrorBodyBytes)
+ }
+ })
+
+ t.Run("body exactly at the cap is kept whole", func(t *testing.T) {
+ body := strings.Repeat("a", maxErrorBodyBytes)
+
+ err := parseResponse(newTestResponse(http.StatusInternalServerError, strings.NewReader(body)), nil)
+
+ var apiErr *APIError
+ if !errors.As(err, &apiErr) {
+ t.Fatalf("parseResponse() = %v, want *APIError", err)
+ }
+ if len(apiErr.Body) != maxErrorBodyBytes {
+ t.Errorf("len(APIError.Body) = %d, want %d", len(apiErr.Body), maxErrorBodyBytes)
+ }
+ })
+}
+
+// The cap must not disturb the normal error path: a structured body still
+// reaches the caller verbatim and its {"code":N} is still extracted.
+func TestParseResponseKeepsSmallErrorBody(t *testing.T) {
+ const body = `{"code":1003,"msg":"knowledge not found"}`
+
+ err := parseResponse(newTestResponse(http.StatusNotFound, strings.NewReader(body)), nil)
+
+ var apiErr *APIError
+ if !errors.As(err, &apiErr) {
+ t.Fatalf("parseResponse() = %v, want *APIError", err)
+ }
+ if apiErr.Body != body {
+ t.Errorf("APIError.Body = %q, want %q", apiErr.Body, body)
+ }
+ if apiErr.Code != ServerErrNotFound {
+ t.Errorf("APIError.Code = %d, want %d", apiErr.Code, ServerErrNotFound)
+ }
+ if !strings.Contains(apiErr.Error(), body) {
+ t.Errorf("APIError.Error() = %q, want it to carry the server body", apiErr.Error())
+ }
+}
+
+// The cap only applies to failures; a successful response still decodes.
+func TestParseResponseStillDecodesSuccessBody(t *testing.T) {
+ var got struct {
+ Name string `json:"name"`
+ }
+
+ if err := parseResponse(newTestResponse(http.StatusOK, strings.NewReader(`{"name":"ok"}`)), &got); err != nil {
+ t.Fatalf("parseResponse() = %v, want nil", err)
+ }
+ if got.Name != "ok" {
+ t.Errorf("decoded name = %q, want %q", got.Name, "ok")
+ }
+}
diff --git a/client/session.go b/client/session.go
index cba820faf..36e6a6861 100644
--- a/client/session.go
+++ b/client/session.go
@@ -9,7 +9,6 @@ import (
"context"
"encoding/json"
"fmt"
- "io"
"net/http"
"net/url"
"strconv"
@@ -321,8 +320,7 @@ func (c *Client) KnowledgeQAStream(
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- body, _ := io.ReadAll(resp.Body)
- err := newAPIError(resp.StatusCode, body)
+ err := newAPIError(resp.StatusCode, readErrorBody(resp.Body))
debugLogger.Debug("request_error_status", "error", err)
return err
}
@@ -417,8 +415,7 @@ func (c *Client) ContinueStream(
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- body, _ := io.ReadAll(resp.Body)
- return newAPIError(resp.StatusCode, body)
+ return newAPIError(resp.StatusCode, readErrorBody(resp.Body))
}
// Use bufio to read SSE data line by line
@@ -561,8 +558,7 @@ func (c *Client) SearchKnowledgeDetailed(
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- body, _ := io.ReadAll(resp.Body)
- err := newAPIError(resp.StatusCode, body)
+ err := newAPIError(resp.StatusCode, readErrorBody(resp.Body))
debugLogger.Debug("request_error_status", "error", err)
return nil, err
}