Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

security: enforce body-size limit for chunked/missing Content-Length (#2644)

LearningCircuit81cd0961326e
diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.py
index c7d2f5c3ef..e401891775 100644
--- a/src/local_deep_research/security/safe_requests.py
+++ b/src/local_deep_research/security/safe_requests.py
@@ -26,6 +26,38 @@ _REDIRECT_STATUS_CODES = frozenset({301, 302, 303, 307, 308})
_MAX_REDIRECTS = 10
+def _install_body_guard(response: requests.Response) -> None:
+ """Install a bounded reader on responses without Content-Length.
+
+ Wraps response.raw.read() to track cumulative bytes and raise
+ ValueError if MAX_RESPONSE_SIZE is exceeded during body consumption.
+ This transparently protects both streamed (.iter_content) and
+ non-streamed (.text, .json(), .content) access patterns.
+
+ No-op when Content-Length is present (header check is sufficient).
+ """
+ content_length = response.headers.get("Content-Length")
+ if content_length:
+ return # Header-based check handles this case
+
+ original_read = response.raw.read
+ bytes_read = 0
+
+ def bounded_read(amt=None, *args, **kwargs):
+ nonlocal bytes_read
+ data = original_read(amt, *args, **kwargs)
+ bytes_read += len(data)
+ if bytes_read > MAX_RESPONSE_SIZE:
+ response.close()
+ raise ValueError(
+ f"Response body too large: >{bytes_read} bytes "
+ f"(max {MAX_RESPONSE_SIZE}, no Content-Length header)"
+ )
+ return data
+
+ response.raw.read = bounded_read
+
+
def _check_response_size(response: requests.Response) -> None:
"""Reject responses whose Content-Length exceeds MAX_RESPONSE_SIZE.
@@ -35,8 +67,8 @@ def _check_response_size(response: requests.Response) -> None:
(trailing/doubled commas) are filtered before parsing. Non-integer
or negative values cause the header to be treated as absent.
- Only checks the Content-Length header; chunked transfer encoding
- responses are not bounded by this check.
+ When Content-Length is absent (e.g. chunked transfer encoding),
+ installs a body guard that enforces the size limit during read.
Must be called before returning a response to the caller. On
rejection the response is closed to avoid leaking the connection.
@@ -54,9 +86,11 @@ def _check_response_size(response: requests.Response) -> None:
raw_parts = [v.strip() for v in content_length.split(",")]
parts = [p for p in raw_parts if p]
if not parts:
+ _install_body_guard(response)
return # Only commas/whitespace — treat as absent
sizes = [int(p) for p in parts]
except (ValueError, TypeError):
+ _install_body_guard(response)
return # Content-Length not a valid number
if len(set(sizes)) > 1:
response.close()
@@ -65,12 +99,18 @@ def _check_response_size(response: requests.Response) -> None:
)
size = sizes[0]
if size < 0:
+ _install_body_guard(response)
return # Malformed Content-Length, treat as absent
if size > MAX_RESPONSE_SIZE:
response.close()
raise ValueError(
f"Response too large: {size} bytes (max {MAX_RESPONSE_SIZE})"
)
+ # Valid Content-Length within limit — no body guard needed
+ return
+
+ # No Content-Length header at all — install body guard
+ _install_body_guard(response)
def _resolve_redirect_method(method: str, status_code: int) -> str:
diff --git a/tests/security/test_ssrf_response_size.py b/tests/security/test_ssrf_response_size.py
index 979e60676b..f2026b6f76 100644
--- a/tests/security/test_ssrf_response_size.py
+++ b/tests/security/test_ssrf_response_size.py
@@ -8,10 +8,13 @@ import requests
import pytest
from unittest.mock import patch, MagicMock
+from io import BytesIO
+
from local_deep_research.security.safe_requests import (
safe_get,
safe_post,
SafeSession,
+ _install_body_guard,
MAX_RESPONSE_SIZE,
)
@@ -402,3 +405,80 @@ class TestSafeSessionResponseSize:
with pytest.raises(ValueError, match="Response too large"):
session.get("https://example.com")
mock_resp.close.assert_called_once()
+
+
+class TestBodySizeEnforcement:
+ """Verify _install_body_guard enforces size limits on responses without CL."""
+
+ def _make_response(self, body: bytes, headers: dict | None = None):
+ """Create a mock response with a real readable raw body."""
+ resp = MagicMock(spec=requests.Response)
+ resp.headers = headers or {}
+ raw = MagicMock()
+ stream = BytesIO(body)
+ raw.read = stream.read
+ resp.raw = raw
+ return resp
+
+ def test_chunked_response_within_limit(self):
+ """Small body without Content-Length succeeds."""
+ body = b"x" * 1024
+ resp = self._make_response(body)
+ _install_body_guard(resp)
+
+ data = resp.raw.read()
+ assert data == body
+
+ def test_chunked_response_exceeds_limit(self):
+ """Large body without Content-Length raises ValueError on read."""
+ body = b"x" * (MAX_RESPONSE_SIZE + 1)
+ resp = self._make_response(body)
+ _install_body_guard(resp)
+
+ with pytest.raises(ValueError, match="Response body too large"):
+ resp.raw.read()
+ resp.close.assert_called_once()
+
+ def test_missing_cl_within_limit(self):
+ """No Content-Length, small body succeeds."""
+ body = b"hello world"
+ resp = self._make_response(body)
+ _install_body_guard(resp)
+
+ data = resp.raw.read()
+ assert data == body
+
+ def test_missing_cl_exceeds_limit(self):
+ """No Content-Length, oversized body raises ValueError."""
+ body = b"x" * (MAX_RESPONSE_SIZE + 100)
+ resp = self._make_response(body)
+ _install_body_guard(resp)
+
+ with pytest.raises(ValueError, match="Response body too large"):
+ resp.raw.read()
+
+ def test_guard_not_installed_when_cl_present(self):
+ """With Content-Length header, raw.read is not wrapped."""
+ body = b"x" * 100
+ resp = self._make_response(body, headers={"Content-Length": "100"})
+ original_read = resp.raw.read
+ _install_body_guard(resp)
+
+ # read function should be unchanged
+ assert resp.raw.read is original_read
+
+ def test_streamed_access_exceeds_limit(self):
+ """Chunked reads that cumulatively exceed limit raise ValueError."""
+ chunk_size = MAX_RESPONSE_SIZE // 2
+ body = b"x" * (MAX_RESPONSE_SIZE + 1)
+ resp = self._make_response(body)
+ _install_body_guard(resp)
+
+ # First chunk: within limit
+ data1 = resp.raw.read(chunk_size)
+ assert len(data1) == chunk_size
+
+ # Second chunk: pushes over the limit
+ with pytest.raises(ValueError, match="Response body too large"):
+ resp.raw.read(chunk_size + 1)
+ resp.close.assert_called_once()