Skip to content

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.

fix(security): stop css_selector and wait_for running page JavaScript from untrusted bodies

ntohidi736a28a06030
diff --git a/crawl4ai/async_configs.py b/crawl4ai/async_configs.py
index e76cae18..0a350fb1 100644
--- a/crawl4ai/async_configs.py
+++ b/crawl4ai/async_configs.py
@@ -372,6 +372,19 @@ def _clamp_untrusted(type_name: str, params: dict) -> dict:
params[f] = _cap_timeout(params[f])
if isinstance(params.get("max_scroll_steps"), int):
params["max_scroll_steps"] = min(params["max_scroll_steps"], _MAX_SCROLL_STEPS)
+ # smart_wait runs "js:...", function-shaped values, and any value that
+ # is not a valid selector as page JavaScript -- the js_code ban by
+ # another name. Untrusted callers get CSS selector waits only; the
+ # "css:" branch never falls back to JS.
+ wait_for = params.get("wait_for")
+ if isinstance(wait_for, str) and wait_for.strip():
+ wait_for = wait_for.strip()
+ if wait_for.startswith(("js:", "()", "function")):
+ raise UntrustedConfigError(
+ "a JavaScript wait_for is not permitted from an untrusted request"
+ )
+ if not wait_for.startswith("css:"):
+ params["wait_for"] = "css:" + wait_for
elif type_name == "BrowserConfig":
for f in ("viewport_width", "viewport_height"):
if isinstance(params.get(f), int):
diff --git a/crawl4ai/async_crawler_strategy.py b/crawl4ai/async_crawler_strategy.py
index 6d0fb476..f25e7217 100644
--- a/crawl4ai/async_crawler_strategy.py
+++ b/crawl4ai/async_crawler_strategy.py
@@ -1099,10 +1099,14 @@ class AsyncPlaywrightCrawlerStrategy(AsyncCrawlerStrategy):
for selector in selectors:
try:
+ # Passed as an argument, never pasted into the
+ # script: a '"' in the selector used to end the
+ # string literal and run the rest as JavaScript.
content = await self.adapter.evaluate(page,
- f"""Array.from(document.querySelectorAll("{selector}"))
+ """(sel) => Array.from(document.querySelectorAll(sel))
.map(el => el.outerHTML)
- .join('')"""
+ .join('')""",
+ selector,
)
html_parts.append(content)
except Error as e:
diff --git a/tests/browser/test_css_selector_injection.py b/tests/browser/test_css_selector_injection.py
new file mode 100644
index 00000000..1e8f8889
--- /dev/null
+++ b/tests/browser/test_css_selector_injection.py
@@ -0,0 +1,59 @@
+"""css_selector is a selector, never script text.
+
+_crawl_web used to paste each selector into an f-string that it evaluated in
+the page, so a '"' in the value closed the string literal and the rest ran as
+JavaScript (0.9.5 report). The selector is now passed to the page as an
+argument. Loopback only; needs a local Chromium.
+"""
+import asyncio
+import threading
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+import pytest
+
+from crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig
+
+PAGE = b'<html><body><p title="x">quoted</p><p>other</p></body></html>'
+
+
+def server():
+ hits = []
+
+ class H(BaseHTTPRequestHandler):
+ def do_GET(self):
+ hits.append(self.path)
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html")
+ self.end_headers()
+ self.wfile.write(PAGE)
+
+ def log_message(self, *a):
+ pass
+
+ srv = HTTPServer(("127.0.0.1", 0), H)
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ yield f"http://127.0.0.1:{srv.server_address[1]}", hits
+ srv.shutdown()
+
+
+async def _crawl(url, selector):
+ async with AsyncWebCrawler(config=BrowserConfig(headless=True, verbose=False)) as c:
+ return await c.arun(url=url, config=CrawlerRunConfig(css_selector=selector))
+
+
+async def test_css_selector_cannot_inject_javascript(server):
+ base, hits = server
+ payload = f'*"))+fetch("{base}/pwned")+Array.from(document.querySelectorAll("*'
+ await _crawl(f"{base}/page", payload)
+ await asyncio.sleep(0.5)
+ assert "/pwned" not in hits
+
+
+async def test_css_selector_with_quotes_still_selects(server):
+ base, _ = server
+ result = await _crawl(f"{base}/page", 'p[title="x"]')
+ assert "quoted" in result.html
+ assert "other" not in result.html
diff --git a/tests/unit/test_untrusted_field_sinks.py b/tests/unit/test_untrusted_field_sinks.py
new file mode 100644
index 00000000..5b974440
--- /dev/null
+++ b/tests/unit/test_untrusted_field_sinks.py
@@ -0,0 +1,49 @@
+"""Allowlisted untrusted fields that reached code, model-load or regex sinks.
+
+Three 0.9.5 reports, one gate (crawl4ai/async_configs.py): a field the
+untrusted gate let through by name still carried code (wait_for "js:..."), a
+HuggingFace repo id (CosineStrategy.model_name), or a regex that backtracks
+for hours with the GIL held (RegexExtractionStrategy.custom,
+RegexChunking.patterns, schema fields of type "regex").
+
+No browser, no network, no model download: everything here is the gate.
+"""
+import pytest
+
+from crawl4ai.async_configs import CrawlerRunConfig, Provenance, UntrustedConfigError
+
+
+def _load(params, provenance=Provenance.UNTRUSTED):
+ return CrawlerRunConfig.load(
+ {"type": "CrawlerRunConfig", "params": params}, provenance=provenance
+ )
+
+
+# ── wait_for ───────────────────────────────────────────────────────────
+
+
+ "value",
+ [
+ "js:() => { fetch('http://x/'); return true; }",
+ "() => { fetch('http://x/'); return true; }",
+ "function () { return true; }",
+ ],
+)
+def test_untrusted_wait_for_javascript_refused(value):
+ with pytest.raises(UntrustedConfigError):
+ _load({"wait_for": value})
+
+
+def test_untrusted_bare_wait_for_is_pinned_to_css():
+ """A bare value used to fall back to JS when it was not a valid selector."""
+ assert _load({"wait_for": "fetch('http://x/'); return true;"}).wait_for == (
+ "css:fetch('http://x/'); return true;"
+ )
+ assert _load({"wait_for": "#main"}).wait_for == "css:#main"
+ assert _load({"wait_for": "css:#main"}).wait_for == "css:#main"
+
+
+def test_trusted_wait_for_unchanged():
+ value = "js:() => true"
+ assert _load({"wait_for": value}, Provenance.TRUSTED).wait_for == value