Repository navigation
fix(proxy): decode zstd and gzip request bodies before auth reads them - #47418
Conversation
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Judge: skipped, the rules alone decided. Pushes do not re-run this check. Comment |
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at 728967d
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
|
@litereview code-review |
Merging this PR will not alter performance
|
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. Checks and execution details
No
Boundary cases checked against code and tests:
Proxy-level tests show auth reads the decoded model: a zstd or gzip body naming a model outside the key gets 403, and the upstream mock is never called. Standards: the new code adds no source comments, uses
View review · Reviewed |
[Medium impact] The changes since the previous review appear safe to merge SummaryThe PR adds gzip and zstd request decoding before auth, with size, expansion, and in-flight memory limits Since the previous review, only test-case labels changed. All test inputs and checks remain intact. The three earlier unnumbered findings remain fixed
Reviews (9) · Last reviewed commit: "test(proxy): name the decompression test..." · Reviewed by Greptile |
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 1 · PR risk: 0/10 |
Limit the decoded size by an expansion ratio and the operator's max_request_size_mb, pass bodies without the coding's magic number through, answer 415 when zstd is unavailable, and register the middleware innermost so errors carry CORS and security headers
|
@litereview code-review |
…in bodies as sent Each worker holds at most MAX_DECOMPRESSED_REQUEST_BODIES_IN_FLIGHT_MB of decoded bodies and answers 503 past it. /plugin-proxy/ bodies reach the plugin as sent, a zstd skippable frame counts as zstd, the decoded-size 413 names the decoded limit, and an integer max_request_size_mb stays an integer in the 413 text.
|
@litereview code-review |
…ared decoded sizes
|
@litereview code-review |
|
@litereview code-review |
… skip the size parse without premium
|
@litereview code-review |
…nd body-less request messages in the decompression middleware
|
@litereview code-review |
|
bugbot run |
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit c7060ca. Configure here.
|
codecov/patch first showed 81% before every shard's coverage arrived, and it reads 99% now that the late upload finished |
|
Post-merge audit is in #48766. Its ten real-proxy cases pass at this merge commit, and the eight regression cases fail at its parent |
TLDR
Problem this solves:
Content-Encoding: zstdorgzipfail with 400 Invalid JSONHow it solves it:
User Flow
Before: TypeSafe SDK bodies of 1 KB or more get 400
TypeSafeClient(base_url="https://litellm-domain", api_key=<virtual key for jev>, model="jev")system_one(...)with 2 KB of state, and the SDK sends a zstdPOST https://litellm-domain/v1/systemoneInvalid JSON: expected value at line 1 column 1withx-litellm-response-cost: 0/v1/chat/completions,/v1/responses,/v1/messages,/v1/decisions, and 500 on/anthropic/v1/messagesjev-only key asking forclaude-haiku-5-5in a zstd body gets that 400, not 403After: the same call returns answers and a cost
TypeSafeClient(base_url="https://litellm-domain", api_key=<virtual key for jev>, model="jev")system_one(...)with 2 KB of state, and the SDK sends a zstdPOST https://litellm-domain/v1/systemonex-litellm-response-cost: 3.8304e-05jev-only key asking forclaude-haiku-5-5in a zstd body gets 403key_model_access_deniedDecisions
Decisions and their alternatives
This supersedes #41567 by @enternal111, which decoded gzip only, and adds zstd and the size cap to the same idea
Pass-through routes are decoded too. Skipping them would not forward the body as sent, since on main a compressed JSON body to a pass-through route gets a 500, and a non-JSON one reaches the target as
{}withContent-Encodingstill set. Two kinds of routes are the exception and get the body andContent-Encodingas sent, like on main./plugin-proxy/is an admin-only reverse proxy that forwards the raw body with its headers. The Claude Code gateway's OTLP export routes (/claude_code_gateway/v1/metrics,/logs, and/traces) decode gzip themselves and accept bodies the middleware refuses, such as two gzip members or a body over the ratio limitThe middleware is registered innermost, inside CORS, the security headers, in-flight tracking, and
RequestSizeLimitMiddleware. So its errors carry the same headers as any other error, and the wire size is checked before any decoding. It still runs before every body reader, so auth, the route handlers, and pass-through routes all see the decoded body. Decoding in the handler or in the shared body reader would leave auth checking the compressed bytesOnly a single
gziporzstdcoding is decoded, matched without regard to case or surrounding spaces. No header,identity,br,deflate, a list such asgzip, zstd, and websocket requests pass through untouched, so anyone sending those today sees no change. The alternatives were a 415 for codings the proxy can't decode, as RFC 9110 suggests, or decoding stacked codings.x-gzipis decoded asgzip, since RFC 9110 section 8.4.1.3 asks recipients to treat the two the sameA body labeled
gziporzstdthat doesn't start with that format's magic number (1f 8bfor gzip,28 b5 2f fdfor zstd) reaches the route as sent, with the header dropped. Some clients set the header on plain JSON. On main those requests work on the LLM routes, while pass-through routes forward the header and the vendor answers 400, so dropping the header makes both work. The proxy reads those first bytes before any size limit, so a plain body over the decoded size limit, or a plain body labeledzstdon a proxy without zstd support, also reaches the route as sent. The alternative was a 400 for every body that fails to decodeDecoding stops at the smaller of two limits. The first is 200 times the body's size on the wire, set by
MAX_REQUEST_BODY_DECOMPRESSION_RATIO, the same default as Apache'sDeflateInflateRatioLimit. Without it a 250 KB body could make the proxy inflate 50 MB before auth on every request. The second isMAX_DECOMPRESSED_REQUEST_BODY_SIZE_MB(default 50), lowered tomax_request_size_mbwhen that enterprise setting is on, so the operator's limit applies to the decoded body too. Past the ratio the proxy answers 413Request body expands more than 200 times when decoded, and past the size limit 413Request body is larger than 50 MB when decoded. A body already over the size limit on the wire gets the 413 bodyRequestSizeLimitMiddlewarealready sends. The decoder stops at the limit plus one byte, so a 200 MB bomb never inflates past it. A new env var is used for the size limit becausemax_request_size_mbis enterprise-only and unset by default, which would leave open-source proxies with no bomb protectionA body must be exactly one gzip member or one zstd frame. Concatenated members or frames, a truncated stream, or bytes after the end get a 400 with
type: invalid_request_error. The alternative was to accept several members like Python'sgzip.decompressdoes. A zstd body that starts with a skippable frame (50to5f, then2a 4d 18) counts as zstd, so it gets that 400 instead of reaching the route as raw bytesEach worker holds at most
MAX_DECOMPRESSED_REQUEST_BODIES_IN_FLIGHT_MB(default 200) of decoded bodies at a time. Before decoding, a request reserves the decoded size its data declares (the gzip trailer or the zstd frame header), capped by the two limits above, or those limits when it declares none. It keeps only its decoded size while the route runs and gives that back when the route returns. A body that decodes past its declared size gets a 400. A request that doesn't fit gets 503overloaded_errorwithRetry-After: 1, the shape admission control uses, and a request always fits when no other decoded body is held. Without it, 16 parallel 391 KB bodies with no key took the proxy from 0.6 GB to 3.2 GB before auth rejected them. The alternatives were reserving the worst case for every request, which let only 4 bodies over 256 KB decode at once per worker, a cap on how many bodies decode at once, which ignores their size, or giving the budget back right after decoding, which leaves decoded bodies waiting on auth uncountedBodies are decoded before auth, because auth reads the body to check the requested model against the key. So a caller with no key can still make a worker decode up to the limits above, and the in-flight budget bounds how much it holds at once. Decoding and parsing those bodies also slows every other request on that worker while the flood lasts. Two keyless senders at 3.3 MB/s took a keyed call's median from 19 ms to 320 ms on one worker, and a plain-body flood on main needs about 68 times the bandwidth for the same slowdown. The budget caps memory, not that latency. Checking for a key header first was the alternative, but a made-up key passes that check and custom auth can read any header. An operator who wants no decoding before auth sets
MAX_DECOMPRESSED_REQUEST_BODY_SIZE_MB=0, which answers every compressed body with 413max_request_size_mbis now read the same way in both size middlewares and the auth size check, through pydantic's lax parsing. So"10"means 10 MB, where on main a string raised a TypeError on every request, andtruestill means 1 MB as on main. Without a license the auth size check returns before it reads the setting, as on main, so a value it can't parse, such as"10MB", changes nothing thereThe zstd decoder refuses windows over 8 MB, the limit RFC 9659 sets for the
zstdcontent coding, so a crafted frame can't make the decoder allocate a huge window. Such a frame gets the same 400Decoding runs in a worker thread, like the response gzip middleware, so a 50 MB decode doesn't block the event loop. The middleware drops
content-encoding,content-length, andtransfer-encodingand setscontent-lengthto the decoded size on a copy of the request scope. A client that disconnects mid-body gets no response, and an empty body with a supported coding reaches the route emptyzstd comes from the standard library's
compression.zstdon Python 3.14 and frombackports-zstdbelow that. It is a proxy extra dependency, and theproxy-devgroup carries it too so the type checker resolves it. It is PSF-2.0 licensed, so it is added to the license allowlist. Thezstandardpackage was the alternative, but its API differs from the standard library's. A proxy installed without it still starts and decodes gzip, and answers a zstd body with 415 andAccept-Encoding: gzip, as RFC 9110 describesWith
backports-zstdinstalled,requestsand aiohttp addzstdto their defaultAccept-Encodingand urllib3 decodes zstd replies, which Python 3.14 installs already do on main. litellm's provider calls set their ownAccept-Encodingand don't change. Leaving zstd out of the proxy extra was the alternative, but then the proxy can't decode zstd bodies below Python 3.14Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or moreDelays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Last updated: c7060ca. QA and /live-pr-risk ran on 81faa75, the last commit with a product diff
Two workers per proxy, real provider calls
Setup, config.yaml, the client script, and the curl bodies
Both proxies ran
python litellm/proxy/proxy_cli.py --config config.yaml --port $PORT --num_workers 2from their own worktree on one.envand database. The client istypesafe-sdk==0.7.5on Python 3.14.3, plus curl for the other routes, on real TypeSafe, OpenAI, and Anthropic calls.$JEV_KEYmay use onlyjev, and$LITELLM_KEYall three modelsThe quoted
max_request_size_mbcase ran one more proxy per leg the same way, withLITELLM_LICENSEset andmax_request_size_mb: "10"added undergeneral_settingsjev_client.py, run aspython jev_client.py <base url> <key> small|large default|off [model]Each curl body is the JSON request for its route, compressed with Python's
gzip.compressorcompression.zstd.compress.bomb.json.gzis a 61 KB chat request whose message is 60 MB ofa,corrupt.json.zstis a zstd frame with its last 6 bytes cut and junk added,chat.jsonis the uncompressed chat request,skippable_then_chat.json.zstis a 4-byte zstd skippable frame followed by the zstd chat request, andflood.json.gzis a 523 KB gzip chat request that decodes to 45 MB. Thenotesplugin is a 20-line Python HTTP server that answers with theContent-Encoding, byte count, and SHA-256 prefix of the body it receivedBefore (f07596a)
SDK, zstd
Run
Observed
SDK, disallowed model
Steps and output
Run
Observed
Chat, gzip, x-gzip, stream
Steps and output
Run
Observed
Run
Observed
Run
Observed
Responses, gzip
Steps and output
Run
Observed
Messages, gzip
Steps and output
Run
Observed
Pass-through, zstd
Steps and output
Run
Observed
Decisions, zstd
Steps and output
Run
Observed
gzip bomb, corrupt zstd, skippable frame
Steps and output
Run
Observed
Run
Observed
Run
Observed
Plain bodies
Steps and output
Run
Observed
Run
Observed
Run
Observed
Plain labeled gzip
Steps and output
Run
Observed
Run
Observed
CORS, corrupt zstd
Steps and output
Run
Observed
Run
Observed
Plugin proxy, zstd
Steps and output
Run
Observed
Parallel gzip, then SDK
Steps and output
Run
Observed
Run
Observed
1 MB gzip burst
Steps and output
Run
Observed
SDK spend log row
Steps and output
Run
Observed
Quoted max_request_size_mb
Steps and output
Run
Observed
Run
Observed
After (81faa75)
SDK, zstd
Run
Observed
SDK, disallowed model
Steps and output
Run
Observed
Chat, gzip, x-gzip, stream
Steps and output
Run
Observed
Run
Observed
Run
Observed
Responses, gzip
Steps and output
Run
Observed
Messages, gzip
Steps and output
Run
Observed
Pass-through, zstd
Steps and output
Run
Observed
Decisions, zstd
Steps and output
Run
Observed
gzip bomb, corrupt zstd, skippable frame
Steps and output
Run
Observed
Run
Observed
Run
Observed
Plain bodies
Steps and output
Run
Observed
Run
Observed
Run
Observed
Plain labeled gzip
Steps and output
Run
Observed
Run
Observed
CORS, corrupt zstd
Steps and output
Run
Observed
Run
Observed
Plugin proxy, zstd
Steps and output
Run
Observed
Parallel gzip, then SDK
Steps and output
Run
Observed
Run
Observed
1 MB gzip burst
Steps and output
Run
Observed
SDK spend log row
Steps and output
Run
Observed
Run
Observed
Quoted max_request_size_mb
Steps and output
Run
Observed
Run
Observed
/live-pr-risk (81faa75)
Two regressions in 04c1a68, both fixed in 81faa75
Base, head, and head merged with main ran side by side, two workers each, with a recorder in front of each real provider
Breaking. At 04c1a68, Claude Code OTLP exports to
/claude_code_gateway/v1/logs,/metrics, and/traceswith two gzip members got 400, and one decoding past 200 times its size got 413, where main answers 200. Fixed in 81faa75, since those routes now get the body as sent. All 12 exports (plain, gzip, two members, over the ratio, on each route) answer 200 on head and on the merged tree, like main, and an export with no key gets 401 on all threeBackward incompatible. At 04c1a68 a proxy with no license and an unparseable
max_request_size_mbsuch as"10MB"failed requests that pass on main. Fixed in 81faa75, with a regression test. Withbackports-zstdinstalled,requestsand aiohttp advertisezstdby default, as Python 3.14 installs already do on main. Every recorded provider call keeps the same headers on all three treesRegression risk. Plain bodies skip the middleware, and every plain-body scenario matched main on head and the merged tree. What stays untested live only sees compressed bodies, which no route accepted on main: Vertex, Bedrock SigV4, and the other pass-through families, multipart uploads, MCP, SCIM, and SAML. On the retired
/v1/tracesand/v1/logsroutes a two-member or over-ratio gzip body gets 400 or 413 instead of 410Scenario diffs. Main against head and the merged tree differ only in gzip chat (400 to 200), zstd
/anthropic(500 to 200), a plain body labeled gzip on/anthropic(vendor 400 to 200, the header is no longer forwarded), and a deleted key that still answers on a sibling worker, which main does too (5 of 5 tries on main, 3 of 5 on head)Not verified. The realtime websocket with an unparseable limit,
/v1/files(files_settingsunset on all trees), Vertex and Bedrock SigV4 with a compressed body, multipart uploads, MCP, SCIM, SAML, and the published Docker imageType
Bug Fix
Test
Caveats (if any)
Medium
MAX_DECOMPRESSED_REQUEST_BODY_SIZE_MB=0turns decoding offMAX_REQUEST_BODY_DECOMPRESSION_RATIOor turn off SDK compressionLow
Final Attestation
Bugbot summary