Skip to content

The agent that grows with you

fix(web): a web_extract cache hit re-checks the website policy on the page's final URL

Teknium6778ad55591d
diff --git a/tests/tools/test_web_extract_cache_final_url.py b/tests/tools/test_web_extract_cache_final_url.py
new file mode 100644
index 00000000000..b49f4698e5a
--- /dev/null
+++ b/tests/tools/test_web_extract_cache_final_url.py
@@ -0,0 +1,73 @@
+"""A web_extract cache hit re-runs the website policy / SSRF gates on the URL its content came from.
+
+A redirector page cached while its target was allowed must stop serving that target once the target is
+blocklisted (or resolves private): the cache may skip the vendor call, never a control.
+"""
+
+import asyncio
+
+import pytest
+
+from tools import web_result_cache as wrc
+from tools import web_tools_extract as wte
+
+REDIRECTOR = "https://redirector.example/to-target"
+TARGET = "https://target.example/"
+
+
[email protected](autouse=True)
+def _isolated_cache(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("tools.web_tools_extract._extract_timeout_seconds", lambda: 0)
+
+
+class _RedirectingProvider:
+ """Reports the redirect target in ``url`` and the requested URL in ``metadata.sourceURL``."""
+
+ name = "firecrawl"
+
+ def __init__(self):
+ self.calls = 0
+
+ async def extract(self, urls, format=None):
+ self.calls += 1
+ return [{"url": TARGET, "title": "Target", "content": "TARGET PAGE", "raw_content": "TARGET PAGE",
+ "metadata": {"sourceURL": urls[0]}}]
+
+
+def _policy(blocked_host=None, unsafe_host=None):
+ def check(url, *_a, **_k):
+ if blocked_host and blocked_host in url:
+ return {"host": blocked_host, "rule": blocked_host, "source": "config", "message": "Blocked by website policy"}
+ return None
+
+ async def safe(url):
+ return not (unsafe_host and unsafe_host in url)
+
+ return check, safe
+
+
+def _extract(provider):
+ return asyncio.run(wte._extract_safe_urls(provider, [REDIRECTOR], None))
+
+
[email protected]("gate", ["blocklist", "ssrf"])
+def test_cached_redirect_is_regated_on_its_final_url(monkeypatch, gate):
+ check, safe = _policy()
+ monkeypatch.setattr("tools.website_policy.check_website_access", check)
+ monkeypatch.setattr("tools.url_safety.async_is_safe_url", safe)
+ provider = _RedirectingProvider()
+ assert _extract(provider)[0]["content"] == "TARGET PAGE"
+ assert _extract(provider)[0].get("cached") is True # control: an allowed target is served from cache
+ assert provider.calls == 1
+
+ check, safe = _policy(**({"blocked_host": "target.example"} if gate == "blocklist" else {"unsafe_host": "target.example"}))
+ monkeypatch.setattr("tools.website_policy.check_website_access", check)
+ monkeypatch.setattr("tools.url_safety.async_is_safe_url", safe)
+ result = _extract(provider)[0]
+
+ assert provider.calls == 2, "a hit whose final URL is now refused must be a miss (live fetch re-checks)"
+ assert not result.get("cached")
diff --git a/tools/web_result_cache.py b/tools/web_result_cache.py
index c747f3f3094..f1492805d26 100644
--- a/tools/web_result_cache.py
+++ b/tools/web_result_cache.py
@@ -275,7 +275,20 @@ def extract_cache_get(url: str, format: Optional[str] = None, provider: str = ""
except Exception:
return None
logger.info("web_extract cache hit: %s", url)
- return {"url": url, "title": entry.get("title", ""), "content": content, "error": None, "cached": True}
+ return {"url": url, "title": entry.get("title", ""), "content": content, "error": None, "cached": True,
+ "final_url": entry.get("final_url") or url}
+
+
+def extract_cache_record_final_url(url: str, final_url: str, format: Optional[str] = None, provider: str = "") -> None:
+ """Remember the post-redirect URL behind a cached page, so a hit can re-run the website policy and
+ SSRF gates against the page it actually serves (a blocklist added after caching must still bite)."""
+ with _index_lock:
+ index = _load_index()
+ entry = index.get(_url_digest(url, format, provider))
+ if entry is None:
+ return
+ entry["final_url"] = final_url
+ _save_index(index)
def extract_cache_put(
diff --git a/tools/web_tools_extract.py b/tools/web_tools_extract.py
index a1d9ceeda91..dfc20709890 100644
--- a/tools/web_tools_extract.py
+++ b/tools/web_tools_extract.py
@@ -160,7 +160,7 @@ async def _dispatch_extract(provider, fetch_urls: list[str], format: Optional[st
so a batch with one never triggers it. Rescued batches are never cached.
"""
import inspect
- from tools.web_result_cache import extract_cache_put
+ from tools.web_result_cache import extract_cache_put, extract_cache_record_final_url
timeout = _extract_timeout_seconds()
try:
if inspect.iscoroutinefunction(provider.extract):
@@ -200,15 +200,28 @@ async def _dispatch_extract(provider, fetch_urls: list[str], format: Optional[st
_content = fetched.get("raw_content", "") or fetched.get("content", "")
if url and _content and not fetched.get("error"):
extract_cache_put(url, _content, fetched.get("title", ""), format=format, provider=provider.name)
+ if fetched.get("url") and fetched["url"] != url:
+ extract_cache_record_final_url(url, fetched["url"], format=format, provider=provider.name)
return results
+async def _cached_final_url_allowed(hit: dict, requested: str) -> bool:
+ """Gate a cache hit on the URL its content came from: a redirector cached before its target was
+ blocklisted (or turned private) must not keep serving that target. Consumes ``final_url``."""
+ final_url = hit.pop("final_url", requested)
+ if final_url == requested: # the requested URL already passed both gates
+ return True
+ from tools.url_safety import async_is_safe_url
+ from tools.website_policy import check_website_access
+ return check_website_access(final_url) is None and await async_is_safe_url(final_url)
+
+
async def _extract_safe_urls(provider, safe_urls: list[str], format: Optional[str]) -> list[dict]:
"""Serve cache hits, fetch the rest, and merge back in ``safe_urls`` order.
The disk cache (tools/web_result_cache.py) sits AFTER the secret-URL gate, SSRF gate, and provider
resolution, and is gated per-URL on the website policy — a hit skips only the vendor call, never a
- control; policy-blocked URLs are cache misses. Keys include provider and format, so switching either
+ control; policy-blocked URLs are cache misses, judged on both the requested and the cached final URL. Keys include provider and format, so switching either
within the TTL never serves the other's content."""
from tools.web_result_cache import extract_cache_get
from tools.website_policy import check_website_access as _check_site
@@ -219,6 +232,8 @@ async def _extract_safe_urls(provider, safe_urls: list[str], format: Optional[st
except Exception:
_policy_block = None
hit = extract_cache_get(url, format=format, provider=provider.name) if _policy_block is None else None
+ if hit is not None and not await _cached_final_url_allowed(hit, url):
+ hit = None # a miss: the live fetch re-checks the redirect and refuses with blocked_by_policy
if hit is not None:
cached_results[position] = hit
else: