The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(web): re-gate every provider's redirect target in the shared extract dispatch
Teknium5c5db1a061f5
diff --git a/tests/tools/test_web_extract_redirect_gate.py b/tests/tools/test_web_extract_redirect_gate.pynew file mode 100644index 00000000000..4193c7779e5--- /dev/null+++ b/tests/tools/test_web_extract_redirect_gate.py@@ -0,0 +1,133 @@+"""web_extract re-gates every page a provider reports under a URL it was not asked for.++The website policy and SSRF checks run on the REQUESTED url; a vendor that follows a redirect reports+the target instead (Keenable: ``url`` = target, ``metadata.sourceURL`` = requested; Exa/Parallel/Tavily:+the vendor's URL in both). That target is checked once, in the shared dispatch, for every provider.+"""++import asyncio++import pytest++import plugins.web.keenable.provider as keenable+from tools import web_result_cache as wrc+from tools import web_tools_extract as wte++REDIRECTOR = "https://redirector.example/go"+BLOCKED = "https://blocked.example/secret"++[email protected](autouse=True)+def _isolated(tmp_path, monkeypatch):+ cache_dir = tmp_path / "cache" / "web"+ cache_dir.mkdir(parents=True)+ monkeypatch.setattr(wrc, "_cache_dir", lambda: cache_dir)+ monkeypatch.setattr(wrc, "_web_config", dict)+ monkeypatch.setattr(wte, "_extract_timeout_seconds", lambda: 0)+ _policy(monkeypatch)+++def _policy(monkeypatch, blocked_host: str | None = "blocked.example", unsafe_host: str | None = None):+ def check(url, *_a, **_k):+ if blocked_host and blocked_host in url:+ return {"host": blocked_host, "rule": blocked_host, "source": "config",+ "message": f"Blocked: {blocked_host} is blocked by website policy"}+ return None++ async def safe(url):+ return not (unsafe_host and unsafe_host in url)++ monkeypatch.setattr("tools.website_policy.check_website_access", check)+ monkeypatch.setattr("tools.url_safety.async_is_safe_url", safe)+++def _keenable(monkeypatch, target):+ """The real Keenable provider (keyed path) against a stubbed /v1/fetch that followed a redirect."""+ calls = []++ class _Response:+ status_code = 200++ def json(self):+ return {"url": target, "title": "T", "content": "TARGET PAGE"}++ import requests+ monkeypatch.setattr(requests, "get", lambda *a, **k: (calls.append(k.get("params")), _Response())[1])+ monkeypatch.setattr(keenable, "provider_env", lambda _k: "test-key")+ monkeypatch.setattr(keenable, "use_keyless", lambda *_a: False)+ return keenable.KeenableWebSearchProvider(), calls+++def _extract(provider, urls=(REDIRECTOR,)):+ return asyncio.run(wte._extract_safe_urls(provider, list(urls), None))+++def test_keenable_redirect_into_a_blocked_host_is_refused_and_never_cached(monkeypatch):+ provider, calls = _keenable(monkeypatch, BLOCKED)+ for _ in range(3):+ result = _extract(provider)[0]+ assert result["content"] == "" and "TARGET PAGE" not in str(result)+ assert result["blocked_by_policy"] == {"host": "blocked.example", "rule": "blocked.example", "source": "config"}+ assert result["url"] == BLOCKED and result["error"].startswith("Blocked")+ # Nothing was cached, so no hit is ever refused into a paid re-fetch of a page we will not serve.+ assert wrc.extract_cache_get(REDIRECTOR, provider="keenable") is None+ assert len(calls) == 3+++def test_keenable_allowed_redirect_is_served_from_cache_without_a_refetch_loop(monkeypatch):+ provider, calls = _keenable(monkeypatch, "https://allowed.example/page")+ assert _extract(provider)[0]["content"] == "TARGET PAGE"+ for _ in range(2):+ hit = _extract(provider)[0]+ assert hit.get("cached") is True and hit["content"] == "TARGET PAGE"+ assert len(calls) == 1+++def test_keenable_redirect_to_a_private_address_is_refused(monkeypatch):+ _policy(monkeypatch, blocked_host=None, unsafe_host="internal.example")+ provider, _calls = _keenable(monkeypatch, "http://internal.example/admin")+ result = _extract(provider)[0]+ assert result["content"] == "" and "private or internal" in result["error"]+ assert "blocked_by_policy" not in result+++class _VendorUrlProvider:+ """Exa/Parallel/Tavily shape: the vendor's final URL in ``url`` and ``sourceURL`` alike."""++ name = "exa"++ def extract(self, urls, format=None):+ return [{"url": BLOCKED, "title": "T", "content": "TARGET PAGE", "raw_content": "TARGET PAGE",+ "metadata": {"sourceURL": BLOCKED, "title": "T"}}]+++def test_a_vendor_reported_url_outside_the_request_is_regated():+ result = _extract(_VendorUrlProvider())[0]+ assert result["content"] == "" and result["blocked_by_policy"]["host"] == "blocked.example"+++def test_a_rescued_batch_is_regated(monkeypatch):+ class _Down:+ name = "parallel"++ def extract(self, urls, format=None):+ raise RuntimeError("backend down")++ monkeypatch.setattr(wte, "_rescue_eligible", lambda _p: True)+ monkeypatch.setattr(wte, "_rescue_extract", lambda _n, urls, _f: _VendorUrlProvider().extract(urls))+ result = _extract(_Down())[0]+ assert result["content"] == "" and result["blocked_by_policy"]["host"] == "blocked.example"+++def test_a_policy_check_that_raises_on_a_cached_final_url_is_a_miss(monkeypatch):+ provider, calls = _keenable(monkeypatch, "https://allowed.example/page")+ _extract(provider)++ def boom(url, *_a, **_k):+ if "allowed.example" in url:+ raise RuntimeError("policy unreadable")++ monkeypatch.setattr("tools.website_policy.check_website_access", boom)+ result = _extract(provider)[0]+ assert not result.get("cached") and len(calls) == 2+ assert result["content"] == "" and "policy check failed" in result["error"]diff --git a/tools/web_tools_extract.py b/tools/web_tools_extract.pyindex 846fb9abcb5..4b63be934eb 100644--- a/tools/web_tools_extract.py+++ b/tools/web_tools_extract.py@@ -3,7 +3,9 @@Order of controls (each is a gate, never skipped by a cache hit): secret-URLrefusal -> SSRF filter (in web_tools.web_extract_tool) -> provider resolution(strict selection) -> per-URL website policy -> disk cache -> vendor call with-one-shot keyless rescue. Logs under the origin (tools.web_tools) logger.+one-shot keyless rescue -> website policy + SSRF on every page reported under a+URL that was not requested (redirect targets). Logs under the origin+(tools.web_tools) logger."""import asyncio@@ -152,15 +154,14 @@ def _backend_failed_whole_batch(results: list[dict]) -> bool:return bool(errors) and all(errors) and not any(is_origin_http_error(e) for e in errors)-async def _dispatch_extract(provider, fetch_urls: list[str], format: Optional[str]) -> list[dict]:+async def _fetch_with_rescue(provider, fetch_urls: list[str], format: Optional[str]) -> tuple[list[dict], bool]:"""Call ``provider.extract`` (async or sync-in-thread), with one-shot keyless rescue.Rescue fires on a raised exception — including a dispatch timeout — or when the WHOLE batchfailed (backend outage, not per-page problems): an origin HTTP 4xx/5xx is the page's own answer,- so a batch with one never triggers it. Rescued batches are never cached.+ so a batch with one never triggers it. Returns ``(results, rescued)``."""import inspect- from tools.web_result_cache import extract_cache_put, extract_cache_record_final_urltimeout = _extract_timeout_seconds()try:if inspect.iscoroutinefunction(provider.extract):@@ -177,22 +178,70 @@ async def _dispatch_extract(provider, fetch_urls: list[str], format: Optional[stfailed = [_result_entry(u, f"Extract timed out after {timeout:.0f}s via {provider.name}")for u in fetch_urls]if not _rescue_eligible(provider):- return failed- return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, failed)+ return failed, False+ return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, failed), Trueexcept Exception as exc:if not _rescue_eligible(provider):raisefailed = [_result_entry(u, str(exc)) for u in fetch_urls]- return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, failed)+ return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, failed), Trueif _backend_failed_whole_batch(results) and _rescue_eligible(provider):- return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, results)+ return await asyncio.to_thread(_rescue_extract, provider.name, fetch_urls, results), True+ return results, False+++async def _final_url_refusal(fetched: dict) -> Optional[dict]:+ """Refusal entry when a page's reported (post-redirect) URL fails the website policy or SSRF gate,+ in the shape Firecrawl's own redirect re-check returns; None when it passes. A policy check that+ raises refuses (fail closed): the requested URL passed, but nothing vouches for this one."""+ from tools.url_safety import async_is_safe_url+ from tools.website_policy import check_website_access+ final_url, title = fetched["url"], fetched.get("title", "")+ refusal = {"url": final_url, "title": title, "content": "", "raw_content": ""}+ try:+ blocked = check_website_access(final_url)+ except Exception as exc:+ logger.warning("Website policy check failed for redirect target %s", final_url, exc_info=True)+ return {**refusal, "error": f"Website policy check failed for redirect target: {exc}"}+ if blocked:+ logger.info("Blocked redirected web_extract for %s by rule %s", blocked["host"], blocked["rule"])+ policy = {k: blocked[k] for k in ("host", "rule", "source")}+ return {**refusal, "error": blocked["message"], "blocked_by_policy": policy}+ if not await async_is_safe_url(final_url):+ logger.info("Blocked redirected web_extract for unsafe final URL: %s", final_url)+ return {**refusal, "error": "Blocked: URL targets a private or internal network address"}+ return None+++async def _gate_final_urls(results: list[dict], requested: set[str]) -> list[dict]:+ """Re-gate every page a provider reports under a URL other than one we asked for (a redirect+ target, a canonicalised host): the SSRF and website-policy checks only ever saw the requested URL.+ Covers every provider shape — Keenable reports the target in ``url`` with ``sourceURL`` = requested,+ Exa/Parallel/Tavily report the vendor's URL in both — and rescued batches alike."""+ gated = []+ for fetched in results:+ url = fetched.get("url")+ if url and url not in requested and not fetched.get("error"):+ fetched = await _final_url_refusal(fetched) or fetched+ gated.append(fetched)+ return gated+++async def _dispatch_extract(provider, fetch_urls: list[str], format: Optional[str]) -> list[dict]:+ """Fetch *fetch_urls* (with keyless rescue), re-gate redirect targets, then cache the passes.+ Rescued batches are never cached."""+ from tools.web_result_cache import extract_cache_put, extract_cache_record_final_url+ results, rescued = await _fetch_with_rescue(provider, fetch_urls, format)+ requested = set(fetch_urls)+ results = await _gate_final_urls(results, requested)+ if rescued:+ return results# Cache each successful fetch under the REQUESTED url it reports as its own — never by list# position: providers omit failed URLs or return successes out of request order, and a positional# write filed one page's text under another URL's key for the whole TTL. ``metadata.sourceURL``# counts because Keenable/Firecrawl put the requested URL there when ``url`` is the redirect target.# An entry naming no requested URL is served but not cached (a miss re-fetches; a mis-key poisons).- requested = set(fetch_urls)for fetched in results:meta = fetched.get("metadata")source = meta.get("sourceURL") if isinstance(meta, dict) else None@@ -213,7 +262,13 @@ async def _cached_final_url_allowed(hit: dict, requested: str) -> bool:return Truefrom tools.url_safety import async_is_safe_urlfrom tools.website_policy import check_website_access- return check_website_access(final_url) is None and await async_is_safe_url(final_url)+ try:+ if check_website_access(final_url) is not None:+ return False+ except Exception: # fail closed: a miss, and the live fetch re-gates the redirect+ logger.warning("Website policy check failed for cached final URL %s", final_url, exc_info=True)+ return False+ return await async_is_safe_url(final_url)async def _extract_safe_urls(provider, safe_urls: list[str], format: Optional[str]) -> list[dict]: