Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(proxy): gate the raw request body, not just its Content-Length header (#3338)

Amir Fathic946b6b0b0ae
diff --git a/headroom/proxy/handlers/bedrock.py b/headroom/proxy/handlers/bedrock.py
index 688e1befb..07ac5922b 100644
--- a/headroom/proxy/handlers/bedrock.py
+++ b/headroom/proxy/handlers/bedrock.py
@@ -76,6 +76,8 @@ class BedrockHandlerMixin:
from headroom.proxy.helpers import (
COMPRESSION_TIMEOUT_SECONDS,
MAX_MESSAGE_ARRAY_LENGTH,
+ MAX_REQUEST_BODY_SIZE,
+ RequestBodyTooLarge,
_headroom_bypass_enabled,
_strip_internal_headers,
extract_tags,
@@ -134,12 +136,34 @@ class BedrockHandlerMixin:
if isinstance(err, ClientDisconnect):
logger.debug("[%s] %s client disconnected during body read", request_id, LOG_TAG)
return Response(status_code=204)
+ if isinstance(err, RequestBodyTooLarge):
+ # The read aborted mid-stream once the size ceiling was
+ # crossed, so there is no raw body to fail open with, and
+ # forwarding one anyway would defeat the ceiling. Reject.
+ logger.warning("[%s] %s request body too large: %s", request_id, LOG_TAG, err)
+ return JSONResponse(
+ status_code=413,
+ content={
+ "error": {
+ "type": "request_too_large",
+ "message": (
+ f"Request body too large. Maximum size is "
+ f"{MAX_REQUEST_BODY_SIZE // (1024 * 1024)}MB"
+ ),
+ }
+ },
+ )
logger.warning(
"[%s] %s could not parse body; forwarding verbatim: %s",
request_id,
LOG_TAG,
err,
)
+ # The raw bytes were already fully read by
+ # read_request_json_with_bytes before it failed decoding them,
+ # and it caches them onto request._body the same way Starlette's
+ # own Request.body() would, so this returns the cached bytes
+ # instead of re-draining an already-consumed stream.
raw_only = await request.body()
return await self._forward_bedrock(
url=url,
diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.py
index c1d0cb58d..809aa03d8 100644
--- a/headroom/proxy/helpers.py
+++ b/headroom/proxy/helpers.py
@@ -2893,7 +2893,7 @@ def apply_session_sticky_ccr_tool(
class RequestBodyTooLarge(ValueError):
- """A decompressed request body exceeded :data:`MAX_DECOMPRESSED_BODY_SIZE`.
+ """A raw or decompressed request body exceeded its size ceiling.
Subclasses ``ValueError`` so every existing ``except ValueError`` call site
keeps answering 400 unchanged, while giving a caller that would rather
@@ -3024,8 +3024,9 @@ async def _read_request_body_bytes(request: Request) -> bytes:
encoding = (request.headers.get("content-encoding") or "").lower().strip()
# Content-Length is an optimization only, not the enforcement boundary: it
- # can be absent, understated, or belong to a chunked transfer. The
- # streaming loop below is what actually bounds every case (#3479).
+ # can be absent, understated, or belong to a chunked transfer (the
+ # original gap this fixes, #3326). The streaming loop below is what
+ # actually bounds every case, chunked or not (#3479).
content_length = request.headers.get("content-length")
if content_length is not None:
try:
@@ -3047,8 +3048,9 @@ async def _read_request_body_bytes(request: Request) -> bytes:
)
raw: bytes = bytes(chunks)
# Cache like Starlette's own body() would, so any other .body() caller on
- # this request (there is none today, but future callers get the same
- # semantics) sees the bytes already read rather than a consumed stream.
+ # this request (e.g. a handler's except-branch falling open to a verbatim
+ # forward after a decode failure) sees the bytes already read rather than
+ # a consumed stream.
request._body = raw
# Every branch below decompresses incrementally against
diff --git a/tests/test_proxy/test_bedrock_passthrough.py b/tests/test_proxy/test_bedrock_passthrough.py
index d867fd4bf..694930131 100644
--- a/tests/test_proxy/test_bedrock_passthrough.py
+++ b/tests/test_proxy/test_bedrock_passthrough.py
@@ -328,6 +328,30 @@ def test_upstream_connect_error_returns_502():
assert resp.status_code == 502
+def test_oversized_body_returns_413_and_never_forwards(monkeypatch):
+ """A body over MAX_REQUEST_BODY_SIZE gets a 413 fail-closed response, and
+ _forward_bedrock is never reached: a partially-read oversized body must
+ not go out to the gateway.
+ """
+ import headroom.proxy.helpers as helpers_mod
+
+ small_cap = 1024
+ monkeypatch.setattr(helpers_mod, "MAX_REQUEST_BODY_SIZE", small_cap)
+
+ app = create_app(_make_config())
+ with TestClient(app) as client:
+ proxy = client.app.state.proxy
+ http = _install_fake_client(proxy, _FakeUpstream())
+ proxy.anthropic_pipeline.apply = MagicMock(side_effect=AssertionError("should not run"))
+ body = {"messages": [{"role": "user", "content": "x" * (small_cap * 4)}], "max_tokens": 8}
+ resp = client.post(INVOKE, json=body)
+
+ assert resp.status_code == 413
+ assert resp.json()["error"]["type"] == "request_too_large"
+ http.build_request.assert_not_called()
+ http.send.assert_not_called()
+
+
# ── metrics ───────────────────────────────────────────────────────────
diff --git a/tests/test_request_body_decompression_limits.py b/tests/test_request_body_decompression_limits.py
index 7851ba4ca..5d9395c7a 100644
--- a/tests/test_request_body_decompression_limits.py
+++ b/tests/test_request_body_decompression_limits.py
@@ -74,16 +74,29 @@ class _Request:
"""Minimal stand-in for the Starlette Request the reader actually takes."""
def __init__(
- self, body: bytes, content_encoding: str = "", headers: dict | None = None
+ self,
+ body: bytes,
+ content_encoding: str = "",
+ *,
+ headers: dict | None = None,
+ stream_chunk_size: int = 64 * 1024,
) -> None:
self._body = body
self.headers = {"content-encoding": content_encoding, **(headers or {})}
+ self._stream_chunk_size = stream_chunk_size
+ self.chunks_yielded = 0
async def body(self) -> bytes:
return self._body
async def stream(self):
- yield self._body
+ # Real ASGI servers hand the body over in chunks, not one blob, which
+ # is exactly what lets the streaming bound-check in
+ # `_read_request_body_bytes` refuse a body before all of it has
+ # arrived.
+ for start in range(0, len(self._body), self._stream_chunk_size):
+ self.chunks_yielded += 1
+ yield self._body[start : start + self._stream_chunk_size]
class _NeverStreamedRequest(_Request):
@@ -298,6 +311,26 @@ def test_truncated_gzip_still_errors() -> None:
)
+# ───────────────── raw body ceiling (the chunked-transfer bypass) ──────────
+#
+# The handlers only ever see the *compressed*, wire-level size via
+# `Content-Length`, and that header is absent on a chunked-transfer-encoding
+# request. The streaming loop in `_read_request_body_bytes` is the backstop
+# the handlers fall through to regardless of whether that header was there
+# (#3326).
+
+
+async def test_raw_body_refused_without_consuming_the_whole_stream(small_raw_cap: int) -> None:
+ """The point is refusing early, not just refusing eventually."""
+ request = _Request(b"a" * (small_raw_cap * 10), stream_chunk_size=small_raw_cap // 4)
+ total_chunks = -(-len(request._body) // request._stream_chunk_size) # ceil div
+
+ with pytest.raises(_helpers().RequestBodyTooLarge):
+ await _helpers()._read_request_body_bytes(request)
+
+ assert request.chunks_yielded < total_chunks
+
+
# ──────────────────────────── through the entry point ──────────────────────
@@ -318,6 +351,21 @@ async def test_reader_leaves_uncompressed_bodies_alone(small_cap: int) -> None:
assert await _helpers()._read_request_body_bytes(_Request(PAYLOAD, "identity")) == PAYLOAD
+async def test_reader_refuses_an_oversized_plain_body_with_no_content_length(
+ small_raw_cap: int,
+) -> None:
+ """The regression this PR fixes: no `Content-Length` header, no compression.
+
+ Before this fix, `_read_request_body_bytes` called `request.body()`
+ directly, so a handler's `Content-Length` precheck was the only gate and a
+ chunked request (no `Content-Length` to check) reached this function
+ regardless of size.
+ """
+ oversized = b"a" * (small_raw_cap + 1)
+ with pytest.raises(_helpers().RequestBodyTooLarge):
+ await _helpers()._read_request_body_bytes(_Request(oversized, ""))
+
+
async def test_reader_still_rejects_an_unknown_encoding() -> None:
with pytest.raises(ValueError, match="Unsupported Content-Encoding"):
await _helpers()._read_request_body_bytes(_Request(PAYLOAD, "snappy"))