~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): validate redirect targets in the JS-render (Playwright/Crawl4AI) fetch path (#5536)
LearningCircuit75dd119f6c82
diff --git a/SECURITY.md b/SECURITY.mdindex ce9ffff899..0589b98695 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -129,6 +129,20 @@ By setting this, the operator acknowledges the residual risk above. To minimiseThe general HTTP fetch path (`safe_requests`, used for RAG sources and web scraping) resolves the hostname and connects to that **same** validated address: `security.dns_pinning` pins the resolved IP for the outbound connection (re-resolving and re-validating at connect time, and re-pinning at every redirect hop) so `requests`/`urllib3` cannot connect to a different address than the one the guard checked. The request keeps the original hostname, so TLS SNI and certificate verification are unchanged — only name resolution is pinned. This does not apply to callers that hand a URL to an external client that re-resolves on its own (Apprise above; LLM SDKs — see "LLM Provider URL Validation"); for those, egress restriction remains the primary defense. It also does not apply when `requests` is configured to use a forward proxy (`HTTP(S)_PROXY` / `trust_env`): `urllib3` then resolves the *proxy* host rather than the target, so target-IP selection is delegated to the proxy and the pin is a safe no-op (the pre-connection `validate_url` check still runs).+### JS-Rendering Browser Redirect SSRF++The static fetch path validates every redirect hop via `SafeSession.send` → `ssrf_validator.validate_url`. The JavaScript-rendering browser path (`PlaywrightHTMLDownloader`, used by both Crawl4AI and plain Playwright) previously did not: a public URL that 302-redirected to `169.254.169.254` (cloud metadata) or an RFC1918 host was followed by headless Chromium unchecked. The fix brings the browser path to parity so that **every subrequest the browser makes — the initial navigation, each redirect hop, and every subresource — is validated or blocked** with the same rules and `allow_private_ips` scope as the static path.++- **HTTP(S) requests + redirect chains.** A per-request egress guard is installed on both browser paths (a context-level `route("**/*", …)` handler on plain Playwright, and the same handler installed via Crawl4AI's `on_page_context_created` hook). Because Playwright does not re-fire route handlers for the hops of a server-side redirect chain, the guard follows the chain itself with `route.fetch(max_redirects=0)`, validates **each** hop's target with `ssrf_validator.validate_url` before fetching it, and hands the browser only the final safe response via `route.fulfill`. Cloud-metadata IPs stay blocked regardless of scope. A POST that a redirect downgrades to GET drops its body (parity with `safe_post`).+- **robots.txt.** Crawl4AI's built-in `check_robots_txt` fetches `/robots.txt` with a raw `aiohttp` client that follows redirects with no SSRF check — a redirecting `/robots.txt` was itself an SSRF vector that bypassed the route guard. It is now disabled; the politeness check is performed through the downloader's SSRF-guarded `SafeSession` (every hop validated) before navigation.+- **Service Workers.** Requests made by a Service Worker are not intercepted by route handlers. Plain Playwright creates the page with `service_workers="block"`; the Crawl4AI context (whose `BrowserConfig` exposes no such option) neutralises SW registration via an init script. When these install, all page traffic stays on the guarded normal-request path.+- **WebSockets.** `route("**/*")` does not match WS upgrades, so a WebSocket guard is installed via `route_web_socket("**/*", …)` on both paths. WebSockets are not needed for HTML text extraction and are rejected (the handler never calls `connect_to_server`, so the target is never contacted).+- **WebRTC.** `RTCPeerConnection` ICE gathering (STUN/TURN) opens raw UDP/TCP sockets to an arbitrary `host:port` through Chromium's WebRTC stack — a third data path that neither `route()` nor `route_web_socket()` intercepts. WebRTC is not needed for text extraction, so its constructors (`RTCPeerConnection`/`webkitRTCPeerConnection`/`RTCDataChannel`) are neutralised via an init script before any page script runs, on both paths.++The guards are installed **fail-closed** on the Crawl4AI path. If any of them — the `set_hook` call, or the HTTP-guard / WebSocket-guard / Service-Worker-neutralizer installation inside the `on_page_context_created` hook — is unavailable or raises (crawl4ai / Playwright API drift), `_fetch_with_crawl4ai` returns `None` and the fetch falls back to the guarded plain-Playwright path (which has native `service_workers="block"` and a context-level WebSocket guard). A Crawl4AI page is therefore never navigated with a missing HTTP, WebSocket, or Service-Worker guard. The plain-Playwright WS/SW guarantees hold unconditionally (native browser options, not a hook).++The browser navigation / `route.fetch` path uses **Chromium's own DNS resolver**, not `safe_requests`, so it does not receive the connection-level IP-pinning that the static `safe_requests` / `SafeSession` path applies (per the DNS-pinning hardening). It therefore retains a **DNS-rebinding resolve-vs-connect TOCTOU** — the guard resolves the host at validation time and Chromium resolves again on connect — that the pinned static path closes; the browser path is strictly weaker than the static path on this specific race. Egress restriction is the mitigation for this residual: per-hop `validate_url` plus the `allow_private_ips` scope policy still block metadata/private targets at validation time, and firewall-level egress restriction remains the operator-side defence. Note that the robots.txt politeness check *does* go through the pinned `SafeSession`, so "IP-pinning is intentionally not added" applies specifically to the Chromium navigation / `route.fetch` path.+### Parser-Differential URL Bypass (GHSA-g23j-2vwm-5c25)A reporter ([@Fushuling](https://github.com/Fushuling), [@RacerZ-fighting](https://github.com/RacerZ-fighting)) demonstrated that Python's `urllib.parse.urlparse` and the `requests`/`urllib3` parser disagreed on URLs like `http://127.0.0.1\@1.1.1.1` — `urlparse` extracted `1.1.1.1` (passing the SSRF check) while `requests` connected to `127.0.0.1` (the actual destination). The fix has two layers:diff --git a/changelog.d/+ssrf-browser-redirect-guard.security.md b/changelog.d/+ssrf-browser-redirect-guard.security.mdnew file mode 100644index 0000000000..8e10e56859--- /dev/null+++ b/changelog.d/+ssrf-browser-redirect-guard.security.md@@ -0,0 +1 @@+**SSRF hardening for the JavaScript-rendering fetch path.** The headless-browser downloader (Crawl4AI and plain Playwright) now validates or blocks every subrequest it makes — the initial navigation, each redirect hop, and every subresource — against the same SSRF rules as the static fetch path, so a public page that redirects to a cloud-metadata endpoint or a private/internal host is blocked before the browser connects. This also closes several sibling bypasses on the browser path: robots.txt is now fetched through the SSRF-guarded session instead of an unchecked client, Service Workers are blocked, and WebSocket connections are rejected. Cloud-metadata IPs stay blocked in all cases; the `PRIVATE_ONLY` egress scope still reaches local lab hosts. On both browser engines (Crawl4AI and plain Playwright), cookies set during a redirect chain are now re-scoped per hop from the browser cookie jar, so a cookie belonging to one domain is no longer forwarded to a different domain a later redirect lands on (matching normal browser behavior); same-domain cookie persistence is unchanged, and a cookie the server clears mid-chain (`Max-Age=0` / past `Expires`) is not resurrected.diff --git a/src/local_deep_research/content_fetcher/fetcher.py b/src/local_deep_research/content_fetcher/fetcher.pyindex 0b9964d903..b7c802e7f0 100644--- a/src/local_deep_research/content_fetcher/fetcher.py+++ b/src/local_deep_research/content_fetcher/fetcher.py@@ -195,6 +195,16 @@ class ContentFetcher:session = getattr(downloader, "session", None)if session is not None and hasattr(session, "allow_private_ips"):session.allow_private_ips = True+ # Also thread the relaxation to the JS-render browser path. The+ # AutoHTMLDownloader lazily builds a PlaywrightHTMLDownloader+ # child that SSRF-validates every browser request (initial nav ++ # each redirect hop + subresources) via its own guard, reading+ # ``allow_private_ips`` at build time — so setting it here, before+ # the child is built, threads PRIVATE_ONLY through to the browser.+ # Cloud-metadata IPs stay blocked regardless (validate_url always+ # rejects them).+ if hasattr(downloader, "allow_private_ips"):+ downloader.allow_private_ips = Truedef fetch(self,diff --git a/src/local_deep_research/research_library/downloaders/playwright_html.py b/src/local_deep_research/research_library/downloaders/playwright_html.pyindex 4fbecee3bd..3c80198577 100644--- a/src/local_deep_research/research_library/downloaders/playwright_html.py+++ b/src/local_deep_research/research_library/downloaders/playwright_html.py@@ -11,13 +11,82 @@ honestly via BROWSER_USER_AGENT and respects robots.txt."""import asyncio+import functools+from datetime import datetime, timezone+from email.utils import parsedate_to_datetimefrom typing import Optional-from urllib.parse import urlparse+from urllib.parse import urljoin, urlparsefrom loguru import loggerfrom .html import HTMLDownloaderfrom ...constants import BROWSER_USER_AGENT+from ...security import ssrf_validator+from ...security.safe_requests import (+ _MAX_REDIRECTS,+ _REDIRECT_STATUS_CODES,+ _resolve_redirect_method,+)++# Heavy subresource types dropped when ``block_resources`` is set, mirroring+# the previous extension-glob resource route but keyed on Playwright's+# resource_type (robust to query strings / extensionless URLs).+_BLOCKED_RESOURCE_TYPES = frozenset({"image", "media", "font", "stylesheet"})++# Non-http(s) URL schemes the browser may safely handle itself (they never+# touch the network, so they are not SSRF / local-resource vectors): the route+# guard lets ONLY these fall through via ``route.fallback()``. EVERY other+# non-http(s) scheme — ``file:`` (local file read), ``chrome:``/``chrome-+# extension:``, ``gopher:``, ``ftp:``, ``ws(s):`` handled elsewhere, etc. — is+# aborted fail-closed rather than blanket-allowed, so a redirect (or a page+# resource) cannot pivot the browser to a local file or an internal handler.+_FALLTHROUGH_NON_HTTP_SCHEMES = frozenset({"data", "blob", "about"})++# Neutralise Service Workers on browser paths that cannot set+# service_workers="block" at context creation (Crawl4AI's BrowserConfig+# exposes no such option). Requests made BY a Service Worker are not+# intercepted by page/context route handlers, so a SW could otherwise+# fetch an internal/metadata host unvalidated. Preventing registration+# forces all page traffic back through the guarded normal network path.+# Injected as an init script so it runs before any page script.+_DISABLE_SERVICE_WORKERS_JS = """+try {+ if (window.navigator && window.navigator.serviceWorker) {+ const reject = () =>+ Promise.reject(new Error('service workers are disabled'));+ try { window.navigator.serviceWorker.register = reject; } catch (e) {}+ try {+ Object.defineProperty(window.navigator, 'serviceWorker', {+ configurable: true,+ get() { return undefined; },+ });+ } catch (e) {}+ }+} catch (e) {}+"""+++# SSRF hardening: WebRTC (RTCPeerConnection ICE / STUN / TURN) opens raw+# UDP/TCP sockets to an arbitrary host:port through Chromium's WebRTC stack —+# a data path that neither page.route() (Fetch) nor route_web_socket()+# instruments, so it bypasses ssrf_validator entirely. Text extraction never+# needs WebRTC, so neutralize the constructors before any page script runs+# (same fail-closed reasoning as the service-worker block).+_DISABLE_WEBRTC_JS = """+(() => {+ const deny = function () {+ throw new DOMException('WebRTC is disabled', 'NotSupportedError');+ };+ for (const name of ['RTCPeerConnection', 'webkitRTCPeerConnection',+ 'mozRTCPeerConnection', 'RTCDataChannel']) {+ try {+ Object.defineProperty(window, name, {+ configurable: false, enumerable: false, get() { return deny; },+ });+ } catch (e) {}+ }+})();+"""# Signals that a page is a JS-rendered SPA and needs browser rendering@@ -34,6 +103,127 @@ SPA_SIGNALS = []+def _cookie_domain_matches(host: str, cookie_domain: str) -> bool:+ """Whether a ``Set-Cookie`` ``Domain=`` attribute may be honored for a+ response served by ``host``.++ Mirrors RFC 6265 §5.1.3 domain-matching (and real-browser behavior): the+ host must equal the cookie domain or be a subdomain of it. A leading dot+ on the attribute is ignored. Returns False for a Domain that points at a+ DIFFERENT or unrelated registrable domain — a cookie a browser drops —+ so the caller can fall back to host-scoping instead of letting a redirect+ hop plant a cookie on someone else's domain (session fixation).++ Note: this does NOT consult the Public Suffix List, so a suffix like+ ``Domain=co.uk`` set by ``a.co.uk`` is honored here and could be re-sent+ to a sibling host later in the SAME redirect chain. The residual is very+ narrow — the browser context is ephemeral (one fetch) and Chromium+ enforces the PSL on its own jar — and it is strictly better than the+ pre-fix behavior, which forwarded all cookies cross-domain. Wiring in a+ PSL check would tighten it further (optional follow-up).+ """+ if not host or not cookie_domain:+ return False+ host = host.lower().rstrip(".")+ cookie_domain = cookie_domain.lower().lstrip(".").rstrip(".")+ if not cookie_domain:+ return False+ return host == cookie_domain or host.endswith("." + cookie_domain)+++def _same_registrable_site(host_a: str, host_b: str) -> bool:+ """Whether two request hosts belong to the same domain family for the+ purpose of forwarding credentialed request headers across a redirect hop.++ Mirrors the host/subdomain relation ``_cookie_domain_matches`` already+ uses (RFC 6265 §5.1.3 style): equal hosts, or one a subdomain of the+ other, count as the SAME site; anything else is cross-site. Like that+ helper it does NOT consult the Public Suffix List, so it is a deliberately+ conservative approximation of "registrable domain" — consistent with the+ rest of this guard, while Chromium still enforces its own PSL on the+ browser jar. Used to decide when to drop ``Authorization`` /+ ``Proxy-Authorization`` on a cross-site hop, the twin of the per-hop+ ``Cookie`` re-scoping (a browser strips credentials cross-origin too).++ Fail-CLOSED: a missing/empty host on either side returns False (treated as+ cross-site), so credentialed headers are dropped rather than forwarded on+ any ambiguity.+ """+ if not host_a or not host_b:+ return False+ a = host_a.lower().rstrip(".")+ b = host_b.lower().rstrip(".")+ if not a or not b:+ return False+ return a == b or a.endswith("." + b) or b.endswith("." + a)+++def _parse_one_set_cookie(raw: str):+ """Parse a single ``Set-Cookie`` header value into ``(name, value, attrs)``.++ A manual RFC 6265 §5.2 split rather than ``http.cookies.SimpleCookie``:+ SimpleCookie silently DROPS cookies whose name is not a strict RFC token+ (e.g. ``data[uid]``, which real browsers accept), so those cookies would+ vanish from the re-applied jar. This split keeps them.++ Returns ``None`` when the header has no ``name=value`` pair. ``attrs``+ keys are lowercased; value-less flag attributes (``Secure``, ``HttpOnly``)+ map to ``True``. Each ``Set-Cookie`` header carries exactly one cookie+ (RFC 6265 §3), and the only comma that can appear inside a value belongs+ to an ``Expires`` HTTP-date, which never contains a semicolon — so a+ plain ``;`` split is safe.+ """+ if not raw:+ return None+ parts = raw.split(";")+ name, sep, value = parts[0].partition("=")+ name = name.strip()+ if not sep or not name:+ return None+ value = value.strip()+ # Strip one layer of surrounding DQUOTEs (mirrors SimpleCookie).+ if len(value) >= 2 and value[0] == '"' and value[-1] == '"':+ value = value[1:-1]+ attrs = {}+ for segment in parts[1:]:+ akey, asep, aval = segment.partition("=")+ akey = akey.strip().lower()+ if not akey:+ continue+ attrs[akey] = aval.strip() if asep else True+ return name, value, attrs+++def _set_cookie_is_expired(attrs: dict) -> bool:+ """Whether a parsed ``Set-Cookie`` is a deletion/expired directive that+ must NOT be re-applied to the jar.++ A ``Max-Age=0`` (or negative) or a past ``Expires`` is how a server+ DELETES a cookie; re-adding it as a live cookie would resurrect a value+ the server just cleared. ``Max-Age`` takes precedence over ``Expires``+ (RFC 6265 §5.3). Fail-OPEN: an unparseable attribute is treated as NOT+ expired, so a live cookie is never dropped by a date-parsing quirk.+ """+ max_age = attrs.get("max-age")+ if isinstance(max_age, str) and max_age.strip():+ try:+ return int(max_age) <= 0+ except ValueError:+ pass # Unparseable Max-Age -> fall through to Expires.+ expires = attrs.get("expires")+ if isinstance(expires, str) and expires.strip():+ try:+ dt = parsedate_to_datetime(expires)+ if dt is None:+ return False+ if dt.tzinfo is None:+ dt = dt.replace(tzinfo=timezone.utc)+ return dt <= datetime.now(timezone.utc)+ except Exception:+ return False+ return False++def _run_async(coro, timeout: float = None):"""Run an async coroutine from synchronous code.@@ -77,21 +267,650 @@ class PlaywrightHTMLDownloader(HTMLDownloader):language: str = "English",wait_until: str = "networkidle",block_resources: bool = True,+ allow_private_ips: bool = False,**kwargs,):super().__init__(timeout=timeout, language=language)self.wait_until = wait_untilself.block_resources = block_resources+ # SSRF policy for the browser route guards (initial navigation ++ # every redirect hop + subresources). Defaults strict; relaxed to+ # True only under the PRIVATE_ONLY egress scope so local lab hosts+ # remain reachable. Cloud-metadata IPs stay blocked regardless+ # (``ssrf_validator`` always rejects them). Mirrors the static+ # SafeSession path's ``allow_private_ips`` handling.+ self.allow_private_ips = allow_private_ips+ # The guarded robots.txt check (below) reuses this SafeSession, whose+ # send() SSRF-validates every hop; keep its policy in lockstep with+ # the browser guard so both honour the same egress scope.+ if hasattr(self.session, "allow_private_ips"):+ self.session.allow_private_ips = allow_private_ips# Plain Playwright fallback stateself._playwright = Noneself._browser = None+ # ------------------------------------------------------------------+ # Per-request egress guard for the JS-render browser paths.+ #+ # WHY a manual redirect loop instead of "validate the request URL and+ # continue": Playwright does NOT re-fire ``page.route`` handlers for the+ # hops of a server-side redirect chain — the browser follows 3xx+ # responses internally, below the interception layer. So a+ # ``route.continue_()`` / ``route.fallback()`` on a public URL that+ # 302-redirects to a cloud-metadata endpoint (link-local) or an RFC1918+ # host would let the browser reach the internal target unchecked —+ # exactly the gap the static ``SafeSession`` path already closes by+ # validating every hop. To reach parity we follow the redirect chain+ # ourselves with ``route.fetch(max_redirects=0)``, validate EACH hop's+ # target before fetching it, and hand the browser only the final, safe+ # response via ``route.fulfill``. The browser therefore never issues its+ # own redirect-following request to an unvalidated destination.+ # ------------------------------------------------------------------++ def _playwright_route_guard(self, route) -> None:+ """Egress guard for the plain-Playwright (sync) browser path.++ Validates the initial navigation and every redirect hop against+ ``ssrf_validator.validate_url`` before the browser connects, and+ drops heavy subresources when ``block_resources`` is set. Also+ re-scopes cookies per redirect hop (via ``_reapply_hop_cookies_sync``)+ so a cookie set on one hop is never forwarded to a different+ registrable domain a later hop redirects to — the same protection the+ crawl4ai path applies via ``_reapply_hop_cookies``.+ """+ request = route.request+ first_url = request.url+ scheme = urlparse(first_url).scheme.lower()+ if scheme not in ("http", "https"):+ # ALLOWLIST, fail-closed: only data:/blob:/about: (never touch the+ # network) may fall through to the browser. Every other non-http(s)+ # scheme — file: (local file read), chrome:, gopher:, ftp: … — is+ # aborted so a redirect or page resource cannot pivot the browser+ # to a local file or an internal handler.+ if scheme in _FALLTHROUGH_NON_HTTP_SCHEMES:+ route.fallback()+ else:+ route.abort()+ return+ if (+ self.block_resources+ and request.resource_type in _BLOCKED_RESOURCE_TYPES+ ):+ route.abort()+ return++ current = first_url+ method = request.method+ # None => reuse the intercepted request's body; "" => drop the body+ # after a POST->GET redirect downgrade (parity with safe_post).+ body_override = None+ # Per-hop "Cookie" header, re-derived from the browser context's+ # cookie jar (scoped to the NEXT hop's URL) on EVERY hop by+ # _reapply_hop_cookies_sync. It stays None only for the very first+ # fetch, which legitimately uses the originally intercepted request's+ # own Cookie header; from the first redirect onward it is always set+ # (possibly to an explicit EMPTY header). This is required because+ # route.fetch() otherwise keeps resending the ORIGINAL intercepted+ # request's Cookie header for the rest of this handler invocation —+ # so without a per-hop override a cookie scoped to hop N's domain+ # would ride along to a cross-host hop N+1 (a cross-origin cookie+ # leak). Mirrors the crawl4ai path's _reapply_hop_cookies.+ cookie_header_override = None+ for _ in range(_MAX_REDIRECTS + 1):+ if not ssrf_validator.validate_url(+ current, allow_private_ips=self.allow_private_ips+ ):+ # Log scheme://host:port only — a request URL may carry+ # credentials in userinfo / query params (RFC 3986 §3.2.1).+ logger.warning(+ "Playwright: blocked SSRF-unsafe browser request to {}",+ ssrf_validator.redact_url_for_log(current),+ )+ route.abort("blockedbyclient")+ return+ fetch_kwargs = {+ "url": current,+ "method": method,+ "max_redirects": 0,+ }+ if body_override is not None:+ fetch_kwargs["post_data"] = body_override+ try:+ self._apply_hop_cookie_header(+ request, fetch_kwargs, cookie_header_override+ )+ except Exception:+ # Fail CLOSED: building the hop headers reads+ # request.headers and must never let an exception escape+ # this route handler and fall through to an unguarded+ # fetch — abort the hop exactly like a failed fetch below.+ logger.debug(+ "Playwright: failed to build guarded hop headers",+ exc_info=True,+ )+ route.abort("failed")+ return+ try:+ response = route.fetch(**fetch_kwargs)+ except Exception:+ logger.debug("Playwright: guarded fetch failed", exc_info=True)+ route.abort("failed")+ return+ next_url = self._redirect_target(current, response)+ # Re-apply this hop's Set-Cookie header(s) to the context AND+ # re-derive, from the context jar scoped to the NEXT hop, the+ # explicit Cookie header for that hop's route.fetch() — BEFORE+ # following it. next_url is None on the terminal hop (no next+ # request needs a header). See _reapply_hop_cookies for why the+ # per-hop re-derivation is required.+ cookie_header_override = self._reapply_hop_cookies_sync(+ route,+ current,+ response,+ next_url,+ )+ if next_url is None:+ route.fulfill(response=response)+ return+ new_method = _resolve_redirect_method(method, response.status)+ if new_method == "GET" and method != "GET":+ body_override = "" # POST->GET downgrade must not leak body+ method = new_method+ current = next_url+ logger.warning(+ "Playwright: too many redirects — blocking browser request"+ )+ route.abort("blockedbyclient")++ def _playwright_ws_guard(self, ws_route) -> None:+ """Block every WebSocket on the plain-Playwright path.++ ``route("**/*")`` does not match WS upgrades, so page JS could open+ ``ws(s)://<internal>`` unvalidated. WebSockets are not needed for+ HTML text extraction, so reject all of them: simply returning+ WITHOUT calling ``connect_to_server`` means the connection to the+ real server is never established (verified: the target sees zero+ connections). We deliberately do NOT call ``ws_route.close()`` here —+ in Playwright's SYNC API a blocking route-handler call re-enters the+ dispatcher thread that ``page.goto`` is parked on and DEADLOCKS; the+ no-op form blocks the server just as effectively without that risk.+ """+ try:+ logger.debug(+ "Playwright: blocking WebSocket to {}",+ ssrf_validator.redact_url_for_log(ws_route.url),+ )+ except Exception:+ logger.debug("Playwright: blocking WebSocket")++ async def _crawl4ai_route_guard(self, route) -> None:+ """Egress guard for the Crawl4AI (async Playwright) browser path.++ Same policy as ``_playwright_route_guard`` but async: the blocking+ DNS resolution inside ``validate_url`` is offloaded to a thread so it+ does not stall Crawl4AI's event loop. Installed on each page context+ via the ``on_page_context_created`` hook.+ """+ request = route.request+ first_url = request.url+ scheme = urlparse(first_url).scheme.lower()+ if scheme not in ("http", "https"):+ # ALLOWLIST, fail-closed (see _playwright_route_guard): only+ # data:/blob:/about: fall through; every other non-http(s) scheme+ # (file:/chrome:/gopher: …) is aborted so it cannot pivot the+ # browser to a local file or an internal handler.+ if scheme in _FALLTHROUGH_NON_HTTP_SCHEMES:+ await route.fallback()+ else:+ await route.abort()+ return+ if (+ self.block_resources+ and request.resource_type in _BLOCKED_RESOURCE_TYPES+ ):+ await route.abort()+ return++ loop = asyncio.get_running_loop()+ current = first_url+ method = request.method+ body_override = None+ # Carries the "Cookie" header for the NEXT hop, re-derived from the+ # context's cookie jar (scoped to that hop's URL) on EVERY hop by+ # _reapply_hop_cookies. It stays None only for the very first fetch,+ # which legitimately uses the originally intercepted request's own+ # Cookie header; from the first redirect onward it is always set+ # (possibly to an explicit EMPTY header). This is required because+ # route.fetch() otherwise keeps resending the ORIGINAL intercepted+ # request's Cookie header for the rest of this handler invocation —+ # so without a per-hop override a cookie scoped to hop N's domain+ # would ride along to hop N+1 even across a DIFFERENT registrable+ # domain (a cross-origin cookie leak).+ cookie_header_override = None+ for _ in range(_MAX_REDIRECTS + 1):+ ok = await loop.run_in_executor(+ None,+ functools.partial(+ ssrf_validator.validate_url,+ current,+ allow_private_ips=self.allow_private_ips,+ ),+ )+ if not ok:+ logger.warning(+ "Crawl4AI: blocked SSRF-unsafe browser request to {}",+ ssrf_validator.redact_url_for_log(current),+ )+ await route.abort("blockedbyclient")+ return+ fetch_kwargs = {+ "url": current,+ "method": method,+ "max_redirects": 0,+ }+ if body_override is not None:+ fetch_kwargs["post_data"] = body_override+ try:+ self._apply_hop_cookie_header(+ request, fetch_kwargs, cookie_header_override+ )+ except Exception:+ # Fail CLOSED: building the hop headers reads+ # request.headers and must never let an exception escape+ # this route handler and fall through to an unguarded+ # fetch — abort the hop exactly like a failed fetch below.+ logger.debug(+ "Crawl4AI: failed to build guarded hop headers",+ exc_info=True,+ )+ await route.abort("failed")+ return+ try:+ response = await route.fetch(**fetch_kwargs)+ except Exception:+ logger.debug("Crawl4AI: guarded fetch failed", exc_info=True)+ await route.abort("failed")+ return+ next_url = self._redirect_target(current, response)+ # Re-apply this hop's Set-Cookie header(s) to the context AND+ # re-derive, from the context jar scoped to the NEXT hop, the+ # explicit Cookie header for that hop's route.fetch() — BEFORE+ # following it. Passing next_url (which is None on the terminal+ # hop) lets _reapply_hop_cookies skip deriving a header when+ # there is no next request. See _reapply_hop_cookies for why the+ # per-hop re-derivation is required on the crawl4ai path.+ cookie_header_override = await self._reapply_hop_cookies(+ route,+ current,+ response,+ next_url,+ )+ if next_url is None:+ await route.fulfill(response=response)+ return+ new_method = _resolve_redirect_method(method, response.status)+ if new_method == "GET" and method != "GET":+ body_override = "" # POST->GET downgrade must not leak body+ method = new_method+ current = next_url+ logger.warning(+ "Crawl4AI: too many redirects — blocking browser request"+ )+ await route.abort("blockedbyclient")++ async def _crawl4ai_ws_guard(self, ws_route) -> None:+ """Block every WebSocket on the Crawl4AI path (async twin of+ ``_playwright_ws_guard``).++ Same no-op-reject strategy: not calling ``connect_to_server`` leaves+ the real server unreached. Kept no-op (no ``close()``) for symmetry+ with the sync guard and to avoid any handler-reentrancy surprises.+ """+ try:+ logger.debug(+ "Crawl4AI: blocking WebSocket to {}",+ ssrf_validator.redact_url_for_log(ws_route.url),+ )+ except Exception:+ logger.debug("Crawl4AI: blocking WebSocket")++ @staticmethod+ def _cookies_from_response(response, response_url: str) -> list:+ """Parse ``Set-Cookie`` response header(s) into Playwright cookie+ dicts, ready for ``BrowserContext.add_cookies()``.++ WHY THIS EXISTS: both browser guards re-derive the ``Cookie`` request+ header per redirect hop from the context's own jar, so this parses a+ hop's ``Set-Cookie`` header(s) and re-applies them to the jar before+ the next hop is followed. On the crawl4ai path it is also load-bearing+ for content fidelity: crawl4ai pre-seeds the page context with a+ marker cookie via ``context.add_cookies()`` before navigation+ (``BrowserManager.setup_context``), and once a context's jar has been+ touched that way, Playwright's ``route.fetch()`` on a subsequent+ redirect hop does NOT merge that hop's ``Set-Cookie`` into the jar for+ us — so a session/auth cookie set on an intermediate hop would+ silently be lost, corrupting the final page (e.g. a login- or+ region-gated redirect).++ A ``Set-Cookie`` that is really a DELETION directive (``Max-Age=0`` or+ a past ``Expires``) is honored and NOT re-added, so a cookie the+ server just cleared is never resurrected onto the jar.++ Uses ``headers_array`` (a list of ``{name, value}`` pairs) rather+ than the ``headers`` dict, because a response can carry MULTIPLE+ ``Set-Cookie`` headers — a plain dict would silently collapse them+ to one.+ """+ host = urlparse(response_url).hostname+ if not host:+ return []+ try:+ headers = response.headers_array+ except Exception:+ return []+ cookies = []+ for header in headers:+ if str(header.get("name", "")).lower() != "set-cookie":+ continue+ raw = header.get("value", "")+ try:+ parsed = _parse_one_set_cookie(raw)+ except Exception:+ logger.debug(+ "Browser guard: failed to parse a Set-Cookie header",+ exc_info=True,+ )+ continue+ if parsed is None:+ continue+ name, value, attrs = parsed+ if _set_cookie_is_expired(attrs):+ # A Max-Age=0 / past-Expires Set-Cookie is a DELETION+ # directive: re-adding it would resurrect a cookie the+ # server just cleared. Honor the expiry and skip it.+ logger.debug(+ "Browser guard: skipping expired/deletion Set-Cookie"+ )+ continue+ raw_domain = attrs.get("domain")+ if (+ isinstance(raw_domain, str)+ and raw_domain+ and _cookie_domain_matches(host, raw_domain)+ ):+ cookie_domain = raw_domain+ else:+ # No Domain attribute, or a Domain that does NOT+ # domain-match the response host (a cross-domain or+ # unrelated Domain a browser rejects). Scope the cookie+ # to the response host — mirroring browser behavior and+ # preventing a hop from planting a cookie on another+ # registrable domain (session fixation).+ if isinstance(raw_domain, str) and raw_domain:+ logger.debug(+ "Browser guard: rejecting a Set-Cookie Domain that "+ "does not match the response host; scoping the "+ "cookie to the host instead"+ )+ cookie_domain = host+ path = attrs.get("path")+ cookie = {+ "name": name,+ "value": value,+ "domain": cookie_domain,+ "path": path if isinstance(path, str) and path else "/",+ }+ if attrs.get("secure"):+ cookie["secure"] = True+ if attrs.get("httponly"):+ cookie["httpOnly"] = True+ cookies.append(cookie)+ return cookies++ async def _reapply_hop_cookies(+ self,+ route,+ current_url: str,+ response,+ next_hop_url: Optional[str],+ ) -> Optional[str]:+ """Apply ``response``'s ``Set-Cookie`` header(s) to the browser+ context and return the ``Cookie`` header the caller must pass to the+ NEXT hop's ``route.fetch(headers=...)`` — re-derived, on EVERY hop,+ from the context jar scoped to ``next_hop_url``.++ Why re-derive on every hop instead of carrying the previous hop's+ header forward: ``route.fetch()`` keeps resending the ORIGINAL+ intercepted request's Cookie header for the rest of this guard+ invocation unless we override it. If we ever carried a previous+ hop's Cookie header (or let the original one ride along) across a+ redirect to a DIFFERENT registrable domain, that domain would+ receive cookies scoped to the previous one — a cross-origin cookie+ leak a real browser never performs. So we ALWAYS read the jar back+ through ``context.cookies(next_hop_url)`` (Playwright scopes it by+ domain/path) and return exactly those cookies:++ * same-domain next hop -> the jar returns that domain's cookies+ (including any just set on this hop, applied below via+ ``add_cookies``), so same-domain persistence keeps working;+ * cross-domain next hop -> the jar returns nothing for that domain,+ so we return an EMPTY header and the caller sends NO Cookie to it.++ ``context.add_cookies()`` still runs for its own sake: it keeps the+ jar correct for anything reading it independently of this walk+ (subresources of the eventually-fulfilled page, ``document.cookie``,+ later navigations in the same context).++ Fail-SAFE: on any parse/apply/read error we return an EMPTY header+ rather than a previous hop's, so an error can only DROP a cookie,+ never leak one cross-domain. This never affects the SSRF+ validate/abort decisions around it. Returns ``None`` only for the+ terminal hop (``next_hop_url is None`` — no next request needs a+ header); that value is unused by the caller.+ """+ try:+ context = route.request.frame.page.context+ cookies = self._cookies_from_response(response, current_url)+ if cookies:+ await context.add_cookies(cookies)+ if next_hop_url is None:+ # Terminal hop: no next request, so no Cookie header to+ # derive. The jar was still updated above.+ return None+ live_cookies = await context.cookies(next_hop_url)+ return "; ".join(f"{c['name']}={c['value']}" for c in live_cookies)+ except Exception:+ logger.debug(+ "Crawl4AI: failed to re-apply redirect-hop cookies",+ exc_info=True,+ )+ # Prefer sending NO cookie to the next hop over resending a+ # previous hop's (possibly cross-domain) one: "" clears the+ # Cookie header. None is used only when there is no next hop.+ return "" if next_hop_url is not None else None++ def _reapply_hop_cookies_sync(+ self,+ route,+ current_url: str,+ response,+ next_hop_url: Optional[str],+ ) -> Optional[str]:+ """Synchronous twin of ``_reapply_hop_cookies`` for the plain+ (sync-API) Playwright path.++ Same contract and fail-SAFE behavior — see ``_reapply_hop_cookies``+ for the full rationale. Applies this hop's ``Set-Cookie`` header(s)+ to the browser context and returns the ``Cookie`` header for the NEXT+ hop, re-derived from the context jar scoped to ``next_hop_url`` so a+ cookie belonging to one domain is never forwarded to a different+ registrable domain a later redirect lands on. Returns ``None`` only+ for the terminal hop; on any error returns an EMPTY header (drop a+ cookie, never leak one cross-domain).+ """+ try:+ context = route.request.frame.page.context+ cookies = self._cookies_from_response(response, current_url)+ if cookies:+ context.add_cookies(cookies)+ if next_hop_url is None:+ # Terminal hop: no next request, so no Cookie header to+ # derive. The jar was still updated above.+ return None+ live_cookies = context.cookies(next_hop_url)+ return "; ".join(f"{c['name']}={c['value']}" for c in live_cookies)+ except Exception:+ logger.debug(+ "Playwright: failed to re-apply redirect-hop cookies",+ exc_info=True,+ )+ return "" if next_hop_url is not None else None++ @staticmethod+ def _apply_hop_cookie_header(+ request, fetch_kwargs: dict, cookie_header_override: Optional[str]+ ) -> None:+ """Override ONLY the ``Cookie`` header on ``fetch_kwargs`` with the+ per-hop re-derived ``cookie_header_override``.++ Shared by both browser guards (sync + crawl4ai). Rebuilds the base+ headers ``route.fetch()`` would otherwise default to (the original+ intercepted request's) MINUS its ``Cookie`` header, then sets the+ freshly re-derived Cookie header. When that value is EMPTY, the Cookie+ header is dropped entirely rather than sent empty: the next hop's+ domain has no cookies in the jar, so sending nothing is correct — and,+ crucially, this stops ``route.fetch()`` from resending the ORIGINAL+ intercepted request's Cookie header to what may be a DIFFERENT+ registrable domain (the cross-origin leak this guards against).++ The original request's ``Host`` and ``Content-Length`` are ALSO dropped+ from the rebuilt headers on every hop: a redirect hop's ``Host`` must be+ derived from the NEW target (a forwarded stale ``Host`` is wrong on a+ cross-host hop), and after a POST->GET downgrade (body dropped to "")+ the original ``Content-Length`` no longer matches the body.+ ``route.fetch()`` recomputes both from the hop URL and the actual body+ once these headers are absent.++ On a CROSS-SITE hop the originally intercepted request's+ ``Authorization`` / ``Proxy-Authorization`` headers are ALSO dropped+ (in addition to ``Cookie``): those credentials are scoped to the+ original origin, so — exactly as a real browser strips Authorization+ on a cross-origin redirect — they must never ride along to a different+ registrable domain a later hop lands on. Same-site hops keep them so+ legitimate within-site auth redirects (e.g. api.example.com ->+ example.com) still work. Cross-site is decided by+ ``_same_registrable_site`` — the same host/subdomain notion the cookie+ re-scoping relies on.++ A ``None`` override (the very first hop only) leaves ``fetch_kwargs``+ untouched so the initial request keeps its own Cookie header. The very+ first hop is by construction same-origin (its target IS the original+ request URL), so no credential is ever leaked by that early return.+ """+ if cookie_header_override is None:+ return+ # Dropped on EVERY (post-first) hop, before rebuilding the headers:+ # * cookie — always re-derived per hop below.+ # * host — a redirect hop's Host must come from the NEW target, not a+ # stale forwarded value; a cross-host hop that kept the previous+ # hop's Host would send the wrong Host. ``route.fetch()`` derives the+ # correct Host from the hop URL once this header is absent.+ # * content-length — after a POST->GET redirect downgrade the body is+ # dropped to "" (see the guard loop's ``body_override``), so a+ # forwarded original Content-Length would be incorrect;+ # ``route.fetch()`` recomputes it from the actual (post_data) body.+ drop = {"cookie", "host", "content-length"}+ # On a cross-site hop also strip the credential headers the original+ # request carried (a browser strips Authorization cross-origin too).+ origin_host = urlparse(request.url).hostname+ target_host = urlparse(fetch_kwargs.get("url", "")).hostname+ if not _same_registrable_site(origin_host, target_host):+ drop |= {"authorization", "proxy-authorization"}+ base_headers = {+ k: v for k, v in request.headers.items() if k.lower() not in drop+ }+ if cookie_header_override:+ base_headers["cookie"] = cookie_header_override+ fetch_kwargs["headers"] = base_headers++ @staticmethod+ def _redirect_target(current_url: str, response) -> Optional[str]:+ """Return the absolute redirect target for ``response``, or None.++ None means the response is terminal (not a followed 3xx, or a 3xx+ with no ``Location``) and should be served to the browser as-is.+ Mirrors the static path's redirect handling so both validate the+ same hops.+ """+ if response.status not in _REDIRECT_STATUS_CODES:+ return None+ location = response.headers.get("location")+ if not location:+ return None+ return urljoin(current_url, location.strip())++ def _robots_allows(self, url: str) -> bool:+ """Guarded robots.txt politeness check.++ REPLACES Crawl4AI's built-in ``check_robots_txt`` fetch, which used a+ raw ``aiohttp`` client (redirect-following, no SSRF check) — a+ ``/robots.txt`` that 302-redirected to an internal/metadata host was+ fetched unguarded. Here the fetch goes through the downloader's+ ``SafeSession``, whose ``send()`` SSRF-validates every hop (initial ++ redirects) under the same egress scope as the browser guard.++ Fails OPEN (returns True) on any non-200, network error, SSRF block,+ or parse failure — matching the "allow on robots uncertainty"+ convention. It only ever DISALLOWS on an explicit robots rule, so a+ blocked (SSRF-unsafe) robots fetch never grants extra access.+ """+ from urllib.robotparser import RobotFileParser++ try:+ parsed = urlparse(url)+ if not parsed.netloc:+ return True+ scheme = parsed.scheme or "http"+ robots_url = f"{scheme}://{parsed.netloc}/robots.txt"+ response = self.session.get(+ robots_url,+ timeout=min(self.timeout, 10),+ allow_redirects=True,+ )+ if response.status_code != 200 or not response.text:+ return True+ parser = RobotFileParser()+ parser.parse(response.text.splitlines())+ return parser.can_fetch(BROWSER_USER_AGENT, url)+ except Exception:+ # SafeSession raises ValueError on an SSRF-unsafe hop; network /+ # parse errors land here too. Fail open for politeness — the+ # actual navigation is still validated by the browser guard.+ logger.debug("Guarded robots.txt check failed open", exc_info=True)+ return True+def _fetch_html(self, url: str) -> Optional[str]:"""Fetch HTML with JS rendering.Tries Crawl4AI first (with robots.txt, shadow DOM, iframes),falls back to plain Playwright."""+ # Entry-URL scheme guard (fail-closed). The browser downloader is+ # reachable via download()/download_with_result(), which do NOT+ # constrain the scheme themselves — only can_handle() checks it, and+ # not every caller consults can_handle() (e.g.+ # extraction/pipeline.py calls download() directly). The per-request+ # route guard validates redirect hops and subresources, but a+ # top-level page.goto()/crawler.arun() on a non-http(s) entry URL+ # (e.g. file:///etc/passwd) could read a LOCAL FILE and return it as+ # page content before any hop is walked. Refuse non-http(s) entry URLs+ # here so such a URL is never navigated.+ if urlparse(url).scheme.lower() not in ("http", "https"):+ logger.warning(+ "Browser downloader: refusing non-http(s) entry URL {}",+ ssrf_validator.redact_url_for_log(url),+ )+ return None# Try Crawl4AI first (richer features, robots.txt)html = self._fetch_with_crawl4ai(url)if html is not None:@@ -118,6 +937,18 @@ class PlaywrightHTMLDownloader(HTMLDownloader):logger.debug("crawl4ai not installed — using Playwright")return None+ # Ethical robots.txt check — done HERE through the guarded+ # SafeSession, NOT via crawl4ai's check_robots_txt (disabled below):+ # crawl4ai fetches robots.txt with a raw aiohttp client that follows+ # redirects with no SSRF validation, so a redirecting /robots.txt is+ # an SSRF vector that bypasses the browser route guard entirely.+ if not self._robots_allows(url):+ logger.info(+ "Crawl4AI: blocked by robots.txt for {}",+ ssrf_validator.redact_url_for_log(url),+ )+ return "" # Empty string signals intentional skip+logger.debug(f"Crawl4AI fetch: {url}")wait_time = self.rate_tracker.apply_rate_limit(engine_type)@@ -127,8 +958,9 @@ class PlaywrightHTMLDownloader(HTMLDownloader):user_agent=BROWSER_USER_AGENT,)run_cfg = CrawlerRunConfig(- # Ethical: respect robots.txt- check_robots_txt=True,+ # robots.txt handled by the guarded _robots_allows() above;+ # crawl4ai's own fetch is unguarded (SSRF), so keep it OFF.+ check_robots_txt=False,# Better extraction: flatten modern web featuresflatten_shadow_dom=True,process_iframes=True,@@ -149,10 +981,70 @@ class PlaywrightHTMLDownloader(HTMLDownloader):async def _crawl():async with AsyncWebCrawler(config=browser_cfg) as crawler:+ # Install the SSRF route guard on every page context+ # BEFORE any navigation. FAIL-SAFE: if the hook API is+ # unavailable (crawl4ai API drift), do NOT run crawl4ai+ # unguarded — return None so _fetch_html falls through+ # to the guarded plain-Playwright path.+ async def _on_page_context_created(+ page, context=None, config=None, **kwargs+ ):+ # Install ALL three guards fail-CLOSED: if any raises+ # (crawl4ai/Playwright API drift, or a context with+ # incomplete API parity), let it propagate so the+ # crawl is abandoned — crawl4ai's execute_hook does not+ # swallow it, so it reaches the outer ``except`` below+ # and _fetch_with_crawl4ai returns None, falling back+ # to the guarded plain-Playwright path. Never navigate+ # with a missing HTTP, WebSocket, or SW guard.+ target = context if context is not None else page+ # HTTP(S) requests: SSRF-validate every hop.+ await target.route("**/*", self._crawl4ai_route_guard)+ # WebSockets: route("**/*") does not match WS upgrades+ # — block them explicitly.+ await target.route_web_socket(+ "**/*", self._crawl4ai_ws_guard+ )+ # Service Workers: crawl4ai's BrowserConfig cannot set+ # service_workers="block", and SW-made requests bypass+ # route handlers — prevent SW registration via an init+ # script so all traffic stays on the guarded path.+ await target.add_init_script(+ _DISABLE_SERVICE_WORKERS_JS+ )+ # WebRTC: RTCPeerConnection ICE (STUN/TURN) opens raw+ # UDP/TCP sockets via Chromium's WebRTC stack, which+ # neither route() nor route_web_socket() intercept —+ # neutralize it before any page script runs.+ await target.add_init_script(_DISABLE_WEBRTC_JS)+ return page++ try:+ crawler.crawler_strategy.set_hook(+ "on_page_context_created",+ _on_page_context_created,+ )+ except Exception:+ logger.warning(+ "Crawl4AI: could not install SSRF route guard — "+ "refusing to crawl unguarded, falling back to "+ "the guarded Playwright path"+ )+ return Nonereturn await crawler.arun(url=url, config=run_cfg)+ # A guard-install failure raised inside the hook propagates out of+ # crawl4ai's execute_hook and arun, landing in the outer ``except``+ # below (return None -> guarded plain-Playwright fallback). This is+ # the fail-CLOSED path: a crawl NEVER proceeds with a missing HTTP,+ # WebSocket, or Service-Worker guard.result = _run_async(_crawl(), timeout=self.timeout + 30)+ if result is None:+ # Guard could not be installed (fail-safe) — defer to the+ # guarded plain-Playwright path rather than crawl unguarded.+ return None+if result.success and result.html:html = result.htmllogger.debug(f"Crawl4AI: got {len(html)} bytes from {url}")@@ -168,7 +1060,10 @@ class PlaywrightHTMLDownloader(HTMLDownloader):# Check if blocked by robots.txterror_msg = getattr(result, "error_message", "") or ""if "robots.txt" in error_msg.lower():- logger.info(f"Crawl4AI: blocked by robots.txt for {url}")+ logger.info(+ "Crawl4AI: blocked by robots.txt for {}",+ ssrf_validator.redact_url_for_log(url),+ )# Don't fall back to Playwright — respect the blockself.rate_tracker.record_outcome(engine_type=engine_type,@@ -235,17 +1130,39 @@ class PlaywrightHTMLDownloader(HTMLDownloader):raiseself._playwright = pw+ # ``browser.new_page()`` creates a FRESH BrowserContext for this+ # fetch (Playwright makes the page own that context) — only+ # ``self._browser`` is cached across fetches, NOT the context. The+ # route/WS handlers and init scripts below are therefore registered+ # on a per-fetch context that ``page.close()`` (in the finally)+ # tears down together with them, so they do NOT accumulate across+ # fetches; each fetch gets exactly one of each guard.page = self._browser.new_page(user_agent=BROWSER_USER_AGENT,+ # Block Service Workers: their requests are not intercepted by+ # route handlers, so a SW could fetch an internal/metadata+ # host unvalidated. Blocking forces all traffic through the+ # guarded normal path (SWs aren't needed for text extraction).+ service_workers="block",)try:- # Block heavy resources to speed up rendering- if self.block_resources:- page.route(- "**/*.{png,jpg,jpeg,gif,webp,svg,ico,woff,woff2,"- "ttf,eot,mp4,webm,mp3,ogg,css}",- lambda route: route.abort(),- )+ # Egress guard for EVERY request: validates the initial+ # navigation and each redirect hop before the browser+ # connects (see _playwright_route_guard), and also drops+ # heavy subresources when block_resources is set — so it+ # subsumes the old extension-glob resource route. Registered+ # at the CONTEXT level so it also covers requests a blocked+ # SW would otherwise have made.+ page.context.route("**/*", self._playwright_route_guard)+ # WebSockets bypass route("**/*") — block them explicitly.+ page.context.route_web_socket("**/*", self._playwright_ws_guard)+ # WebRTC (RTCPeerConnection ICE/STUN/TURN) opens raw sockets via+ # Chromium's WebRTC stack, which no route handler intercepts —+ # neutralize it before any page script runs. Install at the+ # CONTEXT level (like the route guards above) so it also covers+ # popups (window.open) — a page-level init script does not+ # propagate to new pages, leaving a popup with live WebRTC.+ page.context.add_init_script(_DISABLE_WEBRTC_JS)page.goto(url,@@ -327,11 +1244,16 @@ class AutoHTMLDownloader(HTMLDownloader):# ``web.enable_javascript_rendering`` setting, or pass ``True``# explicitly when constructing the downloader.enable_js_rendering: bool = False,+ allow_private_ips: bool = False,**kwargs,):super().__init__(timeout=timeout, language=language)self.min_content_length = min_content_lengthself.enable_js_rendering = enable_js_rendering+ # SSRF policy threaded to the lazily-built Playwright child so the+ # JS-render browser path honours the active egress scope. Default+ # strict; ContentFetcher relaxes to True under PRIVATE_ONLY.+ self.allow_private_ips = allow_private_ipsself._playwright_downloader = Nonedef _get_playwright_downloader(self) -> PlaywrightHTMLDownloader:@@ -340,6 +1262,7 @@ class AutoHTMLDownloader(HTMLDownloader):self._playwright_downloader = PlaywrightHTMLDownloader(timeout=self.timeout,language=self.language,+ allow_private_ips=self.allow_private_ips,)return self._playwright_downloaderdiff --git a/tests/research_library/downloaders/test_playwright_html_ssrf_guard.py b/tests/research_library/downloaders/test_playwright_html_ssrf_guard.pynew file mode 100644index 0000000000..306bc943c2--- /dev/null+++ b/tests/research_library/downloaders/test_playwright_html_ssrf_guard.py@@ -0,0 +1,2575 @@+"""SSRF route-guard tests for the JS-render browser download path.++The static ``SafeSession`` fetch path validates every redirect hop via+``ssrf_validator.validate_url``. Before this fix the JS-render browser path+(Crawl4AI + plain Playwright) followed redirects with NO SSRF check, so a+public URL that 302-redirects to ``169.254.169.254`` (cloud metadata) or an+RFC1918 host was fetched by headless Chromium unchecked. Playwright does not+re-fire ``page.route`` handlers on the hops of a redirect chain (the browser+follows 3xx internally), so the guard follows the chain ITSELF via+``route.fetch(max_redirects=0)``, validates every hop before fetching it, and+hands the browser only the final safe response via ``route.fulfill``.++Layers, cheapest first:+- Deterministic guard-decision tests (no browser): a fake ``route`` whose+ ``fetch`` returns canned responses drives ``_playwright_route_guard`` (sync)+ and ``_crawl4ai_route_guard`` (async). We assert abort vs fulfill for+ metadata / RFC1918 / safe-public / non-http schemes / heavy subresources,+ and — the core property — that a redirect target is validated and aborted+ BEFORE the browser (or route.fetch) ever contacts it.+- Crawl4AI hook wiring (no browser): a fake ``AsyncWebCrawler`` verifies the+ ``on_page_context_created`` hook installs the guard route, and that a+ hook-install failure is FAIL-SAFE (returns None -> guarded Playwright+ fallback), never an unguarded crawl.+- Real-browser integration (skipped when Chromium is absent): a loopback+ server 302-redirects into a sentinel loopback server; with ``validate_url``+ patched to reject the redirect target, the sentinel records ZERO hits.+"""++from __future__ import annotations++import asyncio+import http.server+import socket+import threading+from pathlib import Path+from unittest.mock import AsyncMock, MagicMock, patch+from urllib.parse import urlparse++import pytest++from local_deep_research.research_library.downloaders.playwright_html import (+ PlaywrightHTMLDownloader,+)+from local_deep_research.security import ssrf_validator+from local_deep_research.security.safe_requests import _MAX_REDIRECTS+++METADATA_URL = "http://169.254.169.254/latest/meta-data/iam/"+RFC1918_URL = "http://10.0.0.5/internal"+PUBLIC_URL = "https://example.com/page"+++class _FakeAPIResponse:+ """Stand-in for the Playwright APIResponse returned by route.fetch."""++ def __init__(+ self,+ status: int,+ headers: dict | None = None,+ headers_array: list | None = None,+ ):+ self.status = status+ self.headers = headers or {}+ # Mirrors the real APIResponse.headers_array: a list of+ # {"name", "value"} pairs that (unlike the ``headers`` dict) can+ # carry multiple entries for the same header name (e.g.+ # Set-Cookie). Defaults to a 1:1 projection of ``headers`` when not+ # given explicitly, so existing callers that only set ``headers``+ # are unaffected.+ self.headers_array = (+ headers_array+ if headers_array is not None+ else [{"name": k, "value": v} for k, v in self.headers.items()]+ )+++def _sync_route(url: str, resource_type: str = "document") -> MagicMock:+ """A fake Playwright sync ``Route``; fetch returns HTTP 200 by default."""+ route = MagicMock()+ route.request.url = url+ route.request.method = "GET"+ route.request.resource_type = resource_type+ route.fetch = MagicMock(return_value=_FakeAPIResponse(200))+ return route+++def _async_route(url: str, resource_type: str = "document") -> MagicMock:+ """A fake Playwright async ``Route`` (fetch/fulfill/abort awaitable)."""+ route = MagicMock()+ route.request.url = url+ route.request.method = "GET"+ route.request.resource_type = resource_type+ route.fetch = AsyncMock(return_value=_FakeAPIResponse(200))+ route.fulfill = AsyncMock()+ route.abort = AsyncMock()+ route.fallback = AsyncMock()+ return route+++# ---------------------------------------------------------------------------+# Deterministic sync guard decisions (the primary lock)+# ---------------------------------------------------------------------------+++class TestSyncGuardDecisions:+ """``_playwright_route_guard`` aborts SSRF-unsafe requests (never fetching+ them) and serves safe ones via fetch + fulfill. No browser involved."""++ def setup_method(self):+ self.dl = PlaywrightHTMLDownloader(timeout=5)++ def teardown_method(self):+ self.dl.close()++ @pytest.mark.parametrize("allow_private_ips", [False, True])+ def test_metadata_always_aborted(self, allow_private_ips):+ """Cloud-metadata is aborted EVEN when allow_private_ips=True — the+ relaxation must never open IMDS — and is never fetched."""+ self.dl.allow_private_ips = allow_private_ips+ route = _sync_route(METADATA_URL)+ self.dl._playwright_route_guard(route)+ route.abort.assert_called_once_with("blockedbyclient")+ route.fetch.assert_not_called()+ route.fulfill.assert_not_called()++ def test_rfc1918_aborted_when_strict(self):+ """RFC1918 is aborted with the strict default (allow_private_ips=False)."""+ self.dl.allow_private_ips = False+ route = _sync_route(RFC1918_URL)+ self.dl._playwright_route_guard(route)+ route.abort.assert_called_once_with("blockedbyclient")+ route.fetch.assert_not_called()++ def test_rfc1918_allowed_when_private_allowed(self):+ """RFC1918 is served (fetch + fulfill, no abort) when+ allow_private_ips=True — the PRIVATE_ONLY egress lab case."""+ self.dl.allow_private_ips = True+ route = _sync_route(RFC1918_URL)+ self.dl._playwright_route_guard(route)+ route.fetch.assert_called_once()+ route.fulfill.assert_called_once()+ route.abort.assert_not_called()++ def test_safe_public_url_served(self):+ """A safe public URL is fetched and fulfilled, never aborted."""+ with patch.object(ssrf_validator, "validate_url", return_value=True):+ route = _sync_route(PUBLIC_URL)+ self.dl._playwright_route_guard(route)+ route.fetch.assert_called_once()+ route.fulfill.assert_called_once()+ route.abort.assert_not_called()++ def test_non_http_scheme_falls_through(self):+ """Non-network schemes (data:/blob:/about:) are not SSRF vectors and+ defer via fallback without touching validate_url or fetch."""+ with patch.object(ssrf_validator, "validate_url") as mock_validate:+ route = _sync_route("data:text/html,<h1>hi</h1>")+ self.dl._playwright_route_guard(route)+ mock_validate.assert_not_called()+ route.fallback.assert_called_once()+ route.abort.assert_not_called()+ route.fetch.assert_not_called()++ @pytest.mark.parametrize(+ "url",+ [+ "file:///etc/passwd",+ "chrome://settings",+ "gopher://127.0.0.1:70/",+ "ftp://internal.example.com/secret",+ ],+ )+ def test_dangerous_non_http_scheme_aborted(self, url):+ """SECURITY: every non-http(s) scheme OUTSIDE the data:/blob:/about:+ allowlist (file:/chrome:/gopher:/ftp: …) is aborted, never handed to+ the browser via fallback — so a redirect or resource cannot pivot to a+ local file or an internal handler."""+ with patch.object(ssrf_validator, "validate_url") as mock_validate:+ route = _sync_route(url)+ self.dl._playwright_route_guard(route)+ mock_validate.assert_not_called()+ route.abort.assert_called_once()+ route.fallback.assert_not_called()+ route.fetch.assert_not_called()++ def test_heavy_subresource_blocked_for_perf(self):+ """With block_resources set, an image is aborted early (no SSRF check,+ no fetch) — the guard subsumes the old resource route."""+ assert self.dl.block_resources is True+ with patch.object(ssrf_validator, "validate_url") as mock_validate:+ route = _sync_route(+ "https://cdn.example.com/x.png", resource_type="image"+ )+ self.dl._playwright_route_guard(route)+ mock_validate.assert_not_called()+ route.abort.assert_called_once_with() # plain abort, no error code+ route.fetch.assert_not_called()++ def test_subresource_validated_when_blocking_disabled(self):+ """With block_resources False, an image request is still SSRF-checked+ and served like any other request."""+ self.dl.block_resources = False+ with patch.object(ssrf_validator, "validate_url", return_value=True):+ route = _sync_route(+ "https://cdn.example.com/x.png", resource_type="image"+ )+ self.dl._playwright_route_guard(route)+ route.fetch.assert_called_once()+ route.fulfill.assert_called_once()++ def test_redirect_target_validated_before_fetch(self):+ """THE core property: a safe entry URL that redirects to metadata must+ have the redirect target validated and ABORTED before it is fetched.+ Only the entry hop is fetched; the metadata hop never reaches fetch."""++ def _side_effect(url, *args, **kwargs):+ return "169.254.169.254" not in url++ route = _sync_route(PUBLIC_URL)+ route.fetch.return_value = _FakeAPIResponse(+ 302, {"location": METADATA_URL}+ )+ with patch.object(+ ssrf_validator, "validate_url", side_effect=_side_effect+ ):+ self.dl._playwright_route_guard(route)+ # Entry hop fetched exactly once; redirect target never fetched.+ assert route.fetch.call_count == 1+ route.abort.assert_called_once_with("blockedbyclient")+ route.fulfill.assert_not_called()++ def test_hop_header_build_failure_aborts_hop(self):+ """SECURITY, fail-closed: if building the per-hop headers raises+ (e.g. reading request.headers unexpectedly fails), the hop must be+ ABORTED rather than falling through to an unguarded fetch — and the+ exception must never escape the route handler."""+ route = _sync_route(PUBLIC_URL)+ with (+ patch.object(ssrf_validator, "validate_url", return_value=True),+ patch.object(+ PlaywrightHTMLDownloader,+ "_apply_hop_cookie_header",+ side_effect=RuntimeError("simulated header-build failure"),+ ),+ ):+ self.dl._playwright_route_guard(route) # must not raise+ route.fetch.assert_not_called()+ route.fulfill.assert_not_called()+ route.abort.assert_called_once_with("failed")++ def test_safe_redirect_chain_served(self):+ """A safe entry that 302s to a safe target follows the hop and serves+ the final response (two fetches, one fulfill, no abort)."""+ final_target = "https://example.com/final"+ responses = [+ _FakeAPIResponse(302, {"location": final_target}),+ _FakeAPIResponse(200),+ ]+ route = _sync_route(PUBLIC_URL)+ route.fetch.side_effect = responses+ with patch.object(ssrf_validator, "validate_url", return_value=True):+ self.dl._playwright_route_guard(route)+ assert route.fetch.call_count == 2+ route.fulfill.assert_called_once()+ route.abort.assert_not_called()++ def test_redirect_loop_aborted(self):+ """An endless redirect loop is aborted after _MAX_REDIRECTS hops."""+ route = _sync_route(PUBLIC_URL)+ route.fetch.return_value = _FakeAPIResponse(+ 302, {"location": PUBLIC_URL}+ )+ with patch.object(ssrf_validator, "validate_url", return_value=True):+ self.dl._playwright_route_guard(route)+ route.abort.assert_called_once_with("blockedbyclient")+ route.fulfill.assert_not_called()+ assert route.fetch.call_count <= _MAX_REDIRECTS + 1++ def test_blocked_log_does_not_leak_full_url(self):+ """The block warning logs scheme://host only, never credentials in+ userinfo / query params."""+ creds_url = "http://user:[email protected]/internal?token=abc"+ self.dl.allow_private_ips = False+ with patch(+ "local_deep_research.research_library.downloaders."+ "playwright_html.logger"+ ) as mock_logger:+ route = _sync_route(creds_url)+ self.dl._playwright_route_guard(route)+ logged = " ".join(+ str(a)+ for call in mock_logger.warning.call_args_list+ for a in call.args+ )+ assert "s3cret" not in logged+ assert "token=abc" not in logged+ route.abort.assert_called_once_with("blockedbyclient")+++# ---------------------------------------------------------------------------+# Deterministic async guard decisions (Crawl4AI path)+# ---------------------------------------------------------------------------+++class TestAsyncGuardDecisions:+ """``_crawl4ai_route_guard`` makes the SAME decisions as the sync guard,+ offloading validate_url to a thread. Driven via asyncio.run, no browser."""++ def setup_method(self):+ self.dl = PlaywrightHTMLDownloader(timeout=5)++ def teardown_method(self):+ self.dl.close()++ @pytest.mark.parametrize("allow_private_ips", [False, True])+ def test_metadata_always_aborted(self, allow_private_ips):+ self.dl.allow_private_ips = allow_private_ips+ route = _async_route(METADATA_URL)+ asyncio.run(self.dl._crawl4ai_route_guard(route))+ route.abort.assert_awaited_once_with("blockedbyclient")+ route.fetch.assert_not_awaited()+ route.fulfill.assert_not_awaited()++ def test_rfc1918_aborted_when_strict(self):+ self.dl.allow_private_ips = False+ route = _async_route(RFC1918_URL)+ asyncio.run(self.dl._crawl4ai_route_guard(route))+ route.abort.assert_awaited_once_with("blockedbyclient")+ route.fetch.assert_not_awaited()++ def test_rfc1918_allowed_when_private_allowed(self):+ self.dl.allow_private_ips = True+ route = _async_route(RFC1918_URL)+ asyncio.run(self.dl._crawl4ai_route_guard(route))+ route.fetch.assert_awaited_once()+ route.fulfill.assert_awaited_once()+ route.abort.assert_not_awaited()++ def test_safe_public_url_served(self):+ with patch.object(ssrf_validator, "validate_url", return_value=True):+ route = _async_route(PUBLIC_URL)+ asyncio.run(self.dl._crawl4ai_route_guard(route))+ route.fetch.assert_awaited_once()+ route.fulfill.assert_awaited_once()+ route.abort.assert_not_awaited()++ def test_non_http_scheme_falls_through(self):+ with patch.object(ssrf_validator, "validate_url") as mock_validate:+ route = _async_route("about:blank")+ asyncio.run(self.dl._crawl4ai_route_guard(route))+ mock_validate.assert_not_called()+ route.fallback.assert_awaited_once()+ route.abort.assert_not_awaited()++ @pytest.mark.parametrize(+ "url",+ [+ "file:///etc/passwd",+ "chrome://settings",+ "gopher://127.0.0.1:70/",+ "ftp://internal.example.com/secret",+ ],+ )+ def test_dangerous_non_http_scheme_aborted(self, url):+ """SECURITY (crawl4ai path): every non-http(s) scheme outside the+ data:/blob:/about: allowlist is aborted, never handed to the browser+ via fallback."""+ with patch.object(ssrf_validator, "validate_url") as mock_validate:+ route = _async_route(url)+ asyncio.run(self.dl._crawl4ai_route_guard(route))+ mock_validate.assert_not_called()+ route.abort.assert_awaited_once()+ route.fallback.assert_not_awaited()+ route.fetch.assert_not_awaited()++ def test_heavy_subresource_blocked_for_perf(self):+ route = _async_route(+ "https://cdn.example.com/x.png", resource_type="image"+ )+ with patch.object(ssrf_validator, "validate_url") as mock_validate:+ asyncio.run(self.dl._crawl4ai_route_guard(route))+ mock_validate.assert_not_called()+ route.abort.assert_awaited_once_with()+ route.fetch.assert_not_awaited()++ def test_redirect_target_validated_before_fetch(self):+ """The core property, async twin: redirect target validated + aborted+ before it is fetched; only the entry hop reaches route.fetch."""++ def _side_effect(url, *args, **kwargs):+ return "169.254.169.254" not in url++ route = _async_route(PUBLIC_URL)+ route.fetch.return_value = _FakeAPIResponse(+ 302, {"location": METADATA_URL}+ )+ with patch.object(+ ssrf_validator, "validate_url", side_effect=_side_effect+ ):+ asyncio.run(self.dl._crawl4ai_route_guard(route))+ assert route.fetch.await_count == 1+ route.abort.assert_awaited_once_with("blockedbyclient")+ route.fulfill.assert_not_awaited()++ def test_hop_header_build_failure_aborts_hop(self):+ """Async twin: a header-build failure aborts the hop instead of+ letting the exception escape the route handler or falling through+ to an unguarded fetch."""+ route = _async_route(PUBLIC_URL)+ with (+ patch.object(ssrf_validator, "validate_url", return_value=True),+ patch.object(+ PlaywrightHTMLDownloader,+ "_apply_hop_cookie_header",+ side_effect=RuntimeError("simulated header-build failure"),+ ),+ ):+ asyncio.run(self.dl._crawl4ai_route_guard(route)) # must not raise+ route.fetch.assert_not_awaited()+ route.fulfill.assert_not_awaited()+ route.abort.assert_awaited_once_with("failed")+++# ---------------------------------------------------------------------------+# Crawl4AI mid-redirect Set-Cookie persistence (no browser)+#+# crawl4ai pre-seeds the page context with a marker cookie via+# ``context.add_cookies()`` before navigation (BrowserManager.setup_context).+# Once a context's cookie jar has been touched that way, Playwright's+# ``route.fetch()`` does NOT itself re-derive the "Cookie" request header+# from the context's jar on every call — verified against a real browser+# (see TestCrawl4aiMidRedirectCookieRealBrowser below): within one guard+# invocation it keeps resending the ORIGINALLY intercepted request's Cookie+# header for every subsequent hop, even after ``context.add_cookies()`` has+# just added a brand-new cookie to the jar. So ``_reapply_hop_cookies`` does+# two things for every hop that carries a Set-Cookie: (1) applies it to the+# context via ``add_cookies()`` — keeping the jar itself correct for+# anything that reads it independently of this walk — and (2) reads the+# jar back via ``context.cookies(next_hop_url)`` and returns an explicit+# "Cookie" header string that the caller passes to the NEXT hop's+# ``route.fetch(headers=...)``, which is what actually makes that next+# request carry it. The plain-Playwright path has no such pre-seed, so+# Playwright DOES merge each hop's Set-Cookie into its own jar there — but+# ``route.fetch()`` STILL resends the ORIGINALLY intercepted request's Cookie+# header to every subsequent hop, so the SAME cross-domain leak exists on the+# sync path and its guard now applies the SAME per-hop re-scoping via+# ``_reapply_hop_cookies_sync`` (see the plain-path tests below).+# ---------------------------------------------------------------------------+++class TestCrawl4aiMidRedirectCookiePersistence:+ def setup_method(self):+ self.dl = PlaywrightHTMLDownloader(timeout=5)++ def teardown_method(self):+ self.dl.close()++ def test_set_cookie_on_redirect_hop_applied_before_next_fetch(self):+ """A 302 hop that sets ``Set-Cookie: session=X`` must have that+ cookie (a) applied to the context and (b) present as an explicit+ Cookie header on the NEXT hop's route.fetch() call — both BEFORE+ that next hop is fetched, not just after the chain terminates.++ Only mocking context.add_cookies (and not context.cookies, which+ the real fix also depends on — see the module docstring above)+ would let this test pass on a build that calls add_cookies but+ never actually gets the cookie onto the next request; that gap is+ exactly what regressed against a real browser during development+ of this fix, so context.cookies is mocked and asserted on too.+ """+ final_target = "https://example.com/final"+ call_order = []+ responses = [+ _FakeAPIResponse(+ 302,+ headers={"location": final_target},+ headers_array=[+ {"name": "Location", "value": final_target},+ {"name": "Set-Cookie", "value": "session=X; Path=/"},+ ],+ ),+ _FakeAPIResponse(200),+ ]++ def _fetch_side_effect(*args, **kwargs):+ call_order.append(+ ("fetch", kwargs.get("url"), kwargs.get("headers"))+ )+ return responses.pop(0)++ async def _add_cookies_side_effect(cookies):+ call_order.append(("add_cookies", cookies))++ async def _cookies_side_effect(url):+ call_order.append(("cookies", url))+ return [{"name": "session", "value": "X"}]++ route = _async_route(PUBLIC_URL)+ route.fetch = AsyncMock(side_effect=_fetch_side_effect)+ context = route.request.frame.page.context+ context.add_cookies = AsyncMock(side_effect=_add_cookies_side_effect)+ context.cookies = AsyncMock(side_effect=_cookies_side_effect)++ with patch.object(ssrf_validator, "validate_url", return_value=True):+ asyncio.run(self.dl._crawl4ai_route_guard(route))++ assert route.fetch.await_count == 2+ context.add_cookies.assert_awaited_once_with(+ [+ {+ "name": "session",+ "value": "X",+ "domain": "example.com",+ "path": "/",+ }+ ]+ )+ context.cookies.assert_awaited_once_with(final_target)+ # THE core property: the SECOND route.fetch() call (the next hop)+ # must explicitly carry the refreshed Cookie header.+ second_fetch_headers = route.fetch.await_args_list[1].kwargs.get(+ "headers"+ )+ assert second_fetch_headers is not None+ assert second_fetch_headers.get("cookie") == "session=X"+ # And the FIRST fetch (before any cookie was known) must NOT have+ # been given a synthetic cookie header.+ assert "headers" not in route.fetch.await_args_list[0].kwargs+ # Ordering: add_cookies and cookies both happen strictly between+ # the entry-hop fetch and the redirect-target fetch.+ assert call_order == [+ ("fetch", PUBLIC_URL, None),+ (+ "add_cookies",+ [+ {+ "name": "session",+ "value": "X",+ "domain": "example.com",+ "path": "/",+ }+ ],+ ),+ ("cookies", final_target),+ (+ "fetch",+ final_target,+ {**route.request.headers, "cookie": "session=X"},+ ),+ ]+ route.fulfill.assert_awaited_once()++ def test_no_set_cookie_header_still_rederives_and_clears_next_hop(self):+ """With no Set-Cookie on any hop, the jar is never written+ (add_cookies is not called), but the next hop's Cookie header is+ STILL re-derived from the context jar scoped to that hop — and when+ the jar holds nothing for it, the next hop's fetch carries no+ (leaked) Cookie. Re-deriving unconditionally is what stops the+ originally-intercepted request's Cookie header from riding along to+ a cross-domain hop."""+ final_target = "https://example.com/final"+ route = _async_route(PUBLIC_URL)+ route.fetch.side_effect = [+ _FakeAPIResponse(302, {"location": final_target}),+ _FakeAPIResponse(200),+ ]+ context = route.request.frame.page.context+ context.add_cookies = AsyncMock()+ context.cookies = AsyncMock(return_value=[])++ with patch.object(ssrf_validator, "validate_url", return_value=True):+ asyncio.run(self.dl._crawl4ai_route_guard(route))++ # Nothing to add (no Set-Cookie anywhere) ...+ context.add_cookies.assert_not_awaited()+ # ... but the next hop's Cookie header is re-derived from the jar+ # (scoped to that hop) on every redirect — not carried over blindly.+ context.cookies.assert_awaited_once_with(final_target)+ # The jar holds nothing for the next hop, so its fetch carries no+ # leaked Cookie.+ next_headers = (+ route.fetch.await_args_list[1].kwargs.get("headers") or {}+ )+ assert not next_headers.get("cookie")++ def test_multiple_set_cookie_headers_all_applied(self):+ """Multiple Set-Cookie headers on one hop (the common case: a session+ cookie plus a CSRF token) must ALL be applied, not just the first —+ proving headers_array is used instead of the ``headers`` dict, which+ would collapse duplicates — and both must end up in the next hop's+ explicit Cookie header."""+ final_target = "https://example.com/final"+ route = _async_route(PUBLIC_URL)+ route.fetch.side_effect = [+ _FakeAPIResponse(+ 302,+ headers={"location": final_target},+ headers_array=[+ {"name": "Location", "value": final_target},+ {"name": "Set-Cookie", "value": "session=X; Path=/"},+ {"name": "Set-Cookie", "value": "csrf=Y; Path=/"},+ ],+ ),+ _FakeAPIResponse(200),+ ]+ context = route.request.frame.page.context+ context.add_cookies = AsyncMock()+ context.cookies = AsyncMock(+ return_value=[+ {"name": "session", "value": "X"},+ {"name": "csrf", "value": "Y"},+ ]+ )++ with patch.object(ssrf_validator, "validate_url", return_value=True):+ asyncio.run(self.dl._crawl4ai_route_guard(route))++ applied = context.add_cookies.await_args.args[0]+ names = {c["name"]: c["value"] for c in applied}+ assert names == {"session": "X", "csrf": "Y"}++ second_fetch_headers = route.fetch.await_args_list[1].kwargs.get(+ "headers"+ )+ assert second_fetch_headers.get("cookie") == "session=X; csrf=Y"++ def test_cookie_apply_failure_does_not_break_the_redirect_chain(self):+ """Fail-open: if applying the cookie raises (e.g. a Playwright API+ error), the redirect chain still completes normally rather than+ aborting the whole fetch — this is a content-fidelity fix, not a+ security control."""+ final_target = "https://example.com/final"+ route = _async_route(PUBLIC_URL)+ route.fetch.side_effect = [+ _FakeAPIResponse(+ 302,+ headers={"location": final_target},+ headers_array=[+ {"name": "Location", "value": final_target},+ {"name": "Set-Cookie", "value": "session=X; Path=/"},+ ],+ ),+ _FakeAPIResponse(200),+ ]+ route.request.frame.page.context.add_cookies = AsyncMock(+ side_effect=RuntimeError("simulated Playwright API failure")+ )++ with patch.object(ssrf_validator, "validate_url", return_value=True):+ asyncio.run(self.dl._crawl4ai_route_guard(route))++ assert route.fetch.await_count == 2+ route.fulfill.assert_awaited_once()+ route.abort.assert_not_awaited()+ # Fail-SAFE: the next hop must carry NO cookie (explicitly cleared),+ # never a half-computed or stale one that could leak cross-domain.+ next_headers = (+ route.fetch.await_args_list[1].kwargs.get("headers") or {}+ )+ assert not next_headers.get("cookie")++ def test_cookies_lookup_failure_does_not_break_the_redirect_chain(self):+ """Fail-open twin: add_cookies succeeds but the follow-up+ context.cookies() read raises — the chain still completes and the+ next hop simply falls back to no synthetic Cookie header rather than+ aborting."""+ final_target = "https://example.com/final"+ route = _async_route(PUBLIC_URL)+ route.fetch.side_effect = [+ _FakeAPIResponse(+ 302,+ headers={"location": final_target},+ headers_array=[+ {"name": "Location", "value": final_target},+ {"name": "Set-Cookie", "value": "session=X; Path=/"},+ ],+ ),+ _FakeAPIResponse(200),+ ]+ context = route.request.frame.page.context+ context.add_cookies = AsyncMock()+ context.cookies = AsyncMock(+ side_effect=RuntimeError("simulated Playwright API failure")+ )++ with patch.object(ssrf_validator, "validate_url", return_value=True):+ asyncio.run(self.dl._crawl4ai_route_guard(route))++ assert route.fetch.await_count == 2+ route.fulfill.assert_awaited_once()+ route.abort.assert_not_awaited()+ # Fail-SAFE: a failed jar read clears the next hop's Cookie rather+ # than letting a previous (possibly cross-domain) one ride along.+ next_headers = (+ route.fetch.await_args_list[1].kwargs.get("headers") or {}+ )+ assert not next_headers.get("cookie")++ def test_cross_domain_redirect_does_not_leak_cookie(self):+ """SECURITY: a cookie set mid-redirect on domain A must NOT be sent to+ a DIFFERENT domain B that a later hop redirects to.++ Chain: A/a sets ``session=SECRET`` and 302s to A/b (same domain), so+ the guard picks the cookie up into the per-hop Cookie override; A/b+ then 302s cross-domain to B/landing (which sets no cookie). B's+ request must NOT carry ``session=SECRET`` — a real browser scopes the+ cookie to A and never sends it to B. ``context.cookies`` is modelled+ as a real domain-scoped jar (Playwright scopes by domain/path), so+ the guard's re-derivation is what has to keep B clean.++ This is the regression lock: reverting the fix (restoring the+ ``existing_cookie_header`` fallbacks in ``_reapply_hop_cookies``) makes+ the override ride from A across to B and this assertion fails.+ """+ a_first = "https://example.com/a"+ a_second = "https://example.com/b"+ b_url = "https://evil.example.net/landing"+ route = _async_route(a_first)+ route.fetch.side_effect = [+ _FakeAPIResponse(+ 302,+ headers={"location": a_second},+ headers_array=[+ {"name": "Location", "value": a_second},+ {"name": "Set-Cookie", "value": "session=SECRET; Path=/"},+ ],+ ),+ _FakeAPIResponse(302, {"location": b_url}), # A/b -> B, no cookie+ _FakeAPIResponse(200), # B/landing, sets nothing+ ]++ # A realistic domain-scoped cookie jar: context.cookies(url) returns+ # only cookies whose domain domain-matches the queried URL's host,+ # exactly as Playwright/Chromium does.+ jar: list[dict] = []++ async def _add(cookies):+ jar.extend(cookies)++ async def _cookies(url):+ host = (urlparse(url).hostname or "").lower()+ out = []+ for c in jar:+ dom = c["domain"].lower().lstrip(".")+ if host == dom or host.endswith("." + dom):+ out.append({"name": c["name"], "value": c["value"]})+ return out++ context = route.request.frame.page.context+ context.add_cookies = AsyncMock(side_effect=_add)+ context.cookies = AsyncMock(side_effect=_cookies)++ with patch.object(ssrf_validator, "validate_url", return_value=True):+ asyncio.run(self.dl._crawl4ai_route_guard(route))++ assert route.fetch.await_count == 3+ # The same-domain hop (A/b) DID receive the cookie ...+ a_second_headers = (+ route.fetch.await_args_list[1].kwargs.get("headers") or {}+ )+ assert a_second_headers.get("cookie") == "session=SECRET"+ # ... but the cross-domain hop (B) must NOT.+ b_headers = route.fetch.await_args_list[2].kwargs.get("headers") or {}+ assert "SECRET" not in (b_headers.get("cookie") or ""), (+ "cross-domain cookie leak: domain A's cookie reached domain B"+ )+ assert not b_headers.get("cookie")+ route.fulfill.assert_awaited_once()++ def test_sync_path_rescopes_cookies_per_hop(self):+ """The plain-Playwright (sync) guard now re-scopes cookies per hop+ exactly like the crawl4ai path: a 302 that sets ``Set-Cookie`` is+ applied to the context AND re-derived (from the jar scoped to the+ next hop) into an explicit Cookie header on the next hop's+ route.fetch() — both BEFORE that next hop is fetched.++ This is the sync twin of+ ``test_set_cookie_on_redirect_hop_applied_before_next_fetch`` and+ replaces the old ``test_sync_playwright_path_unaffected`` control,+ which asserted the (now-fixed) leaky behavior.+ """+ final_target = "https://example.com/final"+ call_order = []+ responses = [+ _FakeAPIResponse(+ 302,+ headers={"location": final_target},+ headers_array=[+ {"name": "Location", "value": final_target},+ {"name": "Set-Cookie", "value": "session=X; Path=/"},+ ],+ ),+ _FakeAPIResponse(200),+ ]+ expected_cookie = {+ "name": "session",+ "value": "X",+ "domain": "example.com",+ "path": "/",+ }++ def _fetch_side_effect(*args, **kwargs):+ call_order.append(+ ("fetch", kwargs.get("url"), kwargs.get("headers"))+ )+ return responses.pop(0)++ def _add_cookies(cookies):+ call_order.append(("add_cookies", cookies))++ def _cookies(url):+ call_order.append(("cookies", url))+ return [{"name": "session", "value": "X"}]++ route = _sync_route(PUBLIC_URL)+ route.request.headers = {}+ route.fetch = MagicMock(side_effect=_fetch_side_effect)+ context = route.request.frame.page.context+ context.add_cookies = MagicMock(side_effect=_add_cookies)+ context.cookies = MagicMock(side_effect=_cookies)++ with patch.object(ssrf_validator, "validate_url", return_value=True):+ self.dl._playwright_route_guard(route)++ assert route.fetch.call_count == 2+ context.add_cookies.assert_called_once_with([expected_cookie])+ context.cookies.assert_called_once_with(final_target)+ # The FIRST fetch (before any cookie was known) must NOT be given a+ # synthetic cookie header.+ assert "headers" not in route.fetch.call_args_list[0].kwargs+ # The SECOND fetch (the next hop) must explicitly carry the refreshed+ # Cookie header.+ second_headers = route.fetch.call_args_list[1].kwargs.get("headers")+ assert second_headers is not None+ assert second_headers.get("cookie") == "session=X"+ # Ordering: add_cookies and cookies both happen strictly between the+ # entry-hop fetch and the redirect-target fetch.+ assert call_order == [+ ("fetch", PUBLIC_URL, None),+ ("add_cookies", [expected_cookie]),+ ("cookies", final_target),+ ("fetch", final_target, {"cookie": "session=X"}),+ ]+ route.fulfill.assert_called_once()++ def test_sync_cross_domain_redirect_does_not_leak_cookie(self):+ """SECURITY (plain-Playwright path): a cookie set mid-redirect on+ domain A — AND the ORIGINAL intercepted request's own Cookie header —+ must NOT be forwarded to a DIFFERENT domain B a later hop redirects+ to.++ This is the regression lock the old ``test_sync_playwright_path_+ unaffected`` could not provide: that test drove ``route.fetch`` with a+ request carrying NO Cookie header, so it could not observe the leak+ where ``route.fetch`` resends the intercepted request's Cookie header+ verbatim to every hop. Here the intercepted request carries+ ``orig=INTERCEPTED`` and hop A sets ``session=SECRET``; the+ domain-scoped jar re-derivation must keep cross-domain hop B clean of+ both.+ """+ a_first = "https://example.com/a"+ a_second = "https://example.com/b"+ b_url = "https://evil.example.net/landing"+ route = _sync_route(a_first)+ # The intercepted request already carries a Cookie header — the gap+ # the old control test could not catch.+ route.request.headers = {"cookie": "orig=INTERCEPTED", "accept": "*/*"}+ route.fetch.side_effect = [+ _FakeAPIResponse(+ 302,+ headers={"location": a_second},+ headers_array=[+ {"name": "Location", "value": a_second},+ {"name": "Set-Cookie", "value": "session=SECRET; Path=/"},+ ],+ ),+ _FakeAPIResponse(302, {"location": b_url}), # A/b -> B, no cookie+ _FakeAPIResponse(200), # B/landing, sets nothing+ ]++ # A realistic domain-scoped cookie jar (Playwright scopes by+ # domain/path), so the guard's re-derivation is what keeps B clean.+ jar: list[dict] = []++ def _add(cookies):+ jar.extend(cookies)++ def _cookies(url):+ host = (urlparse(url).hostname or "").lower()+ out = []+ for c in jar:+ dom = c["domain"].lower().lstrip(".")+ if host == dom or host.endswith("." + dom):+ out.append({"name": c["name"], "value": c["value"]})+ return out++ context = route.request.frame.page.context+ context.add_cookies = MagicMock(side_effect=_add)+ context.cookies = MagicMock(side_effect=_cookies)++ with patch.object(ssrf_validator, "validate_url", return_value=True):+ self.dl._playwright_route_guard(route)++ assert route.fetch.call_count == 3+ # The same-domain hop (A/b) DID receive the mid-chain cookie, and the+ # intercepted request's original Cookie header was replaced (not+ # merged) — so orig=INTERCEPTED does not ride along even same-domain.+ a_second_headers = (+ route.fetch.call_args_list[1].kwargs.get("headers") or {}+ )+ assert a_second_headers.get("cookie") == "session=SECRET"+ # The cross-domain hop (B) must carry NEITHER the mid-chain cookie NOR+ # the intercepted request's original Cookie header.+ b_headers = route.fetch.call_args_list[2].kwargs.get("headers") or {}+ assert not b_headers.get("cookie"), (+ "cross-domain cookie leak on the plain-Playwright path"+ )+ assert "SECRET" not in (b_headers.get("cookie") or "")+ assert "INTERCEPTED" not in (b_headers.get("cookie") or "")+ route.fulfill.assert_called_once()+++# ---------------------------------------------------------------------------+# _apply_hop_cookie_header: Authorization / Proxy-Authorization stripping+# ---------------------------------------------------------------------------+++class TestApplyHopHeaderCredentialStripping:+ """A browser strips ``Authorization`` on a cross-origin redirect; the guard+ must do the same for the credentials the original intercepted request+ carried, alongside the per-hop ``Cookie`` re-scoping — without breaking+ same-site auth redirects."""++ @staticmethod+ def _apply(+ request_url: str,+ hop_url: str,+ *,+ method: str = "GET",+ extra_headers: dict | None = None,+ ) -> dict:+ request = MagicMock()+ request.url = request_url+ headers = {+ "authorization": "Bearer SECRET",+ "proxy-authorization": "Basic UFJPWFk=",+ "accept": "*/*",+ "cookie": "orig=INTERCEPTED",+ # A stale Host from the ORIGINAL request and a Content-Length from+ # the original (possibly POST) body — both must be dropped so the+ # hop derives its own Host/Content-Length from the target + body.+ "host": urlparse(request_url).netloc,+ "content-length": "1234",+ }+ if extra_headers:+ headers.update(extra_headers)+ request.headers = headers+ fetch_kwargs = {"url": hop_url, "method": method}+ # A non-None cookie override is what marks a post-first hop (the first+ # hop keeps the original headers untouched); "" clears the Cookie.+ PlaywrightHTMLDownloader._apply_hop_cookie_header(+ request, fetch_kwargs, ""+ )+ return fetch_kwargs["headers"]++ def test_authorization_dropped_cross_site(self):+ """SECURITY: on a hop to a DIFFERENT registrable domain, both+ Authorization and Proxy-Authorization are removed so the original+ origin's credentials never reach the other domain."""+ headers = self._apply(+ "https://example.com/a", "https://evil.example.net/landing"+ )+ assert "authorization" not in headers+ assert "proxy-authorization" not in headers+ # Non-credential headers are preserved; Cookie was cleared.+ assert headers.get("accept") == "*/*"+ assert "cookie" not in headers++ def test_authorization_kept_same_site(self):+ """A within-site hop (subdomain of the same registrable domain) keeps+ Authorization so legitimate auth redirects still work."""+ headers = self._apply(+ "https://example.com/a", "https://api.example.com/token"+ )+ assert headers.get("authorization") == "Bearer SECRET"+ assert headers.get("proxy-authorization") == "Basic UFJPWFk="++ def test_authorization_kept_same_host(self):+ """The trivial same-host hop keeps the credentials."""+ headers = self._apply("https://example.com/a", "https://example.com/b")+ assert headers.get("authorization") == "Bearer SECRET"++ def test_host_dropped_cross_host_hop(self):+ """SECURITY/CORRECTNESS: a cross-host hop must NOT forward the original+ request's Host; route.fetch() derives the correct Host from the target+ URL once the header is absent (a stale forwarded Host would be wrong)."""+ headers = self._apply(+ "https://example.com/a", "https://other.example.net/landing"+ )+ assert "host" not in {k.lower() for k in headers}++ def test_host_dropped_same_registrable_site_different_host(self):+ """Even a same-registrable-site hop to a DIFFERENT host (api.example.com+ -> example.com) must drop the original Host so it is re-derived; keeping+ it would send api.example.com's Host to example.com."""+ headers = self._apply(+ "https://api.example.com/a", "https://example.com/b"+ )+ assert "host" not in {k.lower() for k in headers}++ def test_host_dropped_same_host_hop(self):+ """The trivial same-host hop also drops Host — route.fetch() re-derives+ the identical value from the target, so nothing is lost."""+ headers = self._apply("https://example.com/a", "https://example.com/b")+ assert "host" not in {k.lower() for k in headers}++ def test_host_dropped_case_insensitive(self):+ """A mixed-case ``Host`` header is dropped too (case-insensitive)."""+ headers = self._apply(+ "https://example.com/a",+ "https://other.example.net/b",+ extra_headers={"Host": "example.com"},+ )+ assert "host" not in {k.lower() for k in headers}++ def test_content_length_dropped_after_post_to_get_downgrade(self):+ """CORRECTNESS: after a POST->GET downgrade the body is dropped to "",+ so the original Content-Length is wrong and must not be forwarded;+ route.fetch() recomputes it from the actual body."""+ headers = self._apply(+ "https://example.com/a",+ "https://example.com/landing",+ method="GET", # downgraded from the original POST+ extra_headers={"content-length": "4096"},+ )+ assert "content-length" not in {k.lower() for k in headers}++ def test_content_length_dropped_case_insensitive_cross_host(self):+ """A mixed-case ``Content-Length`` is dropped on a cross-host hop."""+ headers = self._apply(+ "https://example.com/a",+ "https://other.example.net/landing",+ extra_headers={"Content-Length": "4096"},+ )+ assert "content-length" not in {k.lower() for k in headers}+ # Non-credential, non-hop-specific headers still survive the rebuild.+ assert headers.get("accept") == "*/*"+++# ---------------------------------------------------------------------------+# _fetch_html entry-URL scheme guard (fail-closed, no browser)+# ---------------------------------------------------------------------------+++class TestEntryUrlSchemeGuard:+ """``_fetch_html`` refuses a non-http(s) entry URL before any navigation,+ so a top-level file:// (or other local/internal scheme) can never be+ opened and returned as page content."""++ @pytest.mark.parametrize(+ "url",+ [+ "file:///etc/passwd",+ "chrome://settings",+ "gopher://127.0.0.1:70/",+ "FILE:///etc/passwd",+ ],+ )+ def test_non_http_entry_url_refused_without_navigating(self, url):+ dl = PlaywrightHTMLDownloader(timeout=5)+ dl._fetch_with_crawl4ai = MagicMock()+ dl._fetch_with_playwright = MagicMock()+ try:+ assert dl._fetch_html(url) is None+ finally:+ dl.close()+ dl._fetch_with_crawl4ai.assert_not_called()+ dl._fetch_with_playwright.assert_not_called()++ def test_http_entry_url_proceeds(self):+ """Control: an http(s) entry URL is NOT short-circuited by the guard+ (it reaches the crawl4ai path)."""+ dl = PlaywrightHTMLDownloader(timeout=5)+ dl._fetch_with_crawl4ai = MagicMock(return_value="<html>ok</html>")+ dl._fetch_with_playwright = MagicMock()+ try:+ assert dl._fetch_html("https://example.com/page") == (+ "<html>ok</html>"+ )+ finally:+ dl.close()+ dl._fetch_with_crawl4ai.assert_called_once()+++# ---------------------------------------------------------------------------+# _cookies_from_response: Set-Cookie Domain-attribute validation (no browser)+# ---------------------------------------------------------------------------+++class TestCookiesFromResponseDomainScoping:+ """``_cookies_from_response`` must honor a Set-Cookie ``Domain=`` only when+ it domain-matches the response host (RFC 6265 / browser behavior), else+ fall back to host-scoping — closing a session-fixation vector where a+ redirect hop plants a cookie scoped to a DIFFERENT registrable domain."""++ def _parse(self, set_cookie_value: str, response_url: str) -> list:+ resp = _FakeAPIResponse(+ 200,+ headers_array=[{"name": "Set-Cookie", "value": set_cookie_value}],+ )+ return PlaywrightHTMLDownloader._cookies_from_response(+ resp, response_url+ )++ def test_cross_domain_domain_attribute_rejected(self):+ """A Domain= pointing at an unrelated registrable domain is rejected;+ the cookie is scoped to the response host instead."""+ cookies = self._parse(+ "session=SECRET; Domain=evil.example.net; Path=/",+ "https://example.com/page",+ )+ assert len(cookies) == 1+ assert cookies[0]["domain"] == "example.com"+ assert cookies[0]["domain"] != "evil.example.net"++ def test_sibling_subdomain_domain_attribute_rejected(self):+ """A Domain= for a sibling subdomain (host is not within it) is+ rejected and falls back to the response host."""+ cookies = self._parse(+ "session=SECRET; Domain=b.example.com; Path=/",+ "https://a.example.com/page",+ )+ assert cookies[0]["domain"] == "a.example.com"++ def test_parent_domain_attribute_honored(self):+ """A Domain= for a parent domain (host IS a subdomain of it) is a+ legitimate domain-match and is honored."""+ cookies = self._parse(+ "session=OK; Domain=example.com; Path=/",+ "https://sub.example.com/page",+ )+ assert cookies[0]["domain"] == "example.com"++ def test_leading_dot_domain_attribute_honored(self):+ """A leading dot on a matching Domain= is ignored (RFC 6265) and the+ cookie is still honored."""+ cookies = self._parse(+ "session=OK; Domain=.example.com; Path=/",+ "https://example.com/page",+ )+ assert cookies[0]["domain"] in (".example.com", "example.com")++ def test_no_domain_attribute_scopes_to_host(self):+ """No Domain= at all -> host-scoped (unchanged behavior)."""+ cookies = self._parse("session=OK; Path=/", "https://example.com/page")+ assert cookies[0]["domain"] == "example.com"+++# ---------------------------------------------------------------------------+# _cookies_from_response: expiry honoring + non-token cookie names (no browser)+# ---------------------------------------------------------------------------+++class TestCookiesFromResponseExpiryAndNames:+ """``_cookies_from_response`` must (1) NOT re-apply a Set-Cookie that is+ really a DELETION directive (``Max-Age=0`` / past ``Expires``) — otherwise+ a cookie the server just cleared would be resurrected onto the jar — and+ (2) still parse cookie names that ``SimpleCookie`` rejects (e.g.+ ``data[uid]``) rather than silently dropping them."""++ def _parse(self, set_cookie_value: str, response_url: str) -> list:+ resp = _FakeAPIResponse(+ 200,+ headers_array=[{"name": "Set-Cookie", "value": set_cookie_value}],+ )+ return PlaywrightHTMLDownloader._cookies_from_response(+ resp, response_url+ )++ def test_max_age_zero_cookie_not_readded(self):+ """A ``Max-Age=0`` deletion cookie is honored and NOT re-added."""+ cookies = self._parse(+ "session=deleted; Max-Age=0; Path=/",+ "https://example.com/page",+ )+ assert cookies == []++ def test_negative_max_age_cookie_not_readded(self):+ """A negative Max-Age is also a deletion and NOT re-added."""+ cookies = self._parse(+ "session=deleted; Max-Age=-1; Path=/",+ "https://example.com/page",+ )+ assert cookies == []++ def test_past_expires_cookie_not_readded(self):+ """A past ``Expires`` is a deletion and NOT re-added."""+ cookies = self._parse(+ "session=deleted; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Path=/",+ "https://example.com/page",+ )+ assert cookies == []++ def test_positive_max_age_cookie_readded(self):+ """A live positive ``Max-Age`` cookie is still applied."""+ cookies = self._parse(+ "session=live; Max-Age=3600; Path=/",+ "https://example.com/page",+ )+ assert len(cookies) == 1+ assert cookies[0]["name"] == "session"+ assert cookies[0]["value"] == "live"++ def test_future_expires_cookie_readded(self):+ """A future ``Expires`` cookie is still applied."""+ cookies = self._parse(+ "session=live; Expires=Tue, 01 Jan 2999 00:00:00 GMT; Path=/",+ "https://example.com/page",+ )+ assert len(cookies) == 1+ assert cookies[0]["value"] == "live"++ def test_bracketed_cookie_name_parsed_not_dropped(self):+ """A cookie name SimpleCookie rejects (``data[uid]``, which browsers+ accept) is parsed rather than silently dropped."""+ cookies = self._parse(+ "data[uid]=42; Path=/",+ "https://example.com/page",+ )+ assert len(cookies) == 1+ assert cookies[0]["name"] == "data[uid]"+ assert cookies[0]["value"] == "42"+ assert cookies[0]["domain"] == "example.com"++ def test_secure_and_httponly_flags_preserved(self):+ """Secure / HttpOnly flag attributes survive the manual parse."""+ cookies = self._parse(+ "session=X; Path=/; Secure; HttpOnly",+ "https://example.com/page",+ )+ assert cookies[0].get("secure") is True+ assert cookies[0].get("httpOnly") is True++ def test_malformed_header_never_raises(self):+ """A header with no name=value pair is skipped, never raised."""+ cookies = self._parse("; Path=/", "https://example.com/page")+ assert cookies == []+++# ---------------------------------------------------------------------------+# Crawl4AI hook wiring + fail-safe (no real browser)+# ---------------------------------------------------------------------------+++class _FakeStrategy:+ def __init__(self):+ self.hooks = {}++ def set_hook(self, hook_type, hook):+ self.hooks[hook_type] = hook+++class _RaisingStrategy:+ def set_hook(self, hook_type, hook):+ raise RuntimeError("simulated: set_hook API unavailable")+++def _fake_crawler_factory(created, strategy_cls):+ class _FakeCrawler:+ def __init__(self, *args, **kwargs):+ self.crawler_strategy = strategy_cls()+ self.arun_called = False+ created.append(self)++ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return False++ async def arun(self, url, config):+ self.arun_called = True+ result = MagicMock()+ result.success = True+ result.html = "<html><body>ok</body></html>"+ return result++ return _FakeCrawler+++def _hook_invoking_crawler_factory(+ created, *, ws_raises=False, sw_raises=False+):+ """A fake crawler whose ``arun`` FIRES the registered on_page_context_created+ hook (as real crawl4ai does), with a context whose ``route_web_socket`` /+ ``add_init_script`` optionally raise — mirroring crawl4ai's ``execute_hook``,+ which does NOT swallow hook exceptions."""++ class _HookInvokingCrawler:+ def __init__(self, *args, **kwargs):+ self.crawler_strategy = _FakeStrategy()+ self.arun_called = False+ self.hook_completed = False+ created.append(self)++ async def __aenter__(self):+ return self++ async def __aexit__(self, *args):+ return False++ async def arun(self, url, config):+ self.arun_called = True+ hook = self.crawler_strategy.hooks.get("on_page_context_created")+ ctx = MagicMock()+ ctx.route = AsyncMock()+ ctx.route_web_socket = AsyncMock(+ side_effect=RuntimeError("no route_web_socket API")+ if ws_raises+ else None+ )+ ctx.add_init_script = AsyncMock(+ side_effect=RuntimeError("no add_init_script API")+ if sw_raises+ else None+ )+ # crawl4ai's execute_hook awaits the hook and does not catch —+ # a raise here propagates out of arun.+ await hook(MagicMock(), context=ctx, config=None)+ self.hook_completed = True+ result = MagicMock()+ result.success = True+ result.html = "<html><body>ok</body></html>"+ return result++ return _HookInvokingCrawler+++class TestCrawl4aiGuardInstallation:+ """The crawl4ai path installs the guard via the on_page_context_created+ hook, and a hook-install failure is fail-safe."""++ def _downloader(self):+ dl = PlaywrightHTMLDownloader(timeout=5)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ # Stub the guarded robots.txt check so the crawl4ai path does not+ # make a live network request in these hook-wiring tests. The robots+ # guard itself is covered by TestGuardedRobots.+ dl._robots_allows = MagicMock(return_value=True)+ return dl++ def test_hook_installs_guard_ws_and_sw_block(self):+ crawl4ai = pytest.importorskip("crawl4ai")++ created: list = []+ dl = self._downloader()+ try:+ with patch.object(+ crawl4ai,+ "AsyncWebCrawler",+ _fake_crawler_factory(created, _FakeStrategy),+ ):+ html = dl._fetch_with_crawl4ai("https://example.com")+ finally:+ dl.close()++ assert html == "<html><body>ok</body></html>"+ assert len(created) == 1+ crawler = created[0]+ assert crawler.arun_called is True+ hook = crawler.crawler_strategy.hooks.get("on_page_context_created")+ assert hook is not None++ # Invoking the hook must install the HTTP guard, the WebSocket block,+ # and the Service-Worker + WebRTC neutralizer init scripts on the+ # page context.+ ctx = MagicMock()+ ctx.route = AsyncMock()+ ctx.route_web_socket = AsyncMock()+ ctx.add_init_script = AsyncMock()+ page = MagicMock()+ asyncio.run(hook(page, context=ctx, config=None))++ ctx.route.assert_awaited_once()+ pattern, handler = ctx.route.await_args.args+ assert pattern == "**/*"+ assert handler == dl._crawl4ai_route_guard++ ctx.route_web_socket.assert_awaited_once()+ ws_pattern, ws_handler = ctx.route_web_socket.await_args.args+ assert ws_pattern == "**/*"+ assert ws_handler == dl._crawl4ai_ws_guard++ # Both the Service-Worker and WebRTC neutralizer init scripts install.+ from local_deep_research.research_library.downloaders.playwright_html import ( # noqa: E501+ _DISABLE_SERVICE_WORKERS_JS,+ _DISABLE_WEBRTC_JS,+ )++ assert ctx.add_init_script.await_count == 2+ installed = [c.args[0] for c in ctx.add_init_script.await_args_list]+ assert _DISABLE_SERVICE_WORKERS_JS in installed+ assert _DISABLE_WEBRTC_JS in installed++ def test_robots_disallow_returns_skip_signal(self):+ """When the guarded robots check disallows, _fetch_with_crawl4ai+ returns "" (intentional skip) and never constructs a crawler."""+ crawl4ai = pytest.importorskip("crawl4ai")++ created: list = []+ dl = self._downloader()+ dl._robots_allows = MagicMock(return_value=False)+ try:+ with patch.object(+ crawl4ai,+ "AsyncWebCrawler",+ _fake_crawler_factory(created, _FakeStrategy),+ ):+ html = dl._fetch_with_crawl4ai("https://example.com")+ finally:+ dl.close()++ assert html == ""+ assert created == [] # no crawler built, no navigation++ def test_hook_install_failure_is_failsafe(self):+ """If set_hook raises, _fetch_with_crawl4ai returns None (-> guarded+ Playwright fallback) and NEVER navigates unguarded."""+ crawl4ai = pytest.importorskip("crawl4ai")++ created: list = []+ dl = self._downloader()+ try:+ with patch.object(+ crawl4ai,+ "AsyncWebCrawler",+ _fake_crawler_factory(created, _RaisingStrategy),+ ):+ html = dl._fetch_with_crawl4ai("https://example.com")+ finally:+ dl.close()++ assert html is None+ assert len(created) == 1+ assert created[0].arun_called is False++ def test_ws_guard_install_failure_is_failsafe(self):+ """If installing the WebSocket guard raises inside the hook, the crawl+ is abandoned fail-CLOSED: _fetch_with_crawl4ai returns None (-> guarded+ plain-Playwright fallback) and never yields an unguarded page."""+ crawl4ai = pytest.importorskip("crawl4ai")++ created: list = []+ dl = self._downloader()+ try:+ with patch.object(+ crawl4ai,+ "AsyncWebCrawler",+ _hook_invoking_crawler_factory(created, ws_raises=True),+ ):+ html = dl._fetch_with_crawl4ai("https://example.com")+ finally:+ dl.close()++ assert html is None+ assert len(created) == 1+ # The hook fired (arun ran) but raised before completing — no page+ # was returned with a missing WebSocket guard.+ assert created[0].hook_completed is False++ def test_sw_neutralizer_install_failure_is_failsafe(self):+ """Same fail-CLOSED behaviour when the Service-Worker-disable init+ script cannot be installed."""+ crawl4ai = pytest.importorskip("crawl4ai")++ created: list = []+ dl = self._downloader()+ try:+ with patch.object(+ crawl4ai,+ "AsyncWebCrawler",+ _hook_invoking_crawler_factory(created, sw_raises=True),+ ):+ html = dl._fetch_with_crawl4ai("https://example.com")+ finally:+ dl.close()++ assert html is None+ assert len(created) == 1+ assert created[0].hook_completed is False++ def test_all_guards_install_lets_crawl_proceed(self):+ """Control: when every guard installs cleanly, the hook completes and+ the crawl proceeds (proves the fail-safe tests aren't vacuous)."""+ crawl4ai = pytest.importorskip("crawl4ai")++ created: list = []+ dl = self._downloader()+ try:+ with patch.object(+ crawl4ai,+ "AsyncWebCrawler",+ _hook_invoking_crawler_factory(created),+ ):+ html = dl._fetch_with_crawl4ai("https://example.com")+ finally:+ dl.close()++ assert html == "<html><body>ok</body></html>"+ assert created[0].hook_completed is True+++# ---------------------------------------------------------------------------+# Real-browser integration test (skipped when Chromium is absent)+# ---------------------------------------------------------------------------+++def _chromium_available() -> bool:+ try:+ from playwright.sync_api import sync_playwright+ except Exception:+ return False+ try:+ with sync_playwright() as p:+ path = p.chromium.executable_path+ return bool(path) and Path(path).exists()+ except Exception:+ return False+++_CHROMIUM = _chromium_available()+++def _start_server(handler_cls):+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler_cls)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ return server, thread+++ not _CHROMIUM, reason="Chromium not installed for Playwright"+)+class TestPlaywrightRedirectGuardRealBrowser:+ """Drive a real headless Chromium through ``_fetch_with_playwright`` and+ prove the SSRF guard aborts a redirect to a blocked target before the+ browser connects to it."""++ @pytest.mark.timeout(90)+ def test_redirect_to_blocked_target_never_reaches_it(self):+ sentinel_hits = {"n": 0}++ class SentinelHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ sentinel_hits["n"] += 1+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ self.wfile.write(b"<html><body>SENTINEL</body></html>")++ def log_message(self, *args):+ pass++ sentinel_server, _ = _start_server(SentinelHandler)+ sentinel_port = sentinel_server.server_address[1]+ sentinel_url = f"http://127.0.0.1:{sentinel_port}/"++ class RedirectHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ self.send_response(302)+ self.send_header("Location", sentinel_url)+ self.end_headers()++ def log_message(self, *args):+ pass++ redirect_server, _ = _start_server(RedirectHandler)+ redirect_port = redirect_server.server_address[1]+ redirect_url = f"http://127.0.0.1:{redirect_port}/"++ # Per-URL decision: the entry point (redirect server) validates True,+ # the redirect target (sentinel) validates False — the exact+ # public-entry -> internal-target SSRF shape.+ def _side_effect(url, *args, **kwargs):+ return f"127.0.0.1:{sentinel_port}" not in url++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ try:+ with patch.object(+ ssrf_validator, "validate_url", side_effect=_side_effect+ ):+ result = dl._fetch_with_playwright(redirect_url)+ finally:+ dl.close()+ sentinel_server.shutdown()+ redirect_server.shutdown()++ # The blocked redirect target must never have been contacted.+ assert sentinel_hits["n"] == 0, (+ "SSRF guard failed: browser reached the blocked redirect target"+ )+ # And the fetch yields no content (navigation was aborted).+ assert not result++ @pytest.mark.timeout(90)+ def test_safe_redirect_is_served(self):+ """Control: a redirect to an ALLOWED loopback target is followed and+ its content returned — proving the guard is not blanket-blocking."""++ class ContentHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ self.wfile.write(+ b"<html><body><h1>SAFE-CONTENT</h1></body></html>"+ )++ def log_message(self, *args):+ pass++ content_server, _ = _start_server(ContentHandler)+ content_url = f"http://127.0.0.1:{content_server.server_address[1]}/"++ class RedirectHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ self.send_response(302)+ self.send_header("Location", content_url)+ self.end_headers()++ def log_message(self, *args):+ pass++ redirect_server, _ = _start_server(RedirectHandler)+ redirect_url = f"http://127.0.0.1:{redirect_server.server_address[1]}/"++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ try:+ # All loopback hosts allowed here (allow_private_ips=True).+ dl.allow_private_ips = True+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ result = dl._fetch_with_playwright(redirect_url)+ finally:+ dl.close()+ content_server.shutdown()+ redirect_server.shutdown()++ assert result and "SAFE-CONTENT" in result+++# ---------------------------------------------------------------------------+# POST body cleared on GET-downgrade + WebSocket guard decisions (no browser)+# ---------------------------------------------------------------------------+++class TestPostBodyAndWsGuards:+ def setup_method(self):+ self.dl = PlaywrightHTMLDownloader(timeout=5)++ def teardown_method(self):+ self.dl.close()++ def test_sync_post_body_cleared_on_get_downgrade(self):+ """A POST that 302-redirects downgrades to GET; the follow-up fetch+ must NOT carry the original body (parity with safe_post)."""+ route = _sync_route(PUBLIC_URL)+ route.request.method = "POST"+ route.fetch.side_effect = [+ _FakeAPIResponse(302, {"location": "https://example.com/final"}),+ _FakeAPIResponse(200),+ ]+ with patch.object(ssrf_validator, "validate_url", return_value=True):+ self.dl._playwright_route_guard(route)+ assert route.fetch.call_count == 2+ first = route.fetch.call_args_list[0].kwargs+ assert first.get("method") == "POST"+ assert "post_data" not in first # hop 1 keeps the original body+ second = route.fetch.call_args_list[1].kwargs+ assert second.get("method") == "GET"+ assert second.get("post_data") == "" # body dropped on downgrade+ route.fulfill.assert_called_once()++ def test_async_post_body_cleared_on_get_downgrade(self):+ route = _async_route(PUBLIC_URL)+ route.request.method = "POST"+ route.fetch.side_effect = [+ _FakeAPIResponse(303, {"location": "https://example.com/final"}),+ _FakeAPIResponse(200),+ ]+ with patch.object(ssrf_validator, "validate_url", return_value=True):+ asyncio.run(self.dl._crawl4ai_route_guard(route))+ assert route.fetch.await_count == 2+ second = route.fetch.await_args_list[1].kwargs+ assert second.get("method") == "GET"+ assert second.get("post_data") == ""++ def test_sync_ws_guard_never_connects_to_server(self):+ """The WS guard must reject: never call connect_to_server (which is+ what would open the socket to the target)."""+ ws = MagicMock()+ ws.url = "ws://10.0.0.5/socket"+ self.dl._playwright_ws_guard(ws)+ ws.connect_to_server.assert_not_called()++ def test_async_ws_guard_never_connects_to_server(self):+ ws = MagicMock()+ ws.url = "ws://169.254.169.254/socket"+ ws.connect_to_server = MagicMock()+ asyncio.run(self.dl._crawl4ai_ws_guard(ws))+ ws.connect_to_server.assert_not_called()+++# ---------------------------------------------------------------------------+# WebRTC neutralizer install scope on the plain-Playwright path (no browser)+# ---------------------------------------------------------------------------+++class TestPlainPlaywrightWebRTCContextScope:+ """Regression test for commit 6a5bab9ff.++ The plain-Playwright WebRTC neutralizer (``_DISABLE_WEBRTC_JS``) MUST be+ installed via ``page.context.add_init_script(...)``, NOT+ ``page.add_init_script(...)``. A page-level init script does not+ propagate to new pages opened via ``window.open`` — a popup would keep+ live WebRTC (RTCPeerConnection ICE/STUN/TURN), which opens raw+ UDP/TCP sockets to an arbitrary host:port that no ``route()`` handler+ intercepts, reopening the exact SSRF gap the neutralizer exists to+ close. Installing at the CONTEXT level covers popups too. This drives+ ``_fetch_with_playwright`` with a fully mocked Playwright object graph+ (no real browser) and pins the installation to the context.+ """++ def test_webrtc_neutralizer_installed_on_context_not_page(self):+ dl = PlaywrightHTMLDownloader(timeout=5)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0++ mock_page = MagicMock()+ mock_page.content.return_value = "<html><body>ok</body></html>"+ # page.context is reached via attribute access on the MagicMock, so+ # page-level vs context-level add_init_script calls are recorded on+ # two independently-observable mocks.+ mock_context = mock_page.context++ mock_browser = MagicMock()+ mock_browser.new_page.return_value = mock_page++ mock_pw_instance = MagicMock()+ mock_pw_instance.chromium.launch.return_value = mock_browser++ mock_pw_cm = MagicMock()+ mock_pw_cm.start.return_value = mock_pw_instance++ try:+ with patch(+ "playwright.sync_api.sync_playwright",+ return_value=mock_pw_cm,+ ):+ result = dl._fetch_with_playwright("https://example.com")+ finally:+ dl.close()++ assert result == "<html><body>ok</body></html>"++ # THE regression lock: the WebRTC neutralizer must be installed at+ # context scope, where it also reaches popups spawned via+ # window.open.+ from local_deep_research.research_library.downloaders.playwright_html import ( # noqa: E501+ _DISABLE_WEBRTC_JS,+ )++ mock_context.add_init_script.assert_called_once_with(_DISABLE_WEBRTC_JS)+ # And it must NEVER be installed directly on the page — a+ # page-level init script does not propagate to popups, which would+ # silently reopen the WebRTC SSRF gap.+ mock_page.add_init_script.assert_not_called()++ def test_route_and_ws_guards_also_installed_on_context(self):+ """Companion check: the HTTP egress guard and WebSocket block are+ likewise registered on the context (not the page), matching the+ WebRTC neutralizer's scope so popups inherit all three guards."""+ dl = PlaywrightHTMLDownloader(timeout=5)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0++ mock_page = MagicMock()+ mock_page.content.return_value = "<html><body>ok</body></html>"+ mock_context = mock_page.context++ mock_browser = MagicMock()+ mock_browser.new_page.return_value = mock_page++ mock_pw_instance = MagicMock()+ mock_pw_instance.chromium.launch.return_value = mock_browser++ mock_pw_cm = MagicMock()+ mock_pw_cm.start.return_value = mock_pw_instance++ try:+ with patch(+ "playwright.sync_api.sync_playwright",+ return_value=mock_pw_cm,+ ):+ dl._fetch_with_playwright("https://example.com")+ finally:+ dl.close()++ mock_context.route.assert_called_once_with(+ "**/*", dl._playwright_route_guard+ )+ mock_context.route_web_socket.assert_called_once_with(+ "**/*", dl._playwright_ws_guard+ )+ mock_page.route.assert_not_called()+ mock_page.route_web_socket.assert_not_called()+++# ---------------------------------------------------------------------------+# Guarded robots.txt: SafeSession-backed, redirect hops validated (no browser)+# ---------------------------------------------------------------------------+++class TestGuardedRobots:+ """``_robots_allows`` fetches robots.txt through the SSRF-guarded+ SafeSession (every hop validated), replacing crawl4ai's unguarded+ aiohttp fetch."""++ def _dl(self):+ return PlaywrightHTMLDownloader(timeout=5)++ def test_robots_redirect_to_blocked_is_guarded_and_fails_open(self):+ sentinel_hits = {"n": 0}++ class SentinelHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ sentinel_hits["n"] += 1+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b"blocked-target")++ def log_message(self, *args):+ pass++ sentinel_server, _ = _start_server(SentinelHandler)+ sentinel_port = sentinel_server.server_address[1]+ sentinel_url = f"http://127.0.0.1:{sentinel_port}/"++ class RobotsRedirectHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ self.send_response(302)+ self.send_header("Location", sentinel_url)+ self.end_headers()++ def log_message(self, *args):+ pass++ robots_server, _ = _start_server(RobotsRedirectHandler)+ page_url = f"http://127.0.0.1:{robots_server.server_address[1]}/page"++ def _side_effect(url, *args, **kwargs):+ return f"127.0.0.1:{sentinel_port}" not in url++ dl = self._dl()+ try:+ with patch.object(+ ssrf_validator, "validate_url", side_effect=_side_effect+ ):+ allowed = dl._robots_allows(page_url)+ finally:+ dl.close()+ sentinel_server.shutdown()+ robots_server.shutdown()++ # The robots redirect to a blocked host must never be fetched...+ assert sentinel_hits["n"] == 0+ # ...and robots uncertainty fails OPEN (navigation still guarded).+ assert allowed is True++ def test_robots_disallow_blocks(self):+ class RobotsHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ self.send_response(200)+ self.send_header("Content-Type", "text/plain")+ self.end_headers()+ self.wfile.write(b"User-agent: *\nDisallow: /\n")++ def log_message(self, *args):+ pass++ robots_server, _ = _start_server(RobotsHandler)+ page_url = f"http://127.0.0.1:{robots_server.server_address[1]}/secret"++ dl = self._dl()+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ allowed = dl._robots_allows(page_url)+ finally:+ dl.close()+ robots_server.shutdown()++ assert allowed is False++ def test_robots_allow_permits(self):+ class RobotsHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ self.send_response(200)+ self.send_header("Content-Type", "text/plain")+ self.end_headers()+ self.wfile.write(b"User-agent: *\nAllow: /\n")++ def log_message(self, *args):+ pass++ robots_server, _ = _start_server(RobotsHandler)+ page_url = f"http://127.0.0.1:{robots_server.server_address[1]}/ok"++ dl = self._dl()+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ allowed = dl._robots_allows(page_url)+ finally:+ dl.close()+ robots_server.shutdown()++ assert allowed is True+++# ---------------------------------------------------------------------------+# Real-browser subrequest bypass tests (skipped when Chromium is absent)+# ---------------------------------------------------------------------------+++def _start_socket_sentinel():+ """A raw TCP accept-counter — records connection attempts (a WS handshake+ starts with a TCP connect, so 0 accepts == the target was never reached)."""+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ sock.bind(("127.0.0.1", 0))+ sock.listen(5)+ port = sock.getsockname()[1]+ hits = {"n": 0}++ def _loop():+ while True:+ try:+ conn, _ = sock.accept()+ hits["n"] += 1+ conn.close()+ except OSError:+ break++ threading.Thread(target=_loop, daemon=True).start()+ return sock, port, hits+++ not _CHROMIUM, reason="Chromium not installed for Playwright"+)+class TestBrowserSubrequestGuardsRealBrowser:+ """Real headless Chromium: the redirect guard's siblings — Crawl4AI+ redirect walk, Service Workers, and WebSockets — must also never reach a+ blocked target."""++ @pytest.mark.timeout(120)+ def test_crawl4ai_redirect_walk_blocked(self):+ """Crawl4AI end-to-end: a public entry that 302s to a blocked host is+ aborted before connect, AND the guarded robots.txt fetch (also a 302+ to the blocked host) never reaches it either."""+ sentinel_hits = {"n": 0}++ class SentinelHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ sentinel_hits["n"] += 1+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ self.wfile.write(b"<html><body>SENTINEL</body></html>")++ def log_message(self, *args):+ pass++ sentinel_server, _ = _start_server(SentinelHandler)+ sentinel_port = sentinel_server.server_address[1]+ sentinel_url = f"http://127.0.0.1:{sentinel_port}/"++ class RedirectHandler(http.server.BaseHTTPRequestHandler):+ # 302 to the blocked host for EVERY path, including /robots.txt.+ def do_GET(self): # noqa: N802+ self.send_response(302)+ self.send_header("Location", sentinel_url)+ self.end_headers()++ def log_message(self, *args):+ pass++ entry_server, _ = _start_server(RedirectHandler)+ entry_url = f"http://127.0.0.1:{entry_server.server_address[1]}/"++ def _side_effect(url, *args, **kwargs):+ return f"127.0.0.1:{sentinel_port}" not in url++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ try:+ with patch.object(+ ssrf_validator, "validate_url", side_effect=_side_effect+ ):+ result = dl._fetch_with_crawl4ai(entry_url)+ finally:+ dl.close()+ sentinel_server.shutdown()+ entry_server.shutdown()++ assert sentinel_hits["n"] == 0, (+ "Crawl4AI path reached the blocked redirect target"+ )+ assert not result++ @pytest.mark.timeout(90)+ def test_plain_playwright_websocket_blocked(self):+ """Page JS opening a WebSocket to a blocked host must not connect."""+ ws_sock, ws_port, ws_hits = _start_socket_sentinel()++ page_html = (+ "<!doctype html><html><body><h1>PAGE</h1><script>"+ f"try {{ new WebSocket('ws://127.0.0.1:{ws_port}/'); }}"+ "catch(e){}"+ "</script></body></html>"+ ).encode()++ class PageHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ self.wfile.write(page_html)++ def log_message(self, *args):+ pass++ page_server, _ = _start_server(PageHandler)+ page_url = f"http://127.0.0.1:{page_server.server_address[1]}/"++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ result = dl._fetch_with_playwright(page_url)+ finally:+ dl.close()+ page_server.shutdown()+ ws_sock.close()++ assert ws_hits["n"] == 0, "WebSocket reached the blocked target"+ assert result and "PAGE" in result++ @pytest.mark.timeout(90)+ def test_plain_playwright_service_worker_blocked(self):+ """A page that registers a Service Worker which fetches a blocked host+ must not reach it (Service Workers are blocked at the context)."""+ sentinel_hits = {"n": 0}++ class SentinelHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ sentinel_hits["n"] += 1+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b"SENTINEL")++ def log_message(self, *args):+ pass++ sentinel_server, _ = _start_server(SentinelHandler)+ sentinel_port = sentinel_server.server_address[1]++ page_html = (+ "<!doctype html><html><body><h1>PAGE</h1><script>"+ "if (navigator.serviceWorker) {"+ "navigator.serviceWorker.register('/sw.js').catch(function(){});"+ "}</script></body></html>"+ ).encode()+ sw_js = (+ f"fetch('http://127.0.0.1:{sentinel_port}/from-sw')"+ ".catch(function(){});"+ ).encode()++ class PageHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == "/sw.js":+ body, ctype = sw_js, "application/javascript"+ else:+ body, ctype = page_html, "text/html"+ self.send_response(200)+ self.send_header("Content-Type", ctype)+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass++ page_server, _ = _start_server(PageHandler)+ page_url = f"http://127.0.0.1:{page_server.server_address[1]}/"++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ result = dl._fetch_with_playwright(page_url)+ finally:+ dl.close()+ sentinel_server.shutdown()+ page_server.shutdown()++ assert sentinel_hits["n"] == 0, (+ "Service Worker reached the blocked target"+ )+ assert result and "PAGE" in result++ @pytest.mark.timeout(120)+ def test_crawl4ai_websocket_blocked(self):+ """Crawl4AI twin: page JS opening a WebSocket to a blocked host must+ not connect (WS guard installed via the on_page_context_created hook)."""+ ws_sock, ws_port, ws_hits = _start_socket_sentinel()++ page_html = (+ "<!doctype html><html><body><h1>PAGE</h1><script>"+ f"try {{ new WebSocket('ws://127.0.0.1:{ws_port}/'); }}"+ "catch(e){}"+ "</script></body></html>"+ ).encode()++ class PageHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ self.wfile.write(page_html)++ def log_message(self, *args):+ pass++ page_server, _ = _start_server(PageHandler)+ page_url = f"http://127.0.0.1:{page_server.server_address[1]}/"++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ dl._fetch_with_crawl4ai(page_url)+ finally:+ dl.close()+ page_server.shutdown()+ ws_sock.close()++ assert ws_hits["n"] == 0, (+ "Crawl4AI path: WebSocket reached the blocked target"+ )++ @pytest.mark.timeout(120)+ def test_crawl4ai_service_worker_blocked(self):+ """Crawl4AI twin: a page registering a Service Worker that fetches a+ blocked host must not reach it (SW registration neutralised via the+ init script installed in the hook)."""+ sentinel_hits = {"n": 0}++ class SentinelHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ sentinel_hits["n"] += 1+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b"SENTINEL")++ def log_message(self, *args):+ pass++ sentinel_server, _ = _start_server(SentinelHandler)+ sentinel_port = sentinel_server.server_address[1]++ page_html = (+ "<!doctype html><html><body><h1>PAGE</h1><script>"+ "if (navigator.serviceWorker) {"+ "navigator.serviceWorker.register('/sw.js').catch(function(){});"+ "}</script></body></html>"+ ).encode()+ sw_js = (+ f"fetch('http://127.0.0.1:{sentinel_port}/from-sw')"+ ".catch(function(){});"+ ).encode()++ class PageHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == "/sw.js":+ body, ctype = sw_js, "application/javascript"+ else:+ body, ctype = page_html, "text/html"+ self.send_response(200)+ self.send_header("Content-Type", ctype)+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, *args):+ pass++ page_server, _ = _start_server(PageHandler)+ page_url = f"http://127.0.0.1:{page_server.server_address[1]}/"++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ dl._fetch_with_crawl4ai(page_url)+ finally:+ dl.close()+ sentinel_server.shutdown()+ page_server.shutdown()++ assert sentinel_hits["n"] == 0, (+ "Crawl4AI path: Service Worker reached the blocked target"+ )+++ not _CHROMIUM, reason="Chromium not installed for Playwright"+)+class TestCrawl4aiMidRedirectCookieRealBrowser:+ """End-to-end (real headless Chromium) twin of+ ``TestCrawl4aiMidRedirectCookiePersistence``: a 302 that sets+ ``Set-Cookie: session=X`` and redirects to ``/final`` must have that+ cookie applied by the crawl4ai path so the request that actually reaches+ ``/final`` carries it — proving the fix works through the real crawl4ai+ + Playwright + Chromium stack, not just against a mocked ``route``.+ """++ @pytest.mark.timeout(120)+ def test_cookie_set_on_redirect_hop_reaches_final_page(self):+ seen_cookie_header = {"value": None}+ # crawl4ai's anti-bot heuristic flags stripped HTML under 100 bytes+ # on a HTTP 200 as a "near-empty content" block signal — pad well+ # past that so this test exercises cookie persistence, not that+ # unrelated heuristic.+ final_body = (+ "<html><body><h1>FINAL</h1><p>"+ + "This page confirms the redirect-hop cookie was carried "+ "through to the final destination request. "+ * 3+ + "</p></body></html>"+ ).encode()++ class RedirectThenFinalHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == "/final":+ seen_cookie_header["value"] = self.headers.get("Cookie")+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ self.wfile.write(final_body)+ else:+ self.send_response(302)+ self.send_header("Set-Cookie", "session=X; Path=/")+ self.send_header("Location", "/final")+ self.end_headers()++ def log_message(self, *args):+ pass++ server, _ = _start_server(RedirectThenFinalHandler)+ entry_url = f"http://127.0.0.1:{server.server_address[1]}/"++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ dl.allow_private_ips = True+ # Skip the guarded robots.txt fetch: it would hit this same handler+ # (every non-/final path 302s) and is irrelevant to what this test+ # is checking — keep it focused on the browser-driven redirect walk.+ dl._robots_allows = MagicMock(return_value=True)+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ result = dl._fetch_with_crawl4ai(entry_url)+ finally:+ dl.close()+ server.shutdown()++ assert result and "FINAL" in result+ assert seen_cookie_header["value"] is not None, (+ "The redirect-hop Set-Cookie never reached the final request"+ )+ assert "session=X" in seen_cookie_header["value"]++ @pytest.mark.timeout(120)+ def test_cookie_set_on_hop_does_not_leak_across_domains(self):+ """SECURITY (real browser): a cookie set mid-redirect on domain A must+ NOT reach a DIFFERENT domain B a later hop redirects to.++ Two loopback origins with DIFFERENT hostnames (hence different cookie+ domains): A = 127.0.0.1, B = 127.0.0.2. Chain, all driven through the+ real crawl4ai + Playwright + Chromium stack:++ A/a -> 302 Set-Cookie: session=SECRET; Location: /b (same host)+ A/b -> 302 Location: http://127.0.0.2:<port>/landing (cross host)+ B/landing -> 200 (sets no cookie), records its Cookie header++ A real browser scopes ``session=SECRET`` to 127.0.0.1 and never sends+ it to 127.0.0.2, so B's recorded Cookie header must not contain it.+ """+ seen_b_cookie = {"value": "__unset__"}+ b_body = (+ "<html><body><h1>LANDING</h1><p>"+ + "Cross-domain landing page used to confirm a cookie set on "+ "the first origin is not leaked to this different origin. "+ * 3+ + "</p></body></html>"+ ).encode()++ class BHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == "/landing":+ seen_b_cookie["value"] = self.headers.get("Cookie")+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ self.wfile.write(b_body)+ else:+ self.send_response(404)+ self.end_headers()++ def log_message(self, *args):+ pass++ # Server B bound to a DIFFERENT loopback host (127.0.0.2) so its+ # cookie domain differs from A's (127.0.0.1) — ports do not scope+ # cookies, hostnames do.+ try:+ b_server = http.server.ThreadingHTTPServer(+ ("127.0.0.2", 0), BHandler+ )+ except OSError:+ # 127.0.0.2 is a usable loopback alias on Linux, but macOS (and+ # some BSDs) do not bind it by default. Skip rather than fail —+ # this test needs a SECOND, distinct loopback host to prove the+ # cookie set on 127.0.0.1 is not leaked cross-domain to it.+ pytest.skip(+ "cannot bind 127.0.0.2 (second loopback host unavailable, "+ "e.g. macOS) — cross-domain cookie test needs two hosts"+ )+ threading.Thread(target=b_server.serve_forever, daemon=True).start()+ b_landing = f"http://127.0.0.2:{b_server.server_address[1]}/landing"++ class AHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == "/b":+ self.send_response(302)+ self.send_header("Location", b_landing)+ self.end_headers()+ else:+ self.send_response(302)+ self.send_header("Set-Cookie", "session=SECRET; Path=/")+ self.send_header("Location", "/b")+ self.end_headers()++ def log_message(self, *args):+ pass++ a_server, _ = _start_server(AHandler) # bound to 127.0.0.1+ entry_url = f"http://127.0.0.1:{a_server.server_address[1]}/a"++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ dl.allow_private_ips = True+ dl._robots_allows = MagicMock(return_value=True)+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ result = dl._fetch_with_crawl4ai(entry_url)+ finally:+ dl.close()+ a_server.shutdown()+ b_server.shutdown()++ assert result and "LANDING" in result+ # The cross-domain landing request must have happened ...+ assert seen_b_cookie["value"] != "__unset__", (+ "the cross-domain landing page was never reached"+ )+ # ... but it must NOT carry domain A's cookie.+ assert "SECRET" not in (seen_b_cookie["value"] or ""), (+ "cross-domain cookie leak: 127.0.0.1's cookie reached 127.0.0.2"+ )+++ not _CHROMIUM, reason="Chromium not installed for Playwright"+)+class TestPlaywrightMidRedirectCookieRealBrowser:+ """End-to-end (real headless Chromium) twin of+ ``TestCrawl4aiMidRedirectCookieRealBrowser`` for the PLAIN-Playwright+ (sync) path, driven through ``_fetch_with_playwright``. Proves the per-hop+ cookie re-scoping added to ``_playwright_route_guard`` works through the+ real Playwright + Chromium stack, not just against a mocked ``route``."""++ @pytest.mark.timeout(120)+ def test_cookie_set_on_redirect_hop_reaches_final_page(self):+ """Same-domain: a cookie set on a redirect hop must still reach the+ final request — the per-hop re-scoping must not break same-domain+ persistence."""+ seen_cookie_header = {"value": None}+ final_body = (+ "<html><body><h1>FINAL</h1><p>"+ + "This page confirms the redirect-hop cookie was carried "+ "through to the final destination request. "+ * 3+ + "</p></body></html>"+ ).encode()++ class RedirectThenFinalHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == "/final":+ seen_cookie_header["value"] = self.headers.get("Cookie")+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ self.wfile.write(final_body)+ else:+ self.send_response(302)+ self.send_header("Set-Cookie", "session=X; Path=/")+ self.send_header("Location", "/final")+ self.end_headers()++ def log_message(self, *args):+ pass++ server, _ = _start_server(RedirectThenFinalHandler)+ entry_url = f"http://127.0.0.1:{server.server_address[1]}/"++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ dl.allow_private_ips = True+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ result = dl._fetch_with_playwright(entry_url)+ finally:+ dl.close()+ server.shutdown()++ assert result and "FINAL" in result+ assert seen_cookie_header["value"] is not None, (+ "the redirect-hop Set-Cookie never reached the final request"+ )+ assert "session=X" in seen_cookie_header["value"]++ @pytest.mark.timeout(120)+ def test_cookie_set_on_hop_does_not_leak_across_domains(self):+ """SECURITY (real browser, plain-Playwright path): a cookie set+ mid-redirect on domain A must NOT reach a DIFFERENT domain B a later+ hop redirects to.++ A/a -> 302 Set-Cookie: session=SECRET; Location: /b (same host)+ A/b -> 302 Location: http://127.0.0.2:<port>/landing (cross host)+ B/landing -> 200 (sets no cookie), records its Cookie header++ A real browser scopes ``session=SECRET`` to 127.0.0.1 and never sends+ it to 127.0.0.2, so B's recorded Cookie header must not contain it.+ """+ seen_b_cookie = {"value": "__unset__"}+ b_body = (+ "<html><body><h1>LANDING</h1><p>"+ + "Cross-domain landing page used to confirm a cookie set on "+ "the first origin is not leaked to this different origin. "+ * 3+ + "</p></body></html>"+ ).encode()++ class BHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == "/landing":+ seen_b_cookie["value"] = self.headers.get("Cookie")+ self.send_response(200)+ self.send_header("Content-Type", "text/html")+ self.end_headers()+ self.wfile.write(b_body)+ else:+ self.send_response(404)+ self.end_headers()++ def log_message(self, *args):+ pass++ try:+ b_server = http.server.ThreadingHTTPServer(+ ("127.0.0.2", 0), BHandler+ )+ except OSError:+ # 127.0.0.2 is a usable loopback alias on Linux, but macOS (and+ # some BSDs) do not bind it by default. Skip rather than fail —+ # this test needs a SECOND, distinct loopback host to prove the+ # cookie set on 127.0.0.1 is not leaked cross-domain to it.+ pytest.skip(+ "cannot bind 127.0.0.2 (second loopback host unavailable, "+ "e.g. macOS) — cross-domain cookie test needs two hosts"+ )+ threading.Thread(target=b_server.serve_forever, daemon=True).start()+ b_landing = f"http://127.0.0.2:{b_server.server_address[1]}/landing"++ class AHandler(http.server.BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == "/b":+ self.send_response(302)+ self.send_header("Location", b_landing)+ self.end_headers()+ else:+ self.send_response(302)+ self.send_header("Set-Cookie", "session=SECRET; Path=/")+ self.send_header("Location", "/b")+ self.end_headers()++ def log_message(self, *args):+ pass++ a_server, _ = _start_server(AHandler) # bound to 127.0.0.1+ entry_url = f"http://127.0.0.1:{a_server.server_address[1]}/a"++ dl = PlaywrightHTMLDownloader(timeout=15, block_resources=True)+ dl.rate_tracker = MagicMock()+ dl.rate_tracker.apply_rate_limit.return_value = 0+ dl.allow_private_ips = True+ try:+ with patch.object(+ ssrf_validator, "validate_url", return_value=True+ ):+ result = dl._fetch_with_playwright(entry_url)+ finally:+ dl.close()+ a_server.shutdown()+ b_server.shutdown()++ assert result and "LANDING" in result+ # The cross-domain landing request must have happened ...+ assert seen_b_cookie["value"] != "__unset__", (+ "the cross-domain landing page was never reached"+ )+ # ... but it must NOT carry domain A's cookie.+ assert "SECRET" not in (seen_b_cookie["value"] or ""), (+ "cross-domain cookie leak: 127.0.0.1's cookie reached 127.0.0.2"+ )diff --git a/tests/security/test_egress_downloader_threading_followup.py b/tests/security/test_egress_downloader_threading_followup.pyindex f5022e7fff..5bb704441f 100644--- a/tests/security/test_egress_downloader_threading_followup.py+++ b/tests/security/test_egress_downloader_threading_followup.py@@ -25,6 +25,8 @@ or an explicit edge case that would FAIL if the guarded behaviour regressed.from __future__ import annotations+import pytest+from local_deep_research.content_fetcher import ContentFetcherfrom local_deep_research.content_fetcher.url_classifier import URLTypefrom local_deep_research.security.egress.fetch import policy_aware_validate_url@@ -73,6 +75,60 @@ def test_get_downloader_real_path_strict_does_not_relax():assert downloader.session.allow_private_ips is False+# ---------------------------------------------------------------------------+# JS-render browser path: allow_private_ips threads through to the lazily+# built Playwright child. The browser route guards read this flag, so+# PRIVATE_ONLY must reach the browser exactly like it reaches the+# SafeSession; every other scope must stay strict.+# ---------------------------------------------------------------------------+++def test_html_downloader_private_only_threads_allow_private_ips_to_browser():+ """Under PRIVATE_ONLY the AutoHTMLDownloader AND its lazily-built+ Playwright child both carry allow_private_ips=True, so the browser SSRF+ guard permits private lab hosts (metadata still blocked in the guard)."""+ cf = ContentFetcher(egress_context=make_ctx(scope=EgressScope.PRIVATE_ONLY))+ downloader = cf._get_downloader(URLType.HTML)+ assert downloader is not None+ assert downloader.allow_private_ips is True+ child = downloader._get_playwright_downloader()+ try:+ assert child.allow_private_ips is True+ finally:+ child.close()+++ "scope",+ [EgressScope.STRICT, EgressScope.PUBLIC_ONLY, EgressScope.BOTH],+)+def test_html_downloader_non_private_scopes_keep_browser_strict(scope):+ """Deny side: STRICT / PUBLIC_ONLY / BOTH must NOT relax the browser path —+ both the AutoHTMLDownloader and its Playwright child stay strict."""+ cf = ContentFetcher(egress_context=make_ctx(scope=scope))+ downloader = cf._get_downloader(URLType.HTML)+ assert downloader is not None+ assert downloader.allow_private_ips is False+ child = downloader._get_playwright_downloader()+ try:+ assert child.allow_private_ips is False+ finally:+ child.close()+++def test_html_downloader_no_egress_context_keeps_browser_strict():+ """No egress context (the default) must leave the browser path strict."""+ cf = ContentFetcher()+ downloader = cf._get_downloader(URLType.HTML)+ assert downloader is not None+ assert downloader.allow_private_ips is False+ child = downloader._get_playwright_downloader()+ try:+ assert child.allow_private_ips is False+ finally:+ child.close()++# ---------------------------------------------------------------------------# _apply_egress_policy_to_downloader: scope coverage (STRICT / BOTH) + edge# ---------------------------------------------------------------------------