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(pdf): validate egress destinations and bound resource use in PDF fetch

ntohidi4772236b9ed0
diff --git a/crawl4ai/async_configs.py b/crawl4ai/async_configs.py
index 87500a90..383079fe 100644
--- a/crawl4ai/async_configs.py
+++ b/crawl4ai/async_configs.py
@@ -296,6 +296,8 @@ UNTRUSTED_FIELD_ALLOWLIST = {
_MAX_TIMEOUT_MS = 60_000
_MAX_SCROLL_STEPS = 1000
_MAX_VIEWPORT = 4000
+_MAX_PDF_BYTES = 100 * 1024 * 1024
+_MAX_PDF_PAGES = 2000
def _filter_untrusted_fields(type_name: str, params: dict) -> dict:
@@ -332,6 +334,17 @@ def _clamp_untrusted(type_name: str, params: dict) -> dict:
for f in ("viewport_width", "viewport_height"):
if isinstance(params.get(f), int):
params[f] = max(1, min(params[f], _MAX_VIEWPORT))
+ elif type_name == "PDFContentScrapingStrategy":
+ # This class has no field allowlist, so without clamping a body could
+ # simply raise its own caps back to unbounded and re-open the DoS.
+ for f, cap in (("max_pdf_bytes", _MAX_PDF_BYTES), ("max_pdf_pages", _MAX_PDF_PAGES)):
+ if f in params:
+ v = params[f]
+ # <=0 or non-int would read as "no limit"; pin to the cap.
+ params[f] = cap if not isinstance(v, int) or v <= 0 else min(v, cap)
+ # Rasterizing every page is the most expensive thing this strategy can
+ # do, and nothing about untrusted crawling needs it.
+ params["extract_images"] = False
return params
diff --git a/crawl4ai/processors/pdf/__init__.py b/crawl4ai/processors/pdf/__init__.py
index b41677c6..9fc5ad78 100644
--- a/crawl4ai/processors/pdf/__init__.py
+++ b/crawl4ai/processors/pdf/__init__.py
@@ -7,7 +7,44 @@ from crawl4ai.models import AsyncCrawlResponse, ScrapingResult
from crawl4ai.content_scraping_strategy import ContentScrapingStrategy
from .processor import NaivePDFProcessorStrategy # Assuming your current PDF code is in pdf_processor.py
-MAX_PDF_DOWNLOAD_REDIRECTS = 10 # Max redirect hops to follow when downloading a PDF
+# Default resource bounds for remote PDF fetches. These cap what an untrusted
+# caller can make the process download and parse; see set_url_validator() for
+# the destination side of the same problem.
+DEFAULT_MAX_PDF_BYTES = 100 * 1024 * 1024 # 100 MiB
+DEFAULT_MAX_PDF_PAGES = 2000
+DEFAULT_MAX_REDIRECTS = 5
+
+_REDIRECT_STATUSES = (301, 302, 303, 307, 308)
+
+# Destination-policy hooks, injected by whoever embeds the library.
+#
+# 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 installs the egress
+# broker here at boot so the PDF path enforces the same non-global-IP policy
+# the browser path already gets via enforce_egress().
+#
+# _url_validator runs on every hop (initial URL and each redirect Location).
+# _peer_ip_validator runs on the IP actually connected to; without it a name
+# that passed validation could still resolve to an internal address on the
+# second lookup requests performs (DNS rebinding).
+# Both must raise to block; returning anything is treated as "allowed".
+_url_validator = None
+_peer_ip_validator = None
+
+
+def set_url_validator(fn):
+ """Install a per-hop destination validator: fn(url) -> None, raises to block."""
+ global _url_validator
+ _url_validator = fn
+
+
+def set_peer_ip_validator(fn):
+ """Install a connected-peer check: fn(ip: str) -> None, raises to block."""
+ global _peer_ip_validator
+ _peer_ip_validator = fn
+
class PDFCrawlerStrategy(AsyncCrawlerStrategy):
"""Crawler strategy for PDF documents.
@@ -18,7 +55,6 @@ class PDFCrawlerStrategy(AsyncCrawlerStrategy):
which performs the actual PDF download and content extraction. With any
other scraping strategy the result will contain only the placeholder text.
"""
-
def __init__(self, logger: AsyncLogger = None):
self.logger = logger
@@ -65,20 +101,30 @@ class PDFContentScrapingStrategy(ContentScrapingStrategy):
)
"""
- def __init__(self,
+ def __init__(self,
save_images_locally : bool = False,
extract_images : bool = False,
image_save_dir : str = None,
batch_size: int = 4,
+ max_pdf_bytes: int = DEFAULT_MAX_PDF_BYTES,
+ max_pdf_pages: int = DEFAULT_MAX_PDF_PAGES,
+ max_redirects: int = DEFAULT_MAX_REDIRECTS,
logger: AsyncLogger = None,
url_validator=None):
self.logger = logger
- self.url_validator = url_validator # vets the download URL before fetch
+ # Per-instance validator, set by deploy/docker/api.py on the strategy it
+ # builds for a request. It runs in addition to the module-level policy
+ # installed at server boot, not instead of it.
+ self.url_validator = url_validator
+ self.max_pdf_bytes = max_pdf_bytes
+ self.max_pdf_pages = max_pdf_pages
+ self.max_redirects = max_redirects
self.pdf_processor = NaivePDFProcessorStrategy(
save_images_locally=save_images_locally,
extract_images=extract_images,
image_save_dir=image_save_dir,
- batch_size=batch_size
+ batch_size=batch_size,
+ max_pages=max_pdf_pages
)
self._temp_files = [] # Track temp files for cleanup
@@ -152,79 +198,159 @@ class PDFContentScrapingStrategy(ContentScrapingStrategy):
return await asyncio.to_thread(self.scrap, url, html, **kwargs)
+ def _discard_temp_file(self, path: str) -> None:
+ Path(path).unlink(missing_ok=True)
+ if path in self._temp_files:
+ self._temp_files.remove(path)
+
+ @staticmethod
+ def _peer_ip(response):
+ """Best-effort peer address of a streaming response, or None.
+
+ The socket lives in a different place across urllib3 majors, and on a
+ bodyless response (a redirect) it is already released -- hence None
+ rather than an exception, and hence `strict` in _check_peer_ip.
+ """
+ for get_sock in (
+ lambda: response.raw._fp.fp.raw._sock, # urllib3 2.x
+ lambda: response.raw._original_response.fp.raw._sock, # urllib3 1.x
+ lambda: response.raw._connection.sock,
+ ):
+ try:
+ sock = get_sock()
+ if sock is not None:
+ return sock.getpeername()[0]
+ except Exception:
+ continue
+ return None
+
+ def _check_peer_ip(self, response, strict: bool = True) -> None:
+ """Validate the address actually connected to.
+
+ Validating the URL only proves the *name* resolved somewhere allowed;
+ requests resolves it again when it dials, so a hostname with a short
+ TTL can point somewhere internal by then (DNS rebinding). Checking the
+ connected peer is what closes that window.
+
+ `strict` is False for redirect hops, where urllib3 has already released
+ the socket and no peer is observable. Those hops are still covered by
+ the per-hop URL validation; what strict mode protects is the response
+ whose body we are about to read back to the caller, which is where a
+ rebound connection would actually exfiltrate something.
+ """
+ if not _peer_ip_validator:
+ return
+
+ peer = self._peer_ip(response)
+ if peer is None:
+ if not strict:
+ return
+ # Fail closed: a policy was installed, so an unverifiable peer on
+ # the response we are about to read is not something to wave through.
+ response.close()
+ raise RuntimeError("Could not determine peer address for PDF download")
+
+ try:
+ _peer_ip_validator(peer)
+ except Exception:
+ response.close()
+ raise
+
+ def _fetch_with_redirect_checks(self, requests, url: str):
+ """GET `url`, validating every hop against the injected destination policy.
+
+ Redirects are followed by hand because requests would otherwise chase a
+ Location into a private address without consulting the validator at all
+ -- a public URL that 302s to 169.254.169.254 was the reported SSRF.
+ Returns an open streaming response; the caller closes it.
+ """
+ from urllib.parse import urljoin
+
+ current = url
+ # One Session for the whole chain: a bare requests.get() per hop starts
+ # with an empty cookie jar, so a host that sets a cookie and then
+ # redirects (common for gated or CDN-signed PDFs) would never get it
+ # back. allow_redirects=True used to carry cookies for us.
+ session = requests.Session()
+ for _ in range(self.max_redirects + 1):
+ if self.url_validator:
+ self.url_validator(current)
+ if _url_validator:
+ _url_validator(current)
+
+ # Connection timeout: 20s, Read timeout: 600s (for large PDFs)
+ response = session.get(
+ current, stream=True, timeout=(20, 60 * 10), allow_redirects=False
+ )
+ is_redirect = response.status_code in _REDIRECT_STATUSES
+ self._check_peer_ip(response, strict=not is_redirect)
+
+ if is_redirect:
+ location = response.headers.get('location')
+ response.close()
+ if not location:
+ raise RuntimeError(f"Redirect without Location header from {current}")
+ # Relative Locations are legal, so resolve against the current
+ # URL before validating -- the validator needs an absolute URL.
+ current = urljoin(current, location)
+ continue
+
+ response.raise_for_status()
+ return response
+
+ raise RuntimeError(
+ f"Too many redirects (>{self.max_redirects}) downloading PDF from {url}"
+ )
+
def _get_pdf_path(self, url: str) -> str:
if url.startswith(("http://", "https://")):
import tempfile
import requests
-
+
# Create temp file with .pdf extension
temp_file = tempfile.NamedTemporaryFile(suffix='.pdf', delete=False)
temp_file.close() # Close handle immediately; file persists due to delete=False
self._temp_files.append(temp_file.name)
-
+
try:
if self.logger:
self.logger.info(f"Downloading PDF from {url}...")
-
- # Download PDF with streaming and timeout
- # Connection timeout: 10s, Read timeout: 300s (5 minutes for large PDFs)
- # Redirects are followed manually so url_validator (when set) can vet every hop BEFORE it is fetched
- from urllib.parse import urljoin
- current_url = url
- # One Session for the whole chain: a bare requests.get() per hop
- # starts with an empty cookie jar, so a host that sets a cookie
- # and then redirects (common for gated/CDN-signed PDFs) would
- # get its own cookie back. allow_redirects=True used to carry
- # them for us; following hops by hand means we carry them here.
- session = requests.Session()
- for _ in range(MAX_PDF_DOWNLOAD_REDIRECTS):
- if self.url_validator:
- self.url_validator(current_url)
- response = session.get(current_url, stream=True, timeout=(20, 60 * 10),
- allow_redirects=False)
- if response.is_redirect:
- location = response.headers.get("location")
- response.close() # hop response holds its connection open (stream=True)
- if not location:
- raise RuntimeError(f"Redirect without Location header from {current_url}")
- current_url = urljoin(current_url, location)
- continue
- break
- else:
- raise RuntimeError(
- f"Too many redirects (>{MAX_PDF_DOWNLOAD_REDIRECTS}) downloading PDF from {url}")
- response.raise_for_status()
-
- # Get file size if available
- total_size = int(response.headers.get('content-length', 0))
+
+ response = self._fetch_with_redirect_checks(requests, url)
+
+ # content-length is a hint only: it is attacker-controlled and
+ # may be absent or understated, so the running total is what
+ # enforces the cap.
+ total_size = int(response.headers.get('content-length', 0) or 0)
downloaded = 0
-
- # Write to temp file
- with open(temp_file.name, 'wb') as f:
- for chunk in response.iter_content(chunk_size=8192):
- f.write(chunk)
- downloaded += len(chunk)
- if self.logger and total_size > 0:
- progress = (downloaded / total_size) * 100
- if progress % 10 < 0.1: # Log every 10%
- self.logger.debug(f"PDF download progress: {progress:.0f}%")
-
+
+ with response:
+ with open(temp_file.name, 'wb') as f:
+ for chunk in response.iter_content(chunk_size=8192):
+ downloaded += len(chunk)
+ if downloaded > self.max_pdf_bytes:
+ raise RuntimeError(
+ f"PDF from {url} exceeds max_pdf_bytes "
+ f"({self.max_pdf_bytes} bytes)"
+ )
+ f.write(chunk)
+ if self.logger and total_size > 0:
+ progress = (downloaded / total_size) * 100
+ if progress % 10 < 0.1: # Log every 10%
+ self.logger.debug(f"PDF download progress: {progress:.0f}%")
+
if self.logger:
self.logger.info(f"PDF downloaded successfully: {temp_file.name}")
-
+
return temp_file.name
-
+
except requests.exceptions.Timeout as e:
- # Clean up temp file if download fails
- Path(temp_file.name).unlink(missing_ok=True)
- self._temp_files.remove(temp_file.name)
+ self._discard_temp_file(temp_file.name)
raise RuntimeError(f"Timeout downloading PDF from {url}: {str(e)}")
except Exception as e:
- # Clean up temp file if download fails
- Path(temp_file.name).unlink(missing_ok=True)
- self._temp_files.remove(temp_file.name)
+ self._discard_temp_file(temp_file.name)
raise RuntimeError(f"Failed to download PDF from {url}: {str(e)}")
-
+
elif url.startswith("file://"):
return url[7:] # Strip file:// prefix
diff --git a/crawl4ai/processors/pdf/processor.py b/crawl4ai/processors/pdf/processor.py
index 1af25c05..96ff0d26 100644
--- a/crawl4ai/processors/pdf/processor.py
+++ b/crawl4ai/processors/pdf/processor.py
@@ -55,8 +55,9 @@ class PDFProcessorStrategy(ABC):
pass
class NaivePDFProcessorStrategy(PDFProcessorStrategy):
- def __init__(self, image_dpi: int = 144, image_quality: int = 85, extract_images: bool = True,
- save_images_locally: bool = False, image_save_dir: Optional[Path] = None, batch_size: int = 4):
+ def __init__(self, image_dpi: int = 144, image_quality: int = 85, extract_images: bool = True,
+ save_images_locally: bool = False, image_save_dir: Optional[Path] = None, batch_size: int = 4,
+ max_pages: Optional[int] = None):
# Import check at initialization time
try:
import pypdf
@@ -70,8 +71,24 @@ class NaivePDFProcessorStrategy(PDFProcessorStrategy):
self.save_images_locally = save_images_locally
self.image_save_dir = image_save_dir
self.batch_size = batch_size
+ # None means unbounded, which is the right default for a library caller
+ # opening a file they chose. Callers accepting untrusted PDFs (the
+ # Docker server) pass a cap so page count can't be used to burn CPU.
+ self.max_pages = max_pages
self._temp_dir = None
+ def _page_limit(self, total_pages: int) -> int:
+ """Number of pages to actually process, honouring max_pages."""
+ if self.max_pages is None:
+ return total_pages
+ capped = min(total_pages, self.max_pages)
+ if capped < total_pages:
+ logger.warning(
+ f"PDF has {total_pages} pages; processing first {capped} "
+ f"(max_pages={self.max_pages})"
+ )
+ return capped
+
def process(self, pdf_path: Path) -> PDFProcessResult:
# Import inside method to allow dependency to be optional
try:
@@ -101,7 +118,10 @@ class NaivePDFProcessorStrategy(PDFProcessorStrategy):
self._temp_dir = tempfile.mkdtemp(prefix='pdf_images_')
image_dir = Path(self._temp_dir)
+ page_limit = self._page_limit(len(reader.pages))
for page_num, page in enumerate(reader.pages):
+ if page_num >= page_limit:
+ break
self.current_page_number = page_num + 1
pdf_page = self._process_page(page, image_dir)
result.pages.append(pdf_page)
@@ -149,7 +169,7 @@ class NaivePDFProcessorStrategy(PDFProcessorStrategy):
with pdf_path.open('rb') as file:
reader = PdfReader(file)
result.metadata = self._extract_metadata(pdf_path, reader)
- total_pages = len(reader.pages)
+ total_pages = self._page_limit(len(reader.pages))
# Handle image directory setup
image_dir = None
diff --git a/deploy/docker/config.yml b/deploy/docker/config.yml
index 614ac24d..7aabc681 100644
--- a/deploy/docker/config.yml
+++ b/deploy/docker/config.yml
@@ -39,7 +39,7 @@ limits:
max_body_bytes: 10485760 # 10 MiB request body cap (413 if exceeded); 0 = unbounded
max_pages: 100 # deep-crawl page budget clamp (defense in depth)
max_depth: 5 # deep-crawl depth clamp
- wall_clock_s: 0 # per-crawl deadline in seconds (504 on timeout); 0 = no deadline
+ wall_clock_s: 300 # per-crawl deadline in seconds (504 on timeout); 0 = no deadline
queue: # background job queue for /crawl/job and /llm/job
maxsize: 1000 # max queued jobs (503 when full); 0 = unbounded
workers: 4 # concurrent background workers
diff --git a/deploy/docker/server.py b/deploy/docker/server.py
index 70352913..3636efb9 100644
--- a/deploy/docker/server.py
+++ b/deploy/docker/server.py
@@ -159,6 +159,37 @@ async def capped_arun(self, *a, **kw):
return await orig_arun(self, *a, **kw)
AsyncWebCrawler.arun = capped_arun
+
+def _install_pdf_egress_policy() -> None:
+ """Hand the PDF scraping strategy this server's egress policy.
+
+ PDFContentScrapingStrategy is in UNTRUSTED_ALLOWED_TYPES, so any API client
+ can select it and name the URL. It downloads with requests rather than the
+ browser, so none of the Chromium-side pinning applies to it. Injecting the
+ broker here makes the PDF path enforce the same non-global-IP rule on the
+ initial URL, on every redirect hop, and on the peer actually connected to.
+ """
+ from crawl4ai.processors.pdf import set_peer_ip_validator, set_url_validator
+ from egress_broker import (
+ ALLOW_INTERNAL,
+ EgressBlocked,
+ is_forbidden_ip,
+ resolve_and_pin,
+ )
+
+ def _validate_url(url: str) -> None:
+ resolve_and_pin(url) # raises EgressBlocked on a non-global destination
+
+ def _validate_peer(ip: str) -> None:
+ if ALLOW_INTERNAL:
+ return
+ if is_forbidden_ip(ip):
+ raise EgressBlocked()
+
+ set_url_validator(_validate_url)
+ set_peer_ip_validator(_validate_peer)
+
+
# ───────────────────── FastAPI lifespan ──────────────────────
@@ -182,6 +213,11 @@ async def lifespan(_: FastAPI):
app.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.
+ _install_pdf_egress_policy()
+
# Bounded background-job queue (per-principal quotas optional).
from work_queue import WorkQueue, set_job_queue
from governor import job_queue_caps
diff --git a/tests/unit/test_pdf_download_limits.py b/tests/unit/test_pdf_download_limits.py
new file mode 100644
index 00000000..99310735
--- /dev/null
+++ b/tests/unit/test_pdf_download_limits.py
@@ -0,0 +1,409 @@
+"""Regression tests for the PDF fetch path: destination validation and resource caps.
+
+Covers two reported issues:
+ - a public URL that redirects to an internal address must fail closed (SSRF)
+ - an oversized remote PDF must abort instead of filling the disk (DoS)
+
+The fetch helper takes the `requests` module as an argument, so these drive it
+with a stub and need no network or live server.
+"""
+
+import os
+
+import pytest
+
+from crawl4ai.processors.pdf import (
+ PDFContentScrapingStrategy,
+ set_peer_ip_validator,
+ set_url_validator,
+)
+import crawl4ai.processors.pdf as pdf_module
+
+
+class Blocked(Exception):
+ """Stand-in for egress_broker.EgressBlocked."""
+
+
+class FakeResponse:
+ def __init__(self, status_code=200, headers=None, chunks=(), peer_ip="93.184.216.34"):
+ self.status_code = status_code
+ self.headers = headers or {}
+ self._chunks = list(chunks)
+ self.closed = False
+ self.raw = self._make_raw(peer_ip)
+
+ def _make_raw(self, peer_ip):
+ """Mirror urllib3 2.x layout: raw._fp.fp.raw._sock.
+
+ Worth keeping faithful -- an earlier version of this stub exposed the
+ socket somewhere urllib3 does not, and hid a real bug.
+ """
+ if peer_ip is None:
+ return object() # bodyless response: socket already released
+
+ class _Sock:
+ def getpeername(self_inner):
+ return (peer_ip, 443)
+
+ class _SocketIO:
+ _sock = _Sock()
+
+ class _Buffered:
+ raw = _SocketIO()
+
+ class _HTTPResponse:
+ fp = _Buffered()
+
+ class _Raw:
+ _fp = _HTTPResponse()
+
+ return _Raw()
+
+ def iter_content(self, chunk_size=8192):
+ for chunk in self._chunks:
+ yield chunk
+
+ def raise_for_status(self):
+ if self.status_code >= 400:
+ raise RuntimeError(f"HTTP {self.status_code}")
+
+ def close(self):
+ self.closed = True
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *exc):
+ self.close()
+ return False
+
+
+class FakeRequests:
+ """Stub of the `requests` module surface the downloader uses."""
+
+ class exceptions:
+ class Timeout(Exception):
+ pass
+
+ def __init__(self, responses):
+ self._responses = list(responses)
+ self.calls = []
+
+ def get(self, url, **kwargs):
+ self.calls.append((url, kwargs))
+ return self._responses.pop(0)
+
+ def Session(self):
+ # The downloader opens one Session for the whole redirect chain, so a
+ # host that sets a cookie and then redirects gets it back on the next
+ # hop. Returning self keeps every call recorded in one place.
+ return self
+
+
[email protected](autouse=True)
+def _reset_validators():
+ """Validators are module-level globals; leaking one breaks later tests."""
+ yield
+ set_url_validator(None)
+ set_peer_ip_validator(None)
+
+
+def _strategy(**kwargs):
+ return PDFContentScrapingStrategy(**kwargs)
+
+
+# ── destination validation (SSRF) ──────────────────────────────────────
+
+
+def test_redirect_target_is_validated_and_blocked():
+ seen = []
+
+ def validator(url):
+ seen.append(url)
+ if "169.254.169.254" in url or "127.0.0.1" in url:
+ raise Blocked(url)
+
+ set_url_validator(validator)
+ strategy = _strategy()
+ requests = FakeRequests([
+ FakeResponse(302, {"location": "http://169.254.169.254/latest/meta-data/"}),
+ ])
+
+ with pytest.raises(Blocked):
+ strategy._fetch_with_redirect_checks(requests, "https://public.example/doc.pdf")
+
+ assert seen == [
+ "https://public.example/doc.pdf",
+ "http://169.254.169.254/latest/meta-data/",
+ ], "validator must run on the redirect target, not just the seed"
+
+
+def test_redirects_are_never_followed_by_requests_itself():
+ set_url_validator(lambda url: None)
+ strategy = _strategy()
+ requests = FakeRequests([
+ FakeResponse(302, {"location": "https://public.example/real.pdf"}),
+ FakeResponse(200, {"content-length": "4"}, [b"%PDF"]),
+ ])
+
+ strategy._fetch_with_redirect_checks(requests, "https://public.example/doc.pdf")
+
+ assert [kw["allow_redirects"] for _, kw in requests.calls] == [False, False]
+
+
+def test_relative_location_is_resolved_before_validation():
+ seen = []
+ set_url_validator(seen.append)
+ strategy = _strategy()
+ requests = FakeRequests([
+ FakeResponse(302, {"location": "/elsewhere.pdf"}),
+ FakeResponse(200, {}, [b"%PDF"]),
+ ])
+
+ strategy._fetch_with_redirect_checks(requests, "https://public.example/a/doc.pdf")
+
+ assert seen[1] == "https://public.example/elsewhere.pdf"
+
+
+def test_redirect_chain_is_bounded():
+ set_url_validator(lambda url: None)
+ strategy = _strategy(max_redirects=2)
+ requests = FakeRequests([
+ FakeResponse(302, {"location": f"https://public.example/{i}.pdf"})
+ for i in range(5)
+ ])
+
+ with pytest.raises(RuntimeError, match="Too many redirects"):
+ strategy._fetch_with_redirect_checks(requests, "https://public.example/doc.pdf")
+
+
+def test_redirect_without_location_is_rejected():
+ set_url_validator(lambda url: None)
+ strategy = _strategy()
+ requests = FakeRequests([FakeResponse(302, {})])
+
+ with pytest.raises(RuntimeError, match="Redirect without Location"):
+ strategy._fetch_with_redirect_checks(requests, "https://public.example/doc.pdf")
+
+
+def test_peer_ip_is_checked_closing_dns_rebinding():
+ """The name may pass validation and still resolve inward when requests dials."""
+ set_url_validator(lambda url: None)
+
+ def peer_validator(ip):
+ if ip.startswith("127.") or ip.startswith("169.254."):
+ raise Blocked(ip)
+
+ set_peer_ip_validator(peer_validator)
+ strategy = _strategy()
+ response = FakeResponse(200, {}, [b"%PDF"], peer_ip="169.254.169.254")
+ requests = FakeRequests([response])
+
+ with pytest.raises(Blocked):
+ strategy._fetch_with_redirect_checks(requests, "https://public.example/doc.pdf")
+ assert response.closed, "blocked response must be closed, not leaked"
+
+
+def test_unverifiable_peer_fails_closed_on_the_body_response():
+ set_url_validator(lambda url: None)
+ set_peer_ip_validator(lambda ip: None)
+ strategy = _strategy()
+ response = FakeResponse(200, {}, [b"%PDF"], peer_ip=None) # no reachable socket
+ requests = FakeRequests([response])
+
+ with pytest.raises(RuntimeError, match="Could not determine peer address"):
+ strategy._fetch_with_redirect_checks(requests, "https://public.example/doc.pdf")
+
+
+def test_redirect_hop_without_observable_socket_is_not_fatal():
+ """urllib3 releases the socket on a bodyless 302; that must not break redirects."""
+ set_url_validator(lambda url: None)
+ set_peer_ip_validator(lambda ip: None)
+ strategy = _strategy()
+ requests = FakeRequests([
+ FakeResponse(302, {"location": "https://public.example/real.pdf"}, peer_ip=None),
+ FakeResponse(200, {}, [b"%PDF"]),
+ ])
+
+ response = strategy._fetch_with_redirect_checks(requests, "https://public.example/doc.pdf")
+
+ assert response.status_code == 200
+
+
+def test_no_validator_installed_leaves_plain_library_use_working():
+ strategy = _strategy()
+ requests = FakeRequests([FakeResponse(200, {}, [b"%PDF"])])
+
+ response = strategy._fetch_with_redirect_checks(requests, "https://public.example/doc.pdf")
+
+ assert response.status_code == 200
+
+
+# ── resource caps (DoS) ────────────────────────────────────────────────
+
+
+def test_download_aborts_past_max_bytes_and_cleans_up(monkeypatch):
+ strategy = _strategy(max_pdf_bytes=1024)
+ # Understated content-length must not be trusted: the running total decides.
+ requests = FakeRequests([
+ FakeResponse(200, {"content-length": "10"}, [b"A" * 512] * 8),
+ ])
+ monkeypatch.setattr(pdf_module, "requests", requests, raising=False)
+
+ import sys
+ monkeypatch.setitem(sys.modules, "requests", requests)
+
+ with pytest.raises(RuntimeError, match="exceeds max_pdf_bytes"):
+ strategy._get_pdf_path("https://public.example/huge.pdf")
+
+ assert strategy._temp_files == [], "temp file must be dropped from tracking"
+
+
+def test_download_under_cap_succeeds(monkeypatch):
+ import sys
+
+ strategy = _strategy(max_pdf_bytes=1024)
+ requests = FakeRequests([FakeResponse(200, {"content-length": "4"}, [b"%PDF"])])
+ monkeypatch.setitem(sys.modules, "requests", requests)
+
+ path = strategy._get_pdf_path("https://public.example/small.pdf")
+
+ try:
+ assert os.path.getsize(path) == 4
+ finally:
+ strategy._discard_temp_file(path)
+
+
+def test_page_limit_caps_page_count():
+ from crawl4ai.processors.pdf.processor import NaivePDFProcessorStrategy
+
+ processor = NaivePDFProcessorStrategy(max_pages=10)
+ assert processor._page_limit(5000) == 10
+ assert processor._page_limit(3) == 3
+
+
+def test_page_limit_unbounded_by_default():
+ from crawl4ai.processors.pdf.processor import NaivePDFProcessorStrategy
+
+ processor = NaivePDFProcessorStrategy()
+ assert processor._page_limit(5000) == 5000
+
+
+# ── untrusted-body clamping ────────────────────────────────────────────
+
+
+ "sent, expected_bytes, expected_pages",
+ [
+ ({"max_pdf_bytes": 10**12, "max_pdf_pages": 10**6}, 100 * 1024 * 1024, 2000),
+ ({"max_pdf_bytes": 0, "max_pdf_pages": 0}, 100 * 1024 * 1024, 2000),
+ ({"max_pdf_bytes": -1, "max_pdf_pages": -1}, 100 * 1024 * 1024, 2000),
+ ({"max_pdf_bytes": "huge", "max_pdf_pages": None}, 100 * 1024 * 1024, 2000),
+ ({"max_pdf_bytes": 1024, "max_pdf_pages": 5}, 1024, 5),
+ ],
+)
+def test_untrusted_body_cannot_raise_its_own_caps(sent, expected_bytes, expected_pages):
+ """An untrusted client must not be able to restore unbounded behavior."""
+ from crawl4ai.async_configs import _clamp_untrusted
+
+ out = _clamp_untrusted("PDFContentScrapingStrategy", dict(sent))
+
+ assert out["max_pdf_bytes"] == expected_bytes
+ assert out["max_pdf_pages"] == expected_pages
+
+
+# ── against real requests/urllib3 ───────────────────────────────────────
+
+
+def live_server():
+ """Loopback HTTP server serving a redirect and a small PDF body."""
+ import http.server
+ import socketserver
+ import threading
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_GET(self):
+ if self.path == "/redirect":
+ self.send_response(302)
+ self.send_header("Location", "/doc.pdf")
+ self.end_headers()
+ return
+ body = b"%PDF-1.4 " + b"x" * 4096
+ self.send_response(200)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def log_message(self, *args):
+ pass
+
+ server = socketserver.TCPServer(("127.0.0.1", 0), Handler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ try:
+ yield f"http://127.0.0.1:{server.server_address[1]}"
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+def test_real_redirect_chain_validates_every_hop_and_reads_peer(live_server):
+ """Exercises the actual urllib3 object graph, not a stub of it."""
+ import requests as real_requests
+
+ seen_urls, seen_ips = [], []
+ set_url_validator(seen_urls.append)
+ set_peer_ip_validator(seen_ips.append)
+ strategy = _strategy()
+
+ response = strategy._fetch_with_redirect_checks(real_requests, f"{live_server}/redirect")
+ response.close()
+
+ assert seen_urls == [f"{live_server}/redirect", f"{live_server}/doc.pdf"]
+ assert seen_ips == ["127.0.0.1"], "peer must be read from the body response"
+
+
+def test_real_internal_redirect_is_blocked(live_server):
+ """The reported attack shape: public seed -> 302 -> internal address."""
+ import requests as real_requests
+
+ def validator(url):
+ if "169.254.169.254" in url:
+ raise Blocked(url)
+
+ set_url_validator(validator)
+ strategy = _strategy()
+
+ # Point the seed at a redirect whose target is the metadata service.
+ requests = FakeRequests([
+ FakeResponse(302, {"location": "http://169.254.169.254/latest/meta-data/"}),
+ ])
+ with pytest.raises(Blocked):
+ strategy._fetch_with_redirect_checks(requests, f"{live_server}/redirect")
+
+ # And the real client never followed anything on its own.
+ response = real_requests.get(f"{live_server}/redirect", allow_redirects=False)
+ assert response.status_code == 302
+ response.close()
+
+
+def test_real_oversize_body_aborts(live_server, monkeypatch):
+ import sys
+
+ import requests as real_requests
+
+ monkeypatch.setitem(sys.modules, "requests", real_requests)
+ strategy = _strategy(max_pdf_bytes=1024) # server sends ~4 KiB
+
+ with pytest.raises(RuntimeError, match="exceeds max_pdf_bytes"):
+ strategy._get_pdf_path(f"{live_server}/doc.pdf")
+
+ assert strategy._temp_files == []
+
+
+def test_untrusted_body_cannot_enable_image_extraction():
+ from crawl4ai.async_configs import _clamp_untrusted
+
+ out = _clamp_untrusted("PDFContentScrapingStrategy", {"extract_images": True})
+
+ assert out["extract_images"] is False