~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): stop credential headers at a cross-scope redirect hop (#6262)
Ehsan88c2a108a748
diff --git a/changelog.d/6139.security.md b/changelog.d/6139.security.mdnew file mode 100644index 0000000000..e68b753e54--- /dev/null+++ b/changelog.d/6139.security.md@@ -0,0 +1 @@+`safe_get`, `safe_post` and `SafeSession` no longer forward credential headers across a redirect that leaves the scope they were sent to. The standalone helpers follow redirects with their own loop and re-sent the caller's headers verbatim, so an `Authorization` or vendor API-key header (`X-Api-Key`, `X-Goog-Api-Key`, ...) travelled to the new host whenever a vendor endpoint answered with a cross-host 3xx. `SafeSession` inherits requests' `rebuild_auth`, which drops `Authorization` and nothing else, so a session default such as the Semantic Scholar engine's `x-api-key` survived the same hop. All three now drop the credential when the hop changes scheme, host or port, reusing the rule requests already applies, and keep it on a same-host redirect so keyed engines whose endpoints redirect within their own host are unaffected.diff --git a/src/local_deep_research/security/safe_requests.py b/src/local_deep_research/security/safe_requests.pyindex 580dd0d2cd..30f79c9a10 100644--- a/src/local_deep_research/security/safe_requests.py+++ b/src/local_deep_research/security/safe_requests.py@@ -139,6 +139,45 @@ def _resolve_redirect_method(method: str, status_code: int) -> str:return method+# Credential headers: the HTTP-standard set, plus the vendor key/token family.+# The suffixes cover the shapes vendors ship (X-Api-Key, Zotero-API-Key,+# X-Goog-Api-Key, X-Subscription-Token, Ocp-Apim-Subscription-Key, Private-Token),+# so a new vendor needs no edit here. No non-credential header this project+# sends ends in one of them.+_CREDENTIAL_HEADERS = frozenset(+ {"authorization", "proxy-authorization", "cookie"}+)+_CREDENTIAL_HEADER_SUFFIXES = ("key", "token", "secret")++# requests owns the "does this hop leave the credential's scope" rule, so+# reuse it rather than restate it in the hand-rolled loops below.+_redirect_scope = requests.sessions.SessionRedirectMixin()+++def _is_credential_header(name: str) -> bool:+ """Whether a request header carries a caller credential."""+ lowered = name.lower()+ return lowered in _CREDENTIAL_HEADERS or lowered.endswith(+ _CREDENTIAL_HEADER_SUFFIXES+ )+++def _headers_for_redirect(+ headers: Optional[dict], from_url: str, to_url: str+) -> Optional[dict]:+ """Return the headers to send on a redirect hop.++ Credential headers are dropped when the hop leaves the scope they were+ issued for, so a key stays with the host the caller addressed. Returns a+ new dict when it strips, so the caller's own headers object is untouched.+ A chain that leaves scope and later returns to the original host does not+ get the credential back, which is what requests does on its own hops.+ """+ if not headers or not _redirect_scope.should_strip_auth(from_url, to_url):+ return headers+ return {k: v for k, v in headers.items() if not _is_credential_header(k)}++def safe_get(url: str,params: Optional[dict] = None,@@ -248,6 +287,10 @@ def safe_get(f"Redirect target failed SSRF validation: {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+ )current_url = redirect_urlresponse.close()# Note: params are intentionally NOT forwarded to redirect@@ -396,6 +439,10 @@ def safe_post(redirect_method = _resolve_redirect_method(redirect_method, response.status_code)+ # Credentials do not follow the hop out of their own scope.+ kwargs["headers"] = _headers_for_redirect(+ kwargs.get("headers"), current_url, redirect_url+ )current_url = redirect_urlresponse.close()@@ -496,6 +543,26 @@ class SafeSession(requests.Session):self.allow_localhost = allow_localhostself.allow_private_ips = allow_private_ips+ def rebuild_auth(+ self, prepared_request: requests.PreparedRequest, response+ ) -> None:+ """Drop vendor API-key headers too when a hop leaves auth scope.++ 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.+ """+ if self.should_strip_auth(response.request.url, prepared_request.url):+ for name in [+ header+ for header in prepared_request.headers+ if _is_credential_header(header)+ ]:+ del prepared_request.headers[name]+ super().rebuild_auth(prepared_request, response)+def request(self, method: str, url: str, **kwargs) -> requests.Response: # type: ignore[override]"""Override request method to add SSRF validation."""# Validate URLdiff --git a/tests/security/test_ssrf_egress_policy.py b/tests/security/test_ssrf_egress_policy.pyindex 3ca2adf464..85c5100764 100644--- a/tests/security/test_ssrf_egress_policy.py+++ b/tests/security/test_ssrf_egress_policy.py@@ -468,7 +468,13 @@ def stub_http(monkeypatch):assert queue, f"unexpected outbound request to {url}"return queue.pop(0)+ def fake_post(url, **kwargs):+ calls.append((url, kwargs))+ assert queue, f"unexpected outbound request to {url}"+ return queue.pop(0)+monkeypatch.setattr(safe_requests.requests, "get", fake_get)+ monkeypatch.setattr(safe_requests.requests, "post", fake_post)monkeypatch.setattr(safe_requests.dns_pinning, "pinned_request", _NullPin)return {"calls": calls, "queue": queue}@@ -578,32 +584,172 @@ def test_safesession_strips_authorization_on_cross_host_redirect():assert same_host.headers["Authorization"] == "token SECRET"- strict=False,- reason=(- "DEFECT (pre-existing on origin/main, not introduced by the port): "- "safe_get/safe_post hand-roll the redirect loop and re-send the "- "caller's kwargs verbatim, so per-request auth headers survive a "- "cross-host hop. requests' own resolve_redirects would have "- "stripped them via rebuild_auth (see the SafeSession test above). "- "Reachable wherever a user-configured base URL is fetched with a "- "credential header -- e.g. the Paperless engine sends its API "- "token to whatever host paperless api_url redirects to."- ),-)-def test_safe_get_should_strip_authorization_on_cross_host_redirect(- stub_http,-):+_CREDS = {+ "Authorization": "token SECRET",+ "X-Api-Key": "SECRET-VENDOR-KEY",+ "X-Goog-Api-Key": "SECRET-GOOGLE-KEY",+}+++def _hop_headers(stub_http, index=1):+ """Headers actually dialled on hop ``index`` of the recorded call log."""+ _url, kwargs = stub_http["calls"][index]+ return {k.lower(): v for k, v in (kwargs.get("headers") or {}).items()}+++def test_safe_get_strips_credentials_on_cross_host_redirect(stub_http):+ """The standalone helpers hand-roll their redirect loop, so they do not+ inherit the ``rebuild_auth`` behaviour pinned above. Authorization is the+ header requests knows; the vendor keys are the ones the keyed search+ engines actually send."""start = f"http://{PUBLIC_A}/start"target = f"http://{PUBLIC_B}/final"stub_http["queue"].append(_FakeResponse(302, url=start, location=target))stub_http["queue"].append(_FakeResponse(200, url=target))- safe_requests.safe_get(start, headers={"Authorization": "token SECRET"})+ safe_requests.safe_get(start, headers=dict(_CREDS))- hop_url, hop_kwargs = stub_http["calls"][1]+ hop_url, _kwargs = stub_http["calls"][1]assert hop_url == target- assert "Authorization" not in (hop_kwargs.get("headers") or {})+ headers = _hop_headers(stub_http)+ assert "authorization" not in headers+ assert "x-api-key" not in headers+ assert "x-goog-api-key" not in headers+ # The hop still happens, and still carries the non-credential headers.+ assert headers["user-agent"] == safe_requests.USER_AGENT+++def test_safe_get_keeps_credentials_on_same_host_redirect(stub_http):+ """Positive control. Without it, the test above is satisfied by a helper+ that strips credentials from every hop, which would break every keyed+ engine whose endpoint redirects within its own host."""+ start = f"http://{PUBLIC_A}/start"+ target = f"http://{PUBLIC_A}/final"+ stub_http["queue"].append(_FakeResponse(302, url=start, location=target))+ stub_http["queue"].append(_FakeResponse(200, url=target))++ safe_requests.safe_get(start, headers=dict(_CREDS))++ headers = _hop_headers(stub_http)+ assert headers["authorization"] == "token SECRET"+ assert headers["x-api-key"] == "SECRET-VENDOR-KEY"+++def test_safe_get_does_not_mutate_the_caller_headers(stub_http):+ """Engines keep one headers dict on ``self`` and reuse it for every+ search, so stripping must not reach back into the caller's object: an+ in-place drop would disarm the key for all later calls, not just this+ hop. The caller supplies its own User-Agent here because that is the+ real shape (NASA ADS and Paperless both do) and the only one where+ safe_get forwards the caller's dict rather than a copy of it.+ """+ start = f"http://{PUBLIC_A}/start"+ target = f"http://{PUBLIC_B}/final"+ stub_http["queue"].append(_FakeResponse(302, url=start, location=target))+ stub_http["queue"].append(_FakeResponse(200, url=target))+ caller_headers = dict(_CREDS, **{"User-Agent": "engine/1.0"})+ expected = dict(caller_headers)++ safe_requests.safe_get(start, headers=caller_headers)++ assert caller_headers == expected+ # ...and the hop itself still dropped them.+ assert "x-api-key" not in _hop_headers(stub_http)+++def test_safe_post_strips_credentials_on_downgraded_redirect(stub_http):+ """302 converts POST to GET; the credential must not ride the new verb."""+ start = f"http://{PUBLIC_A}/start"+ target = f"http://{PUBLIC_B}/final"+ stub_http["queue"].append(_FakeResponse(302, url=start, location=target))+ stub_http["queue"].append(_FakeResponse(200, url=target))++ safe_requests.safe_post(start, json={"q": 1}, headers=dict(_CREDS))++ headers = _hop_headers(stub_http)+ assert "authorization" not in headers+ assert "x-api-key" not in headers+++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."""+ 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))++ headers = _hop_headers(stub_http)+ assert "authorization" not in headers+ assert "x-api-key" not in headers+++def test_safesession_strips_vendor_api_key_on_cross_host_redirect():+ """``Session.rebuild_auth`` deletes Authorization and nothing else, so a+ session-default vendor key (the Semantic Scholar engine sets ``x-api-key``+ on the session) would otherwise outlive the hop."""+ session = safe_requests.SafeSession()+ original = requests.Request(+ "GET", f"http://{PUBLIC_A}/start", headers=dict(_CREDS)+ ).prepare()+ hop = requests.Request(+ "GET", f"http://{PUBLIC_B}/next", headers=dict(_CREDS)+ ).prepare()+ response = requests.Response()+ response.request = original++ session.rebuild_auth(hop, response)++ assert "X-Api-Key" not in hop.headers+ assert "X-Goog-Api-Key" not in hop.headers++ # Same-host hop keeps it, or the check above proves nothing.+ same_host = requests.Request(+ "GET", f"http://{PUBLIC_A}/next", headers=dict(_CREDS)+ ).prepare()+ session.rebuild_auth(same_host, response)+ assert same_host.headers["X-Api-Key"] == "SECRET-VENDOR-KEY"+++def test_safesession_keeps_netrc_credentials_for_the_new_host(monkeypatch):+ """``Session.rebuild_auth`` reapplies netrc credentials for the redirect+ target after dropping the old ones. The override strips first and calls it+ second, so the credential requests installs for the new host stands."""+ monkeypatch.setattr(+ requests.sessions,+ "get_netrc_auth",+ lambda url: ("netrc-user", "netrc-pass"),+ )+ session = safe_requests.SafeSession()+ original = requests.Request(+ "GET", f"http://{PUBLIC_A}/start", headers=dict(_CREDS)+ ).prepare()+ hop = requests.Request(+ "GET", f"http://{PUBLIC_B}/next", headers=dict(_CREDS)+ ).prepare()+ response = requests.Response()+ response.request = original++ session.rebuild_auth(hop, response)++ assert hop.headers["Authorization"].startswith("Basic ")+ assert "X-Api-Key" not in hop.headers+++def test_safe_get_strips_cookie_on_cross_host_redirect(stub_http):+ """A caller-supplied literal Cookie is re-sent verbatim by the hand-rolled+ loop. ``SafeSession`` rebuilds Cookie from the domain-scoped jar on every+ hop and needs no help; these helpers have no jar to rescope."""+ start = f"http://{PUBLIC_A}/start"+ target = f"http://{PUBLIC_B}/final"+ stub_http["queue"].append(_FakeResponse(302, url=start, location=target))+ stub_http["queue"].append(_FakeResponse(200, url=target))++ safe_requests.safe_get(start, headers={"Cookie": "session=SECRET"})++ assert "cookie" not in _hop_headers(stub_http)# ---------------------------------------------------------------------