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.

fix(security): cap redirect responses before Requests buffers them (#6934)

LearningCircuit3b965431351b
diff --git a/changelog.d/+safe-session-redirect-body.security.md b/changelog.d/+safe-session-redirect-body.security.md
new file mode 100644
index 0000000000..1a701bbe2e
--- /dev/null
+++ b/changelog.d/+safe-session-redirect-body.security.md
@@ -0,0 +1,7 @@
+`SafeSession`, `safe_get` and `safe_post` now reject a redirect response whose
+`Content-Length` exceeds the response-size limit before following it, and
+discard redirect bodies without buffering or decoding them, including when a
+redirect is returned unfollowed (`allow_redirects=False`). This closes a
+response-size bypass affecting arXiv full-text downloads, other session
+callers and the standalone helpers (the redirect-body half of #6813); redirect
+status and headers remain available, and `SafeSession` keeps redirect cookies.
diff --git a/changelog.d/6199.security.md b/changelog.d/6199.security.md
index 6fa6e2920d..95eafe772d 100644
--- a/changelog.d/6199.security.md
+++ b/changelog.d/6199.security.md
@@ -3,4 +3,5 @@ arXiv search engine's PDF fetch is now bounded by a running cap on the
decoded bytes, so neither an oversized nor a small compressed final
response can exceed the response-size limit (this cap now lives in the
shared downloader; see #6691). Bodies of redirect responses followed on
-the way are not covered by this cap (#6813).
+the way are discarded before they are read (see the redirect-body entry
+for #6934).
diff --git a/changelog.d/6691.security.md b/changelog.d/6691.security.md
index 7cfc1f433c..611865d824 100644
--- a/changelog.d/6691.security.md
+++ b/changelog.d/6691.security.md
@@ -3,6 +3,6 @@ stream the response and bound the decoded body of the final response at the
response-size limit, including a compressed body sent with a small, valid
`Content-Length`, which `SafeSession` alone left unbounded. An oversized
body is abandoned without a retry and the fetch returns no content. Both
-fetches still follow redirects, and the body of an intermediate redirect
-response is read by `requests` before this bound applies; that gap is
-tracked in #6813.
+fetches still follow redirects; the body of an intermediate redirect
+response is discarded before `requests` reads it (see the redirect-body
+entry for #6934).
diff --git a/src/local_deep_research/research_library/downloaders/arxiv.py b/src/local_deep_research/research_library/downloaders/arxiv.py
index c147c3c422..d985a12b23 100644
--- a/src/local_deep_research/research_library/downloaders/arxiv.py
+++ b/src/local_deep_research/research_library/downloaders/arxiv.py
@@ -290,10 +290,11 @@ class ArxivDownloader(HTMLDownloader):
"""The PDF URL on ``fetch_host``.
``export.arxiv.org`` answers ``/pdf/{id}.pdf`` with a 301 to the
- suffix-less path, and ``requests`` drains a redirect response's body
- in ``resolve_redirects`` before ``SafeSession`` can size-check it,
- so on that host the suffix is left off and the redirect never
- happens. ``arxiv.org`` keeps the URL it has always been sent.
+ suffix-less path, so on that host the suffix is left off to avoid
+ an unnecessary redirect. (``SafeSession.resolve_redirects`` rejects
+ an oversized redirect ``Content-Length`` and discards redirect bodies
+ before Requests can buffer them.) ``arxiv.org`` keeps the URL it has
+ always been sent.
"""
if self._fetch_host == ARXIV_EXPORT_HOST:
return f"https://{ARXIV_EXPORT_HOST}/pdf/{arxiv_id}"
diff --git a/src/local_deep_research/research_library/downloaders/base.py b/src/local_deep_research/research_library/downloaders/base.py
index 47c2068216..f55aebdaaf 100644
--- a/src/local_deep_research/research_library/downloaders/base.py
+++ b/src/local_deep_research/research_library/downloaders/base.py
@@ -311,10 +311,9 @@ class BaseDownloader(ABC):
this method go on to read (``response.content`` in
``_download_pdf``, the streamed body in
``_fetch_html_with_final_url``). With ``allow_redirects=True``,
- any intermediate redirect responses have their bodies already
- read by ``requests.Session.resolve_redirects`` before this guard
- is installed on the final response, and are not bounded here (see
- #6813).
+ intermediate redirect responses never reach this guard;
+ ``SafeSession.resolve_redirects`` size-checks their
+ ``Content-Length`` and discards their bodies unread.
The request must have been made with ``stream=True`` for this to
matter: with ``stream=False``, ``requests.Session.send`` consumes
@@ -412,8 +411,8 @@ class BaseDownloader(ABC):
# decode whole and unbounded. Streamed, the guard installed
# below is what bounds the decoded read of
# response.content at MAX_RESPONSE_SIZE. That covers the
- # final response only; intermediate redirect bodies are
- # read by requests before the guard exists (#6813).
+ # final response only; SafeSession discards intermediate
+ # redirect bodies unread.
response = self.session.get(
url,
headers=request_headers,
diff --git a/src/local_deep_research/research_library/downloaders/html.py b/src/local_deep_research/research_library/downloaders/html.py
index 1d4d1e7a0b..773270b0c3 100644
--- a/src/local_deep_research/research_library/downloaders/html.py
+++ b/src/local_deep_research/research_library/downloaders/html.py
@@ -302,8 +302,8 @@ class HTMLDownloader(BaseDownloader):
# the guard bounds the decoded read of response.text at
# MAX_RESPONSE_SIZE even for a valid under-cap Content-Length
# (the gap SafeSession leaves unguarded). This bounds the final
- # response only: with allow_redirects=True, requests reads each
- # intermediate redirect body before the guard exists (#6813).
+ # response only: with allow_redirects=True, SafeSession discards
+ # each intermediate redirect body unread.
response = self.session.get(
url,
timeout=self.timeout,
diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.py
index a3c97db1df..6681c7e93c 100644
--- a/src/local_deep_research/security/safe_requests.py
+++ b/src/local_deep_research/security/safe_requests.py
@@ -72,6 +72,13 @@ def _install_body_guard(response: requests.Response) -> None:
f"(max {MAX_RESPONSE_SIZE}, Content-Length absent or invalid)"
)
+ # A response with no transport (raw=None — e.g. a synthetic
+ # Response fed into resolve_redirects by tests or tooling) has no
+ # body to buffer, so there is nothing to guard; skip rather than
+ # crash. Real transport-backed responses always have raw set.
+ if raw is None:
+ return
+
original_read = raw.read
def bounded_read(amt=None, *args, **kwargs):
@@ -149,6 +156,65 @@ def _check_response_size(response: requests.Response) -> None:
_install_body_guard(response)
+def _discard_redirect_body(response: requests.Response) -> None:
+ """Size-check a redirect response, then drop its body unread.
+
+ Requests reads ``response.content`` -- the whole body, decoded -- at the
+ start of ``Session.resolve_redirects``, which ``Session.send`` runs on
+ every redirect: to follow it, and with ``allow_redirects=False`` to
+ prepare ``Response.next``. A redirect body is not needed to follow
+ ``Location``, so close the connection and cache an empty body before
+ that read can happen.
+
+ Raises:
+ ValueError: If the redirect's Content-Length exceeds
+ MAX_RESPONSE_SIZE or conflicts (see ``_check_response_size``).
+ """
+ _check_response_size(response)
+ # Close before marking the body consumed: Response.close() releases an
+ # unread connection only while this flag is false. A synthetic response
+ # with no transport (raw=None) has no connection to release and
+ # Response.close() would crash on it; skip straight to discarding the
+ # (absent) body.
+ if response.raw is not None:
+ response.close()
+ response._content = b""
+ response._content_consumed = True
+
+
+def _discard_redirect_body_hook(response: requests.Response, **_kwargs):
+ """Requests response hook: discard a redirect's body (see above).
+
+ ``Session.send`` dispatches response hooks before it calls
+ ``resolve_redirects``, so this runs ahead of the body read there.
+ """
+ if response.is_redirect:
+ _discard_redirect_body(response)
+
+
+def _with_redirect_body_hook(hooks: Optional[dict]) -> dict:
+ """Return ``hooks`` with ``_discard_redirect_body_hook`` run first.
+
+ ``safe_get``/``safe_post`` send each hop through a plain
+ ``requests.get``/``requests.post``, whose throwaway ``requests.Session``
+ would otherwise buffer every redirect body (see
+ ``_discard_redirect_body``). Caller-supplied hooks are kept and run
+ after it, so they see the redirect's status and headers but an empty
+ body. The caller's dict is not mutated.
+ """
+ merged = dict(hooks or {})
+ caller_response_hooks = merged.get("response")
+ if caller_response_hooks is None:
+ caller_response_hooks = []
+ elif callable(caller_response_hooks):
+ caller_response_hooks = [caller_response_hooks]
+ merged["response"] = [
+ _discard_redirect_body_hook,
+ *caller_response_hooks,
+ ]
+ return merged
+
+
def _resolve_redirect_method(method: str, status_code: int) -> str:
"""Determine HTTP method after redirect, per RFC 7231."""
if status_code == 303 and method != "HEAD":
@@ -241,12 +307,17 @@ def safe_get(
**kwargs: Additional arguments to pass to requests.get()
Returns:
- Response object
+ Response object. A redirect response's body (any 301/302/303/307/308
+ with a ``Location``) is discarded unread, whether the hop is followed
+ or returned because ``allow_redirects=False``: its status and headers
+ stay available, ``content`` is ``b""``. Caller ``hooks`` still run,
+ after that discard.
Raises:
ValueError: If URL fails SSRF validation, or (with
``require_https``) the URL or a redirect hop is not https, or
- ``verify=False`` is passed
+ ``verify=False`` is passed, or a response's Content-Length
+ (a redirect's included) exceeds MAX_RESPONSE_SIZE or conflicts
requests.RequestException: If request fails
"""
if require_https:
@@ -290,6 +361,9 @@ def safe_get(
# each redirect target against SSRF rules
caller_wants_redirects = kwargs.pop("allow_redirects", True)
kwargs["allow_redirects"] = False
+ # Each hop's plain requests call would still buffer a redirect body
+ # while preparing Response.next; drop it unread instead.
+ kwargs["hooks"] = _with_redirect_body_hook(kwargs.get("hooks"))
current_url = url
try:
@@ -427,12 +501,15 @@ def safe_post(
**kwargs: Additional arguments to pass to requests.post()
Returns:
- Response object
+ Response object. Redirect bodies are discarded unread, as in
+ ``safe_get``.
Raises:
- ValueError: If the URL fails SSRF validation, or if a 307/308
+ ValueError: If the URL fails SSRF validation, if a 307/308
redirect would re-send the request body outside the scope of
- the URL the caller addressed
+ the URL the caller addressed, or if a response's
+ Content-Length (a redirect's included) exceeds
+ MAX_RESPONSE_SIZE or conflicts
requests.RequestException: If request fails
"""
# Validate URL to prevent SSRF
@@ -461,6 +538,9 @@ def safe_post(
# each redirect target against SSRF rules
caller_wants_redirects = kwargs.pop("allow_redirects", True)
kwargs["allow_redirects"] = False
+ # Each hop's plain requests call would still buffer a redirect body
+ # while preparing Response.next; drop it unread instead.
+ kwargs["hooks"] = _with_redirect_body_hook(kwargs.get("hooks"))
current_url = url
try:
@@ -594,6 +674,11 @@ class SafeSession(requests.Session):
``requests`` internals; if a future version stops routing hops through
``send()``, redirect targets would no longer be validated.
+ Redirect response bodies are discarded before Requests' redirect loop
+ would buffer them, including its ``Response.next`` preparation when
+ ``allow_redirects=False``. Callers can inspect redirect status and
+ headers, but not its body.
+
Usage:
with SafeSession() as session:
response = session.get(url)
@@ -669,19 +754,28 @@ class SafeSession(requests.Session):
yield_requests=False,
**adapter_kwargs,
):
- """Record whether this pass will follow hops or only prepare one.
+ """Record the redirect mode and discard bodies before Requests drains them.
``Session.send`` calls this with ``yield_requests=True`` even when the
caller passed ``allow_redirects=False``, to populate ``Response.next``.
``rebuild_auth`` runs before that yield and cannot see which mode it is
in, so the flag is published here for it to read.
+ Requests reads ``resp.content`` at the start of its redirect loop,
+ before control returns to ``SafeSession.send`` for the size check.
+ A redirect can therefore buffer an unbounded body (including decoded
+ compressed content) unless it is closed here. Redirect bodies are not
+ needed to follow ``Location``; keep an empty cached body so Requests
+ does not read the closed socket while preparing the next request.
+
The parameter list mirrors ``Session.resolve_redirects`` positionally,
so a caller passing ``stream`` third still gets streamed responses.
"""
previous = self._preparing_next_only
self._redirect_local.preparing_next_only = yield_requests
try:
+ if self.get_redirect_target(resp):
+ _discard_redirect_body(resp)
yield from super().resolve_redirects(
resp,
req,
diff --git a/tests/research_library/downloaders/test_arxiv_html_text.py b/tests/research_library/downloaders/test_arxiv_html_text.py
index 9d61e80aa1..6d6acd2837 100644
--- a/tests/research_library/downloaders/test_arxiv_html_text.py
+++ b/tests/research_library/downloaders/test_arxiv_html_text.py
@@ -1513,8 +1513,8 @@ def test_library_text_path_keeps_pdf_retries_when_rate_limited(mocker):
def test_export_host_downloader_fetches_html_and_pdf_from_export(mocker):
# arXiv asks programmatic clients to use export.arxiv.org. Its PDF URL
- # carries no ".pdf" suffix, which that host would answer with a 301
- # whose body requests drains before SafeSession can size-check it.
+ # carries no ".pdf" suffix, which that host would answer with an
+ # unnecessary 301.
from unittest.mock import Mock
from local_deep_research.research_library.downloaders.arxiv import (
diff --git a/tests/security/test_safe_session_redirect_body.py b/tests/security/test_safe_session_redirect_body.py
new file mode 100644
index 0000000000..f26004965b
--- /dev/null
+++ b/tests/security/test_safe_session_redirect_body.py
@@ -0,0 +1,273 @@
+"""Real Requests redirect handling must not buffer untrusted redirect bodies."""
+
+import gzip
+from contextlib import contextmanager
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from threading import Thread
+from unittest.mock import patch
+
+import pytest
+
+import urllib3.response
+
+from local_deep_research.security.safe_requests import (
+ SafeSession,
+ safe_get,
+ safe_post,
+)
+
+
+@contextmanager
+def _redirect_server(
+ body: bytes,
+ *,
+ content_encoding: str | None = None,
+ second_redirect: tuple[bytes, str | None] | None = None,
+ final_body: bytes | None = None,
+):
+ paths: list[str] = []
+
+ class Handler(BaseHTTPRequestHandler):
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length") or 0)
+ self.rfile.read(length)
+ self.do_GET()
+
+ def do_GET(self):
+ paths.append(self.path)
+ if self.path == "/redirect" or (
+ self.path == "/middle" and second_redirect is not None
+ ):
+ if self.path == "/redirect":
+ redirect_body = body
+ encoding = content_encoding
+ location = "/middle" if second_redirect else "/final"
+ else:
+ redirect_body, encoding = second_redirect
+ location = "/final"
+ self.send_response(302)
+ self.send_header("Location", location)
+ self.send_header("Set-Cookie", "redirect_token=ok; Path=/")
+ self.send_header("Content-Length", str(len(redirect_body)))
+ if encoding:
+ self.send_header("Content-Encoding", encoding)
+ self.end_headers()
+ try:
+ self.wfile.write(redirect_body)
+ except (BrokenPipeError, ConnectionResetError):
+ pass # The size check may close the socket before the write.
+ elif final_body is not None:
+ # No Content-Length: only the streamed body guard bounds it.
+ self.send_response(200)
+ self.send_header("Connection", "close")
+ self.end_headers()
+ try:
+ self.wfile.write(final_body)
+ except (BrokenPipeError, ConnectionResetError):
+ pass # The body guard may close the socket mid-write.
+ self.close_connection = True
+ else:
+ self.send_response(200)
+ self.send_header("Content-Length", "2")
+ self.end_headers()
+ self.wfile.write(b"ok")
+
+ def log_message(self, *_args):
+ pass
+
+ with ThreadingHTTPServer(("127.0.0.1", 0), Handler) as server:
+ thread = Thread(target=server.serve_forever, daemon=True)
+ thread.start()
+ try:
+ yield f"http://127.0.0.1:{server.server_port}/redirect", paths
+ finally:
+ server.shutdown()
+ thread.join(timeout=5)
+
+
[email protected]("follow_redirects", [False, True])
+def test_oversized_redirect_is_rejected_before_following(follow_redirects):
+ with patch(
+ "local_deep_research.security.safe_requests.MAX_RESPONSE_SIZE", 64
+ ):
+ with _redirect_server(b"x" * 128) as (url, paths):
+ with SafeSession(allow_localhost=True) as session:
+ with pytest.raises(ValueError, match="Response too large"):
+ session.get(
+ url,
+ stream=True,
+ allow_redirects=follow_redirects,
+ timeout=5,
+ )
+ assert paths == ["/redirect"]
+
+
+def test_encoded_redirect_body_is_discarded_without_decoding():
+ compressed = gzip.compress(b"x" * 4096)
+ assert len(compressed) < 64
+ with patch(
+ "local_deep_research.security.safe_requests.MAX_RESPONSE_SIZE", 64
+ ):
+ with _redirect_server(compressed, content_encoding="gzip") as (
+ url,
+ paths,
+ ):
+ with SafeSession(allow_localhost=True) as session:
+ response = session.get(url, stream=True, timeout=5)
+ assert response.status_code == 200
+ assert response.content == b"ok"
+ assert response.history[0].content == b""
+ assert "redirect_token=ok" in response.request.headers["Cookie"]
+ assert paths == ["/redirect", "/final"]
+
+
+def test_unfollowed_redirect_body_is_discarded_before_next_is_prepared():
+ compressed = gzip.compress(b"x" * 4096)
+ with patch(
+ "local_deep_research.security.safe_requests.MAX_RESPONSE_SIZE", 64
+ ):
+ with _redirect_server(compressed, content_encoding="gzip") as (
+ url,
+ paths,
+ ):
+ with SafeSession(allow_localhost=True) as session:
+ response = session.get(
+ url, stream=True, allow_redirects=False, timeout=5
+ )
+ assert response.status_code == 302
+ assert response.content == b""
+ assert response.next.url.endswith("/final")
+ assert paths == ["/redirect"]
+
+
+def test_each_hop_discards_its_compressed_redirect_body():
+ compressed = gzip.compress(b"x" * 4096)
+ assert len(compressed) < 64
+ with patch(
+ "local_deep_research.security.safe_requests.MAX_RESPONSE_SIZE", 64
+ ):
+ with _redirect_server(
+ b"first",
+ second_redirect=(compressed, "gzip"),
+ ) as (url, paths):
+ with SafeSession(allow_localhost=True) as session:
+ response = session.get(url, stream=True, timeout=5)
+ assert response.content == b"ok"
+ assert [hop.content for hop in response.history] == [b"", b""]
+ assert paths == ["/redirect", "/middle", "/final"]
+
+
+# safe_get/safe_post follow redirects themselves, sending each hop through a
+# plain ``requests.get``/``requests.post`` with ``allow_redirects=False``.
+# Requests' own Session.send still runs ``resolve_redirects`` on every 3xx to
+# build ``Response.next``, and that reads ``resp.content`` -- the whole body,
+# gzip-decoded -- before ``_check_response_size`` sees the final response.
+
+
+def decoded_gzip_bytes(monkeypatch):
+ """Count every byte urllib3 gunzips during the test."""
+ counter = {"bytes": 0}
+ original = urllib3.response.GzipDecoder.decompress
+
+ def counting(self, data, *args, **kwargs):
+ out = original(self, data, *args, **kwargs)
+ counter["bytes"] += len(out)
+ return out
+
+ monkeypatch.setattr(urllib3.response.GzipDecoder, "decompress", counting)
+ return counter
+
+
+def _call(func, url, **kwargs):
+ if func is safe_post:
+ return safe_post(
+ url, data=b"payload", allow_localhost=True, timeout=5, **kwargs
+ )
+ return safe_get(url, allow_localhost=True, timeout=5, **kwargs)
+
+
[email protected]("stream", [False, True])
[email protected]("func", [safe_get, safe_post])
+def test_safe_helpers_do_not_decode_followed_redirect_body(
+ func, stream, decoded_gzip_bytes
+):
+ compressed = gzip.compress(b"x" * 4096)
+ assert len(compressed) < 64
+ with patch(
+ "local_deep_research.security.safe_requests.MAX_RESPONSE_SIZE", 64
+ ):
+ with _redirect_server(compressed, content_encoding="gzip") as (
+ url,
+ paths,
+ ):
+ response = _call(func, url, stream=stream)
+ assert response.status_code == 200
+ assert response.content == b"ok"
+ assert paths == ["/redirect", "/final"]
+ assert decoded_gzip_bytes["bytes"] == 0
+
+
[email protected]("stream", [False, True])
[email protected]("func", [safe_get, safe_post])
+def test_safe_helpers_do_not_decode_unfollowed_redirect_body(
+ func, stream, decoded_gzip_bytes
+):
+ compressed = gzip.compress(b"x" * 4096)
+ with patch(
+ "local_deep_research.security.safe_requests.MAX_RESPONSE_SIZE", 64
+ ):
+ with _redirect_server(compressed, content_encoding="gzip") as (
+ url,
+ paths,
+ ):
+ response = _call(func, url, stream=stream, allow_redirects=False)
+ assert response.status_code == 302
+ assert response.headers["Location"] == "/final"
+ assert response.content == b""
+ assert paths == ["/redirect"]
+ assert decoded_gzip_bytes["bytes"] == 0
+
+
[email protected]("func", [safe_get, safe_post])
+def test_safe_helpers_reject_oversized_redirect_before_following(func):
+ with patch(
+ "local_deep_research.security.safe_requests.MAX_RESPONSE_SIZE", 64
+ ):
+ with _redirect_server(b"x" * 128) as (url, paths):
+ with pytest.raises(ValueError, match="Response too large"):
+ _call(func, url, stream=True)
+ assert paths == ["/redirect"]
+
+
[email protected]("func", [safe_get, safe_post])
+def test_safe_helpers_still_cap_final_body_after_redirect(
+ func, decoded_gzip_bytes
+):
+ compressed = gzip.compress(b"x" * 4096)
+ with patch(
+ "local_deep_research.security.safe_requests.MAX_RESPONSE_SIZE", 64
+ ):
+ with _redirect_server(
+ compressed, content_encoding="gzip", final_body=b"y" * 4096
+ ) as (url, paths):
+ response = _call(func, url, stream=True)
+ assert response.status_code == 200
+ with pytest.raises(ValueError, match="Response body too large"):
+ _ = response.content
+ assert paths == ["/redirect", "/final"]
+ assert decoded_gzip_bytes["bytes"] == 0
+
+
+def test_safe_get_keeps_caller_response_hooks():
+ seen = []
+ with _redirect_server(b"redirect") as (url, paths):
+ response = safe_get(
+ url,
+ allow_localhost=True,
+ timeout=5,
+ hooks={"response": lambda r, **_kw: seen.append(r.status_code)},
+ )
+ assert response.content == b"ok"
+ assert seen == [302, 200]
+ assert paths == ["/redirect", "/final"]