|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "io" |
| 7 | + "net/http" |
| 8 | + "net/http/httptest" |
| 9 | + "strings" |
| 10 | + "testing" |
| 11 | + "time" |
| 12 | + |
| 13 | + secutils "github.com/Tencent/WeKnora/internal/utils" |
| 14 | +) |
| 15 | + |
| 16 | +// fillerReader streams size bytes without allocating them, so a test can offer |
| 17 | +// a body far larger than the cap without spending the memory. |
| 18 | +type fillerReader struct { |
| 19 | + remaining int64 |
| 20 | +} |
| 21 | + |
| 22 | +func (f *fillerReader) Read(p []byte) (int, error) { |
| 23 | + if f.remaining <= 0 { |
| 24 | + return 0, io.EOF |
| 25 | + } |
| 26 | + if int64(len(p)) > f.remaining { |
| 27 | + p = p[:f.remaining] |
| 28 | + } |
| 29 | + for i := range p { |
| 30 | + p[i] = 'a' |
| 31 | + } |
| 32 | + f.remaining -= int64(len(p)) |
| 33 | + return len(p), nil |
| 34 | +} |
| 35 | + |
| 36 | +// allowLoopback whitelists the loopback host Endpoint.newPost's SSRF check |
| 37 | +// rejects, so a test can point an Endpoint at its own httptest server. |
| 38 | +func allowLoopback(t *testing.T) { |
| 39 | + t.Helper() |
| 40 | + t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") |
| 41 | + t.Setenv("SSRF_WHITELIST_EXTRA", "") |
| 42 | + secutils.ResetSSRFWhitelistForTest() |
| 43 | + t.Cleanup(secutils.ResetSSRFWhitelistForTest) |
| 44 | +} |
| 45 | + |
| 46 | +func TestReadResponseCapped(t *testing.T) { |
| 47 | + t.Run("rejects over the cap", func(t *testing.T) { |
| 48 | + const limit = 1 << 10 |
| 49 | + _, err := ReadResponseCapped(&fillerReader{remaining: limit + 1}, limit) |
| 50 | + if !errors.Is(err, ErrResponseTooLarge) { |
| 51 | + t.Fatalf("err = %v, want ErrResponseTooLarge", err) |
| 52 | + } |
| 53 | + if !strings.Contains(err.Error(), "exceeds maximum size") { |
| 54 | + t.Errorf("error text = %q, want the canonical over-size message", err) |
| 55 | + } |
| 56 | + }) |
| 57 | + |
| 58 | + t.Run("accepts exactly the cap", func(t *testing.T) { |
| 59 | + const limit = 1 << 10 |
| 60 | + got, err := ReadResponseCapped(strings.NewReader(strings.Repeat("a", limit)), limit) |
| 61 | + if err != nil { |
| 62 | + t.Fatalf("ReadResponseCapped() = %v, want nil at exactly the cap", err) |
| 63 | + } |
| 64 | + if len(got) != limit { |
| 65 | + t.Errorf("len = %d, want %d", len(got), limit) |
| 66 | + } |
| 67 | + }) |
| 68 | + |
| 69 | + t.Run("non-positive limit falls back to the production cap", func(t *testing.T) { |
| 70 | + if _, err := ReadResponseCapped(strings.NewReader(`{"ok":true}`), 0); err != nil { |
| 71 | + t.Fatalf("ReadResponseCapped(_, 0) = %v, want nil", err) |
| 72 | + } |
| 73 | + }) |
| 74 | +} |
| 75 | + |
| 76 | +// The cap must not silently truncate: a short read that still parses would look |
| 77 | +// like a successful reply with fewer fields than the vendor sent. |
| 78 | +func TestReadResponseCappedNeverTruncates(t *testing.T) { |
| 79 | + const limit = 1 << 10 |
| 80 | + got, err := ReadResponseCapped(strings.NewReader(strings.Repeat("a", limit*4)), limit) |
| 81 | + if err == nil { |
| 82 | + t.Fatalf("expected refusal, got %d bytes", len(got)) |
| 83 | + } |
| 84 | + if got != nil { |
| 85 | + t.Errorf("returned %d bytes alongside the error; a caller could decode them", len(got)) |
| 86 | + } |
| 87 | +} |
| 88 | + |
| 89 | +// PostJSON is the whole round-trip for rerank, embeddings and transcription. An |
| 90 | +// oversized success body has to surface as an error rather than a decode |
| 91 | +// failure on a truncated payload. |
| 92 | +// |
| 93 | +// Endpoint.newPost validates the URL, so the test server's loopback address has |
| 94 | +// to be whitelisted the same way other tests in this repo reach an httptest |
| 95 | +// server. |
| 96 | +func TestPostJSONRejectsOversizedBody(t *testing.T) { |
| 97 | + allowLoopback(t) |
| 98 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 99 | + w.Header().Set("Content-Type", "application/json") |
| 100 | + w.WriteHeader(http.StatusOK) |
| 101 | + _, _ = w.Write([]byte(`{"data":[`)) |
| 102 | + _, _ = io.Copy(w, &fillerReader{remaining: MaxResponseBytes + (1 << 20)}) |
| 103 | + })) |
| 104 | + defer srv.Close() |
| 105 | + |
| 106 | + var out map[string]any |
| 107 | + err := Endpoint{Client: srv.Client()}.PostJSON( |
| 108 | + context.Background(), srv.URL, []byte(`{}`), &out) |
| 109 | + if err == nil { |
| 110 | + t.Fatal("expected an oversized provider body to be refused") |
| 111 | + } |
| 112 | + if !errors.Is(err, ErrResponseTooLarge) { |
| 113 | + t.Errorf("err = %v, want ErrResponseTooLarge", err) |
| 114 | + } |
| 115 | + if out != nil { |
| 116 | + t.Errorf("out = %v, want nothing decoded from a refused body", out) |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +// withRetry retries only TransportError. An oversized reply is the same answer |
| 121 | +// every time, and retrying it bills the request again for the same bytes, so it |
| 122 | +// must not be classified as a transport failure. |
| 123 | +func TestOversizedBodyIsNotRetried(t *testing.T) { |
| 124 | + allowLoopback(t) |
| 125 | + |
| 126 | + var attempts int |
| 127 | + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 128 | + attempts++ |
| 129 | + w.WriteHeader(http.StatusOK) |
| 130 | + _, _ = w.Write([]byte(`{"data":[`)) |
| 131 | + _, _ = io.Copy(w, &fillerReader{remaining: MaxResponseBytes + (1 << 20)}) |
| 132 | + })) |
| 133 | + defer srv.Close() |
| 134 | + |
| 135 | + policy := RetryPolicy{MaxRetries: 3, BaseDelay: time.Millisecond, MaxDelay: time.Millisecond} |
| 136 | + var out map[string]any |
| 137 | + err := Endpoint{Client: srv.Client()}.PostJSONWithRetry( |
| 138 | + context.Background(), srv.URL, []byte(`{}`), &out, policy, "embedding") |
| 139 | + if err == nil { |
| 140 | + t.Fatal("expected an oversized provider body to be refused") |
| 141 | + } |
| 142 | + if attempts != 1 { |
| 143 | + t.Errorf("made %d attempts, want 1: an oversized reply is deterministic "+ |
| 144 | + "and retrying it bills the request again", attempts) |
| 145 | + } |
| 146 | +} |
0 commit comments