~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): apply the response size cap to chunked bodies (#6339)
Ehsan0db5eff12d05
diff --git a/changelog.d/6180.security.md b/changelog.d/6180.security.mdnew file mode 100644index 0000000000..ca4274743d--- /dev/null+++ b/changelog.d/6180.security.md@@ -0,0 +1 @@+The response size cap now applies to Transfer-Encoding: chunked responses, which previously streamed past the limit unbounded because urllib3 reads them through a path the guard did not cover.diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.pyindex 30f79c9a10..dba7f87c33 100644--- a/src/local_deep_research/security/safe_requests.py+++ b/src/local_deep_research/security/safe_requests.py@@ -50,15 +50,19 @@ def _install_body_guard(response: requests.Response) -> None:This transparently protects both streamed (.iter_content) andnon-streamed (.text, .json(), .content) access patterns.+ A Transfer-Encoding: chunked body never reaches raw.read():+ urllib3's stream() dispatches it to read_chunked(), which pulls the+ socket through raw._fp. That generator is wrapped against the same+ counter so the two paths share one budget.+Always installs — callers (currently only _check_response_size)are responsible for deciding when to call this function."""- original_read = response.raw.read+ raw = response.rawbytes_read = 0- def bounded_read(amt=None, *args, **kwargs):+ def count(data: bytes) -> None:nonlocal bytes_read- data = original_read(amt, *args, **kwargs)bytes_read += len(data)if bytes_read > MAX_RESPONSE_SIZE:response.close()@@ -66,9 +70,26 @@ def _install_body_guard(response: requests.Response) -> None:f"Response body too large: >{bytes_read} bytes "f"(max {MAX_RESPONSE_SIZE}, Content-Length absent or invalid)")++ original_read = raw.read++ def bounded_read(amt=None, *args, **kwargs):+ data = original_read(amt, *args, **kwargs)+ count(data)return data- response.raw.read = bounded_read # type: ignore[method-assign]+ raw.read = bounded_read # type: ignore[method-assign]++ original_read_chunked = getattr(raw, "read_chunked", None)+ if original_read_chunked is None:+ return++ def bounded_read_chunked(amt=None, *args, **kwargs):+ for chunk in original_read_chunked(amt, *args, **kwargs):+ count(chunk)+ yield chunk++ raw.read_chunked = bounded_read_chunked # type: ignore[method-assign]def _check_response_size(response: requests.Response) -> None:diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.pyindex 0b79f517b2..06f42cff84 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_arxiv.py@@ -262,34 +262,21 @@ class ArXivSearchEngine(BaseSearchEngine):for responses that *do* make it past that check (including thisfunction's own errors raised while streaming the body).- It does not fully fix the ``Content-Length``-absent case. The cap+ The ``Content-Length``-absent case is covered since #6180. The capinstalls a guard on ``response.raw.read()``- (``_install_body_guard``), and that guard does run correctly — but- only when the connection is delimited by the socket closing (no- ``Content-Length``, no ``Transfer-Encoding``). When the origin uses- ``Transfer-Encoding: chunked`` instead — the common case for a CDN- serving a PDF of unknown length — ``urllib3``'s- ``HTTPResponse.stream()`` (what ``requests`` uses under- ``iter_content``/``.content``) reads such bodies through- ``read_chunked()``, which pulls bytes directly off the socket via- ``self._fp._safe_read()`` and never calls the patched- ``read()`` — verified by reading the installed ``urllib3``- (2.7.0) source and confirming with a live chunked-response- server: the patched ``read()`` recorded zero calls while a full- chunked body was consumed. So for a genuinely chunked response,- ``_check_response_size`` still cannot bound memory on its own here- — this function's own running byte count during streaming is what- does that instead.-- The ``_check_response_size`` chunked-body gap is a defect in- ``safe_requests.py`` itself (``_check_response_size``/- ``_install_body_guard``) — every ``SafeSession`` caller that- already uses ``stream=True`` has the same exposure for chunked- responses. It is independent of whether this call streams and is- not the same issue as #6172, which is about callers that never- set ``stream=True`` at all (this one now does). It has its own- tracking issue, #6180, and needs its own follow-up rather than- being fixed here.+ (``_install_body_guard``), which used to run only when the+ connection was delimited by the socket closing: a+ ``Transfer-Encoding: chunked`` body, the common case for a CDN+ serving a PDF of unknown length, is read through ``urllib3``'s+ ``HTTPResponse.read_chunked()`` instead, which pulls bytes off the+ socket via ``self._fp._safe_read()`` and never calls the patched+ ``read()``. That generator is wrapped against the same counter now,+ so both framings are bounded. #6172, about callers that never set+ ``stream=True`` at all, is a separate issue (this call does set it).++ This function's own running byte count during streaming is still+ what bounds the *decoded* size, which is what a decompression bomb+ turns on; the cap counts what it is handed."""arxiv_id = self._validated_arxiv_id(paper)if not arxiv_id:diff --git a/tests/security/test_ssrf_response_size.py b/tests/security/test_ssrf_response_size.pyindex ad9d101ec9..66cc6e6252 100644--- a/tests/security/test_ssrf_response_size.py+++ b/tests/security/test_ssrf_response_size.py@@ -9,6 +9,7 @@ import pytestfrom unittest.mock import patch, MagicMockfrom io import BytesIO+from types import SimpleNamespacefrom local_deep_research.security import ssrf_validatorfrom local_deep_research.security.safe_requests import (@@ -509,3 +510,83 @@ class TestBodySizeEnforcement:with pytest.raises(ValueError, match="Response body too large"):resp.raw.read(chunk_size + 1)resp.close.assert_called_once()+++class TestChunkedBodyEnforcement:+ """Serve real wire framings so urllib3 picks the reader, not the mock."""++ CAP = 1024+ BODY = b"x" * (64 * 1024)++ @staticmethod+ def _serve(sock, framing, body):+ conn, _ = sock.accept()+ try:+ conn.recv(65536)+ if framing == "chunked":+ conn.sendall(+ b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n"+ )+ for i in range(0, len(body), 4096):+ part = body[i : i + 4096]+ conn.sendall(b"%x\r\n" % len(part) + part + b"\r\n")+ conn.sendall(b"0\r\n\r\n")+ else:+ conn.sendall(b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n")+ conn.sendall(body)+ except OSError:+ pass # the guard closes the connection mid-body on the over-cap runs+ finally:+ conn.close()+ sock.close()++ def _read_body(self, framing, body):+ """Serve ``body`` with ``framing`` and consume it via iter_content."""+ import socket+ import threading++ sock = socket.socket()+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ sock.bind(("127.0.0.1", 0))+ sock.listen(1)+ port = sock.getsockname()[1]+ threading.Thread(+ target=self._serve, args=(sock, framing, body), daemon=True+ ).start()++ with SafeSession(allow_localhost=True) as session:+ response = session.get(+ f"http://127.0.0.1:{port}/", stream=True, timeout=10+ )+ return sum(len(chunk) for chunk in response.iter_content(4096))++ @pytest.fixture(autouse=True)+ def _small_cap(self):+ with patch(+ "local_deep_research.security.safe_requests.MAX_RESPONSE_SIZE",+ self.CAP,+ ):+ yield++ def test_chunked_body_over_cap_is_rejected(self):+ with pytest.raises(ValueError, match="Response body too large"):+ self._read_body("chunked", self.BODY)++ def test_close_delimited_body_over_cap_is_rejected(self):+ with pytest.raises(ValueError, match="Response body too large"):+ self._read_body("close", self.BODY)++ def test_chunked_body_under_cap_is_delivered_whole(self):+ assert self._read_body("chunked", b"y" * 512) == 512++ def test_close_delimited_body_under_cap_is_delivered_whole(self):+ assert self._read_body("close", b"y" * 512) == 512++ def test_file_like_raw_without_read_chunked_keeps_the_read_guard(self):+ response = MagicMock(spec=requests.Response)+ response.headers = {}+ response.raw = SimpleNamespace(read=BytesIO(b"z" * 2048).read)+ _install_body_guard(response)++ with pytest.raises(ValueError, match="Response body too large"):+ response.raw.read()diff --git a/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py b/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.pyindex f702812fd5..932e24c42b 100644--- a/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py+++ b/tests/web_search_engines/engines/test_arxiv_pdf_egress_gating.py@@ -25,13 +25,10 @@ buffer the whole body in memory) with ``Accept-Encoding: identity``. Arunning byte count enforced while streaming — not ``SafeSession``'s``Content-Length`` check alone — is what bounds this fetch: for a valid,under-cap ``Content-Length`` header, ``_check_response_size`` installs no-body guard at all, and a ``Transfer-Encoding: chunked`` body bypasses the-guard it does install in the no-``Content-Length`` case (``urllib3`` reads-chunked bodies through ``read_chunked()``, which does not call the patched-``read()``). That gap lives in the cap itself-(``_check_response_size``/``_install_body_guard`` in ``safe_requests.py``),-not in this call site, and is unrelated to #6172 (which tracks callers-that never set ``stream=True`` at all — this one now does).+body guard at all. The no-``Content-Length`` case is bounded for both+framings since #6180 (``_install_body_guard`` wraps ``read_chunked()`` as+well as ``read()``), and is unrelated to #6172 (which tracks callers that+never set ``stream=True`` at all; this one now does).``download_dir`` is reachable from per-user web settings, so directorycreation is contained to a dedicated ``arxiv_downloads`` subtree of the