Official Crawl4AI Cloud: a hosted web scraping, extraction, and search API for AI agents. Free API key, 1,000 credits a month, no card. Fully open source: this repo is the Apache-2.0 crawler that powers it, and you can self-host it.
Python aiai-agentscrawl4ai-cloudcrawlerdata-extractionllmmarkdownmcpopen-sourceplaywrightpythonragscraperweb-crawlerweb-crawlingweb-scraping
fix(security): route the seeder and robots.txt fetches through the egress proxy
ntohidi07873f1e226f
diff --git a/crawl4ai/async_configs.py b/crawl4ai/async_configs.pyindex 383079fe..a6691e65 100644--- a/crawl4ai/async_configs.py+++ b/crawl4ai/async_configs.py@@ -298,6 +298,9 @@ _MAX_SCROLL_STEPS = 1000_MAX_VIEWPORT = 4000_MAX_PDF_BYTES = 100 * 1024 * 1024_MAX_PDF_PAGES = 2000+_MAX_LINK_PREVIEW_LINKS = 100 # the class default+_MAX_LINK_PREVIEW_CONCURRENCY = 10 # the class default+_MAX_LINK_PREVIEW_TIMEOUT_S = 10 # seconds here, not msdef _filter_untrusted_fields(type_name: str, params: dict) -> dict:@@ -345,6 +348,18 @@ def _clamp_untrusted(type_name: str, params: dict) -> dict:# Rasterizing every page is the most expensive thing this strategy can# do, and nothing about untrusted crawling needs it.params["extract_images"] = False+ elif type_name == "LinkPreviewConfig":+ # Also no field allowlist, and each link is a separate outbound fetch:+ # unclamped, one request body can order millions of them at any+ # concurrency it likes.+ for f, cap in (+ ("max_links", _MAX_LINK_PREVIEW_LINKS),+ ("concurrency", _MAX_LINK_PREVIEW_CONCURRENCY),+ ("timeout", _MAX_LINK_PREVIEW_TIMEOUT_S),+ ):+ if f in params:+ v = params[f]+ params[f] = cap if not isinstance(v, int) or v <= 0 else min(v, cap)return paramsdiff --git a/crawl4ai/async_url_seeder.py b/crawl4ai/async_url_seeder.pyindex 22fa8f63..7f9fedfb 100644--- a/crawl4ai/async_url_seeder.py+++ b/crawl4ai/async_url_seeder.py@@ -53,6 +53,7 @@ except ImportError:# You might need to adjust this import based on your exact file structure# Import AsyncLogger for default if neededfrom .async_logger import AsyncLoggerBase, AsyncLogger+from .egress_policy import proxy_url# Import SeedingConfig for type hintsfrom typing import TYPE_CHECKING@@ -303,7 +304,11 @@ class AsyncUrlSeeder:):self.ttl = ttlself._owns_client = client is None # Track if we created the client- self.client = client or httpx.AsyncClient(http2=True, timeout=20, headers={+ # proxy=None unless an embedder installed one (the Docker server does).+ # Every request in this class goes through self.client, so this single+ # kwarg puts the seeder's whole fan-out -- sitemaps, robots, link heads,+ # and each redirect hop -- behind the egress policy.+ self.client = client or httpx.AsyncClient(http2=True, timeout=20, proxy=proxy_url(), headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) +AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36"})self.logger = logger # Store the logger instance@@ -1772,7 +1777,7 @@ class AsyncUrlSeeder:self._log("info", "Fetching latest Common Crawl index from {url}",params={"url": COLLINFO_URL}, tag="URL_SEED")try:- async with httpx.AsyncClient() as c:+ async with httpx.AsyncClient(proxy=proxy_url()) as c:j = await c.get(COLLINFO_URL, timeout=10)j.raise_for_status() # Raise an exception for bad status codesidx = j.json()[0]["id"]diff --git a/crawl4ai/egress_policy.py b/crawl4ai/egress_policy.pynew file mode 100644index 00000000..c9b47cbf--- /dev/null+++ b/crawl4ai/egress_policy.py@@ -0,0 +1,35 @@+"""Process-wide egress proxy for the library's own HTTP clients.++The library deliberately has no egress policy of its own: as a plain library+the caller already chooses the URL, so there is nothing to defend against.+It matters when the URL comes from an untrusted API client, which is the+Docker server's situation -- deploy/docker/server.py starts a pinning forward+proxy (egress_proxy.PinningProxy) and registers it here at boot, so the+seeder and robots.txt fetches go through the same resolve-and-pin rule the+browser path already gets.++A proxy rather than a validator hook (the shape used by+crawl4ai/processors/pdf) because a validator resolves the name, checks it and+then throws the address away -- the client re-resolves when it dials, which is+the DNS-rebinding window egress_broker.py exists to close. The proxy resolves,+pins and dials the same address, and re-validates every redirect hop because+each hop is a fresh proxied request.++Unset (the plain-library case) means proxy_url() is None, which is the default+value of the `proxy=` kwarg on both httpx and aiohttp: no behaviour change.+"""++from typing import Optional++_proxy_url: Optional[str] = None+++def set_egress_proxy(url: Optional[str]) -> None:+ """Route the library's own HTTP clients through `url` (None = direct)."""+ global _proxy_url+ _proxy_url = url+++def proxy_url() -> Optional[str]:+ """The installed egress proxy, or None for a direct connection."""+ return _proxy_urldiff --git a/crawl4ai/utils.py b/crawl4ai/utils.pyindex 279c2770..d78b3c35 100644--- a/crawl4ai/utils.py+++ b/crawl4ai/utils.py@@ -36,6 +36,7 @@ from functools import lru_cachefrom packaging import versionfrom . import __version__+from .egress_policy import proxy_urlfrom typing import Sequencefrom itertools import chain@@ -340,8 +341,16 @@ class RobotsParser:scheme = parsed.scheme or 'http'robots_url = f"{scheme}://{domain}/robots.txt"- async with aiohttp.ClientSession() as session:- async with session.get(robots_url, timeout=2, ssl=False) as response:+ # proxy=None unless an embedder installed one (the Docker+ # server does). Without it this fetch is a caller-chosen URL on+ # an unguarded client: it reached internal hosts directly and+ # followed redirects into them.+ # ssl=False is gone: a bad certificate now raises, and the+ # except below fails open, so robots is ignored rather than+ # respected -- more crawling, never a broken crawl.+ timeout = aiohttp.ClientTimeout(total=2)+ async with aiohttp.ClientSession(timeout=timeout) as session:+ async with session.get(robots_url, proxy=proxy_url()) as response:if response.status == 200:rules = await response.text()self._cache_rules(domain, rules)diff --git a/deploy/docker/egress_proxy.py b/deploy/docker/egress_proxy.pyindex 807bb80a..7a1dfdae 100644--- a/deploy/docker/egress_proxy.py+++ b/deploy/docker/egress_proxy.py@@ -103,6 +103,14 @@ def _bracket(ip: str) -> str:return f"[{ip}]" if ":" in ip else ip+def _drop_connection_header(headers: bytes) -> bytes:+ """Strip any Connection: header so the caller can set its own."""+ return b"".join(+ ln + b"\r\n" for ln in headers.split(b"\r\n")+ if ln and not ln.lower().startswith(b"connection:")+ )++class PinningProxy:"""Async HTTP forward-proxy that connects only to pinned, global IPs."""@@ -219,6 +227,11 @@ class PinningProxy:# upstream proxy (which then needs no DNS lookup of its own).if upstream is None:out = f"{method} {path} HTTP/1.1\r\n".encode("latin-1")+ # One validated request per origin connection. After this the bytes+ # are spliced raw, and a keep-alive client would put its next+ # request on the wire in absolute form (it still thinks it is+ # talking to a proxy), which some origins answer with 400.+ headers = _drop_connection_header(headers) + b"Connection: close\r\n"else:out = f"{method} http://{_bracket(pin.ip)}:{port}{path} HTTP/1.1\r\n".encode("latin-1")if upstream[2]:@@ -226,10 +239,7 @@ class PinningProxy:# One validated request per upstream connection: only this first# request is pinned/rewritten, so force close to keep a reused# client connection from smuggling unvalidated requests upstream.- headers = b"".join(- ln + b"\r\n" for ln in headers.split(b"\r\n")- if ln and not ln.lower().startswith(b"connection:")- ) + b"Connection: close\r\n"+ headers = _drop_connection_header(headers) + b"Connection: close\r\n"out += b"Host: " + sp.hostname.encode("latin-1")if sp.port:out += f":{sp.port}".encode("latin-1")diff --git a/deploy/docker/server.py b/deploy/docker/server.pyindex 3636efb9..c232a3e5 100644--- a/deploy/docker/server.py+++ b/deploy/docker/server.py@@ -211,11 +211,18 @@ async def lifespan(_: FastAPI):from egress_proxy import PinningProxyfrom egress_broker import set_egress_proxyapp.state.egress_proxy = PinningProxy()- set_egress_proxy(await app.state.egress_proxy.start())-- # The pinning proxy only covers Chromium. PDFContentScrapingStrategy fetches- # with requests on its own, so hand the library the same destination policy- # or that path stays an unguarded SSRF hole.+ _proxy_url = await app.state.egress_proxy.start()+ set_egress_proxy(_proxy_url)++ # Chromium is only one of the clients that fetch a caller-chosen URL. The+ # library's own HTTP clients -- the URL seeder (link previews, sitemaps) and+ # RobotsParser -- take a proxy kwarg, so point them at the same pinning+ # proxy or those paths stay unguarded SSRF holes.+ from crawl4ai.egress_policy import set_egress_proxy as set_library_egress_proxy+ set_library_egress_proxy(_proxy_url)++ # PDFContentScrapingStrategy fetches with requests, which has no proxy hook+ # we can rely on here, so it gets the same destination policy by injection._install_pdf_egress_policy()# Bounded background-job queue (per-principal quotas optional).diff --git a/deploy/docker/tests/test_security_ssrf_seeder.py b/deploy/docker/tests/test_security_ssrf_seeder.pynew file mode 100644index 00000000..b0a83eff--- /dev/null+++ b/deploy/docker/tests/test_security_ssrf_seeder.py@@ -0,0 +1,233 @@+"""SSRF on the library's own HTTP clients (2026-09 reports), end to end.++Two channels fetched a caller-influenced URL without going through the egress+broker: AsyncUrlSeeder (link previews, sitemaps) and RobotsParser. The seeder+one was not blind -- the internal page's parsed <head> came back to the API+caller in result.links[*].head_data.++These run the real PinningProxy over real loopback sockets with the real+resolve_and_pin rule, so 127.0.0.1 and 169.254.169.254 are refused because they+genuinely are not global. Only "public.example" is stubbed, to stand in for a+global host without touching the network.+"""++import asyncio+import sqlite3++import pytest+from aiohttp import web++import egress_proxy+from egress_broker import PinnedTarget, resolve_and_pin+from egress_proxy import PinningProxy++from crawl4ai import egress_policy+from crawl4ai.async_url_seeder import AsyncUrlSeeder+from crawl4ai.utils import RobotsParser++pytestmark = pytest.mark.posture++INTERNAL_PAGE = (+ '<html><head><title>INTERNAL-MARKER</title>'+ '<meta name="secret" content="internal-only"></head><body>x</body></html>'+)++_PROXY_ENV = (+ "CRAWL4AI_UPSTREAM_PROXY", "HTTP_PROXY", "http_proxy",+ "HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy",+)++[email protected](autouse=True)+def _clear_proxy_env(monkeypatch):+ for name in _PROXY_ENV:+ monkeypatch.delenv(name, raising=False)++[email protected](autouse=True)+def _reset_library_proxy():+ yield+ egress_policy.set_egress_proxy(None)+++async def _serve(handler):+ """Start a loopback HTTP server; return (runner, port)."""+ app = web.Application()+ app.router.add_get("/{tail:.*}", handler)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ return runner, site._server.sockets[0].getsockname()[1]+++async def _start_proxy():+ proxy = PinningProxy()+ egress_policy.set_egress_proxy(await proxy.start())+ return proxy+++def _treat_port_as_public(monkeypatch, port):+ """Let one loopback port through the proxy as if it were a global host.++ Everything else keeps the real not-is_global rule, so the "internal"+ service on its own port is still refused. Using a loopback port rather+ than a made-up hostname matters: the unfixed code must be able to reach+ the first hop, or the test would pass for the wrong reason.+ """+ def fake_pin(url):+ if f":{port}" in url:+ return PinnedTarget("http", "127.0.0.1", port, "127.0.0.1")+ return resolve_and_pin(url)+ monkeypatch.setattr(egress_proxy, "resolve_and_pin", fake_pin)+++class TestSeederEgress:+ async def test_seeder_head_resolution_to_loopback_is_blocked(self):+ """_resolve_head is a separate sink from the head fetch."""+ hits = []++ async def internal(req):+ hits.append(req.path)+ return web.Response(text=INTERNAL_PAGE, content_type="text/html")++ runner, port = await _serve(internal)+ proxy = await _start_proxy()+ seeder = AsyncUrlSeeder()+ try:+ assert await seeder._resolve_head(f"http://127.0.0.1:{port}/") is None+ assert hits == []+ finally:+ await seeder.client.aclose()+ await proxy.stop()+ await runner.cleanup()++ async def test_seeder_direct_loopback_is_blocked(self):+ hits = []++ async def internal(req):+ hits.append(req.path)+ return web.Response(text=INTERNAL_PAGE, content_type="text/html")++ runner, port = await _serve(internal)+ proxy = await _start_proxy()+ seeder = AsyncUrlSeeder()+ try:+ res = await seeder.extract_head_for_urls(+ [f"http://127.0.0.1:{port}/secret"]+ )+ assert hits == [], "the internal service was reached"+ assert not (res[0].get("head_data") or {}).get("title")+ finally:+ await seeder.client.aclose()+ await proxy.stop()+ await runner.cleanup()++ async def test_seeder_redirect_into_internal_is_blocked(self, monkeypatch):+ """A public first hop must not become a free pass for the second."""+ hits = []++ async def internal(req):+ hits.append(req.path)+ return web.Response(text=INTERNAL_PAGE, content_type="text/html")++ irunner, iport = await _serve(internal)++ async def public(req):+ raise web.HTTPFound(f"http://127.0.0.1:{iport}/secret")++ prunner, pport = await _serve(public)+ _treat_port_as_public(monkeypatch, pport)++ proxy = await _start_proxy()+ seeder = AsyncUrlSeeder()+ try:+ ok, html, final = await seeder._fetch_head(+ f"http://127.0.0.1:{pport}/page", timeout=5+ )+ assert hits == [], "the redirect reached the internal service"+ assert "INTERNAL-MARKER" not in html, "the internal page came back"+ finally:+ await seeder.client.aclose()+ await proxy.stop()+ await prunner.cleanup()+ await irunner.cleanup()++ async def test_seeder_public_host_still_works(self, monkeypatch):+ """The fix must not simply block everything."""+ async def public(req):+ return web.Response(+ text='<html><head><title>PUBLIC-OK</title></head><body>x</body></html>',+ content_type="text/html",+ )++ runner, port = await _serve(public)+ _treat_port_as_public(monkeypatch, port)++ proxy = await _start_proxy()+ seeder = AsyncUrlSeeder()+ try:+ res = await seeder.extract_head_for_urls(+ [f"http://127.0.0.1:{port}/page"]+ )+ assert (res[0].get("head_data") or {}).get("title") == "PUBLIC-OK"+ finally:+ await seeder.client.aclose()+ await proxy.stop()+ await runner.cleanup()+++class TestRobotsEgress:+ async def test_robots_fetch_to_loopback_is_blocked(self, tmp_path):+ hits = []++ async def internal(req):+ hits.append(req.path)+ return web.Response(text="User-agent: *\nDisallow: /secret\n")++ runner, port = await _serve(internal)+ proxy = await _start_proxy()+ parser = RobotsParser(cache_dir=str(tmp_path))+ try:+ # Unchanged contract: every failure on this path fails open.+ assert await parser.can_fetch(+ f"http://127.0.0.1:{port}/secret", "bot"+ ) is True+ assert hits == [], "the internal service was reached"+ with sqlite3.connect(parser.db_path) as conn:+ rows = conn.execute("SELECT domain FROM robots_cache").fetchall()+ # The load-bearing assertion: nothing internal was fetched, so+ # nothing internal got persisted for the 7-day cache TTL.+ assert rows == []+ finally:+ await proxy.stop()+ await runner.cleanup()++ async def test_robots_fetch_follows_redirect_into_internal_no_further(+ self, monkeypatch, tmp_path+ ):+ hits = []++ async def internal(req):+ hits.append(req.path)+ return web.Response(text="User-agent: *\nDisallow: /secret\n")++ irunner, iport = await _serve(internal)++ async def public(req):+ raise web.HTTPFound(f"http://127.0.0.1:{iport}/robots.txt")++ prunner, pport = await _serve(public)+ _treat_port_as_public(monkeypatch, pport)++ proxy = await _start_proxy()+ parser = RobotsParser(cache_dir=str(tmp_path))+ try:+ await parser.can_fetch(f"http://127.0.0.1:{pport}/secret", "bot")+ assert hits == [], "robots fetch followed the redirect into loopback"+ finally:+ await proxy.stop()+ await prunner.cleanup()+ await irunner.cleanup()diff --git a/tests/unit/test_egress_policy.py b/tests/unit/test_egress_policy.pynew file mode 100644index 00000000..91202fe4--- /dev/null+++ b/tests/unit/test_egress_policy.py@@ -0,0 +1,159 @@+"""The library's own HTTP clients honour the installed egress proxy.++Two SSRF reports (2026-09) came from the same root cause: AsyncUrlSeeder and+RobotsParser build HTTP clients that never go through the Docker server's+egress broker. The fix is one `proxy=` kwarg per client, fed from+crawl4ai.egress_policy. These tests pin both halves of that: the proxy is used+when installed, and nothing changes for plain-library users when it is not.++No network and no server: everything here is client construction.+"""++import asyncio++import aiohttp+import pytest++from crawl4ai import egress_policy+from crawl4ai.async_url_seeder import AsyncUrlSeeder+from crawl4ai.utils import RobotsParser++PROXY = "http://127.0.0.1:9" # discard port; nothing here connects++[email protected](autouse=True)+def _reset_proxy():+ """The proxy URL is a module-level global; leaking it breaks later tests."""+ yield+ egress_policy.set_egress_proxy(None)+++def _proxy_transport(client):+ """The transport httpx would use for an outbound URL, or None if direct."""+ import httpx++ transport = client._transport_for_url(httpx.URL("http://example.com/"))+ return transport if transport is not client._transport else None+++# ── seeder ─────────────────────────────────────────────────────────────+++def test_seeder_client_has_no_proxy_by_default():+ """Plain-library use must behave exactly as it did before the fix."""+ seeder = AsyncUrlSeeder()+ try:+ assert seeder.client._mounts == {}+ assert _proxy_transport(seeder.client) is None+ finally:+ asyncio.run(seeder.client.aclose())+++def test_seeder_client_uses_installed_proxy():+ egress_policy.set_egress_proxy(PROXY)+ seeder = AsyncUrlSeeder()+ try:+ assert _proxy_transport(seeder.client) is not None+ finally:+ asyncio.run(seeder.client.aclose())+++def test_seeder_keeps_http2_through_proxy():+ """The proxy must not cost the seeder HTTP/2.++ Passing `transport=` to httpx.AsyncClient silently drops http2=True; the+ `proxy=` kwarg does not, and httpcore negotiates h2 inside the CONNECT+ tunnel. This test is what stops that regression sneaking back in.+ """+ egress_policy.set_egress_proxy(PROXY)+ seeder = AsyncUrlSeeder()+ try:+ transport = _proxy_transport(seeder.client)+ assert transport._pool._http2 is True+ finally:+ asyncio.run(seeder.client.aclose())+++def test_collinfo_client_uses_installed_proxy():+ """The throwaway client in _latest_index is a second construction site."""+ import inspect++ src = inspect.getsource(AsyncUrlSeeder._latest_index)+ assert "httpx.AsyncClient(proxy=proxy_url())" in src+++# ── robots.txt ─────────────────────────────────────────────────────────+++class _FakeResponse:+ status = 404++ async def __aenter__(self):+ return self++ async def __aexit__(self, *exc):+ return False+++def _record_robots_get(monkeypatch):+ """Capture the kwargs RobotsParser hands aiohttp, without any network."""+ calls = []++ def fake_get(self, url, **kwargs):+ calls.append((url, kwargs))+ return _FakeResponse()++ monkeypatch.setattr(aiohttp.ClientSession, "get", fake_get)+ return calls+++def test_robots_fetch_passes_proxy(monkeypatch, tmp_path):+ calls = _record_robots_get(monkeypatch)+ egress_policy.set_egress_proxy(PROXY)++ parser = RobotsParser(cache_dir=str(tmp_path))+ asyncio.run(parser.can_fetch("http://example.com/x", "bot"))++ assert len(calls) == 1+ url, kwargs = calls[0]+ assert url == "http://example.com/robots.txt"+ assert kwargs["proxy"] == PROXY+++def test_robots_fetch_is_direct_by_default(monkeypatch, tmp_path):+ calls = _record_robots_get(monkeypatch)++ parser = RobotsParser(cache_dir=str(tmp_path))+ asyncio.run(parser.can_fetch("http://example.com/x", "bot"))++ assert calls[0][1]["proxy"] is None+++def test_robots_fetch_no_longer_disables_tls_verification(monkeypatch, tmp_path):+ """ssl=False made every robots fetch accept any certificate."""+ calls = _record_robots_get(monkeypatch)++ parser = RobotsParser(cache_dir=str(tmp_path))+ asyncio.run(parser.can_fetch("https://example.com/x", "bot"))++ assert calls[0][1].get("ssl", None) is None+++# ── untrusted LinkPreviewConfig clamps ─────────────────────────────────+++ "field,asked,expected",+ [+ ("max_links", 10_000_000, 100),+ ("max_links", 0, 100),+ ("concurrency", 10_000, 10),+ ("timeout", 3600, 10),+ ("max_links", 5, 5), # a reasonable value survives+ ],+)+def test_link_preview_untrusted_values_are_clamped(field, asked, expected):+ from crawl4ai.async_configs import _enforce_untrusted++ out = _enforce_untrusted("LinkPreviewConfig", {field: asked})+ assert out[field] == expected