Only the Codex backend path decoded a Content-Encoding (codexReader); /v1/responses, /v1/chat/completions, /v1/messages, count_tokens, Gemini's routes, embeddings, images, videos and System One read the compressed bytes as JSON. Codex sends zstd to a custom provider's /v1/responses by default. readBoundedRequestBody now always decodes (decodedBody, moved from codexReader): identity, gzip and zstd are read, the header is dropped so the provider gets plain JSON, the size limit holds for the decoded bytes (413), and any other encoding is refused 415 naming it. keyLimited reads a limited key's compressed body the same way, so its reservation is the decoded size, not the compressed one. Verified: request_encoding_test.go posts real gzip and zstd bodies to a running httptest server of New().Handler() on every route. Without the change TestEncodedBodiesOnEveryRoute and TestEncodedEmbeddingsBody fail with 400 "expected a JSON object" / "the body isn't a JSON object", TestEncodedBodyInflatedPastLimit gets 400 instead of 413, TestUnknownBodyEncodingRefused gets 400/502 instead of 415, and with only key_limit.go reverted TestKeyLimitReservesDecodedBody fails "held at 19 tokens for a 40061-byte body sent as 79 bytes". gofmt; go vet -tags nogui ./internal/gateway for GOOS linux, windows, darwin; go test -tags nogui ./internal/gateway (temp HOME, pinned caches) ok; the new tests -race -count=5 ok. Not tried with the real Codex CLI.
137 lines
3.9 KiB
Go
137 lines
3.9 KiB
Go
package gateway
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/provider"
|
|
)
|
|
|
|
func TestRequestBodyProgressRenewsIdleDeadline(t *testing.T) {
|
|
for _, encoding := range []string{"identity", "gzip", "zstd"} {
|
|
t.Run(encoding, func(t *testing.T) {
|
|
payload := bytes.Repeat([]byte("body"), 128)
|
|
wire := encodedBody(t, payload, encoding)
|
|
s := New()
|
|
s.requestLimits.readTimeout = 200 * time.Millisecond
|
|
gw := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
body, ok := s.readRequestBody(w, r, provider.Responses, 0)
|
|
if !ok {
|
|
return
|
|
}
|
|
if !bytes.Equal(body, payload) {
|
|
t.Error("body changed")
|
|
}
|
|
io.WriteString(w, "ok")
|
|
}))
|
|
defer gw.Close()
|
|
conn, err := net.Dial("tcp", strings.TrimPrefix(gw.URL, "http://"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer conn.Close()
|
|
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
|
fmt.Fprintf(conn, "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: %d\r\nContent-Encoding: %s\r\n\r\n", len(wire), encoding)
|
|
// Six progressing reads take longer than one idle interval.
|
|
step := (len(wire) + 5) / 6
|
|
for offset := 0; offset < len(wire); offset += step {
|
|
time.Sleep(50 * time.Millisecond)
|
|
if _, err := conn.Write(wire[offset:min(offset+step, len(wire))]); err != nil {
|
|
break
|
|
}
|
|
}
|
|
res, err := http.ReadResponse(bufio.NewReader(conn), nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer res.Body.Close()
|
|
if res.StatusCode != 200 {
|
|
t.Fatalf("progressing upload: %d", res.StatusCode)
|
|
}
|
|
body, err := io.ReadAll(res.Body)
|
|
if err != nil || string(body) != "ok" {
|
|
t.Fatalf("response: %q, %v", body, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestAdditionalBodyReadersHaveDeadlines(t *testing.T) {
|
|
for _, api := range []string{"systemone", "mcp"} {
|
|
t.Run(api, func(t *testing.T) {
|
|
deadlines := []time.Time{}
|
|
w := httptest.NewRecorder()
|
|
r := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
|
|
if api == "systemone" {
|
|
New().serveSystemOne(deadlineRecorder{w, &deadlines}, r)
|
|
} else {
|
|
r.SetPathValue("token", "run")
|
|
b := &subscriptionBridge{runs: map[string]*subscriptionRun{"run": {}}}
|
|
b.mcpCall(deadlineRecorder{w, &deadlines}, r)
|
|
}
|
|
if len(deadlines) < 2 || deadlines[0].IsZero() || !deadlines[len(deadlines)-1].IsZero() {
|
|
t.Fatalf("body deadlines: %v", deadlines)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestMCPBodyTooLarge(t *testing.T) {
|
|
r := httptest.NewRequest("POST", "/", strings.NewReader(`{}`))
|
|
r.SetPathValue("token", "run")
|
|
r.ContentLength = 17 << 20
|
|
w := httptest.NewRecorder()
|
|
b := &subscriptionBridge{runs: map[string]*subscriptionRun{"run": {}}}
|
|
b.mcpCall(w, r)
|
|
if w.Code != 413 {
|
|
t.Fatalf("oversize MCP: %d", w.Code)
|
|
}
|
|
}
|
|
|
|
func TestMediaJSONPastOldBodyLimit(t *testing.T) {
|
|
payload := append(bytes.Repeat([]byte(" "), 64<<20), []byte(`{"model":"fake/m1","prompt":"tail"}`)...)
|
|
for _, api := range []string{"images", "videos"} {
|
|
t.Run(api, func(t *testing.T) {
|
|
r := httptest.NewRequest("POST", "/", bytes.NewReader(payload))
|
|
var prompt string
|
|
var err error
|
|
if api == "images" {
|
|
d, e := readDrawing(r)
|
|
prompt, err = d.Prompt, e
|
|
} else {
|
|
f, e := readFilming(r)
|
|
prompt, err = f.Prompt, e
|
|
}
|
|
if err != nil || prompt != "tail" {
|
|
t.Fatalf("media body: %q, %v", prompt, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestBodyRejectionErrorShapes(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
proto provider.Protocol
|
|
status int
|
|
want string
|
|
}{
|
|
{provider.Anthropic, 413, `"type":"request_too_large"`},
|
|
{provider.Gemini, 413, `"status":"INVALID_ARGUMENT"`},
|
|
{provider.Gemini, 408, `"status":"DEADLINE_EXCEEDED"`},
|
|
} {
|
|
w := httptest.NewRecorder()
|
|
writeError(w, tc.proto, tc.status, "request body rejected")
|
|
if !strings.Contains(w.Body.String(), tc.want) {
|
|
t.Fatalf("%s/%d: %s", tc.proto, tc.status, w.Body.String())
|
|
}
|
|
}
|
|
}
|