Skip to content

fix(proxy): decode zstd and gzip request bodies before auth reads them - #47379

Closed
mateo-berri wants to merge 1 commit into
mainfrom
litellm_decode_compressed_request_bodies
Closed

mateo-berri wants to merge 1 commit into
mainfrom
litellm_decode_compressed_request_bodies

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Bodies sent with Content-Encoding: zstd or gzip fail with 400 Invalid JSON
  • The TypeSafe SDK zstd-compresses every request body of 1 KB or more
  • Decoding after auth would let a compressed body skip the key's model list

How it solves it:

  • A new ASGI middleware decodes gzip and zstd bodies before anything reads them
  • MAX_DECOMPRESSED_REQUEST_BODY_SIZE_MB (default 50) caps decoded size with a 413
  • Corrupt, truncated, or trailing compressed data gets an OpenAI-style 400
  • This commit ships the middleware, a follow-up commit here registers it

User Flow

Before: a developer using the TypeSafe SDK through the proxy gets a 400 on every call whose body is 1 KB or more

  1. They create TypeSafeClient(base_url="https://litellm-domain", api_key=<virtual key for jev>, model="jev")
  2. They call system_one(...) with about 2 KB of state, so the SDK sends POST https://litellm-domain/v1/systemone with Content-Encoding: zstd
  3. The proxy answers 400 Invalid JSON: expected value at line 1 column 1 with x-litellm-response-cost: 0
  4. The same compressed body naming a model the key can't use gets that same 400, since the key's model check never sees the body

After: the same call comes back with answers and a cost

  1. They create TypeSafeClient(base_url="https://litellm-domain", api_key=<virtual key for jev>, model="jev")
  2. They call system_one(...) with about 2 KB of state, so the SDK sends POST https://litellm-domain/v1/systemone with Content-Encoding: zstd
  3. The proxy answers 200 with the answers and a non-zero x-litellm-response-cost
  4. The same compressed body naming a model the key can't use gets 403 "not available for this API key", like an uncompressed body

Decisions

Pass-through routes are decoded too. The plan was to skip them so a compressed body would be forwarded as sent, but on main that never happens. A compressed JSON body to a pass-through route gets a 500 before it reaches the target, and with a non-JSON content type the target gets {} with the original Content-Encoding header still set. Decoding fixes those routes too, and the target gets the plain body

This supersedes #41567 by @enternal111, which decoded gzip only, and adds zstd and the size cap on top of the same idea

Other decisions and their alternatives

The middleware runs outside 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 bytes. It goes right after RequestSizeLimitMiddleware in proxy_server.py, so that limit measures the decoded body and admission control still runs first

Only a single gzip or zstd coding is decoded, matched without regard to case or surrounding spaces. No header, identity, br, deflate, a list such as gzip, 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-gzip is not accepted

The cap is a new env var instead of max_request_size_mb. That setting is enterprise-only and unset by default, so it would leave open-source proxies with no bomb protection. The cap bounds both the compressed read and the decoded output, and the decoder stops at cap + 1 bytes, so a 200 MB bomb never inflates past the cap. Over the cap gets the 413 body RequestSizeLimitMiddleware already sends, and the cap set to 0 rejects every non-empty compressed body. A compression ratio limit was the other option

A 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's gzip.decompress does

The zstd decoder refuses windows over 8 MB, the limit RFC 9659 sets for the zstd content coding, so a crafted frame can't make the decoder allocate a huge window. Such a frame gets the same 400

Decoding 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, and transfer-encoding and sets content-length to 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 empty

zstd comes from the standard library's compression.zstd on Python 3.14 and from backports-zstd below that. It is a proxy extra dependency, and the proxy-dev group carries it too so the type checker resolves it. It is PSF-2.0 licensed, so it is added to the license allowlist. The zstandard package was the alternative, but its API differs from the standard library's

Known gap

This commit adds the middleware but does not register it yet, so the proxy behaves as before. The next commit on this branch registers it and adds app-level tests, one for the 403 on a compressed body naming another model and one for a zstd /v1/systemone body getting past body parsing

The env var row for the docs is in BerriAI/litellm-docs#2458, which the docs check in CI needs merged

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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 more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays 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

Type

Bug Fix

Caveats (if any)

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Note

Medium Risk
New request-path middleware affects all compressed bodies once registered; size caps and bomb tests mitigate memory/DoS risk, but incorrect wiring order could change auth or size-limit semantics.

Overview
Adds RequestBodyDecompressionMiddleware so the proxy can transparently inflate HTTP request bodies when clients send a single Content-Encoding: gzip or zstd header. Downstream handlers (auth, JSON parsing, pass-through) see the decoded bytes with content-encoding / transfer-encoding stripped and an updated content-length.

MAX_DECOMPRESSED_REQUEST_BODY_SIZE_MB (default 50) caps both the compressed read and decompressed output; oversize bodies return the same 413 as RequestSizeLimitMiddleware via the newly public send_request_too_large. Invalid or truncated compressed data returns an OpenAI-style 400. Decompression runs in a worker thread; zstd uses backports-zstd on Python < 3.14.

This commit ships the middleware, dependency/license updates, and unit tests only—the PR notes registration in proxy_server.py is a follow-up, so behavior is unchanged until that lands.

Reviewed by Cursor Bugbot for commit c62305d. Bugbot is set up for automated code reviews on this repo. Configure here.

@codecov

codecov Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.13043% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...iddleware/request_body_decompression_middleware.py 99.09% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_decode_compressed_request_bodies (c62305d) with main (d7620c7)

Open in CodSpeed

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@kerry-berri

kerry-berri commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

litellm-stampbot: risk high

Not approved at c62305d. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Cursor Bugbot: Medium Risk at c62305d. New request-path middleware affects all compressed bodies once registered; size caps and bomb tests mitigate memory/DoS risk, but incorrect wiring order could change auth or size-limit semantics. Bugbot run requested, finished in 10 min.
Bugbot Low is low, Medium and High are high. The judge model was not called.

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@kerry-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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 c62305d. Configure here.

@kerry-berri kerry-berri added the risk:high Sensitive, broad, or high-risk change label Oct 19, 2026
@mateo-berri

Copy link
Copy Markdown
Contributor Author

Superseded by #47418, which carries these same changes plus the middleware registration, so closing this one in favor of it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants