fix(api): decode gzip request bodies and honor Content-Encoding on Claude routes

- Add gzip/x-gzip support to the shared request body decoder with the configured decoded-size cap, and drop Content-Encoding after a successful decode so nothing downstream decodes or forwards it again.
- Switch ClaudeMessages and ClaudeCountTokens to handlers.ReadRequestBody, and mirror the change in the plugin auth pre-decode path (gzip support, plus /v1/messages and /v1/messages/count_tokens in handlerDecodesBody) and the request-log capture decoder.

Closes: #7711
This commit is contained in:
Luis Pater
2026-11-20 10:49:38 +08:00
parent bba22ed9be
commit 6e7a1b294a
8 changed files with 455 additions and 5 deletions

View File

@@ -5,6 +5,7 @@ package middleware
import (
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
@@ -492,6 +493,18 @@ func decodeCapturedRequestBodyForLogWithLimit(raw []byte, encoding string, limit
}
return append(body, "[DECOMPRESSED REQUEST BODY TRUNCATED]"...)
}
case "gzip", "x-gzip":
decoded, truncated, errDecode := decodeCapturedGzipRequestBodyWithLimit(body, limit)
if errDecode != nil {
return raw
}
body = decoded
if truncated {
if len(body) > 0 && !bytes.HasSuffix(body, []byte("\n")) {
body = append(body, '\n')
}
return append(body, "[DECOMPRESSED REQUEST BODY TRUNCATED]"...)
}
default:
return raw
}
@@ -499,6 +512,31 @@ func decodeCapturedRequestBodyForLogWithLimit(raw []byte, encoding string, limit
return body
}
func decodeCapturedGzipRequestBodyWithLimit(raw []byte, limit int64) ([]byte, bool, error) {
gzReader, errNewReader := gzip.NewReader(bytes.NewReader(raw))
if errNewReader != nil {
return nil, false, fmt.Errorf("failed to create gzip request decoder: %w", errNewReader)
}
defer func() {
if errClose := gzReader.Close(); errClose != nil {
log.Warnf("failed to close gzip request decoder for request log: %v", errClose)
}
}()
var reader io.Reader = gzReader
if limit > 0 && limit < math.MaxInt64 {
reader = io.LimitReader(gzReader, limit+1)
}
decoded, errRead := io.ReadAll(reader)
if errRead != nil {
return nil, false, fmt.Errorf("failed to decode gzip request body: %w", errRead)
}
if int64(len(decoded)) > limit {
return decoded[:limit], true, nil
}
return decoded, false, nil
}
func decodeCapturedZstdRequestBodyWithLimit(raw []byte, limit int64) ([]byte, bool, error) {
// One decoder goroutine and a bounded window: a frame that declares a larger window is not decoded (the raw bytes are logged).
decoder, errNewReader := zstd.NewReader(bytes.NewReader(raw), zstd.WithDecoderConcurrency(1), zstd.WithDecoderMaxWindow(maxCapturedZstdWindowBytes))

View File

@@ -2,6 +2,7 @@ package middleware
import (
"bytes"
"compress/gzip"
"context"
"encoding/hex"
"errors"
@@ -959,6 +960,30 @@ func TestDecodeCapturedZstdRefusesAnOversizedWindow(t *testing.T) {
}
}
// A gzip request body is decoded for the log under the same bound as zstd; truncation is marked.
func TestDecodeCapturedGzipRequestBody(t *testing.T) {
payload := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}]}`)
var compressed bytes.Buffer
w := gzip.NewWriter(&compressed)
if _, errWrite := w.Write(payload); errWrite != nil {
t.Fatalf("gzip write: %v", errWrite)
}
if errClose := w.Close(); errClose != nil {
t.Fatalf("gzip close: %v", errClose)
}
if got := decodeCapturedRequestBodyForLogWithLimit(compressed.Bytes(), "gzip", 1<<20); !bytes.Equal(got, payload) {
t.Fatalf("gzip decoded = %q, want %q", got, payload)
}
if got := decodeCapturedRequestBodyForLogWithLimit(compressed.Bytes(), "x-gzip", 1<<20); !bytes.Equal(got, payload) {
t.Fatalf("x-gzip decoded = %q, want %q", got, payload)
}
truncated := decodeCapturedRequestBodyForLogWithLimit(compressed.Bytes(), "gzip", 8)
if !bytes.HasSuffix(truncated, []byte("[DECOMPRESSED REQUEST BODY TRUNCATED]")) {
t.Fatalf("truncated = %q, want truncation marker", truncated)
}
}
func TestResponseWriterLogOnErrorOnlyZeroBufferUntilActionableError(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()

View File

@@ -2,6 +2,7 @@ package pluginhost
import (
"bytes"
"compress/gzip"
"context"
"errors"
"fmt"
@@ -55,6 +56,22 @@ func decodeAuthBody(body []byte, encoding string, limit int64) ([]byte, error) {
return nil, errReadAll
}
body = out
case "gzip", "x-gzip":
gzReader, errNewReader := gzip.NewReader(bytes.NewReader(body))
if errNewReader != nil {
return nil, errNewReader
}
out, errReadAll := io.ReadAll(io.LimitReader(gzReader, limit+1))
if errClose := gzReader.Close(); errClose != nil && errReadAll == nil {
errReadAll = errClose
}
if int64(len(out)) > limit {
return nil, errAuthBodyTooLarge
}
if errReadAll != nil {
return nil, errReadAll
}
body = out
default:
return nil, fmt.Errorf("unsupported request content encoding: %s", enc)
}
@@ -74,6 +91,7 @@ func handlerDecodesBody(r *http.Request) bool {
switch r.URL.Path {
case "/v1/chat/completions", "/v1/completions", "/v1/responses", "/v1/responses/compact",
"/backend-api/codex/responses", "/backend-api/codex/responses/compact",
"/v1/messages", "/v1/messages/count_tokens",
"/v1/images/generations", "/v1/audio/speech", "/v1/tts",
"/v1/videos", "/v1/videos/generations", "/v1/videos/edits", "/v1/videos/extensions":
return true

View File

@@ -2,6 +2,7 @@ package pluginhost
import (
"bytes"
"compress/gzip"
"context"
"encoding/hex"
"io"
@@ -57,6 +58,47 @@ func zstdCompress(t *testing.T, raw []byte) []byte {
return encoder.EncodeAll(raw, nil)
}
func gzipCompress(t *testing.T, raw []byte) []byte {
t.Helper()
var buf bytes.Buffer
w := gzip.NewWriter(&buf)
if _, errWrite := w.Write(raw); errWrite != nil {
t.Fatalf("gzip write: %v", errWrite)
}
if errClose := w.Close(); errClose != nil {
t.Fatalf("gzip close: %v", errClose)
}
return buf.Bytes()
}
// Claude routes now read through ReadRequestBody: zstd and gzip bodies on /v1/messages and
// /v1/messages/count_tokens reach the plugin as decoded JSON.
func TestAccessAdapterDecodesBodyForClaudeRoutes(t *testing.T) {
plain := []byte(`{"model":"claude-sonnet-4-5","messages":[{"role":"user","content":"hi"}]}`)
for _, tc := range []struct {
name, path, encoding string
body []byte
}{
{"messages zstd", "/v1/messages", "zstd", zstdCompress(t, plain)},
{"count_tokens zstd", "/v1/messages/count_tokens", "zstd", zstdCompress(t, plain)},
{"messages gzip", "/v1/messages", "gzip", gzipCompress(t, plain)},
{"count_tokens gzip", "/v1/messages/count_tokens", "gzip", gzipCompress(t, plain)},
} {
t.Run(tc.name, func(t *testing.T) {
seen, calls, _, authErr := authenticateWithBody(context.Background(), t, http.MethodPost, tc.path, tc.body, tc.encoding, 0)
if authErr != nil || calls != 1 {
t.Fatalf("authErr %v calls %d", authErr, calls)
}
if !bytes.Equal(seen.DecodedBody, plain) {
t.Fatalf("DecodedBody = %q, want %q", seen.DecodedBody, plain)
}
if !bytes.Equal(seen.Body, tc.body) || seen.Headers.Get("Content-Encoding") != tc.encoding {
t.Fatalf("Body or Headers are not raw: headers %v", seen.Headers)
}
})
}
}
// pi and the Codex CLI send zstd bodies on POST /v1/responses; the plugin gets the decoded JSON in
// DecodedBody, Body and Headers stay as sent, and the handler still gets the raw bytes.
func TestAccessAdapterDecodesZstdBodyForPlugin(t *testing.T) {
@@ -90,7 +132,6 @@ func TestAccessAdapterLeavesDecodedBodyNilWhereHandlerDoesNotDecode(t *testing.T
}{
{"GET responses upgrade", http.MethodGet, "/v1/responses", compressed},
{"GET codex responses upgrade", http.MethodGet, "/backend-api/codex/responses", compressed},
{"claude handler reads raw", http.MethodPost, "/v1/messages", compressed},
{"gemini handler reads raw", http.MethodPost, "/v1beta/models/m:generateContent", compressed},
{"plain JSON labeled zstd", http.MethodPost, "/v1/responses", plainJSON},
} {

View File

@@ -72,8 +72,8 @@ func (h *ClaudeCodeAPIHandler) Models() []map[string]any {
// Parameters:
// - c: The Gin context for the request.
func (h *ClaudeCodeAPIHandler) ClaudeMessages(c *gin.Context) {
// Extract raw JSON data from the incoming request
rawJSON, err := c.GetRawData()
// Extract raw JSON data from the incoming request, decoding any supported Content-Encoding.
rawJSON, err := handlers.ReadRequestBody(c)
// If data retrieval fails, return a 400 Bad Request error.
if err != nil {
c.JSON(clienterror.HTTPStatusFromErrorOr(err, http.StatusBadRequest), handlers.ErrorResponse{
@@ -104,8 +104,8 @@ func (h *ClaudeCodeAPIHandler) ClaudeMessages(c *gin.Context) {
// Parameters:
// - c: The Gin context for the request.
func (h *ClaudeCodeAPIHandler) ClaudeCountTokens(c *gin.Context) {
// Extract raw JSON data from the incoming request
rawJSON, err := c.GetRawData()
// Extract raw JSON data from the incoming request, decoding any supported Content-Encoding.
rawJSON, err := handlers.ReadRequestBody(c)
// If data retrieval fails, return a 400 Bad Request error.
if err != nil {
c.JSON(clienterror.HTTPStatusFromErrorOr(err, http.StatusBadRequest), handlers.ErrorResponse{

View File

@@ -0,0 +1,169 @@
package claude
import (
"bytes"
"compress/gzip"
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/gin-gonic/gin"
"github.com/klauspost/compress/zstd"
"github.com/router-for-me/CLIProxyAPI/v8/internal/registry"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/api/handlers"
coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
coreexecutor "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/executor"
sdkconfig "github.com/router-for-me/CLIProxyAPI/v8/sdk/config"
)
type issue7711ClaudeExecutor struct {
called *int32
gotRequest *coreexecutor.Request
gotOptions *coreexecutor.Options
}
func (e *issue7711ClaudeExecutor) Identifier() string { return "claude" }
func (e *issue7711ClaudeExecutor) record(req coreexecutor.Request, opts coreexecutor.Options) {
atomic.AddInt32(e.called, 1)
*e.gotRequest = req
*e.gotOptions = opts
}
func (e *issue7711ClaudeExecutor) Execute(_ context.Context, _ *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) {
coreexecutor.MarkUpstreamAttempt(context.Background())
e.record(req, opts)
return coreexecutor.Response{Payload: []byte(`{"type":"message","model":"m"}`)}, nil
}
func (e *issue7711ClaudeExecutor) ExecuteStream(_ context.Context, _ *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (*coreexecutor.StreamResult, error) {
coreexecutor.MarkUpstreamAttempt(context.Background())
e.record(req, opts)
chunks := make(chan coreexecutor.StreamChunk)
close(chunks)
return &coreexecutor.StreamResult{Chunks: chunks}, nil
}
func (e *issue7711ClaudeExecutor) CountTokens(_ context.Context, _ *coreauth.Auth, req coreexecutor.Request, opts coreexecutor.Options) (coreexecutor.Response, error) {
coreexecutor.MarkUpstreamAttempt(context.Background())
e.record(req, opts)
return coreexecutor.Response{Payload: []byte(`{"input_tokens":1}`)}, nil
}
func (e *issue7711ClaudeExecutor) Refresh(_ context.Context, auth *coreauth.Auth) (*coreauth.Auth, error) {
return auth, nil
}
func (e *issue7711ClaudeExecutor) HttpRequest(_ context.Context, _ *coreauth.Auth, _ *http.Request) (*http.Response, error) {
return nil, nil
}
func issue7711Gzip(t *testing.T, plain []byte) []byte {
t.Helper()
var buf bytes.Buffer
w := gzip.NewWriter(&buf)
if _, errWrite := w.Write(plain); errWrite != nil {
t.Fatalf("gzip write: %v", errWrite)
}
if errClose := w.Close(); errClose != nil {
t.Fatalf("gzip close: %v", errClose)
}
return buf.Bytes()
}
func issue7711Zstd(t *testing.T, plain []byte) []byte {
t.Helper()
var buf bytes.Buffer
w, errNew := zstd.NewWriter(&buf)
if errNew != nil {
t.Fatalf("zstd writer: %v", errNew)
}
if _, errWrite := w.Write(plain); errWrite != nil {
t.Fatalf("zstd write: %v", errWrite)
}
if errClose := w.Close(); errClose != nil {
t.Fatalf("zstd close: %v", errClose)
}
return buf.Bytes()
}
// TestClaudeRoutesDecodeRequestBody verifies that /v1/messages and
// /v1/messages/count_tokens decode Content-Encoding request bodies through the
// shared ReadRequestBody path instead of reading compressed bytes raw.
func TestClaudeRoutesDecodeRequestBody(t *testing.T) {
gin.SetMode(gin.TestMode)
plain := []byte(`{"model":"issue-7711-claude-model","max_tokens":5,"messages":[{"role":"user","content":"hi"}]}`)
for _, tc := range []struct {
name string
path string
encoding string
body []byte
}{
{name: "messages_gzip", path: "/v1/messages", encoding: "gzip", body: issue7711Gzip(t, plain)},
{name: "messages_zstd", path: "/v1/messages", encoding: "zstd", body: issue7711Zstd(t, plain)},
{name: "count_tokens_gzip", path: "/v1/messages/count_tokens", encoding: "gzip", body: issue7711Gzip(t, plain)},
{name: "count_tokens_zstd", path: "/v1/messages/count_tokens", encoding: "zstd", body: issue7711Zstd(t, plain)},
{name: "messages_plain", path: "/v1/messages", encoding: "", body: plain},
} {
t.Run(tc.name, func(t *testing.T) {
var called int32
var gotReq coreexecutor.Request
var gotOpts coreexecutor.Options
manager := coreauth.NewManager(nil, nil, nil)
manager.RegisterExecutor(&issue7711ClaudeExecutor{called: &called, gotRequest: &gotReq, gotOptions: &gotOpts})
reg := registry.GetGlobalRegistry()
authID := fmt.Sprintf("issue-7711-%s", tc.name)
auth := &coreauth.Auth{
ID: authID,
Provider: "claude",
Status: coreauth.StatusActive,
Attributes: map[string]string{"api_key": "key"},
}
if _, errReg := manager.Register(context.Background(), auth); errReg != nil {
t.Fatalf("register auth: %v", errReg)
}
reg.RegisterClient(authID, "claude", []*registry.ModelInfo{{ID: "issue-7711-claude-model"}})
t.Cleanup(func() {
reg.UnregisterClient(authID)
})
handler := NewClaudeCodeAPIHandler(handlers.NewBaseAPIHandlers(&sdkconfig.SDKConfig{}, manager))
router := gin.New()
router.POST("/v1/messages", handler.ClaudeMessages)
router.POST("/v1/messages/count_tokens", handler.ClaudeCountTokens)
req := httptest.NewRequest(http.MethodPost, tc.path, bytes.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
if tc.encoding != "" {
req.Header.Set("Content-Encoding", tc.encoding)
}
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if got := atomic.LoadInt32(&called); got == 0 {
t.Fatalf("executor was never reached; handler saw compressed bytes (status=%d body=%s)", rec.Code, rec.Body.String())
}
if strings.Contains(rec.Body.String(), "unknown provider for model") {
t.Fatalf("misleading model-routing error: %s", rec.Body.String())
}
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body=%s", rec.Code, rec.Body.String())
}
// The executor must see the same bytes a plain request delivers, and the
// decoded body must not travel with a stale Content-Encoding header.
if !bytes.Equal(gotReq.Payload, plain) {
t.Fatalf("executor payload = %q, want %q", gotReq.Payload, plain)
}
if gotOpts.Headers != nil && gotOpts.Headers.Get("Content-Encoding") != "" {
t.Fatalf("executor options still carry Content-Encoding %q", gotOpts.Headers.Get("Content-Encoding"))
}
})
}
}

View File

@@ -2,6 +2,7 @@ package handlers
import (
"bytes"
"compress/gzip"
"errors"
"fmt"
"io"
@@ -12,6 +13,7 @@ import (
"github.com/MoeForge/moego/json"
"github.com/gin-gonic/gin"
"github.com/klauspost/compress/zstd"
log "github.com/sirupsen/logrus"
)
// MaxRequestBodyBytesContextKey stores the configured request body size limit (in bytes) on the Gin context.
@@ -48,6 +50,9 @@ func ReadRequestBody(c *gin.Context) ([]byte, error) {
}
return nil, err
}
// The body is now plaintext: drop Content-Encoding so nothing downstream
// (executors, plugins, header passthrough) decodes or forwards it again.
c.Request.Header.Del("Content-Encoding")
return decoded, nil
}
@@ -65,6 +70,12 @@ func decodeRequestBody(raw []byte, encoding string, maxBytes int64) ([]byte, err
return nil, err
}
body = decoded
case "gzip", "x-gzip":
decoded, err := decodeGzipRequestBody(body, maxBytes)
if err != nil {
return nil, err
}
body = decoded
default:
return nil, fmt.Errorf("unsupported request content encoding: %s", enc)
}
@@ -72,6 +83,31 @@ func decodeRequestBody(raw []byte, encoding string, maxBytes int64) ([]byte, err
return body, nil
}
func decodeGzipRequestBody(raw []byte, maxBytes int64) ([]byte, error) {
gzReader, errNewReader := gzip.NewReader(bytes.NewReader(raw))
if errNewReader != nil {
return nil, fmt.Errorf("failed to create gzip request decoder: %w", errNewReader)
}
defer func() {
if errClose := gzReader.Close(); errClose != nil {
log.Warnf("failed to close gzip request decoder: %v", errClose)
}
}()
var reader io.Reader = gzReader
if maxBytes > 0 && maxBytes < math.MaxInt64 {
reader = io.LimitReader(gzReader, maxBytes+1)
}
decoded, errReadAll := io.ReadAll(reader)
if errReadAll != nil {
return nil, fmt.Errorf("failed to decode gzip request body: %w", errReadAll)
}
if maxBytes > 0 && int64(len(decoded)) > maxBytes {
return nil, &http.MaxBytesError{Limit: maxBytes}
}
return decoded, nil
}
func decodeZstdRequestBody(raw []byte, maxBytes int64) ([]byte, error) {
decoder, err := zstd.NewReader(bytes.NewReader(raw))
if err != nil {

View File

@@ -0,0 +1,123 @@
package handlers
import (
"bytes"
"compress/gzip"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/klauspost/compress/zstd"
)
func gzipBody(t *testing.T, plain []byte) []byte {
t.Helper()
var buf bytes.Buffer
w := gzip.NewWriter(&buf)
if _, errWrite := w.Write(plain); errWrite != nil {
t.Fatalf("gzip write: %v", errWrite)
}
if errClose := w.Close(); errClose != nil {
t.Fatalf("gzip close: %v", errClose)
}
return buf.Bytes()
}
func zstdBody(t *testing.T, plain []byte) []byte {
t.Helper()
var buf bytes.Buffer
w, errNew := zstd.NewWriter(&buf)
if errNew != nil {
t.Fatalf("zstd writer: %v", errNew)
}
if _, errWrite := w.Write(plain); errWrite != nil {
t.Fatalf("zstd write: %v", errWrite)
}
if errClose := w.Close(); errClose != nil {
t.Fatalf("zstd close: %v", errClose)
}
return buf.Bytes()
}
func newBodyRequest(t *testing.T, body []byte, encoding string) (*gin.Context, *httptest.ResponseRecorder) {
t.Helper()
gin.SetMode(gin.TestMode)
req := httptest.NewRequest(http.MethodPost, "/v1/test", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
if encoding != "" {
req.Header.Set("Content-Encoding", encoding)
}
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
c.Request = req
return c, rec
}
func TestReadRequestBodyDecodesSupportedEncodings(t *testing.T) {
plain := []byte(`{"model":"m","messages":[{"role":"user","content":"hi"}]}`)
for _, tc := range []struct {
name string
encoding string
body []byte
}{
{name: "plain", encoding: "", body: plain},
{name: "identity", encoding: "identity", body: plain},
{name: "zstd", encoding: "zstd", body: zstdBody(t, plain)},
{name: "gzip", encoding: "gzip", body: gzipBody(t, plain)},
{name: "x-gzip", encoding: "x-gzip", body: gzipBody(t, plain)},
{name: "gzip_upper", encoding: "GZIP", body: gzipBody(t, plain)},
} {
t.Run(tc.name, func(t *testing.T) {
c, _ := newBodyRequest(t, tc.body, tc.encoding)
decoded, err := ReadRequestBody(c)
if err != nil {
t.Fatalf("ReadRequestBody: %v", err)
}
if !bytes.Equal(decoded, plain) {
t.Fatalf("decoded = %q, want %q", decoded, plain)
}
})
}
}
func TestReadRequestBodyGzipOverCap(t *testing.T) {
plain := bytes.Repeat([]byte("a"), 1024)
c, _ := newBodyRequest(t, gzipBody(t, plain), "gzip")
c.Set(MaxRequestBodyBytesContextKey, int64(64))
if _, err := ReadRequestBody(c); err == nil {
t.Fatalf("expected max bytes error for oversized gzip body")
} else {
var maxErr *http.MaxBytesError
if !asMaxBytesErr(err, &maxErr) {
t.Fatalf("error = %v (%T), want *http.MaxBytesError", err, err)
}
}
}
func TestReadRequestBodyMalformedGzip(t *testing.T) {
// A gzip-looking body that is not valid JSON and cannot be gunzipped must fail
// rather than fall through as compressed bytes.
c, _ := newBodyRequest(t, []byte{0x1f, 0x8b, 0x08, 0x00, 0xde, 0xad}, "gzip")
if _, err := ReadRequestBody(c); err == nil {
t.Fatalf("expected decode error for malformed gzip body")
}
}
func asMaxBytesErr(err error, target **http.MaxBytesError) bool {
for err != nil {
if mbe, ok := err.(*http.MaxBytesError); ok {
*target = mbe
return true
}
type unwrapper interface{ Unwrap() error }
u, ok := err.(unwrapper)
if !ok {
return false
}
err = u.Unwrap()
}
return false
}