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): keep the request body inside the caller's scope on a 307/308 (#6419)

Ehsana34fef6bcb01
diff --git a/changelog.d/6265.security.md b/changelog.d/6265.security.md
new file mode 100644
index 0000000000..8d23ed235b
--- /dev/null
+++ b/changelog.d/6265.security.md
@@ -0,0 +1,16 @@
+`safe_post` and `SafeSession` no longer re-send the request body when a 307
+or 308 redirect leaves the scope of the URL the caller addressed. Those two
+status codes preserve the method and the body, so whatever was posted
+travelled to whatever host the `Location` header named: the search engines
+sent the user's query on, and `api/client.py` sends a username and password
+to its login endpoint. Credential headers are already dropped on such a hop
+(#6139), but a body cannot be dropped without sending a different request
+than the one the server asked us to repeat, so the hop is refused with a
+`ValueError` instead. A 307 or 308 within the same scheme, host and port
+still carries the body, a request with no body is unaffected, and
+301/302/303 already downgraded to GET and left the body behind.
+
+The refusal applies to a hop that is about to be followed. With
+`allow_redirects=False` nothing is sent, so the 3xx response is returned to
+the caller as before and only the credential headers are dropped from the
+`Response.next` it carries.
diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.py
index dba7f87c33..08749a04c8 100644
--- a/src/local_deep_research/security/safe_requests.py
+++ b/src/local_deep_research/security/safe_requests.py
@@ -6,6 +6,7 @@ Wraps requests library to add SSRF protection and security best practices.
import datetime
import email.utils
+import threading
import time
from typing import Any, Optional
from urllib.parse import urljoin
@@ -384,7 +385,9 @@ def safe_post(
Response object
Raises:
- ValueError: If URL fails SSRF validation
+ ValueError: If the URL fails SSRF validation, or if a 307/308
+ redirect would re-send the request body outside the scope of
+ the URL the caller addressed
requests.RequestException: If request fails
"""
# Validate URL to prevent SSRF
@@ -460,6 +463,31 @@ def safe_post(
redirect_method = _resolve_redirect_method(
redirect_method, response.status_code
)
+ # 307/308 keep the body, and it cannot be dropped the way the
+ # credential headers below are without sending a request the
+ # server did not ask for, so refuse the hop instead.
+ body_would_follow = (
+ data is not None
+ or json is not None
+ or kwargs.get("files") is not None
+ )
+ if (
+ redirect_method != "GET"
+ and body_would_follow
+ and _redirect_scope.should_strip_auth(
+ current_url, redirect_url
+ )
+ ):
+ logger.warning(
+ f"Redirect to {redirect_url} not followed: it would "
+ f"re-send the request body outside the scope of "
+ f"{current_url} (hop {redirects_followed + 1})"
+ )
+ response.close()
+ raise ValueError(
+ "Redirect would re-send the request body outside "
+ f"the requested scope: {redirect_url}"
+ )
# Credentials do not follow the hop out of their own scope.
kwargs["headers"] = _headers_for_redirect(
kwargs.get("headers"), current_url, redirect_url
@@ -535,8 +563,9 @@ class SafeSession(requests.Session):
Raises:
ValueError: If a URL (initial or redirect target) fails SSRF
- validation, or if the response Content-Length exceeds
- MAX_RESPONSE_SIZE. Note: ``safe_get``/``safe_post`` also raise
+ validation, if a 307/308 redirect would re-send the request body
+ outside the scope of the URL the caller addressed, or if the
+ response Content-Length exceeds MAX_RESPONSE_SIZE. Note: ``safe_get``/``safe_post`` also raise
``ValueError`` for too-many-redirects, but ``SafeSession`` raises
``requests.TooManyRedirects`` for that case since it delegates
redirect counting to the ``requests`` library.
@@ -563,19 +592,86 @@ class SafeSession(requests.Session):
self.max_redirects = _MAX_REDIRECTS
self.allow_localhost = allow_localhost
self.allow_private_ips = allow_private_ips
+ # Per-thread, because one session is shared across search engines.
+ self._redirect_local = threading.local()
+
+ @property
+ def _preparing_next_only(self) -> bool:
+ """True while ``resolve_redirects`` is only building ``Response.next``."""
+ return getattr(self._redirect_local, "preparing_next_only", False)
+
+ def resolve_redirects(
+ self,
+ resp,
+ req,
+ stream=False,
+ timeout=None,
+ verify=True,
+ cert=None,
+ proxies=None,
+ yield_requests=False,
+ **adapter_kwargs,
+ ):
+ """Record whether this pass will follow hops or only prepare one.
+
+ ``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.
+
+ 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:
+ yield from super().resolve_redirects(
+ resp,
+ req,
+ stream=stream,
+ timeout=timeout,
+ verify=verify,
+ cert=cert,
+ proxies=proxies,
+ yield_requests=yield_requests,
+ **adapter_kwargs,
+ )
+ finally:
+ self._redirect_local.preparing_next_only = previous
def rebuild_auth(
self, prepared_request: requests.PreparedRequest, response
) -> None:
- """Drop vendor API-key headers too when a hop leaves auth scope.
+ """Drop vendor API-key headers too when a hop leaves auth scope, and
+ refuse the hop when it would carry the request body along.
The base implementation removes ``Authorization`` and nothing else, so
a session default such as the Semantic Scholar engine's ``x-api-key``
would otherwise be replayed to the redirect target. The strip runs
before ``super()`` because the base method reapplies netrc credentials
for the new host, and those belong to it.
+
+ ``resolve_redirects`` clears ``body`` before calling this method for
+ every status that downgrades the method, and keeps it for 307 and 308,
+ so a body still present here is one the hop would re-send.
+
+ The refusal is raised only when the hop is about to be followed. With
+ ``allow_redirects=False`` nothing is sent, so raising would deny the
+ caller the 3xx response it asked for; the credential strip still runs,
+ which is what ``Response.next`` needs.
"""
if self.should_strip_auth(response.request.url, prepared_request.url):
+ following_the_hop = not self._preparing_next_only
+ if prepared_request.body is not None and following_the_hop:
+ logger.warning(
+ f"Redirect to {prepared_request.url} not followed: it "
+ f"would re-send the request body outside the scope of "
+ f"{response.request.url}"
+ )
+ raise ValueError(
+ "Redirect would re-send the request body outside "
+ f"the requested scope: {prepared_request.url}"
+ )
for name in [
header
for header in prepared_request.headers
@@ -645,12 +741,20 @@ class SafeSession(requests.Session):
# (resolve_redirects re-enters here), so each hop is independently
# resolved, validated, and pinned — the address validated is the
# address connected to.
- with dns_pinning.pinned_request(
- request.url or "",
- allow_localhost=self.allow_localhost,
- allow_private_ips=self.allow_private_ips,
- ):
- response = super().send(request, **kwargs)
+ # Restore the resolve_redirects flag here rather than relying on the
+ # generator's own finally: Session.send takes one item from it and
+ # drops it, so that finally waits on collection. A leaked True would
+ # disarm the body-scope refusal for the rest of the thread.
+ preparing = self._preparing_next_only
+ try:
+ with dns_pinning.pinned_request(
+ request.url or "",
+ allow_localhost=self.allow_localhost,
+ allow_private_ips=self.allow_private_ips,
+ ):
+ response = super().send(request, **kwargs)
+ finally:
+ self._redirect_local.preparing_next_only = preparing
_check_response_size(response)
return response
diff --git a/tests/security/test_ssrf_dns_pinning.py b/tests/security/test_ssrf_dns_pinning.py
index e0ac435686..32de642ba9 100644
--- a/tests/security/test_ssrf_dns_pinning.py
+++ b/tests/security/test_ssrf_dns_pinning.py
@@ -372,6 +372,11 @@ def test_safe_post_redirect_repins_hop_and_resolves_method(
the fetch would fail instead of completing against the real server —
so host B being resolved exactly twice (validate + pin, no connect-time
lookup) is the discriminating assertion.
+
+ The POST carries no body: a 307 leaving the scope of the URL the caller
+ addressed is refused rather than re-sent (#6265, covered in
+ ``test_ssrf_redirect_bypass.TestSafePostBodyScope``), and the method
+ conversion asserted here does not depend on one.
"""
server_b = HTTPServer(("127.0.0.1", 0), _MethodEchoHandler)
threading.Thread(target=server_b.serve_forever, daemon=True).start()
@@ -409,7 +414,6 @@ def test_safe_post_redirect_repins_hop_and_resolves_method(
with patch.object(dns_pinning, "_real_getaddrinfo", resolver):
resp = safe_post(
f"http://host-a-post.example:{port_a}/",
- data=b"payload",
allow_localhost=True,
timeout=5,
)
diff --git a/tests/security/test_ssrf_egress_policy.py b/tests/security/test_ssrf_egress_policy.py
index 85c5100764..f306a7576f 100644
--- a/tests/security/test_ssrf_egress_policy.py
+++ b/tests/security/test_ssrf_egress_policy.py
@@ -672,14 +672,16 @@ def test_safe_post_strips_credentials_on_downgraded_redirect(stub_http):
def test_safe_post_strips_credentials_on_method_preserving_redirect(stub_http):
- """307 keeps the method and the body, so it takes the other branch of
- the redirect loop and needs its own case."""
+ """307 keeps the method, so it takes the other branch of the redirect
+ loop and needs its own case. Bodiless, because a body on this branch
+ stops the cross-host hop outright (#6265,
+ ``test_ssrf_redirect_bypass.TestSafePostBodyScope``)."""
start = f"http://{PUBLIC_A}/start"
target = f"http://{PUBLIC_B}/final"
stub_http["queue"].append(_FakeResponse(307, url=start, location=target))
stub_http["queue"].append(_FakeResponse(200, url=target))
- safe_requests.safe_post(start, json={"q": 1}, headers=dict(_CREDS))
+ safe_requests.safe_post(start, headers=dict(_CREDS))
headers = _hop_headers(stub_http)
assert "authorization" not in headers
diff --git a/tests/security/test_ssrf_redirect_bypass.py b/tests/security/test_ssrf_redirect_bypass.py
index 30c39f65e0..cf32a09909 100644
--- a/tests/security/test_ssrf_redirect_bypass.py
+++ b/tests/security/test_ssrf_redirect_bypass.py
@@ -8,6 +8,8 @@ Verifies:
- Both safe_get and safe_post
"""
+import io
+
import pytest
from unittest.mock import patch, MagicMock
@@ -361,10 +363,17 @@ class TestSafePostMethodConversion:
assert mock_get.call_count == 1
def test_post_307_preserves_method_and_body(self, mock_validate_url):
- """POST with 307 redirect should preserve method and body."""
+ """POST with 307 redirect should preserve method and body.
+
+ Within the scope of the URL the caller addressed. A hop that leaves
+ that scope is refused instead, so the target here stays on the
+ original host (see TestSafePostBodyScope below).
+ """
test_data = b"form-data"
redirect_resp = _make_response(
- 307, {"Location": "https://other.com"}, "https://example.com"
+ 307,
+ {"Location": "https://example.com/final"},
+ "https://example.com",
)
final_resp = _make_response(200)
@@ -381,10 +390,15 @@ class TestSafePostMethodConversion:
assert mock_post.call_args_list[1].kwargs.get("data") == test_data
def test_post_308_preserves_method_and_body(self, mock_validate_url):
- """POST with 308 redirect should preserve method and body."""
+ """POST with 308 redirect should preserve method and body.
+
+ Same-host target, for the reason given on the 307 case above.
+ """
test_json = {"key": "value"}
redirect_resp = _make_response(
- 308, {"Location": "https://other.com"}, "https://example.com"
+ 308,
+ {"Location": "https://example.com/final"},
+ "https://example.com",
)
final_resp = _make_response(200)
@@ -784,6 +798,194 @@ class TestPostBodyNotForwardedOnConversion:
assert "json" not in call_kwargs
+class TestSafePostBodyScope:
+ """A 307/308 keeps the body, so the hop must stay in the caller's scope.
+
+ Issue #6265. The credential rule (``_headers_for_redirect``) drops an
+ Authorization header when the hop leaves the scope it was issued for,
+ and a body cannot be dropped the same way without sending a different
+ request than the one the server asked us to repeat.
+ """
+
+ def test_post_307_to_another_host_does_not_resend_the_body(
+ self, mock_validate_url
+ ):
+ resp_307 = _make_response(
+ 307, {"Location": "https://other.com"}, "https://example.com"
+ )
+
+ with patch(
+ "local_deep_research.security.safe_requests.requests.post",
+ side_effect=[resp_307, _make_response(200)],
+ ) as mock_post:
+ with pytest.raises(ValueError) as excinfo:
+ safe_post(
+ "https://example.com",
+ json={"query": "user text"},
+ allow_redirects=True,
+ )
+
+ assert "re-send the request body" in str(excinfo.value)
+ assert "https://other.com" in str(excinfo.value)
+ # The second host was never dialled: raising after the POST
+ # would not have prevented anything.
+ assert mock_post.call_count == 1
+
+ def test_post_308_to_another_host_does_not_resend_the_body(
+ self, mock_validate_url
+ ):
+ """308 takes the same branch and needs its own case."""
+ resp_308 = _make_response(
+ 308, {"Location": "https://other.com"}, "https://example.com"
+ )
+
+ with patch(
+ "local_deep_research.security.safe_requests.requests.post",
+ side_effect=[resp_308, _make_response(200)],
+ ) as mock_post:
+ with pytest.raises(ValueError):
+ safe_post(
+ "https://example.com",
+ data=b"form-data",
+ allow_redirects=True,
+ )
+
+ assert mock_post.call_count == 1
+
+ def test_post_307_to_a_different_port_does_not_resend_the_body(
+ self, mock_validate_url
+ ):
+ """Scope is host, port and scheme, the same boundary the credential
+ rule uses, so another service on the same machine is out of scope."""
+ resp_307 = _make_response(
+ 307,
+ {"Location": "http://127.0.0.1:9999/api"},
+ "http://127.0.0.1:11434",
+ )
+
+ with patch(
+ "local_deep_research.security.safe_requests.requests.post",
+ side_effect=[resp_307, _make_response(200)],
+ ) as mock_post:
+ with pytest.raises(ValueError):
+ safe_post(
+ "http://127.0.0.1:11434/api/show",
+ json={"model": "nomic-embed-text"},
+ allow_redirects=True,
+ allow_localhost=True,
+ )
+
+ assert mock_post.call_count == 1
+
+ def test_post_307_to_another_host_without_a_body_is_followed(
+ self, mock_validate_url
+ ):
+ """Nothing to protect when the caller sent no body, so the hop is
+ not refused. Without this the rule would read as "safe_post never
+ follows a cross-host 307"."""
+ resp_307 = _make_response(
+ 307, {"Location": "https://other.com"}, "https://example.com"
+ )
+
+ with patch(
+ "local_deep_research.security.safe_requests.requests.post",
+ side_effect=[resp_307, _make_response(200)],
+ ) as mock_post:
+ result = safe_post("https://example.com", allow_redirects=True)
+
+ assert result.status_code == 200
+ assert mock_post.call_count == 2
+
+ def test_post_302_to_another_host_still_follows_and_drops_the_body(
+ self, mock_validate_url
+ ):
+ """The method-downgrade arm already leaves the body behind, so a
+ 302 across hosts is unaffected by the refusal above."""
+ resp_302 = _make_response(
+ 302, {"Location": "https://other.com"}, "https://example.com"
+ )
+
+ with (
+ patch(
+ "local_deep_research.security.safe_requests.requests.post",
+ return_value=resp_302,
+ ),
+ patch(
+ "local_deep_research.security.safe_requests.requests.get",
+ return_value=_make_response(200),
+ ) as mock_get,
+ ):
+ result = safe_post(
+ "https://example.com",
+ json={"query": "user text"},
+ allow_redirects=True,
+ )
+
+ assert result.status_code == 200
+ assert mock_get.call_count == 1
+ assert "json" not in mock_get.call_args.kwargs
+
+
+class TestSafeSessionBodyScope:
+ """The same rule for ``SafeSession``, which reaches it through requests'
+ own ``resolve_redirects`` rather than the hand-rolled loop.
+
+ ``resolve_redirects`` clears ``body`` for every status that downgrades
+ the method and keeps it for 307/308, then calls ``rebuild_auth``, so the
+ body still being set there is what identifies the hop that would re-send
+ it. ``api/client.py`` posts a username and password through this session.
+ """
+
+ @staticmethod
+ def _hop(from_url, to_url, body):
+ session = SafeSession()
+ original = requests.Request("POST", from_url, json=body).prepare()
+ hop = requests.Request("POST", to_url, json=body).prepare()
+ response = requests.Response()
+ response.request = original
+ return session, hop, response
+
+ def test_cross_host_hop_carrying_a_body_is_refused(self):
+ session, hop, response = self._hop(
+ "http://127.0.0.1:5000/auth/login",
+ "http://198.51.100.7/auth/login",
+ {"username": "u", "password": "SECRET"},
+ )
+
+ with pytest.raises(ValueError) as excinfo:
+ session.rebuild_auth(hop, response)
+
+ assert "re-send the request body" in str(excinfo.value)
+
+ def test_same_host_hop_carrying_a_body_is_allowed(self):
+ """Without this, "refused" could just mean SafeSession refuses every
+ POST redirect."""
+ session, hop, response = self._hop(
+ "http://127.0.0.1:5000/auth/login",
+ "http://127.0.0.1:5000/auth/login/v2",
+ {"username": "u", "password": "SECRET"},
+ )
+
+ session.rebuild_auth(hop, response)
+
+ assert hop.body is not None
+
+ def test_cross_host_hop_without_a_body_is_allowed(self):
+ """The method-downgrade statuses reach ``rebuild_auth`` with the body
+ already cleared, and a GET never had one."""
+ session = SafeSession()
+ original = requests.Request(
+ "GET", "http://127.0.0.1:5000/start"
+ ).prepare()
+ hop = requests.Request("GET", "http://198.51.100.7/next").prepare()
+ response = requests.Response()
+ response.request = original
+
+ session.rebuild_auth(hop, response)
+
+ assert hop.body is None
+
+
class TestSafePostPerHopValidation:
"""Verify validate_url is called for each hop in safe_post."""
@@ -991,3 +1193,169 @@ class TestRedirectParserDifferentialBypass:
):
with pytest.raises(ValueError, match="Redirect target failed SSRF"):
safe_get("https://example.com", allow_redirects=True)
+
+
+class TestSafeSessionBodyScopeThroughSend:
+ """The same rule driven through ``Session.send``, not by calling
+ ``rebuild_auth`` directly.
+
+ ``Session.send`` calls ``resolve_redirects(..., yield_requests=True)`` to
+ populate ``Response.next`` even when the caller passed
+ ``allow_redirects=False``, and that generator calls ``rebuild_auth``
+ before it yields. Refusing there would deny the caller the 3xx response
+ it asked for, so the two cases need separating and only a test that
+ goes through ``send`` can tell them apart.
+ """
+
+ class _RecordingAdapter(requests.adapters.HTTPAdapter):
+ """Answers from a script and records what was actually dialled."""
+
+ def __init__(self, script):
+ super().__init__()
+ self.script = list(script)
+ self.sent = []
+
+ def send(self, request, **kwargs):
+ self.sent.append(request.url)
+ status, location = self.script.pop(0)
+ response = requests.Response()
+ response.status_code = status
+ response.url = request.url
+ response.request = request
+ response.raw = io.BytesIO(b"")
+ if location:
+ response.headers["Location"] = location
+ return response
+
+ def _session(self, script):
+ session = SafeSession(allow_private_ips=True)
+ adapter = self._RecordingAdapter(script)
+ session.mount("http://", adapter)
+ return session, adapter
+
+ @pytest.mark.parametrize("status", [307, 308])
+ def test_redirects_disabled_returns_the_3xx_and_dials_once(
+ self, status, mock_validate_url
+ ):
+ session, adapter = self._session(
+ [(status, "http://198.51.100.7/auth/login"), (200, None)]
+ )
+
+ with session:
+ response = session.post(
+ "http://127.0.0.1:5000/auth/login",
+ json={"username": "u", "password": "SECRET"},
+ allow_redirects=False,
+ )
+
+ assert response.status_code == status
+ assert adapter.sent == ["http://127.0.0.1:5000/auth/login"]
+
+ @pytest.mark.parametrize("status", [307, 308])
+ def test_redirects_enabled_refuses_before_the_second_call(
+ self, status, mock_validate_url
+ ):
+ session, adapter = self._session(
+ [(status, "http://198.51.100.7/auth/login"), (200, None)]
+ )
+
+ with session:
+ with pytest.raises(ValueError) as excinfo:
+ session.post(
+ "http://127.0.0.1:5000/auth/login",
+ json={"username": "u", "password": "SECRET"},
+ allow_redirects=True,
+ )
+
+ assert "re-send the request body" in str(excinfo.value)
+ assert adapter.sent == ["http://127.0.0.1:5000/auth/login"]
+
+ @pytest.mark.parametrize("status", [307, 308])
+ def test_same_scope_hop_is_followed_with_redirects_enabled(
+ self, status, mock_validate_url
+ ):
+ """Without this, passing could just mean every POST hop is refused."""
+ session, adapter = self._session(
+ [(status, "http://127.0.0.1:5000/auth/login/v2"), (200, None)]
+ )
+
+ with session:
+ response = session.post(
+ "http://127.0.0.1:5000/auth/login",
+ json={"username": "u", "password": "SECRET"},
+ allow_redirects=True,
+ )
+
+ assert response.status_code == 200
+ assert adapter.sent == [
+ "http://127.0.0.1:5000/auth/login",
+ "http://127.0.0.1:5000/auth/login/v2",
+ ]
+
+ @pytest.mark.parametrize("status", [307, 308])
+ def test_disabled_pass_does_not_disarm_the_next_request(
+ self, status, mock_validate_url
+ ):
+ """The ``yield_requests`` flag must not outlive the send that set it.
+
+ ``Session.send`` takes one item from the generator and drops it, so
+ the generator's own ``finally`` waits on collection. If the flag
+ leaked, the refusal would be disarmed for every later request on this
+ thread, which is the failure this whole class exists to prevent.
+ """
+ session, adapter = self._session(
+ [
+ (status, "http://198.51.100.7/auth/login"),
+ (status, "http://198.51.100.7/auth/login"),
+ (200, None),
+ ]
+ )
+
+ with session:
+ first = session.post(
+ "http://127.0.0.1:5000/auth/login",
+ json={"username": "u", "password": "SECRET"},
+ allow_redirects=False,
+ )
+ assert first.status_code == status
+
+ with pytest.raises(ValueError) as excinfo:
+ session.post(
+ "http://127.0.0.1:5000/auth/login",
+ json={"username": "u", "password": "SECRET"},
+ allow_redirects=True,
+ )
+
+ assert "re-send the request body" in str(excinfo.value)
+ assert adapter.sent == [
+ "http://127.0.0.1:5000/auth/login",
+ "http://127.0.0.1:5000/auth/login",
+ ]
+
+ def test_third_positional_argument_is_stream(self, mock_validate_url):
+ """``Session.resolve_redirects`` takes ``stream`` third, not
+ ``yield_requests``.
+
+ A direct positional caller asking to stream must still get responses
+ back and the hop must still be dialled. Reading that slot as
+ ``yield_requests`` instead hands back prepared requests and sends
+ nothing.
+ """
+ session, adapter = self._session([(200, None)])
+
+ request = requests.Request(
+ "GET", "http://127.0.0.1:5000/start"
+ ).prepare()
+ initial = requests.Response()
+ initial.status_code = 302
+ initial.url = request.url
+ initial.request = request
+ initial.raw = io.BytesIO(b"")
+ initial.headers["Location"] = "http://127.0.0.1:5000/next"
+
+ with session:
+ first = next(session.resolve_redirects(initial, request, True))
+
+ assert isinstance(first, requests.Response)
+ assert first.status_code == 200
+ assert adapter.sent == ["http://127.0.0.1:5000/next"]