diff --git a/internal/models/api/anthropicmessages/client.go b/internal/models/api/anthropicmessages/client.go index 0edc39e1..30360773 100644 --- a/internal/models/api/anthropicmessages/client.go +++ b/internal/models/api/anthropicmessages/client.go @@ -118,7 +118,7 @@ func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Opt } } defer func() { _ = resp.body.Close() }() - raw, err := io.ReadAll(resp.body) + raw, err := api.ReadResponseCapped(resp.body, 0) if err != nil { return nil, fmt.Errorf("read response: %w", err) } diff --git a/internal/models/api/endpoint.go b/internal/models/api/endpoint.go index 3df928d0..14e119ed 100644 --- a/internal/models/api/endpoint.go +++ b/internal/models/api/endpoint.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -172,8 +173,15 @@ func (e Endpoint) roundTrip(req *http.Request, out any) error { return err } defer func() { _ = resp.Body.Close() }() - raw, err := io.ReadAll(resp.Body) + raw, err := ReadResponseCapped(resp.Body, 0) if err != nil { + // A body over the cap is the vendor answering with something we cannot + // use, not the network failing. withRetry retries only TransportError, + // and repeating an oversized reply would bill the request again for the + // same bytes, so it is returned as-is. + if errors.Is(err, ErrResponseTooLarge) { + return err + } // The connection broke before the reply arrived whole: nothing was // received, so this is the network failing, not the vendor answering. return &TransportError{Op: "read response", Err: err} diff --git a/internal/models/api/googlegenai/client.go b/internal/models/api/googlegenai/client.go index 4bb1e2b5..14081189 100644 --- a/internal/models/api/googlegenai/client.go +++ b/internal/models/api/googlegenai/client.go @@ -117,7 +117,7 @@ func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Opt } } defer func() { _ = resp.Body.Close() }() - raw, err := io.ReadAll(resp.Body) + raw, err := api.ReadResponseCapped(resp.Body, 0) if err != nil { return nil, fmt.Errorf("read response: %w", err) } diff --git a/internal/models/api/openaicompletions/client.go b/internal/models/api/openaicompletions/client.go index ee789cfd..d001a97f 100644 --- a/internal/models/api/openaicompletions/client.go +++ b/internal/models/api/openaicompletions/client.go @@ -84,7 +84,7 @@ func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Opt } } defer func() { _ = resp.Body.Close() }() - raw, err := io.ReadAll(resp.Body) + raw, err := api.ReadResponseCapped(resp.Body, 0) if err != nil { return nil, fmt.Errorf("read response: %w", err) } diff --git a/internal/models/api/openairesponses/client.go b/internal/models/api/openairesponses/client.go index 2949a57a..a38270b3 100644 --- a/internal/models/api/openairesponses/client.go +++ b/internal/models/api/openairesponses/client.go @@ -84,7 +84,7 @@ func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Opt } } defer func() { _ = resp.Body.Close() }() - raw, err := io.ReadAll(resp.Body) + raw, err := api.ReadResponseCapped(resp.Body, 0) if err != nil { return nil, fmt.Errorf("read response: %w", err) } diff --git a/internal/models/api/response_limit.go b/internal/models/api/response_limit.go new file mode 100644 index 00000000..af3c1c20 --- /dev/null +++ b/internal/models/api/response_limit.go @@ -0,0 +1,45 @@ +package api + +import ( + "errors" + "fmt" + "io" +) + +// MaxResponseBytes bounds a single non-streaming provider response body. +// +// Streaming replies are assembled incrementally and are not covered by this. It +// has to clear every non-streaming payload the catalog can legitimately return: +// an embeddings batch is bounded by BATCH_EMBED_SIZE (default 5) times the +// model's dimensions, and a chat reply by the model's output-token ceiling, so +// both sit far below this even at their largest. It is also well above the 20 MiB +// the older models/chat layer applies to the same replies, so nothing that +// worked before can be refused by it. +const MaxResponseBytes = 64 << 20 + +// ErrResponseTooLarge marks a body over the cap. It is deterministic: the same +// request returns the same oversized body, so a retry cannot help. +var ErrResponseTooLarge = errors.New("response exceeds maximum size") + +// ReadResponseCapped reads a non-streaming response body, refusing anything +// larger than limit instead of buffering it. Oversized payloads are reported as +// an error rather than truncated, because a truncated body would otherwise be +// decoded as if it were the whole reply - producing a short answer or a +// plausible-looking partial embedding instead of an error. A non-positive limit +// falls back to MaxResponseBytes. +// +// Endpoint.Do already bounds the error body; this is the same guard for the +// success body, which until now was read whole. +func ReadResponseCapped(body io.Reader, limit int64) ([]byte, error) { + if limit <= 0 { + limit = MaxResponseBytes + } + 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 +} diff --git a/internal/models/api/response_limit_test.go b/internal/models/api/response_limit_test.go new file mode 100644 index 00000000..323c134a --- /dev/null +++ b/internal/models/api/response_limit_test.go @@ -0,0 +1,146 @@ +package api + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + secutils "github.com/Tencent/WeKnora/internal/utils" +) + +// fillerReader streams size bytes without allocating them, so a test can offer +// a body far larger than the cap without spending the memory. +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] = 'a' + } + f.remaining -= int64(len(p)) + return len(p), nil +} + +// allowLoopback whitelists the loopback host Endpoint.newPost's SSRF check +// rejects, so a test can point an Endpoint at its own httptest server. +func allowLoopback(t *testing.T) { + t.Helper() + t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") + t.Setenv("SSRF_WHITELIST_EXTRA", "") + secutils.ResetSSRFWhitelistForTest() + t.Cleanup(secutils.ResetSSRFWhitelistForTest) +} + +func TestReadResponseCapped(t *testing.T) { + t.Run("rejects over the cap", func(t *testing.T) { + const limit = 1 << 10 + _, err := ReadResponseCapped(&fillerReader{remaining: limit + 1}, limit) + if !errors.Is(err, ErrResponseTooLarge) { + t.Fatalf("err = %v, want ErrResponseTooLarge", err) + } + if !strings.Contains(err.Error(), "exceeds maximum size") { + t.Errorf("error text = %q, want the canonical over-size message", err) + } + }) + + t.Run("accepts exactly the cap", func(t *testing.T) { + const limit = 1 << 10 + got, err := ReadResponseCapped(strings.NewReader(strings.Repeat("a", limit)), limit) + if err != nil { + t.Fatalf("ReadResponseCapped() = %v, want nil at exactly the cap", err) + } + if len(got) != limit { + t.Errorf("len = %d, want %d", len(got), limit) + } + }) + + t.Run("non-positive limit falls back to the production cap", func(t *testing.T) { + if _, err := ReadResponseCapped(strings.NewReader(`{"ok":true}`), 0); err != nil { + t.Fatalf("ReadResponseCapped(_, 0) = %v, want nil", err) + } + }) +} + +// The cap must not silently truncate: a short read that still parses would look +// like a successful reply with fewer fields than the vendor sent. +func TestReadResponseCappedNeverTruncates(t *testing.T) { + const limit = 1 << 10 + got, err := ReadResponseCapped(strings.NewReader(strings.Repeat("a", limit*4)), limit) + if err == nil { + t.Fatalf("expected refusal, got %d bytes", len(got)) + } + if got != nil { + t.Errorf("returned %d bytes alongside the error; a caller could decode them", len(got)) + } +} + +// PostJSON is the whole round-trip for rerank, embeddings and transcription. An +// oversized success body has to surface as an error rather than a decode +// failure on a truncated payload. +// +// Endpoint.newPost validates the URL, so the test server's loopback address has +// to be whitelisted the same way other tests in this repo reach an httptest +// server. +func TestPostJSONRejectsOversizedBody(t *testing.T) { + allowLoopback(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"data":[`)) + _, _ = io.Copy(w, &fillerReader{remaining: MaxResponseBytes + (1 << 20)}) + })) + defer srv.Close() + + var out map[string]any + err := Endpoint{Client: srv.Client()}.PostJSON( + context.Background(), srv.URL, []byte(`{}`), &out) + if err == nil { + t.Fatal("expected an oversized provider body to be refused") + } + if !errors.Is(err, ErrResponseTooLarge) { + t.Errorf("err = %v, want ErrResponseTooLarge", err) + } + if out != nil { + t.Errorf("out = %v, want nothing decoded from a refused body", out) + } +} + +// withRetry retries only TransportError. An oversized reply is the same answer +// every time, and retrying it bills the request again for the same bytes, so it +// must not be classified as a transport failure. +func TestOversizedBodyIsNotRetried(t *testing.T) { + allowLoopback(t) + + var attempts int + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + attempts++ + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{"data":[`)) + _, _ = io.Copy(w, &fillerReader{remaining: MaxResponseBytes + (1 << 20)}) + })) + defer srv.Close() + + policy := RetryPolicy{MaxRetries: 3, BaseDelay: time.Millisecond, MaxDelay: time.Millisecond} + var out map[string]any + err := Endpoint{Client: srv.Client()}.PostJSONWithRetry( + context.Background(), srv.URL, []byte(`{}`), &out, policy, "embedding") + if err == nil { + t.Fatal("expected an oversized provider body to be refused") + } + if attempts != 1 { + t.Errorf("made %d attempts, want 1: an oversized reply is deterministic "+ + "and retrying it bills the request again", attempts) + } +}