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
release: merge 0.9.0 secure-by-default Docker server hardening into develop
unclecode60886d1a0c52
diff --git a/.github/workflows/security.yml b/.github/workflows/security.ymlnew file mode 100644index 00000000..14c80a1e--- /dev/null+++ b/.github/workflows/security.yml@@ -0,0 +1,65 @@+name: Security++# Runs the offline Docker-server security suite: behavioral tests for the+# secure-by-default posture (R1-R7). No network, browser, Redis or Docker needed+# - it boots the app via TestClient and monkeypatches DNS, so it is fast+# (~seconds) and deterministic.++on:+ push:+ branches: [main, develop, "security/**"]+ paths:+ - "deploy/docker/**"+ - "crawl4ai/async_configs.py"+ - ".github/workflows/security.yml"+ pull_request:+ paths:+ - "deploy/docker/**"+ - "crawl4ai/async_configs.py"+ - ".github/workflows/security.yml"++jobs:+ security-offline:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-python@v5+ with:+ python-version: "3.10"+ cache: pip++ - name: Install dependencies+ run: |+ python -m pip install --upgrade pip+ pip install -e .+ pip install -r deploy/docker/requirements.txt+ pip install pytest pytest-asyncio++ - name: Run security suite+ run: |+ pytest deploy/docker/tests/test_security_*.py -q++ posture-gate:+ # The headline secure-by-default acceptance gate, isolated so it can be a+ # required status check. xfail-marked items (e.g. the build-gated+ # --no-sandbox removal) do not fail this job.+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v4++ - uses: actions/setup-python@v5+ with:+ python-version: "3.10"+ cache: pip++ - name: Install dependencies+ run: |+ python -m pip install --upgrade pip+ pip install -e .+ pip install -r deploy/docker/requirements.txt+ pip install pytest pytest-asyncio++ - name: Default-posture gate+ run: |+ pytest deploy/docker/tests/test_security_default_posture.py -qdiff --git a/.gitignore b/.gitignoreindex b1beaf6c..9238148d 100644--- a/.gitignore+++ b/.gitignore@@ -308,3 +308,6 @@ HANDOFF-*.md# Local pipeline/run outputout/++# entrypoint.sh is a required deployment artifact (Dockerfile COPYs it)+!deploy/docker/entrypoint.shdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 883bb7b7..c09b7d2e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,51 @@ All notable changes to Crawl4AI will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.9.0] - 2026-06-18++0.9.0 is a major, secure-by-default release of the Crawl4AI Docker API server. The out-of-the-box deployment is now hardened with defense in depth: authentication is on by default, the server binds loopback unless you give it a token, and the network request body is treated as an untrusted trust boundary. This release contains breaking changes for the self-hosted HTTP server only. The core pip library (SDK / in-process use) is unchanged.++**What changed:** the Docker server moved from an open, trust-the-caller posture to a closed, secure-by-default one. Defaults that used to be permissive (open bind, no auth, request-supplied browser internals, TLS verification off, Redis with no password) are now safe by default and gated behind explicit configuration.++**What you must do:** set `CRAWL4AI_API_TOKEN` and re-issue any tokens, then review whether you relied on any of the request fields or features that are now configured server-side. Most plain "crawl these URLs" users only need the two steps in the "Everyone" section of the migration guide. The full guide is at `deploy/docker/MIGRATION.md`.++### Security++This release completes the secure-by-default hardening of the Docker API server begun in 0.8.7 and 0.8.8. It moves the worst remaining issues from mitigation to architecture: unauthenticated access and request-supplied code/config are eliminated by design rather than patched in place. Every change is hardening; users self-hosting the Docker server should upgrade and follow the migration guide.++- **Authentication on by default, loopback bind**: the server no longer serves an unauthenticated API on `0.0.0.0`. With no token it binds `127.0.0.1` and prints a one-off local token; exposing it requires `CRAWL4AI_API_TOKEN` and `Authorization: Bearer <token>` on every request except `GET /health`.+- **Request trust boundary**: a crawl request body now carries declarative, scalar options only. Fields that previously let a caller drive browser internals or arbitrary code are rejected at the network boundary.+- **Declarative hooks replace hook code**: arbitrary Python hook strings are replaced by a fixed set of declarative actions, removing request-supplied code from the server entirely.+- **Strengthened JWT, admin-scoped monitor actions, deny-by-default CORS, strict security headers, TLS verification on, password-protected loopback-only Redis, bounded job queue, generic error responses with correlation ids, and validated webhook headers** round out the defense-in-depth posture. See the migration guide for the full list.+- **Download path confinement (CWE-22)**: both download sinks now confine writes with basename plus realpath plus `O_NOFOLLOW`, closing a path-traversal-to-file-write class. Credit: Y4tacker.+- **SSRF destination validation on the streaming crawl path (CWE-918)**: `/crawl/stream` and `/crawl` with `stream=true` now validate the destination and return HTTP 400 for disallowed targets, matching the non-streaming handlers. Credit: KOH Jun Sheng.+- **Request-supplied `browser_config.extra_args` rejected (CWE-94)**: launch arguments can no longer be supplied over the network, closing a Chromium launch-arg injection class. Credit: Y4tacker, UDU_RisePho ([hoanggxyuuki](https://github.com/hoanggxyuuki)).++All reporters are credited in `SECURITY-CREDITS.md`. GitHub Security Advisories accompany this release.++### Breaking Changes++These apply to the self-hosted Docker API server only. The pip library is unaffected. See `deploy/docker/MIGRATION.md` for the step-by-step migration and `deploy/docker/SECURITY-VERIFY.md` for the deployment checklist.++- **Auth is on by default**: set `CRAWL4AI_API_TOKEN` and send `Authorization: Bearer <token>`. With no token the server binds loopback only.+- **Loopback bind by default**: the server no longer binds `0.0.0.0` without a token; put a TLS-terminating reverse proxy in front when you expose it.+- **Tokens must be re-issued**: the JWT implementation changed and tokens from older versions are no longer valid. Re-mint via `POST /token`.+- **Request trust boundary**: `js_code`, `js_code_before_wait`, `c4a_script`, `proxy` / `proxy_config`, `extra_args`, `user_data_dir`, `cdp_url`, `cookies`, `headers`, `init_scripts`, `base_url`, `deep_crawl_strategy`, `simulate_user`, `magic`, `process_in_browser`, and nested LLM config objects are rejected with HTTP 400 when sent over the network. Configure them server-side or use the in-process SDK. Unknown fields are dropped; timeouts, viewport, and scroll counts are clamped.+- **Hooks are declarative**: `hooks.code` is replaced by a fixed action set (`block_resources`, `add_cookies`, `set_headers`, `scroll_to_bottom`, `wait_for_timeout`). See `GET /hooks/info`.+- **`output_path` removed, replaced by an artifact id**: `/screenshot` and `/pdf` store the result and return `artifact_id` + URL; fetch via authenticated `GET /artifacts/{artifact_id}` (TTL and quota apply).+- **LLM `base_url` removed**: `/md`, `/llm`, and `/llm/job` select a provider by name only; endpoint and key are configured server-side and constrained by `config.llm.allowed_providers`.+- **Monitor actions require an admin token**: `POST /monitor/actions/*` and `/monitor/stats/reset` need an admin-scope principal.+- **CORS deny-by-default**: cross-origin browser requests are denied unless listed in `security.cors_allow_origins`.+- **TLS verification on**: self-signed / internal TLS targets fail by default. Escape hatches for trusted internal testing: `CRAWL4AI_ALLOW_INSECURE_TLS=true`, `CRAWL4AI_ALLOW_INTERNAL_URLS=true`.+- **Webhook headers validated**: malformed or hop-by-hop / sensitive headers are rejected with HTTP 422.+- **Redis requires a password**: in-container Redis is loopback-only, password-protected, and its port is no longer published. For external Redis set `REDIS_PASSWORD`.+- **Bounded background job queue**: request body size, per-crawl wall clock, queue size, and per-principal concurrency are now capped (configurable; `0` = unbounded).+- **Generic 5xx responses**: server errors return `{"error": "Internal server error", "correlation_id": "…"}`; match the id in the logs for detail.++### Security Credits++Y4tacker, KOH Jun Sheng, and UDU_RisePho ([hoanggxyuuki](https://github.com/hoanggxyuuki)). See `SECURITY-CREDITS.md`.+## [0.8.9] - 2026-06-040.8.9 is a follow-up, backward-compatible security patch for the self-hosted Docker API server, closing an SSRF path that 0.8.8 did not cover. Upgrade in place; no configuration changes required.diff --git a/Dockerfile b/Dockerfileindex 8d7e06f7..6434ff73 100644--- a/Dockerfile+++ b/Dockerfile@@ -1,7 +1,7 @@FROM python:3.12-slim-bookworm AS build# C4ai version-ARG C4AI_VER=0.8.9+ARG C4AI_VER=0.9.0ENV C4AI_VERSION=$C4AI_VERLABEL c4ai.version=$C4AI_VER@@ -193,12 +193,18 @@ COPY deploy/docker/* ${APP_HOME}/# copy the playground + any future static assetsCOPY deploy/docker/static ${APP_HOME}/static-# Change ownership of the application directory to the non-root user-RUN chown -R appuser:appuser ${APP_HOME}+# /app is root-owned and read-only to the runtime user: a write bug can no+# longer plant a persistent self-RCE in the application directory.+RUN chown -R root:root ${APP_HOME} && chmod -R a-w ${APP_HOME}# give permissions to redis persistence dirs if usedRUN mkdir -p /var/lib/redis /var/log/redis && chown -R appuser:appuser /var/lib/redis /var/log/redis+# Sandboxed artifact store (server-owned screenshot/PDF outputs), 0700.+RUN mkdir -p /var/lib/crawl4ai/outputs \+ && chown -R appuser:appuser /var/lib/crawl4ai \+ && chmod 700 /var/lib/crawl4ai/outputs+HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \CMD bash -c '\MEM=$(free -m | awk "/^Mem:/{print \$2}"); \@@ -209,12 +215,15 @@ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \redis-cli ping > /dev/null && \curl -f http://localhost:11235/health || exit 1'-EXPOSE 6379+# Redis is in-container only (loopback + requirepass); never expose its port.+# (was: EXPOSE 6379)# Switch to the non-root user before starting the applicationUSER appuser# Set environment variables to ptoductionENV PYTHON_ENV=production-# Start the application using supervisord-CMD ["supervisord", "-c", "supervisord.conf"]\ No newline at end of file+# Start via entrypoint.sh, which resolves the socket-level auth/egress posture+# (loopback unless a credential is present) and the redis password, then execs+# supervisord.+CMD ["bash", "entrypoint.sh"]\ No newline at end of filediff --git a/README.md b/README.mdindex 1ab6fd26..733678be 100644--- a/README.md+++ b/README.md@@ -37,9 +37,11 @@ Limited slots._Crawl4AI turns the web into clean, LLM ready Markdown for RAG, agents, and data pipelines. Fast, controllable, battle tested by a 50k+ star community.-[✨ Check out latest update v0.8.9](#-recent-updates)+[✨ Check out latest update v0.9](#-recent-updates)-✨ **New in v0.8.9**: Follow-up security patch for the self-hosted Docker API server, closing an SSRF via proxy settings that 0.8.8 did not cover. Backward compatible. If you run the Docker server, upgrade. A larger secure-by-default release with breaking changes is coming in ~1-2 weeks. [Release notes →](https://github.com/unclecode/crawl4ai/blob/main/docs/blog/release-v0.8.9.md)+✨ **New in v0.9**: Major secure-by-default release of the Docker API server. Auth is on by default, the server binds loopback unless given a token, and the request body is now an untrusted trust boundary. Breaking changes for the self-hosted server only; the pip library is unchanged. If you self-host the Docker API, read the [migration guide](https://github.com/unclecode/crawl4ai/blob/main/deploy/docker/MIGRATION.md) before upgrading. [Release notes →](https://github.com/unclecode/crawl4ai/blob/main/docs/blog/release-v0.9.0.md)++✨ Recent v0.8.7: Security-hardening release. Fixes critical Docker API vulnerabilities (RCE, SSRF, auth bypass, file write, XSS, hardcoded JWT secret), adds DomainMapper, and ships scraping, deep-crawl, and LLM fixes. [Release notes →](https://github.com/unclecode/crawl4ai/blob/main/docs/blog/release-v0.8.7.md)✨ Recent v0.8.6: Security hotfix that replaced `litellm` with `unclecode-litellm` due to a PyPI supply chain compromise.@@ -565,28 +567,17 @@ async def test_news_crawl():## ✨ Recent Updates<details open>-<summary><strong>Version 0.8.9 Release Highlights - Proxy SSRF Patch</strong></summary>--A follow-up, backward-compatible security patch for the self-hosted Docker API server: closes an SSRF via proxy settings (`proxy_config.server`, the deprecated `proxy`, `crawler_config.proxy_config`, and proxy/DNS flags in `extra_args`) that 0.8.8 did not cover. Proxy destinations are now validated like crawl URLs. Upgrade in place, no config changes. A larger secure-by-default release with breaking changes is coming in ~1-2 weeks; a migration guide will accompany the pre-announcement.--```bash-pip install -U crawl4ai-```--[Full v0.8.9 Release Notes →](https://github.com/unclecode/crawl4ai/blob/main/docs/blog/release-v0.8.9.md)+<summary><strong>Version 0.9.0 Release Highlights - Secure-by-Default Docker Server</strong></summary>-</details>--<details>-<summary><strong>Version 0.8.8 Release Highlights - Docker Server Security Patch</strong></summary>+A major, secure-by-default release of the Docker API server. The out-of-the-box deployment is hardened with defense in depth: authentication is on by default, the server binds loopback unless you give it a token, and the network request body is treated as an untrusted trust boundary. Request-supplied browser internals and hook code are gone; hooks are declarative, `output_path` is replaced by an artifact store, TLS verification is on, CORS is deny-by-default, and Redis is password-protected and loopback-only.-A focused, backward-compatible security patch for the self-hosted Docker API server: closes SSRF filter gaps (IPv6 transition forms), hardens screenshot/PDF `output_path` against a symlink write, stops LLM credential exfiltration via a request `base_url`, and adds CRLF-safe logging and webhook header validation. Upgrade in place, no config changes.+This is a breaking release for the self-hosted Docker server only. The core pip library (SDK / in-process use) is unchanged. If you self-host the Docker API, read the migration guide before upgrading.```bashpip install -U crawl4ai```-[Full v0.8.8 Release Notes →](https://github.com/unclecode/crawl4ai/blob/main/docs/blog/release-v0.8.8.md)+[Migration Guide →](https://github.com/unclecode/crawl4ai/blob/main/deploy/docker/MIGRATION.md) · [Full v0.9.0 Release Notes →](https://github.com/unclecode/crawl4ai/blob/main/docs/blog/release-v0.9.0.md)</details>diff --git a/SECURITY-CREDITS.md b/SECURITY-CREDITS.mdindex 37ed89e8..9a6f1324 100644--- a/SECURITY-CREDITS.md+++ b/SECURITY-CREDITS.md@@ -8,8 +8,11 @@ We thank the following security researchers for their responsible disclosure:| Jeongbean Jeon | [email protected] | File write, SSRF, monitor auth bypass, stored XSS | 2026-04-13 || wulonchia | [email protected] | File write via output_path (independent report) | 2026-04-13 || by111 (August829) | GitHub: [August829](https://github.com/August829) | Hardcoded JWT secret, eval in /config/dump, /execute_js, hook sandbox escape | 2026-04-14 |-| secsys_codex ([FORIMOC](https://github.com/FORIMOC)) | [email protected] | SSRF via /md, /crawl, /llm endpoints (URL destination validation) | 2026-04-18 |+| secsys_codex | [email protected] | SSRF via /md, /crawl, /llm endpoints (URL destination validation) | 2026-04-18 || Velayutham Selvaraj | [LinkedIn](https://www.linkedin.com/in/velayuthamselvaraj) | SSRF via missing host validation in validate_url_scheme (independent report) | 2026-05-06 || IcySun & Yashon | [email protected], [email protected] | SSRF, file write via output_path, missing auth by default, hook sandbox bypass via asyncio (independent report) | 2026-05-15 || Geo ([geo-chen](https://github.com/geo-chen)) | [email protected] | LLM API key exfiltration via unvalidated base_url (0.8.8) | 2026-06-02 || Geo ([geo-chen](https://github.com/geo-chen)) | [email protected] | SSRF via proxy_config.server bypassing the SSRF check (0.8.9) | 2026-06-04 |+| Y4tacker | [email protected] | Download path traversal -> file write; Chromium launch-arg injection via extra_args (0.9.0) | 2026-06-18 |+| KOH Jun Sheng ([seankohjs](https://github.com/seankohjs)) | [email protected] | SSRF on the streaming crawl path /crawl/stream (0.9.0) | 2026-06-18 |+| UDU_RisePho | GitHub: [hoanggxyuuki](https://github.com/hoanggxyuuki) | Chromium launch-flag RCE class via extra_args (0.9.0) | 2026-06-18 |diff --git a/crawl4ai/__version__.py b/crawl4ai/__version__.pyindex f575cbdf..b7a714c5 100644--- a/crawl4ai/__version__.py+++ b/crawl4ai/__version__.py@@ -1,7 +1,7 @@# crawl4ai/__version__.py# This is the version that will be used for stable releases-__version__ = "0.8.9"+__version__ = "0.9.0"# For nightly builds, this gets set during build process__nightly_version__ = Nonediff --git a/crawl4ai/async_configs.py b/crawl4ai/async_configs.pyindex 92e5ac5f..27320fd4 100644--- a/crawl4ai/async_configs.py+++ b/crawl4ai/async_configs.py@@ -156,6 +156,166 @@ ALLOWED_DESERIALIZE_TYPES = {}+# ───────────────────────── untrusted-input trust boundary ─────────────────────────+# When a config is deserialized from an untrusted source (a network request body+# on the Docker server), it may only construct a strict subset of types and may+# only set scalar, non-power fields, which are then clamped. SDK / in-process use+# is TRUSTED by default, so this changes nothing for library callers.+++class Provenance(Enum):+ """Where deserialized config data came from.++ TRUSTED - SDK / in-process construction (unchanged behavior).+ UNTRUSTED - a network request body; gated by the allowlists below.+ """+ TRUSTED = "trusted"+ UNTRUSTED = "untrusted"+++class UntrustedConfigError(ValueError):+ """An untrusted request tried to construct a forbidden type or set a+ forbidden power-field. The Docker layer maps this to HTTP 400."""+++# Types an untrusted body may construct - a strict subset of+# ALLOWED_DESERIALIZE_TYPES. Deliberately EXCLUDES everything that can run code,+# read secrets, route traffic, or recurse the crawl: LLMConfig,+# LLMExtractionStrategy, LLMContentFilter, LLMTableExtraction, ProxyConfig,+# RoundRobinProxyStrategy, all DeepCrawl*/Filter/Scorer/Dispatcher classes,+# SeedingConfig and DomainMapperConfig.+UNTRUSTED_ALLOWED_TYPES = {+ "CrawlerRunConfig", "BrowserConfig", "HTTPCrawlerConfig",+ "GeolocationConfig", "VirtualScrollConfig", "LinkPreviewConfig",+ # non-LLM extraction / markdown / scraping / chunking strategies+ "JsonCssExtractionStrategy", "JsonXPathExtractionStrategy",+ "JsonLxmlExtractionStrategy", "RegexExtractionStrategy", "CosineStrategy",+ "DefaultMarkdownGenerator", "PruningContentFilter", "BM25ContentFilter",+ "LXMLWebScrapingStrategy", "PDFContentScrapingStrategy",+ "RegexChunking",+ "DefaultTableExtraction", "NoTableExtraction",+ # safe scalar enums+ "CacheMode", "MatchMode", "DisplayMode",+}++# Fields that must NEVER come from an untrusted body. Presence => 400 (loud), so+# a client smuggling these gets an explicit error rather than a silent drop.+UNTRUSTED_FORBIDDEN_FIELDS = {+ "BrowserConfig": {+ "proxy", "proxy_config", "extra_args", "user_data_dir", "channel",+ "chrome_channel", "cdp_url", "debugging_port", "host", "storage_state",+ "cookies", "headers", "init_scripts", "browser_context_id", "target_id",+ },+ "CrawlerRunConfig": {+ "js_code", "js_code_before_wait", "c4a_script", "deep_crawl_strategy",+ "proxy_config", "proxy_rotation_strategy", "proxy_session_id",+ "proxy_session_ttl", "proxy_session_auto_release",+ "fallback_fetch_function", "experimental", "base_url", "simulate_user",+ "override_navigator", "magic", "process_in_browser", "shared_data",+ "session_id",+ },+}++# Scalar knobs an untrusted body MAY set, per class. A field not listed here is+# dropped (forward-compatible: new SDK fields don't open a hole). Strategy-object+# fields are kept so the nested object is itself type-gated by the recursion.+UNTRUSTED_FIELD_ALLOWLIST = {+ "BrowserConfig": {+ "browser_type", "headless", "browser_mode", "viewport_width",+ "viewport_height", "viewport", "device_scale_factor", "accept_downloads",+ "java_script_enabled", "text_mode", "light_mode", "enable_stealth",+ "avoid_ads", "avoid_css", "user_agent", "user_agent_mode",+ "user_agent_generator_config", "verbose", "memory_saving_mode",+ "max_pages_before_recycle",+ },+ "CrawlerRunConfig": {+ # content selection / cleaning+ "word_count_threshold", "only_text", "css_selector", "target_elements",+ "excluded_tags", "excluded_selector", "keep_data_attributes", "keep_attrs",+ "remove_forms", "prettiify", "parser_type",+ # strategy objects (nested type is gated by the recursion)+ "extraction_strategy", "chunking_strategy", "markdown_generator",+ "scraping_strategy", "table_extraction",+ # locale / geo+ "locale", "timezone_id", "geolocation",+ # cache+ "cache_mode", "bypass_cache", "disable_cache", "no_cache_read",+ "no_cache_write", "check_cache_freshness", "cache_validation_timeout",+ "fetch_ssl_certificate",+ # timing / waiting+ "wait_until", "page_timeout", "wait_for", "wait_for_timeout",+ "wait_for_images", "delay_before_return_html", "mean_delay", "max_range",+ # scrolling / rendering+ "ignore_body_visibility", "scan_full_page", "scroll_delay",+ "max_scroll_steps", "process_iframes", "flatten_shadow_dom",+ "remove_overlay_elements", "remove_consent_popups",+ "adjust_viewport_to_content", "virtual_scroll_config",+ # media / capture+ "screenshot", "screenshot_wait_for", "screenshot_height_threshold",+ "force_viewport_screenshot", "pdf", "capture_mhtml",+ "image_description_min_word_threshold", "image_score_threshold",+ "table_score_threshold",+ # links / images filtering+ "exclude_external_images", "exclude_all_images",+ "exclude_social_media_domains", "exclude_external_links",+ "exclude_social_media_links", "exclude_domains", "exclude_internal_links",+ "score_links", "preserve_https_for_internal_links", "link_preview_config",+ # misc safe knobs+ "verbose", "log_console", "capture_network_requests",+ "capture_console_messages", "method", "stream", "prefetch", "url",+ "check_robots_txt", "user_agent", "user_agent_mode",+ "user_agent_generator_config", "url_matcher", "match_mode", "max_retries",+ },+}++# Upper bounds applied to attacker-influenced quantities after filtering.+_MAX_TIMEOUT_MS = 60_000+_MAX_SCROLL_STEPS = 1000+_MAX_VIEWPORT = 4000+++def _filter_untrusted_fields(type_name: str, params: dict) -> dict:+ """Drop non-allowlisted fields and raise on forbidden (power) fields."""+ forbidden = UNTRUSTED_FORBIDDEN_FIELDS.get(type_name, set())+ allowlist = UNTRUSTED_FIELD_ALLOWLIST.get(type_name) # None => keep all non-forbidden+ out = {}+ for key, value in params.items():+ if key in forbidden:+ raise UntrustedConfigError(+ f"field '{key}' is not permitted on {type_name} from an untrusted request"+ )+ if allowlist is not None and key not in allowlist:+ continue # silently drop unknown/unsafe fields (forward-compatible)+ out[key] = value+ return out+++def _clamp_untrusted(type_name: str, params: dict) -> dict:+ """Clamp attacker-influenced quantities to safe upper bounds."""+ def _cap_timeout(v):+ # 0 historically meant "no timeout"; treat as the cap, never unbounded.+ if not isinstance(v, (int, float)) or v <= 0:+ return _MAX_TIMEOUT_MS+ return min(int(v), _MAX_TIMEOUT_MS)++ if type_name == "CrawlerRunConfig":+ for f in ("page_timeout", "wait_for_timeout"):+ if f in params:+ 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)+ elif type_name == "BrowserConfig":+ for f in ("viewport_width", "viewport_height"):+ if isinstance(params.get(f), int):+ params[f] = max(1, min(params[f], _MAX_VIEWPORT))+ return params+++def _enforce_untrusted(type_name: str, params: dict) -> dict:+ """Filter then clamp a parameter dict for an untrusted construction."""+ return _clamp_untrusted(type_name, _filter_untrusted_fields(type_name, params))++def to_serializable_dict(obj: Any, ignore_default_value : bool = False):"""Recursively convert an object to a serializable dictionary using {type, params} structure@@ -237,10 +397,17 @@ def to_serializable_dict(obj: Any, ignore_default_value : bool = False):return str(obj)-def from_serializable_dict(data: Any) -> Any:+def from_serializable_dict(data: Any, provenance: "Provenance" = None) -> Any:"""Recursively convert a serializable dictionary back to an object instance.++ provenance defaults to TRUSTED (SDK/in-process). When UNTRUSTED, every typed+ object must be in UNTRUSTED_ALLOWED_TYPES and its params are filtered (drop+ unknown, raise on forbidden) and clamped before construction."""+ if provenance is None:+ provenance = Provenance.TRUSTED+if data is None:return None@@ -262,7 +429,7 @@ def from_serializable_dict(data: Any) -> Any:):# Handle plain dictionariesif data["type"] == "dict" and "value" in data:- return {k: from_serializable_dict(v) for k, v in data["value"].items()}+ return {k: from_serializable_dict(v, provenance) for k, v in data["value"].items()}# Security: only allow known-safe types to be deserialized.# Unknown types (e.g. logging.Logger serialized by older clients) are@@ -271,6 +438,13 @@ def from_serializable_dict(data: Any) -> Any:if type_name not in ALLOWED_DESERIALIZE_TYPES:return None+ # Untrusted bodies may only construct the strict subset of types and+ # may not set forbidden power-fields.+ if provenance == Provenance.UNTRUSTED and type_name not in UNTRUSTED_ALLOWED_TYPES:+ raise UntrustedConfigError(+ f"type '{type_name}' may not be constructed from an untrusted request"+ )+cls = Nonemodule_paths = ["crawl4ai"]for module_path in module_paths:@@ -288,19 +462,22 @@ def from_serializable_dict(data: Any) -> Any:return cls(data["params"])if "params" in data:+ params = data["params"]+ if provenance == Provenance.UNTRUSTED:+ params = _enforce_untrusted(type_name, dict(params))# Handle class instancesconstructor_args = {- k: from_serializable_dict(v) for k, v in data["params"].items()+ k: from_serializable_dict(v, provenance) for k, v in params.items()}return cls(**constructor_args)# Handle listsif isinstance(data, list):- return [from_serializable_dict(item) for item in data]+ return [from_serializable_dict(item, provenance) for item in data]# Handle raw dictionaries (legacy support)if isinstance(data, dict):- return {k: from_serializable_dict(v) for k, v in data.items()}+ return {k: from_serializable_dict(v, provenance) for k, v in data.items()}return data@@ -838,11 +1015,17 @@ class BrowserConfig:return to_serializable_dict(self)@staticmethod- def load(data: dict) -> "BrowserConfig":+ def load(data: dict, provenance: "Provenance" = None) -> "BrowserConfig":# Deserialize the object from a dictionary- config = from_serializable_dict(data)+ if provenance is None:+ provenance = Provenance.TRUSTED+ config = from_serializable_dict(data, provenance)if isinstance(config, BrowserConfig):return config+ # Plain-dict path: enforce the untrusted gate on top-level fields too,+ # so a body that sends bare kwargs (no {type,params}) cannot bypass it.+ if provenance == Provenance.UNTRUSTED and isinstance(config, dict):+ config = _enforce_untrusted("BrowserConfig", config)return BrowserConfig.from_kwargs(config)def set_nstproxy(@@ -1133,10 +1316,14 @@ class HTTPCrawlerConfig:return to_serializable_dict(self)@staticmethod- def load(data: dict) -> "HTTPCrawlerConfig":- config = from_serializable_dict(data)+ def load(data: dict, provenance: "Provenance" = None) -> "HTTPCrawlerConfig":+ if provenance is None:+ provenance = Provenance.TRUSTED+ config = from_serializable_dict(data, provenance)if isinstance(config, HTTPCrawlerConfig):return config+ if provenance == Provenance.UNTRUSTED and isinstance(config, dict):+ config = _enforce_untrusted("HTTPCrawlerConfig", config)return HTTPCrawlerConfig.from_kwargs(config)@_with_defaults@@ -1889,11 +2076,15 @@ class CrawlerRunConfig():return to_serializable_dict(self)@staticmethod- def load(data: dict) -> "CrawlerRunConfig":+ def load(data: dict, provenance: "Provenance" = None) -> "CrawlerRunConfig":# Deserialize the object from a dictionary- config = from_serializable_dict(data)+ if provenance is None:+ provenance = Provenance.TRUSTED+ config = from_serializable_dict(data, provenance)if isinstance(config, CrawlerRunConfig):return config+ if provenance == Provenance.UNTRUSTED and isinstance(config, dict):+ config = _enforce_untrusted("CrawlerRunConfig", config)return CrawlerRunConfig.from_kwargs(config)def to_dict(self):@@ -2022,30 +2213,6 @@ class CrawlerRunConfig():config_dict.update(kwargs)return CrawlerRunConfig.from_kwargs(config_dict)--# Environment variable names that `LLMConfig(api_token="env:NAME")` may NOT-# resolve. This blocks the credential-exfil gadget where an untrusted config-# body sets api_token="env:SECRET_KEY" and pairs it with a base_url to leak a-# server secret. Normal provider keys (OPENAI_API_KEY, ANTHROPIC_API_KEY,-# HF_TOKEN, ...) are unaffected.-_FORBIDDEN_ENV_SUBSTRINGS = ("SECRET", "PASSWORD", "PRIVATE", "PASSWD")-_FORBIDDEN_ENV_PREFIXES = ("CRAWL4AI", "AWS_SECRET")-_FORBIDDEN_ENV_EXACT = {"SECRET_KEY", "REDIS_PASSWORD", "TOKEN"}---def _is_forbidden_env_name(name: str) -> bool:- if not name:- return True- u = name.upper()- if u in _FORBIDDEN_ENV_EXACT:- return True- if any(s in u for s in _FORBIDDEN_ENV_SUBSTRINGS):- return True- if any(u.startswith(p) for p in _FORBIDDEN_ENV_PREFIXES):- return True- return False--class LLMConfig:def __init__(self,@@ -2062,23 +2229,40 @@ class LLMConfig:backoff_base_delay: Optional[int] = None,backoff_max_attempts: Optional[int] = None,backoff_exponential_factor: Optional[int] = None,+ provenance: "Provenance" = None,):"""Configuaration class for LLM provider and API token."""+ if provenance is None:+ provenance = Provenance.TRUSTED+ # Defense in depth: untrusted callers can already not reach here (the+ # type gate forbids constructing LLMConfig from a request body), but if+ # they ever do, never resolve env vars or read provider keys from the+ # environment - that is the credential-exfil gadget.+ if provenance == Provenance.UNTRUSTED:+ if api_token and api_token.startswith("env:"):+ raise UntrustedConfigError(+ "LLMConfig.api_token may not reference an environment variable "+ "from an untrusted request"+ )+ self.provider = provider+ self.api_token = api_token # never os.getenv+ self.base_url = base_url+ self.temperature = temperature+ self.max_tokens = max_tokens+ self.top_p = top_p+ self.frequency_penalty = frequency_penalty+ self.presence_penalty = presence_penalty+ self.stop = stop+ self.n = n+ self.backoff_base_delay = backoff_base_delay if backoff_base_delay is not None else 2+ self.backoff_max_attempts = backoff_max_attempts if backoff_max_attempts is not None else 3+ self.backoff_exponential_factor = backoff_exponential_factor if backoff_exponential_factor is not None else 2+ returnself.provider = providerif api_token and not api_token.startswith("env:"):self.api_token = api_tokenelif api_token and api_token.startswith("env:"):- # `env:NAME` resolves an environment variable. Refuse to read names- # that are clearly server secrets, so an untrusted config body cannot- # exfiltrate them via `env:SECRET_KEY` and a paired base_url. Normal- # provider keys (…_API_KEY / …_TOKEN) are unaffected.- _env_name = api_token[4:]- if _is_forbidden_env_name(_env_name):- raise ValueError(- f"LLMConfig.api_token may not reference the protected "- f"environment variable {_env_name!r}"- )- self.api_token = os.getenv(_env_name)+ self.api_token = os.getenv(api_token[4:])else:# Check if given provider starts with any of key in PROVIDER_MODELS_PREFIXES# If not, check if it is in PROVIDER_MODELSdiff --git a/crawl4ai/async_crawler_strategy.back.py b/crawl4ai/async_crawler_strategy.back.pydeleted file mode 100644index 9f1ed38d..00000000--- a/crawl4ai/async_crawler_strategy.back.py+++ /dev/null@@ -1,2450 +0,0 @@-from __future__ import annotations--import asyncio-import base64-import time-from abc import ABC, abstractmethod-from typing import Callable, Dict, Any, List, Union-from typing import Optional, AsyncGenerator, Final-import os-from playwright.async_api import Page, Error-from playwright.async_api import TimeoutError as PlaywrightTimeoutError-from io import BytesIO-from PIL import Image, ImageDraw, ImageFont-import hashlib-import uuid-from .js_snippet import load_js_script-from .models import AsyncCrawlResponse-from .config import SCREENSHOT_HEIGHT_TRESHOLD-from .async_configs import BrowserConfig, CrawlerRunConfig, HTTPCrawlerConfig-from .async_logger import AsyncLogger-from .ssl_certificate import SSLCertificate-from .user_agent_generator import ValidUAGenerator-from .browser_manager import BrowserManager--import aiofiles-import aiohttp-import chardet-from aiohttp.client import ClientTimeout-from urllib.parse import urlparse-from types import MappingProxyType-import contextlib-from functools import partial--class AsyncCrawlerStrategy(ABC):- """- Abstract base class for crawler strategies.- Subclasses must implement the crawl method.- """-- @abstractmethod- async def crawl(self, url: str, **kwargs) -> AsyncCrawlResponse:- pass # 4 + 3--class AsyncPlaywrightCrawlerStrategy(AsyncCrawlerStrategy):- """- Crawler strategy using Playwright.-- Attributes:- browser_config (BrowserConfig): Configuration object containing browser settings.- logger (AsyncLogger): Logger instance for recording events and errors.- _downloaded_files (List[str]): List of downloaded file paths.- hooks (Dict[str, Callable]): Dictionary of hooks for custom behavior.- browser_manager (BrowserManager): Manager for browser creation and management.-- Methods:- __init__(self, browser_config=None, logger=None, **kwargs):- Initialize the AsyncPlaywrightCrawlerStrategy with a browser configuration.- __aenter__(self):- Start the browser and initialize the browser manager.- __aexit__(self, exc_type, exc_val, exc_tb):- Close the browser and clean up resources.- start(self):- Start the browser and initialize the browser manager.- close(self):- Close the browser and clean up resources.- kill_session(self, session_id):- Kill a browser session and clean up resources.- crawl(self, url, **kwargs):- Run the crawler for a single URL.-- """-- def __init__(- self, browser_config: BrowserConfig = None, logger: AsyncLogger = None, **kwargs- ):- """- Initialize the AsyncPlaywrightCrawlerStrategy with a browser configuration.-- Args:- browser_config (BrowserConfig): Configuration object containing browser settings.- If None, will be created from kwargs for backwards compatibility.- logger: Logger instance for recording events and errors.- **kwargs: Additional arguments for backwards compatibility and extending functionality.- """- # Initialize browser config, either from provided object or kwargs- self.browser_config = browser_config or BrowserConfig.from_kwargs(kwargs)- self.logger = logger-- # Initialize session management- self._downloaded_files = []-- # Initialize hooks system- self.hooks = {- "on_browser_created": None,- "on_page_context_created": None,- "on_user_agent_updated": None,- "on_execution_started": None,- "on_execution_ended": None,- "before_goto": None,- "after_goto": None,- "before_return_html": None,- "before_retrieve_html": None,- }-- # Initialize browser manager with config- self.browser_manager = BrowserManager(- browser_config=self.browser_config, logger=self.logger- )-- async def __aenter__(self):- await self.start()- return self-- async def __aexit__(self, exc_type, exc_val, exc_tb):- await self.close()-- async def start(self):- """- Start the browser and initialize the browser manager.- """- await self.browser_manager.start()- await self.execute_hook(- "on_browser_created",- self.browser_manager.browser,- context=self.browser_manager.default_context,- )-- async def close(self):- """- Close the browser and clean up resources.- """- await self.browser_manager.close()- # Explicitly reset the static Playwright instance- BrowserManager._playwright_instance = None-- async def kill_session(self, session_id: str):- """- Kill a browser session and clean up resources.-- Args:- session_id (str): The ID of the session to kill.-- Returns:- None- """- # Log a warning message and no need kill session, in new version auto kill session- self.logger.warning(- message="Session auto-kill is enabled in the new version. No need to manually kill sessions.",- tag="WARNING",- )- await self.browser_manager.kill_session(session_id)-- def set_hook(self, hook_type: str, hook: Callable):- """- Set a hook function for a specific hook type. Following are list of hook types:- - on_browser_created: Called when a new browser instance is created.- - on_page_context_created: Called when a new page context is created.- - on_user_agent_updated: Called when the user agent is updated.- - on_execution_started: Called when the execution starts.- - before_goto: Called before a goto operation.- - after_goto: Called after a goto operation.- - before_return_html: Called before returning HTML content.- - before_retrieve_html: Called before retrieving HTML content.-- All hooks except on_browser_created accepts a context and a page as arguments and **kwargs. However, on_browser_created accepts a browser and a context as arguments and **kwargs.-- Args:- hook_type (str): The type of the hook.- hook (Callable): The hook function to set.-- Returns:- None- """- if hook_type in self.hooks:- self.hooks[hook_type] = hook- else:- raise ValueError(f"Invalid hook type: {hook_type}")-- async def execute_hook(self, hook_type: str, *args, **kwargs):- """- Execute a hook function for a specific hook type.-- Args:- hook_type (str): The type of the hook.- *args: Variable length positional arguments.- **kwargs: Keyword arguments.-- Returns:- The return value of the hook function, if any.- """- hook = self.hooks.get(hook_type)- if hook:- if asyncio.iscoroutinefunction(hook):- return await hook(*args, **kwargs)- else:- return hook(*args, **kwargs)- return args[0] if args else None-- def update_user_agent(self, user_agent: str):- """- Update the user agent for the browser.-- Args:- user_agent (str): The new user agent string.-- Returns:- None- """- self.user_agent = user_agent-- def set_custom_headers(self, headers: Dict[str, str]):- """- Set custom headers for the browser.-- Args:- headers (Dict[str, str]): A dictionary of headers to set.-- Returns:- None- """- self.headers = headers-- async def smart_wait(self, page: Page, wait_for: str, timeout: float = 30000):- """- Wait for a condition in a smart way. This functions works as below:-- 1. If wait_for starts with 'js:', it assumes it's a JavaScript function and waits for it to return true.- 2. If wait_for starts with 'css:', it assumes it's a CSS selector and waits for it to be present.- 3. Otherwise, it tries to evaluate wait_for as a JavaScript function and waits for it to return true.- 4. If it's not a JavaScript function, it assumes it's a CSS selector and waits for it to be present.-- This is a more advanced version of the wait_for parameter in CrawlerStrategy.crawl().- Args:- page: Playwright page object- wait_for (str): The condition to wait for. Can be a CSS selector, a JavaScript function, or explicitly prefixed with 'js:' or 'css:'.- timeout (float): Maximum time to wait in milliseconds-- Returns:- None- """- wait_for = wait_for.strip()-- if wait_for.startswith("js:"):- # Explicitly specified JavaScript- js_code = wait_for[3:].strip()- return await self.csp_compliant_wait(page, js_code, timeout)- elif wait_for.startswith("css:"):- # Explicitly specified CSS selector- css_selector = wait_for[4:].strip()- try:- await page.wait_for_selector(css_selector, timeout=timeout)- except Error as e:- if "Timeout" in str(e):- raise TimeoutError(- f"Timeout after {timeout}ms waiting for selector '{css_selector}'"- )- else:- raise ValueError(f"Invalid CSS selector: '{css_selector}'")- else:- # Auto-detect based on content- if wait_for.startswith("()") or wait_for.startswith("function"):- # It's likely a JavaScript function- return await self.csp_compliant_wait(page, wait_for, timeout)- else:- # Assume it's a CSS selector first- try:- await page.wait_for_selector(wait_for, timeout=timeout)- except Error as e:- if "Timeout" in str(e):- raise TimeoutError(- f"Timeout after {timeout}ms waiting for selector '{wait_for}'"- )- else:- # If it's not a timeout error, it might be an invalid selector- # Let's try to evaluate it as a JavaScript function as a fallback- try:- return await self.csp_compliant_wait(- page, f"() => {{{wait_for}}}", timeout- )- except Error:- raise ValueError(- f"Invalid wait_for parameter: '{wait_for}'. "- "It should be either a valid CSS selector, a JavaScript function, "- "or explicitly prefixed with 'js:' or 'css:'."- )-- async def csp_compliant_wait(- self, page: Page, user_wait_function: str, timeout: float = 30000- ):- """- Wait for a condition in a CSP-compliant way.-- Args:- page: Playwright page object- user_wait_function: JavaScript function as string that returns boolean- timeout: Maximum time to wait in milliseconds-- Returns:- bool: True if condition was met, False if timed out-- Raises:- RuntimeError: If there's an error evaluating the condition- """- wrapper_js = f"""- async () => {{- const userFunction = {user_wait_function};- const startTime = Date.now();- try {{- while (true) {{- if (await userFunction()) {{- return true;- }}- if (Date.now() - startTime > {timeout}) {{- return false; // Return false instead of throwing- }}- await new Promise(resolve => setTimeout(resolve, 100));- }}- }} catch (error) {{- throw new Error(`Error evaluating condition: ${{error.message}}`);- }}- }}- """-- try:- result = await page.evaluate(wrapper_js)- return result- except Exception as e:- if "Error evaluating condition" in str(e):- raise RuntimeError(f"Failed to evaluate wait condition: {str(e)}")- # For timeout or other cases, just return False- return False-- async def process_iframes(self, page):- """- Process iframes on a page. This function will extract the content of each iframe and replace it with a div containing the extracted content.-- Args:- page: Playwright page object-- Returns:- Playwright page object- """- # Find all iframes- iframes = await page.query_selector_all("iframe")-- for i, iframe in enumerate(iframes):- try:- # Add a unique identifier to the iframe- await iframe.evaluate(f'(element) => element.id = "iframe-{i}"')-- # Get the frame associated with this iframe- frame = await iframe.content_frame()-- if frame:- # Wait for the frame to load- await frame.wait_for_load_state(- "load", timeout=30000- ) # 30 seconds timeout-- # Extract the content of the iframe's body- iframe_content = await frame.evaluate(- "() => document.body.innerHTML"- )-- # Generate a unique class name for this iframe- class_name = f"extracted-iframe-content-{i}"-- # Replace the iframe with a div containing the extracted content- _iframe = iframe_content.replace("`", "\\`")- await page.evaluate(- f"""- () => {{- const iframe = document.getElementById('iframe-{i}');- const div = document.createElement('div');- div.innerHTML = `{_iframe}`;- div.className = '{class_name}';- iframe.replaceWith(div);- }}- """- )- else:- self.logger.warning(- message="Could not access content frame for iframe {index}",- tag="SCRAPE",- params={"index": i},- )- except Exception as e:- self.logger.error(- message="Error processing iframe {index}: {error}",- tag="ERROR",- params={"index": i, "error": str(e)},- )-- # Return the page object- return page-- async def create_session(self, **kwargs) -> str:- """- Creates a new browser session and returns its ID. A browse session is a unique openned page can be reused for multiple crawls.- This function is asynchronous and returns a string representing the session ID.-- Args:- **kwargs: Optional keyword arguments to configure the session.-- Returns:- str: The session ID.- """- await self.start()-- session_id = kwargs.get("session_id") or str(uuid.uuid4())-- user_agent = kwargs.get("user_agent", self.user_agent)- # Use browser_manager to get a fresh page & context assigned to this session_id- page, context = await self.browser_manager.get_page(CrawlerRunConfig(- session_id=session_id,- user_agent=user_agent,- **kwargs,- ))- return session_id-- async def crawl(- self, url: str, config: CrawlerRunConfig, **kwargs- ) -> AsyncCrawlResponse:- """- Crawls a given URL or processes raw HTML/local file content based on the URL prefix.-- Args:- url (str): The URL to crawl. Supported prefixes:- - 'http://' or 'https://': Web URL to crawl.- - 'file://': Local file path to process.- - 'raw://': Raw HTML content to process.- **kwargs: Additional parameters:- - 'screenshot' (bool): Whether to take a screenshot.- - ... [other existing parameters]-- Returns:- AsyncCrawlResponse: The response containing HTML, headers, status code, and optional screenshot.- """- config = config or CrawlerRunConfig.from_kwargs(kwargs)- response_headers = {}- status_code = 200 # Default for local/raw HTML- screenshot_data = None-- if url.startswith(("http://", "https://", "view-source:")):- return await self._crawl_web(url, config)-- elif url.startswith("file://"):- # initialize empty lists for console messages- captured_console = []-- # Process local file- local_file_path = url[7:] # Remove 'file://' prefix- if not os.path.exists(local_file_path):- raise FileNotFoundError(f"Local file not found: {local_file_path}")- with open(local_file_path, "r", encoding="utf-8") as f:- html = f.read()- if config.screenshot:- screenshot_data = await self._generate_screenshot_from_html(html)- if config.capture_console_messages:- page, context = await self.browser_manager.get_page(crawlerRunConfig=config)- captured_console = await self._capture_console_messages(page, url)-- return AsyncCrawlResponse(- html=html,- response_headers=response_headers,- status_code=status_code,- screenshot=screenshot_data,- get_delayed_content=None,- console_messages=captured_console,- )-- #####- # Since both "raw:" and "raw://" start with "raw:", the first condition is always true for both, so "raw://" will be sliced as "//...", which is incorrect.- # Fix: Check for "raw://" first, then "raw:"- # Also, the prefix "raw://" is actually 6 characters long, not 7, so it should be sliced accordingly: url[6:]- #####- elif url.startswith("raw://") or url.startswith("raw:"):- # Process raw HTML content- # raw_html = url[4:] if url[:4] == "raw:" else url[7:]- raw_html = url[6:] if url.startswith("raw://") else url[4:]- html = raw_html- if config.screenshot:- screenshot_data = await self._generate_screenshot_from_html(html)- return AsyncCrawlResponse(- html=html,- response_headers=response_headers,- status_code=status_code,- screenshot=screenshot_data,- get_delayed_content=None,- )- else:- raise ValueError(- "URL must start with 'http://', 'https://', 'file://', or 'raw:'"- )-- async def _crawl_web(- self, url: str, config: CrawlerRunConfig- ) -> AsyncCrawlResponse:- """- Internal method to crawl web URLs with the specified configuration.- Includes optional network and console capturing.-- Args:- url (str): The web URL to crawl- config (CrawlerRunConfig): Configuration object controlling the crawl behavior-- Returns:- AsyncCrawlResponse: The response containing HTML, headers, status code, and optional data- """- config.url = url- response_headers = {}- execution_result = None- status_code = None- redirected_url = url-- # Reset downloaded files list for new crawl- self._downloaded_files = []-- # Initialize capture lists- captured_requests = []- captured_console = []-- # Handle user agent with magic mode- user_agent_to_override = config.user_agent- if user_agent_to_override:- self.browser_config.user_agent = user_agent_to_override- elif config.magic or config.user_agent_mode == "random":- self.browser_config.user_agent = ValidUAGenerator().generate(- **(config.user_agent_generator_config or {})- )-- # Get page for session- page, context = await self.browser_manager.get_page(crawlerRunConfig=config)-- # await page.goto(URL)-- # Add default cookie- # await context.add_cookies(- # [{"name": "cookiesEnabled", "value": "true", "url": url}]- # )-- # Handle navigator overrides- if config.override_navigator or config.simulate_user or config.magic:- await context.add_init_script(load_js_script("navigator_overrider"))-- # Call hook after page creation- await self.execute_hook("on_page_context_created", page, context=context, config=config)-- # Network Request Capturing- if config.capture_network_requests:- async def handle_request_capture(request):- try:- post_data_str = None- try:- # Be cautious with large post data- post_data = request.post_data_buffer- if post_data:- # Attempt to decode, fallback to base64 or size indication- try:- post_data_str = post_data.decode('utf-8', errors='replace')- except UnicodeDecodeError:- post_data_str = f"[Binary data: {len(post_data)} bytes]"- except Exception:- post_data_str = "[Error retrieving post data]"-- captured_requests.append({- "event_type": "request",- "url": request.url,- "method": request.method,- "headers": dict(request.headers), # Convert Header dict- "post_data": post_data_str,- "resource_type": request.resource_type,- "is_navigation_request": request.is_navigation_request(),- "timestamp": time.time()- })- except Exception as e:- if self.logger:- self.logger.warning(f"Error capturing request details for {request.url}: {e}", tag="CAPTURE")- captured_requests.append({"event_type": "request_capture_error", "url": request.url, "error": str(e), "timestamp": time.time()})-- async def handle_response_capture(response):- try:- try:- # body = await response.body()- # json_body = await response.json()- text_body = await response.text()- except Exception as e:- body = None- # json_body = None- # text_body = None- captured_requests.append({- "event_type": "response",- "url": response.url,- "status": response.status,- "status_text": response.status_text,- "headers": dict(response.headers), # Convert Header dict- "from_service_worker": response.from_service_worker,- "request_timing": response.request.timing, # Detailed timing info- "timestamp": time.time(),- "body" : {- # "raw": body,- # "json": json_body,- "text": text_body- }- })- except Exception as e:- if self.logger:- self.logger.warning(f"Error capturing response details for {response.url}: {e}", tag="CAPTURE")- captured_requests.append({"event_type": "response_capture_error", "url": response.url, "error": str(e), "timestamp": time.time()})-- async def handle_request_failed_capture(request):- try:- captured_requests.append({- "event_type": "request_failed",- "url": request.url,- "method": request.method,- "resource_type": request.resource_type,- "failure_text": str(request.failure) if request.failure else "Unknown failure",- "timestamp": time.time()- })- except Exception as e:- if self.logger:- self.logger.warning(f"Error capturing request failed details for {request.url}: {e}", tag="CAPTURE")- captured_requests.append({"event_type": "request_failed_capture_error", "url": request.url, "error": str(e), "timestamp": time.time()})-- page.on("request", handle_request_capture)- page.on("response", handle_response_capture)- page.on("requestfailed", handle_request_failed_capture)-- # Console Message Capturing- if config.capture_console_messages:- def handle_console_capture(msg):- try:- message_type = "unknown"- try:- message_type = msg.type- except:- pass-- message_text = "unknown"- try:- message_text = msg.text- except:- pass-- # Basic console message with minimal content- entry = {- "type": message_type,- "text": message_text,- "timestamp": time.time()- }-- captured_console.append(entry)-- except Exception as e:- if self.logger:- self.logger.warning(f"Error capturing console message: {e}", tag="CAPTURE")- # Still add something to the list even on error- captured_console.append({- "type": "console_capture_error",- "error": str(e),- "timestamp": time.time()- })-- def handle_pageerror_capture(err):- try:- error_message = "Unknown error"- try:- error_message = err.message- except:- pass-- error_stack = ""- try:- error_stack = err.stack- except:- pass-- captured_console.append({- "type": "error",- "text": error_message,- "stack": error_stack,- "timestamp": time.time()- })- except Exception as e:- if self.logger:- self.logger.warning(f"Error capturing page error: {e}", tag="CAPTURE")- captured_console.append({- "type": "pageerror_capture_error",- "error": str(e),- "timestamp": time.time()- })-- # Add event listeners directly- page.on("console", handle_console_capture)- page.on("pageerror", handle_pageerror_capture)-- # Set up console logging if requested- if config.log_console:- def log_consol(- msg, console_log_type="debug"- ): # Corrected the parameter syntax- if console_log_type == "error":- self.logger.error(- message=f"Console error: {msg}", # Use f-string for variable interpolation- tag="CONSOLE"- )- elif console_log_type == "debug":- self.logger.debug(- message=f"Console: {msg}", # Use f-string for variable interpolation- tag="CONSOLE"- )-- page.on("console", log_consol)- page.on("pageerror", lambda e: log_consol(e, "error"))-- try:- # Get SSL certificate information if requested and URL is HTTPS- ssl_cert = None- if config.fetch_ssl_certificate:- ssl_cert = SSLCertificate.from_url(url)-- # Set up download handling- if self.browser_config.accept_downloads:- page.on(- "download",- lambda download: asyncio.create_task(- self._handle_download(download)- ),- )-- # Handle page navigation and content loading- if not config.js_only:- await self.execute_hook("before_goto", page, context=context, url=url, config=config)-- try:- # Generate a unique nonce for this request- if config.experimental.get("use_csp_nonce", False):- nonce = hashlib.sha256(os.urandom(32)).hexdigest()-- # Add CSP headers to the request- await page.set_extra_http_headers(- {- "Content-Security-Policy": f"default-src 'self'; script-src 'self' 'nonce-{nonce}' 'strict-dynamic'"- }- )-- response = await page.goto(- url, wait_until=config.wait_until, timeout=config.page_timeout- )- redirected_url = page.url- except Error as e:- # Allow navigation to be aborted when downloading files- # This is expected behavior for downloads in some browser engines- if 'net::ERR_ABORTED' in str(e) and self.browser_config.accept_downloads:- self.logger.info(- message=f"Navigation aborted, likely due to file download: {url}",- tag="GOTO",- params={"url": url},- )- response = None- else:- raise RuntimeError(f"Failed on navigating ACS-GOTO:\n{str(e)}")-- await self.execute_hook(- "after_goto", page, context=context, url=url, response=response, config=config- )-- # ──────────────────────────────────────────────────────────────- # Walk the redirect chain. Playwright returns only the last- # hop, so we trace the `request.redirected_from` links until the- # first response that differs from the final one and surface its- # status-code.- # ──────────────────────────────────────────────────────────────- if response is None:- status_code = 200- response_headers = {}- else:- first_resp = response- req = response.request- while req and req.redirected_from:- prev_req = req.redirected_from- prev_resp = await prev_req.response()- if prev_resp: # keep earliest- first_resp = prev_resp- req = prev_req-- status_code = first_resp.status- response_headers = first_resp.headers- # if response is None:- # status_code = 200- # response_headers = {}- # else:- # status_code = response.status- # response_headers = response.headers-- else:- status_code = 200- response_headers = {}-- # Wait for body element and visibility- try:- await page.wait_for_selector("body", state="attached", timeout=30000)-- # Use the new check_visibility function with csp_compliant_wait- is_visible = await self.csp_compliant_wait(- page,- """() => {- const element = document.body;- if (!element) return false;- const style = window.getComputedStyle(element);- const isVisible = style.display !== 'none' &&- style.visibility !== 'hidden' &&- style.opacity !== '0';- return isVisible;- }""",- timeout=30000,- )-- if not is_visible and not config.ignore_body_visibility:- visibility_info = await self.check_visibility(page)- raise Error(f"Body element is hidden: {visibility_info}")-- except Error:- visibility_info = await self.check_visibility(page)-- if self.browser_config.verbose:- self.logger.debug(- message="Body visibility info: {info}",- tag="DEBUG",- params={"info": visibility_info},- )-- if not config.ignore_body_visibility:- raise Error(f"Body element is hidden: {visibility_info}")-- # try:- # await page.wait_for_selector("body", state="attached", timeout=30000)-- # await page.wait_for_function(- # """- # () => {- # const body = document.body;- # const style = window.getComputedStyle(body);- # return style.display !== 'none' &&- # style.visibility !== 'hidden' &&- # style.opacity !== '0';- # }- # """,- # timeout=30000,- # )- # except Error as e:- # visibility_info = await page.evaluate(- # """- # () => {- # const body = document.body;- # const style = window.getComputedStyle(body);- # return {- # display: style.display,- # visibility: style.visibility,- # opacity: style.opacity,- # hasContent: body.innerHTML.length,- # classList: Array.from(body.classList)- # }- # }- # """- # )-- # if self.config.verbose:- # self.logger.debug(- # message="Body visibility info: {info}",- # tag="DEBUG",- # params={"info": visibility_info},- # )-- # if not config.ignore_body_visibility:- # raise Error(f"Body element is hidden: {visibility_info}")-- # Handle content loading and viewport adjustment- if not self.browser_config.text_mode and (- config.wait_for_images or config.adjust_viewport_to_content- ):- await page.wait_for_load_state("domcontentloaded")- await asyncio.sleep(0.1)-- # Check for image loading with improved error handling- images_loaded = await self.csp_compliant_wait(- page,- "() => Array.from(document.getElementsByTagName('img')).every(img => img.complete)",- timeout=1000,- )-- if not images_loaded and self.logger:- self.logger.warning(- message="Some images failed to load within timeout",- tag="SCRAPE",- )-- # Adjust viewport if needed- if not self.browser_config.text_mode and config.adjust_viewport_to_content:- try:- dimensions = await self.get_page_dimensions(page)- page_height = dimensions["height"]- page_width = dimensions["width"]- # page_width = await page.evaluate(- # "document.documentElement.scrollWidth"- # )- # page_height = await page.evaluate(- # "document.documentElement.scrollHeight"- # )-- target_width = self.browser_config.viewport_width- target_height = int(target_width * page_width / page_height * 0.95)- await page.set_viewport_size(- {"width": target_width, "height": target_height}- )-- scale = min(target_width / page_width, target_height / page_height)- cdp = await page.context.new_cdp_session(page)- await cdp.send(- "Emulation.setDeviceMetricsOverride",- {- "width": page_width,- "height": page_height,- "deviceScaleFactor": 1,- "mobile": False,- "scale": scale,- },- )- except Exception as e:- self.logger.warning(- message="Failed to adjust viewport to content: {error}",- tag="VIEWPORT",- params={"error": str(e)},- )-- # Handle full page scanning- if config.scan_full_page:- # await self._handle_full_page_scan(page, config.scroll_delay)- await self._handle_full_page_scan(page, config.scroll_delay, config.max_scroll_steps)-- # Handle virtual scroll if configured- if config.virtual_scroll_config:- await self._handle_virtual_scroll(page, config.virtual_scroll_config)-- # Execute JavaScript if provided- # if config.js_code:- # if isinstance(config.js_code, str):- # await page.evaluate(config.js_code)- # elif isinstance(config.js_code, list):- # for js in config.js_code:- # await page.evaluate(js)-- if config.js_code:- # execution_result = await self.execute_user_script(page, config.js_code)- execution_result = await self.robust_execute_user_script(- page, config.js_code- )-- if not execution_result["success"]:- self.logger.warning(- message="User script execution had issues: {error}",- tag="JS_EXEC",- params={"error": execution_result.get("error")},- )-- await self.execute_hook("on_execution_started", page, context=context, config=config)- await self.execute_hook("on_execution_ended", page, context=context, config=config, result=execution_result)-- # Handle user simulation- if config.simulate_user or config.magic:- await page.mouse.move(100, 100)- await page.mouse.down()- await page.mouse.up()- await page.keyboard.press("ArrowDown")-- # Handle wait_for condition- # Todo: Decide how to handle this- if not config.wait_for and config.css_selector and False:- # if not config.wait_for and config.css_selector:- config.wait_for = f"css:{config.css_selector}"-- if config.wait_for:- try:- # Use wait_for_timeout if specified, otherwise fall back to page_timeout- timeout = config.wait_for_timeout if config.wait_for_timeout is not None else config.page_timeout- await self.smart_wait(- page, config.wait_for, timeout=timeout- )- except Exception as e:- raise RuntimeError(f"Wait condition failed: {str(e)}")-- # Update image dimensions if needed- if not self.browser_config.text_mode:- update_image_dimensions_js = load_js_script("update_image_dimensions")- try:- try:- await page.wait_for_load_state("domcontentloaded", timeout=5)- except PlaywrightTimeoutError:- pass- await page.evaluate(update_image_dimensions_js)- except Exception as e:- self.logger.error(- message="Error updating image dimensions: {error}",- tag="ERROR",- params={"error": str(e)},- )-- # Process iframes if needed- if config.process_iframes:- page = await self.process_iframes(page)-- # Pre-content retrieval hooks and delay- await self.execute_hook("before_retrieve_html", page, context=context, config=config)- if config.delay_before_return_html:- await asyncio.sleep(config.delay_before_return_html)-- # Handle overlay removal- if config.remove_overlay_elements:- await self.remove_overlay_elements(page)-- if config.css_selector:- try:- # Handle comma-separated selectors by splitting them- selectors = [s.strip() for s in config.css_selector.split(',')]- html_parts = []-- for selector in selectors:- try:- content = await page.evaluate(- f"""Array.from(document.querySelectorAll("{selector}"))- .map(el => el.outerHTML)- .join('')"""- )- html_parts.append(content)- except Error as e:- print(f"Warning: Could not get content for selector '{selector}': {str(e)}")-- # Wrap in a div to create a valid HTML structure- html = f"<div class='crawl4ai-result'>\n" + "\n".join(html_parts) + "\n</div>"- except Error as e:- raise RuntimeError(f"Failed to extract HTML content: {str(e)}")- else:- html = await page.content()-- # # Get final HTML content- # html = await page.content()- await self.execute_hook(- "before_return_html", page=page, html=html, context=context, config=config- )-- # Handle PDF, MHTML and screenshot generation- start_export_time = time.perf_counter()- pdf_data = None- screenshot_data = None- mhtml_data = None-- if config.pdf:- pdf_data = await self.export_pdf(page)-- if config.capture_mhtml:- mhtml_data = await self.capture_mhtml(page)-- if config.screenshot:- if config.screenshot_wait_for:- await asyncio.sleep(config.screenshot_wait_for)- screenshot_data = await self.take_screenshot(- page, screenshot_height_threshold=config.screenshot_height_threshold- )-- if screenshot_data or pdf_data or mhtml_data:- self.logger.info(- message="Exporting media (PDF/MHTML/screenshot) took {duration:.2f}s",- tag="EXPORT",- params={"duration": time.perf_counter() - start_export_time},- )-- # Define delayed content getter- async def get_delayed_content(delay: float = 5.0) -> str:- self.logger.info(- message="Waiting for {delay} seconds before retrieving content for {url}",- tag="INFO",- params={"delay": delay, "url": url},- )- await asyncio.sleep(delay)- return await page.content()-- # Return complete response- return AsyncCrawlResponse(- html=html,- response_headers=response_headers,- js_execution_result=execution_result,- status_code=status_code,- screenshot=screenshot_data,- pdf_data=pdf_data,- mhtml_data=mhtml_data,- get_delayed_content=get_delayed_content,- ssl_certificate=ssl_cert,- downloaded_files=(- self._downloaded_files if self._downloaded_files else None- ),- redirected_url=redirected_url,- # Include captured data if enabled- network_requests=captured_requests if config.capture_network_requests else None,- console_messages=captured_console if config.capture_console_messages else None,- )-- except Exception as e:- raise e-- finally:- # If no session_id is given we should close the page- all_contexts = page.context.browser.contexts- total_pages = sum(len(context.pages) for context in all_contexts)- if config.session_id:- pass- elif total_pages <= 1 and (self.browser_config.use_managed_browser or self.browser_config.headless):- pass- else:- # Detach listeners before closing to prevent potential errors during close- if config.capture_network_requests:- page.remove_listener("request", handle_request_capture)- page.remove_listener("response", handle_response_capture)- page.remove_listener("requestfailed", handle_request_failed_capture)- if config.capture_console_messages:- page.remove_listener("console", handle_console_capture)- page.remove_listener("pageerror", handle_pageerror_capture)-- # Close the page- await page.close()-- # async def _handle_full_page_scan(self, page: Page, scroll_delay: float = 0.1):- async def _handle_full_page_scan(self, page: Page, scroll_delay: float = 0.1, max_scroll_steps: Optional[int] = None):- """- Helper method to handle full page scanning.-- How it works:- 1. Get the viewport height.- 2. Scroll to the bottom of the page.- 3. Get the total height of the page.- 4. Scroll back to the top of the page.- 5. Scroll to the bottom of the page again.- 6. Continue scrolling until the bottom of the page is reached.-- Args:- page (Page): The Playwright page object- scroll_delay (float): The delay between page scrolls- max_scroll_steps (Optional[int]): Maximum number of scroll steps to perform. If None, scrolls until end.-- """- try:- viewport_size = page.viewport_size- if viewport_size is None:- await page.set_viewport_size(- {"width": self.browser_config.viewport_width, "height": self.browser_config.viewport_height}- )- viewport_size = page.viewport_size-- viewport_height = viewport_size.get(- "height", self.browser_config.viewport_height- )- current_position = viewport_height-- # await page.evaluate(f"window.scrollTo(0, {current_position})")- await self.safe_scroll(page, 0, current_position, delay=scroll_delay)- # await self.csp_scroll_to(page, 0, current_position)- # await asyncio.sleep(scroll_delay)-- # total_height = await page.evaluate("document.documentElement.scrollHeight")- dimensions = await self.get_page_dimensions(page)- total_height = dimensions["height"]-- scroll_step_count = 0- while current_position < total_height:- ####- # NEW FEATURE: Check if we've reached the maximum allowed scroll steps- # This prevents infinite scrolling on very long pages or infinite scroll scenarios- # If max_scroll_steps is None, this check is skipped (unlimited scrolling - original behavior)- ####- if max_scroll_steps is not None and scroll_step_count >= max_scroll_steps:- break- current_position = min(current_position + viewport_height, total_height)- await self.safe_scroll(page, 0, current_position, delay=scroll_delay)-- # Increment the step counter for max_scroll_steps tracking- scroll_step_count += 1-- # await page.evaluate(f"window.scrollTo(0, {current_position})")- # await asyncio.sleep(scroll_delay)-- # new_height = await page.evaluate("document.documentElement.scrollHeight")- dimensions = await self.get_page_dimensions(page)- new_height = dimensions["height"]-- if new_height > total_height:- total_height = new_height-- # await page.evaluate("window.scrollTo(0, 0)")- await self.safe_scroll(page, 0, 0)-- except Exception as e:- self.logger.warning(- message="Failed to perform full page scan: {error}",- tag="PAGE_SCAN",- params={"error": str(e)},- )- else:- # await page.evaluate("window.scrollTo(0, document.body.scrollHeight)")- await self.safe_scroll(page, 0, total_height)-- async def _handle_virtual_scroll(self, page: Page, config: "VirtualScrollConfig"):- """- Handle virtual scroll containers (e.g., Twitter-like feeds) by capturing- content at different scroll positions and merging unique elements.-- Following the design:- 1. Get container HTML- 2. Scroll by container height- 3. Wait and check if container HTML changed- 4. Three cases:- - No change: continue scrolling- - New items added (appended): continue (items already in page)- - Items replaced: capture HTML chunk and add to list- 5. After N scrolls, merge chunks if any were captured-- Args:- page: The Playwright page object- config: Virtual scroll configuration- """- try:- # Import VirtualScrollConfig to avoid circular import- from .async_configs import VirtualScrollConfig-- # Ensure config is a VirtualScrollConfig instance- if isinstance(config, dict):- config = VirtualScrollConfig.from_dict(config)-- self.logger.info(- message="Starting virtual scroll capture for container: {selector}",- tag="VSCROLL",- params={"selector": config.container_selector}- )-- # JavaScript function to handle virtual scroll capture- virtual_scroll_js = """- async (config) => {- const container = document.querySelector(config.container_selector);- if (!container) {- throw new Error(`Container not found: ${config.container_selector}`);- }-- // List to store HTML chunks when content is replaced- const htmlChunks = [];- let previousHTML = container.innerHTML;- let scrollCount = 0;-- // Determine scroll amount- let scrollAmount;- if (typeof config.scroll_by === 'number') {- scrollAmount = config.scroll_by;- } else if (config.scroll_by === 'page_height') {- scrollAmount = window.innerHeight;- } else { // container_height- scrollAmount = container.offsetHeight;- }-- // Perform scrolling- while (scrollCount < config.scroll_count) {- // Scroll the container- container.scrollTop += scrollAmount;-- // Wait for content to potentially load- await new Promise(resolve => setTimeout(resolve, config.wait_after_scroll * 1000));-- // Get current HTML- const currentHTML = container.innerHTML;-- // Determine what changed- if (currentHTML === previousHTML) {- // Case 0: No change - continue scrolling- console.log(`Scroll ${scrollCount + 1}: No change in content`);- } else if (currentHTML.startsWith(previousHTML)) {- // Case 1: New items appended - content already in page- console.log(`Scroll ${scrollCount + 1}: New items appended`);- } else {- // Case 2: Items replaced - capture the previous HTML- console.log(`Scroll ${scrollCount + 1}: Content replaced, capturing chunk`);- htmlChunks.push(previousHTML);- }-- // Update previous HTML for next iteration- previousHTML = currentHTML;- scrollCount++;-- // Check if we've reached the end- if (container.scrollTop + container.clientHeight >= container.scrollHeight - 10) {- console.log(`Reached end of scrollable content at scroll ${scrollCount}`);- // Capture final chunk if content was replaced- if (htmlChunks.length > 0) {- htmlChunks.push(currentHTML);- }- break;- }- }-- // If we have chunks (case 2 occurred), merge them- if (htmlChunks.length > 0) {- console.log(`Merging ${htmlChunks.length} HTML chunks`);-- // Parse all chunks to extract unique elements- const tempDiv = document.createElement('div');- const seenTexts = new Set();- const uniqueElements = [];-- // Process each chunk- for (const chunk of htmlChunks) {- tempDiv.innerHTML = chunk;- const elements = tempDiv.children;-- for (let i = 0; i < elements.length; i++) {- const element = elements[i];- // Normalize text for deduplication- const normalizedText = element.innerText- .toLowerCase()- .replace(/[\\s\\W]/g, ''); // Remove spaces and symbols-- if (!seenTexts.has(normalizedText)) {- seenTexts.add(normalizedText);- uniqueElements.push(element.outerHTML);- }- }- }-- // Replace container content with merged unique elements- container.innerHTML = uniqueElements.join('\\n');- console.log(`Merged ${uniqueElements.length} unique elements from ${htmlChunks.length} chunks`);-- return {- success: true,- chunksCount: htmlChunks.length,- uniqueCount: uniqueElements.length,- replaced: true- };- } else {- console.log('No content replacement detected, all content remains in page');- return {- success: true,- chunksCount: 0,- uniqueCount: 0,- replaced: false- };- }- }- """-- # Execute virtual scroll capture- result = await page.evaluate(virtual_scroll_js, config.to_dict())-- if result.get("replaced", False):- self.logger.success(- message="Virtual scroll completed. Merged {unique} unique elements from {chunks} chunks",- tag="VSCROLL",- params={- "unique": result.get("uniqueCount", 0),- "chunks": result.get("chunksCount", 0)- }- )- else:- self.logger.info(- message="Virtual scroll completed. Content was appended, no merging needed",- tag="VSCROLL"- )-- except Exception as e:- self.logger.error(- message="Virtual scroll capture failed: {error}",- tag="VSCROLL",- params={"error": str(e)}- )- # Continue with normal flow even if virtual scroll fails-- async def _handle_download(self, download):- """- Handle file downloads.-- How it works:- 1. Get the suggested filename.- 2. Get the download path.- 3. Log the download.- 4. Start the download.- 5. Save the downloaded file.- 6. Log the completion.-- Args:- download (Download): The Playwright download object-- Returns:- None- """- try:- suggested_filename = download.suggested_filename- download_path = os.path.join(self.browser_config.downloads_path, suggested_filename)-- self.logger.info(- message="Downloading {filename} to {path}",- tag="FETCH",- params={"filename": suggested_filename, "path": download_path},- )-- start_time = time.perf_counter()- await download.save_as(download_path)- end_time = time.perf_counter()- self._downloaded_files.append(download_path)-- self.logger.success(- message="Downloaded {filename} successfully",- tag="COMPLETE",- params={- "filename": suggested_filename,- "path": download_path,- "duration": f"{end_time - start_time:.2f}s",- },- )- except Exception as e:- self.logger.error(- message="Failed to handle download: {error}",- tag="ERROR",- params={"error": str(e)},- )-- async def remove_overlay_elements(self, page: Page) -> None:- """- Removes popup overlays, modals, cookie notices, and other intrusive elements from the page.-- Args:- page (Page): The Playwright page instance- """- remove_overlays_js = load_js_script("remove_overlay_elements")-- try:- await page.evaluate(- f"""- (() => {{- try {{- {remove_overlays_js}- return {{ success: true }};- }} catch (error) {{- return {{- success: false,- error: error.toString(),- stack: error.stack- }};- }}- }})()- """- )- await page.wait_for_timeout(500) # Wait for any animations to complete- except Exception as e:- self.logger.warning(- message="Failed to remove overlay elements: {error}",- tag="SCRAPE",- params={"error": str(e)},- )-- async def export_pdf(self, page: Page) -> bytes:- """- Exports the current page as a PDF.-- Args:- page (Page): The Playwright page object-- Returns:- bytes: The PDF data- """- pdf_data = await page.pdf(print_background=True)- return pdf_data-- async def capture_mhtml(self, page: Page) -> Optional[str]:- """- Captures the current page as MHTML using CDP.-- MHTML (MIME HTML) is a web page archive format that combines the HTML content- with its resources (images, CSS, etc.) into a single MIME-encoded file.-- Args:- page (Page): The Playwright page object-- Returns:- Optional[str]: The MHTML content as a string, or None if there was an error- """- try:- # Ensure the page is fully loaded before capturing- try:- # Wait for DOM content and network to be idle- await page.wait_for_load_state("domcontentloaded", timeout=5000)- await page.wait_for_load_state("networkidle", timeout=5000)-- # Give a little extra time for JavaScript execution- await page.wait_for_timeout(1000)-- # Wait for any animations to complete- await page.evaluate("""- () => new Promise(resolve => {- // First requestAnimationFrame gets scheduled after the next repaint- requestAnimationFrame(() => {- // Second requestAnimationFrame gets called after all animations complete- requestAnimationFrame(resolve);- });- })- """)- except Error as e:- if self.logger:- self.logger.warning(- message="Wait for load state timed out: {error}",- tag="MHTML",- params={"error": str(e)},- )-- # Create a new CDP session- cdp_session = await page.context.new_cdp_session(page)-- # Call Page.captureSnapshot with format "mhtml"- result = await cdp_session.send("Page.captureSnapshot", {"format": "mhtml"})-- # The result contains a 'data' field with the MHTML content- mhtml_content = result.get("data")-- # Detach the CDP session to clean up resources- await cdp_session.detach()-- return mhtml_content- except Exception as e:- # Log the error but don't raise it - we'll just return None for the MHTML- if self.logger:- self.logger.error(- message="Failed to capture MHTML: {error}",- tag="MHTML",- params={"error": str(e)},- )- return None-- async def _capture_console_messages(- self, page: Page, file_path: str- ) -> List[Dict[str, Union[str, float]]]:- """- Captures console messages from the page.- Args:-- page (Page): The Playwright page object- Returns:- List[Dict[str, Union[str, float]]]: A list of captured console messages- """- captured_console = []-- def handle_console_message(msg):- try:- message_type = msg.type- message_text = msg.text-- entry = {- "type": message_type,- "text": message_text,- "timestamp": time.time(),- }- captured_console.append(entry)- except Exception as e:- if self.logger:- self.logger.warning(- f"Error capturing console message: {e}", tag="CAPTURE"- )-- page.on("console", handle_console_message)-- await page.goto(file_path)-- return captured_console-- async def take_screenshot(self, page, **kwargs) -> str:- """- Take a screenshot of the current page.-- Args:- page (Page): The Playwright page object- kwargs: Additional keyword arguments-- Returns:- str: The base64-encoded screenshot data- """- need_scroll = await self.page_need_scroll(page)-- if not need_scroll:- # Page is short enough, just take a screenshot- return await self.take_screenshot_naive(page)- else:- # Page is too long, try to take a full-page screenshot- return await self.take_screenshot_scroller(page, **kwargs)- # return await self.take_screenshot_from_pdf(await self.export_pdf(page))-- async def take_screenshot_from_pdf(self, pdf_data: bytes) -> str:- """- Convert the first page of the PDF to a screenshot.-- Requires pdf2image and poppler.-- Args:- pdf_data (bytes): The PDF data-- Returns:- str: The base64-encoded screenshot data- """- try:- from pdf2image import convert_from_bytes-- images = convert_from_bytes(pdf_data)- final_img = images[0].convert("RGB")- buffered = BytesIO()- final_img.save(buffered, format="JPEG")- return base64.b64encode(buffered.getvalue()).decode("utf-8")- except Exception as e:- error_message = f"Failed to take PDF-based screenshot: {str(e)}"- self.logger.error(- message="PDF Screenshot failed: {error}",- tag="ERROR",- params={"error": error_message},- )- # Return error image as fallback- img = Image.new("RGB", (800, 600), color="black")- draw = ImageDraw.Draw(img)- font = ImageFont.load_default()- draw.text((10, 10), error_message, fill=(255, 255, 255), font=font)- buffered = BytesIO()- img.save(buffered, format="JPEG")- return base64.b64encode(buffered.getvalue()).decode("utf-8")-- async def take_screenshot_scroller(self, page: Page, **kwargs) -> str:- """- Attempt to set a large viewport and take a full-page screenshot.- If still too large, segment the page as before.-- Requires pdf2image and poppler.-- Args:- page (Page): The Playwright page object- kwargs: Additional keyword arguments-- Returns:- str: The base64-encoded screenshot data- """- try:- # Get page height- dimensions = await self.get_page_dimensions(page)- page_width = dimensions["width"]- page_height = dimensions["height"]- # page_height = await page.evaluate("document.documentElement.scrollHeight")- # page_width = await page.evaluate("document.documentElement.scrollWidth")-- # Set a large viewport- large_viewport_height = min(- page_height,- kwargs.get("screenshot_height_threshold", SCREENSHOT_HEIGHT_TRESHOLD),- )- await page.set_viewport_size(- {"width": page_width, "height": large_viewport_height}- )-- # Page still too long, segment approach- segments = []- viewport_size = page.viewport_size- viewport_height = viewport_size["height"]-- num_segments = (page_height // viewport_height) + 1- for i in range(num_segments):- y_offset = i * viewport_height- # Special handling for the last segment- if i == num_segments - 1:- last_part_height = page_height % viewport_height-- # If page_height is an exact multiple of viewport_height,- # we don't need an extra segment- if last_part_height == 0:- # Skip last segment if page height is exact multiple of viewport- break-- # Adjust viewport to exactly match the remaining content height- await page.set_viewport_size({"width": page_width, "height": last_part_height})-- await page.evaluate(f"window.scrollTo(0, {y_offset})")- await asyncio.sleep(0.01) # wait for render-- # Capture the current segment- # Note: Using compression options (format, quality) would go here- seg_shot = await page.screenshot(full_page=False, type="jpeg", quality=85)- # seg_shot = await page.screenshot(full_page=False)- img = Image.open(BytesIO(seg_shot)).convert("RGB")- segments.append(img)-- # Reset viewport to original size after capturing segments- await page.set_viewport_size({"width": page_width, "height": viewport_height})-- total_height = sum(img.height for img in segments)- stitched = Image.new("RGB", (segments[0].width, total_height))- offset = 0- for img in segments:- # stitched.paste(img, (0, offset))- stitched.paste(img.convert("RGB"), (0, offset))- offset += img.height-- buffered = BytesIO()- stitched = stitched.convert("RGB")- stitched.save(buffered, format="BMP", quality=85)- encoded = base64.b64encode(buffered.getvalue()).decode("utf-8")-- return encoded- except Exception as e:- error_message = f"Failed to take large viewport screenshot: {str(e)}"- self.logger.error(- message="Large viewport screenshot failed: {error}",- tag="ERROR",- params={"error": error_message},- )- # return error image- img = Image.new("RGB", (800, 600), color="black")- draw = ImageDraw.Draw(img)- font = ImageFont.load_default()- draw.text((10, 10), error_message, fill=(255, 255, 255), font=font)- buffered = BytesIO()- img.save(buffered, format="JPEG")- return base64.b64encode(buffered.getvalue()).decode("utf-8")- # finally:- # await page.close()-- async def take_screenshot_naive(self, page: Page) -> str:- """- Takes a screenshot of the current page.-- Args:- page (Page): The Playwright page instance-- Returns:- str: Base64-encoded screenshot image- """- try:- # The page is already loaded, just take the screenshot- screenshot = await page.screenshot(full_page=False)- return base64.b64encode(screenshot).decode("utf-8")- except Exception as e:- error_message = f"Failed to take screenshot: {str(e)}"- self.logger.error(- message="Screenshot failed: {error}",- tag="ERROR",- params={"error": error_message},- )-- # Generate an error image- img = Image.new("RGB", (800, 600), color="black")- draw = ImageDraw.Draw(img)- font = ImageFont.load_default()- draw.text((10, 10), error_message, fill=(255, 255, 255), font=font)-- buffered = BytesIO()- img.save(buffered, format="JPEG")- return base64.b64encode(buffered.getvalue()).decode("utf-8")- # finally:- # await page.close()-- async def export_storage_state(self, path: str = None) -> dict:- """- Exports the current storage state (cookies, localStorage, sessionStorage)- to a JSON file at the specified path.-- Args:- path (str): The path to save the storage state JSON file-- Returns:- dict: The exported storage state- """- if self.default_context:- state = await self.default_context.storage_state(path=path)- self.logger.info(- message="Exported storage state to {path}",- tag="INFO",- params={"path": path},- )- return state- else:- self.logger.warning(- message="No default_context available to export storage state.",- tag="WARNING",- )-- async def robust_execute_user_script(- self, page: Page, js_code: Union[str, List[str]]- ) -> Dict[str, Any]:- """- Executes user-provided JavaScript code with proper error handling and context,- supporting both synchronous and async user code, plus navigations.-- How it works:- 1. Wait for load state 'domcontentloaded'- 2. If js_code is a string, execute it directly- 3. If js_code is a list, execute each element in sequence- 4. Wait for load state 'networkidle'- 5. Return results-- Args:- page (Page): The Playwright page instance- js_code (Union[str, List[str]]): The JavaScript code to execute-- Returns:- Dict[str, Any]: The results of the execution- """- try:- await page.wait_for_load_state("domcontentloaded")-- if isinstance(js_code, str):- scripts = [js_code]- else:- scripts = js_code-- results = []- for script in scripts:- try:- # Attempt the evaluate- # If the user code triggers navigation, we catch the "context destroyed" error- # then wait for the new page to load before continuing- result = None- try:- # OLD VERSION:- # result = await page.evaluate(- # f"""- # (async () => {{- # try {{- # const script_result = {script};- # return {{ success: true, result: script_result }};- # }} catch (err) {{- # return {{ success: false, error: err.toString(), stack: err.stack }};- # }}- # }})();- # """- # )-- # """ NEW VERSION:- # When {script} contains statements (e.g., const link = …; link.click();),- # this forms invalid JavaScript, causing Playwright execution error: SyntaxError: Unexpected token 'const'.- # """- result = await page.evaluate(- f"""- (async () => {{- try {{- return await (async () => {{- {script}- }})();- }} catch (err) {{- return {{ success: false, error: err.toString(), stack: err.stack }};- }}- }})();- """- )- except Error as e:- # If it's due to navigation destroying the context, handle gracefully- if "Execution context was destroyed" in str(e):- self.logger.info(- "Navigation triggered by script, waiting for load state",- tag="JS_EXEC",- )- try:- await page.wait_for_load_state("load", timeout=30000)- except Error as nav_err:- self.logger.warning(- message="Navigation wait failed: {error}",- tag="JS_EXEC",- params={"error": str(nav_err)},- )- try:- await page.wait_for_load_state(- "networkidle", timeout=30000- )- except Error as nav_err:- self.logger.warning(- message="Network idle wait failed: {error}",- tag="JS_EXEC",- params={"error": str(nav_err)},- )- # Return partial success, or adapt as you see fit- result = {- "success": True,- "info": "Navigation triggered, ignoring context destroyed error",- }- else:- # It's some other error, log and continue- self.logger.error(- message="Playwright execution error: {error}",- tag="JS_EXEC",- params={"error": str(e)},- )- result = {"success": False, "error": str(e)}-- # If we made it this far with no repeated error, do post-load waits- t1 = time.time()- try:- await page.wait_for_load_state("domcontentloaded", timeout=5000)- except Error as e:- self.logger.warning(- message="DOM content load timeout: {error}",- tag="JS_EXEC",- params={"error": str(e)},- )-- # t1 = time.time()- # try:- # await page.wait_for_load_state('networkidle', timeout=5000)- # print("Network idle after script execution in", time.time() - t1)- # except Error as e:- # self.logger.warning(- # message="Network idle timeout: {error}",- # tag="JS_EXEC",- # params={"error": str(e)}- # )-- results.append(result if result else {"success": True})-- except Exception as e:- # Catch anything else- self.logger.error(- message="Script chunk failed: {error}",- tag="JS_EXEC",- params={"error": str(e)},- )- results.append({"success": False, "error": str(e)})-- return {"success": True, "results": results}-- except Exception as e:- self.logger.error(- message="Script execution failed: {error}",- tag="JS_EXEC",- params={"error": str(e)},- )- return {"success": False, "error": str(e)}-- async def execute_user_script(- self, page: Page, js_code: Union[str, List[str]]- ) -> Dict[str, Any]:- """- Executes user-provided JavaScript code with proper error handling and context.-- Args:- page: Playwright page object- js_code: Single JavaScript string or list of JavaScript code strings-- Returns:- Dict containing execution status and results/errors- """- try:- # Ensure the page is ready for script execution- await page.wait_for_load_state("domcontentloaded")-- # Handle single script or multiple scripts- if isinstance(js_code, str):- scripts = [js_code]- else:- scripts = js_code-- results = []- for script in scripts:- try:- # Execute the script and wait for network idle- result = await page.evaluate(- f"""- (() => {{- return new Promise((resolve) => {{- try {{- const result = (function() {{- {script}- }})();-- // If result is a promise, wait for it- if (result instanceof Promise) {{- result.then(() => {{- // Wait a bit for any triggered effects- setTimeout(() => resolve({{ success: true }}), 100);- }}).catch(error => {{- resolve({{- success: false,- error: error.toString(),- stack: error.stack- }});- }});- }} else {{- // For non-promise results, still wait a bit for effects- setTimeout(() => resolve({{ success: true }}), 100);- }}- }} catch (error) {{- resolve({{- success: false,- error: error.toString(),- stack: error.stack- }});- }}- }});- }})()- """- )-- # Wait for network idle after script execution- t1 = time.time()- await page.wait_for_load_state("domcontentloaded", timeout=5000)--- t1 = time.time()- await page.wait_for_load_state("networkidle", timeout=5000)-- results.append(result if result else {"success": True})-- except Error as e:- # Handle Playwright-specific errors- self.logger.error(- message="Playwright execution error: {error}",- tag="JS_EXEC",- params={"error": str(e)},- )- results.append({"success": False, "error": str(e)})-- return {"success": True, "results": results}-- except Exception as e:- self.logger.error(- message="Script execution failed: {error}",- tag="JS_EXEC",- params={"error": str(e)},- )- return {"success": False, "error": str(e)}-- except Exception as e:- self.logger.error(- message="Script execution failed: {error}",- tag="JS_EXEC",- params={"error": str(e)},- )- return {"success": False, "error": str(e)}-- async def check_visibility(self, page):- """- Checks if an element is visible on the page.-- Args:- page: Playwright page object-- Returns:- Boolean indicating visibility- """- return await page.evaluate(- """- () => {- const element = document.body;- if (!element) return false;- const style = window.getComputedStyle(element);- const isVisible = style.display !== 'none' &&- style.visibility !== 'hidden' &&- style.opacity !== '0';- return isVisible;- }- """- )-- async def safe_scroll(self, page: Page, x: int, y: int, delay: float = 0.1):- """- Safely scroll the page with rendering time.-- Args:- page: Playwright page object- x: Horizontal scroll position- y: Vertical scroll position- """- result = await self.csp_scroll_to(page, x, y)- if result["success"]:- await page.wait_for_timeout(delay * 1000)- return result-- async def csp_scroll_to(self, page: Page, x: int, y: int) -> Dict[str, Any]:- """- Performs a CSP-compliant scroll operation and returns the result status.-- Args:- page: Playwright page object- x: Horizontal scroll position- y: Vertical scroll position-- Returns:- Dict containing scroll status and position information- """- try:- result = await page.evaluate(- f"""() => {{- try {{- const startX = window.scrollX;- const startY = window.scrollY;- window.scrollTo({x}, {y});-- // Get final position after scroll- const endX = window.scrollX;- const endY = window.scrollY;-- return {{- success: true,- startPosition: {{ x: startX, y: startY }},- endPosition: {{ x: endX, y: endY }},- targetPosition: {{ x: {x}, y: {y} }},- delta: {{- x: Math.abs(endX - {x}),- y: Math.abs(endY - {y})- }}- }};- }} catch (e) {{- return {{- success: false,- error: e.toString()- }};- }}- }}"""- )-- if not result["success"]:- self.logger.warning(- message="Scroll operation failed: {error}",- tag="SCROLL",- params={"error": result.get("error")},- )-- return result-- except Exception as e:- self.logger.error(- message="Failed to execute scroll: {error}",- tag="SCROLL",- params={"error": str(e)},- )- return {"success": False, "error": str(e)}-- async def get_page_dimensions(self, page: Page):- """- Get the dimensions of the page.-- Args:- page: Playwright page object-- Returns:- Dict containing width and height of the page- """- return await page.evaluate(- """- () => {- const {scrollWidth, scrollHeight} = document.documentElement;- return {width: scrollWidth, height: scrollHeight};- }- """- )-- async def page_need_scroll(self, page: Page) -> bool:- """- Determine whether the page need to scroll-- Args:- page: Playwright page object-- Returns:- bool: True if page needs scrolling- """- try:- need_scroll = await page.evaluate(- """- () => {- const scrollHeight = document.documentElement.scrollHeight;- const viewportHeight = window.innerHeight;- return scrollHeight > viewportHeight;- }- """- )- return need_scroll- except Exception as e:- self.logger.warning(- message="Failed to check scroll need: {error}. Defaulting to True for safety.",- tag="SCROLL",- params={"error": str(e)},- )- return True # Default to scrolling if check fails---####################################################################################################-# HTTP Crawler Strategy-####################################################################################################--class HTTPCrawlerError(Exception):- """Base error class for HTTP crawler specific exceptions"""- pass---class ConnectionTimeoutError(HTTPCrawlerError):- """Raised when connection timeout occurs"""- pass---class HTTPStatusError(HTTPCrawlerError):- """Raised for unexpected status codes"""- def __init__(self, status_code: int, message: str):- self.status_code = status_code- super().__init__(f"HTTP {status_code}: {message}")---class AsyncHTTPCrawlerStrategy(AsyncCrawlerStrategy):- """- Fast, lightweight HTTP-only crawler strategy optimized for memory efficiency.- """-- __slots__ = ('logger', 'max_connections', 'dns_cache_ttl', 'chunk_size', '_session', 'hooks', 'browser_config')-- DEFAULT_TIMEOUT: Final[int] = 30- DEFAULT_CHUNK_SIZE: Final[int] = 64 * 1024- DEFAULT_MAX_CONNECTIONS: Final[int] = min(32, (os.cpu_count() or 1) * 4)- DEFAULT_DNS_CACHE_TTL: Final[int] = 300- VALID_SCHEMES: Final = frozenset({'http', 'https', 'file', 'raw'})-- _BASE_HEADERS: Final = MappingProxyType({- 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',- 'Accept-Language': 'en-US,en;q=0.5',- 'Accept-Encoding': 'gzip, deflate, br',- 'Connection': 'keep-alive',- 'Upgrade-Insecure-Requests': '1',- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'- })-- def __init__(- self,- browser_config: Optional[HTTPCrawlerConfig] = None,- logger: Optional[AsyncLogger] = None,- max_connections: int = DEFAULT_MAX_CONNECTIONS,- dns_cache_ttl: int = DEFAULT_DNS_CACHE_TTL,- chunk_size: int = DEFAULT_CHUNK_SIZE- ):- """Initialize the HTTP crawler with config"""- self.browser_config = browser_config or HTTPCrawlerConfig()- self.logger = logger- self.max_connections = max_connections- self.dns_cache_ttl = dns_cache_ttl- self.chunk_size = chunk_size- self._session: Optional[aiohttp.ClientSession] = None-- self.hooks = {- k: partial(self._execute_hook, k)- for k in ('before_request', 'after_request', 'on_error')- }-- # Set default hooks- self.set_hook('before_request', lambda *args, **kwargs: None)- self.set_hook('after_request', lambda *args, **kwargs: None)- self.set_hook('on_error', lambda *args, **kwargs: None)--- async def __aenter__(self) -> AsyncHTTPCrawlerStrategy:- await self.start()- return self-- async def __aexit__(self, exc_type, exc_val, exc_tb) -> None:- await self.close()-- @contextlib.asynccontextmanager- async def _session_context(self):- try:- if not self._session:- await self.start()- yield self._session- finally:- pass-- def set_hook(self, hook_type: str, hook_func: Callable) -> None:- if hook_type in self.hooks:- self.hooks[hook_type] = partial(self._execute_hook, hook_type, hook_func)- else:- raise ValueError(f"Invalid hook type: {hook_type}")-- async def _execute_hook(- self,- hook_type: str,- hook_func: Callable,- *args: Any,- **kwargs: Any- ) -> Any:- if asyncio.iscoroutinefunction(hook_func):- return await hook_func(*args, **kwargs)- return hook_func(*args, **kwargs)-- async def start(self) -> None:- if not self._session:- connector = aiohttp.TCPConnector(- limit=self.max_connections,- ttl_dns_cache=self.dns_cache_ttl,- use_dns_cache=True,- force_close=False- )- self._session = aiohttp.ClientSession(- headers=dict(self._BASE_HEADERS),- connector=connector,- timeout=ClientTimeout(total=self.DEFAULT_TIMEOUT)- )-- async def close(self) -> None:- if self._session and not self._session.closed:- try:- await asyncio.wait_for(self._session.close(), timeout=5.0)- except asyncio.TimeoutError:- if self.logger:- self.logger.warning(- message="Session cleanup timed out",- tag="CLEANUP"- )- finally:- self._session = None-- async def _stream_file(self, path: str) -> AsyncGenerator[memoryview, None]:- async with aiofiles.open(path, mode='rb') as f:- while chunk := await f.read(self.chunk_size):- yield memoryview(chunk)-- async def _handle_file(self, path: str) -> AsyncCrawlResponse:- if not os.path.exists(path):- raise FileNotFoundError(f"Local file not found: {path}")-- chunks = []- async for chunk in self._stream_file(path):- chunks.append(chunk.tobytes().decode('utf-8', errors='replace'))-- return AsyncCrawlResponse(- html=''.join(chunks),- response_headers={},- status_code=200- )-- async def _handle_raw(self, content: str) -> AsyncCrawlResponse:- return AsyncCrawlResponse(- html=content,- response_headers={},- status_code=200- )--- async def _handle_http(- self,- url: str,- config: CrawlerRunConfig- ) -> AsyncCrawlResponse:- async with self._session_context() as session:- timeout = ClientTimeout(- total=config.page_timeout or self.DEFAULT_TIMEOUT,- connect=10,- sock_read=30- )-- headers = dict(self._BASE_HEADERS)- if self.browser_config.headers:- headers.update(self.browser_config.headers)-- request_kwargs = {- 'timeout': timeout,- 'allow_redirects': self.browser_config.follow_redirects,- 'ssl': self.browser_config.verify_ssl,- 'headers': headers- }-- if self.browser_config.method == "POST":- if self.browser_config.data:- request_kwargs['data'] = self.browser_config.data- if self.browser_config.json:- request_kwargs['json'] = self.browser_config.json-- await self.hooks['before_request'](url, request_kwargs)-- try:- async with session.request(self.browser_config.method, url, **request_kwargs) as response:- content = memoryview(await response.read())-- if not (200 <= response.status < 300):- raise HTTPStatusError(- response.status,- f"Unexpected status code for {url}"- )-- encoding = response.charset- if not encoding:- encoding = chardet.detect(content.tobytes())['encoding'] or 'utf-8'-- result = AsyncCrawlResponse(- html=content.tobytes().decode(encoding, errors='replace'),- response_headers=dict(response.headers),- status_code=response.status,- redirected_url=str(response.url)- )-- await self.hooks['after_request'](result)- return result-- except aiohttp.ServerTimeoutError as e:- await self.hooks['on_error'](e)- raise ConnectionTimeoutError(f"Request timed out: {str(e)}")-- except aiohttp.ClientConnectorError as e:- await self.hooks['on_error'](e)- raise ConnectionError(f"Connection failed: {str(e)}")-- except aiohttp.ClientError as e:- await self.hooks['on_error'](e)- raise HTTPCrawlerError(f"HTTP client error: {str(e)}")-- except asyncio.exceptions.TimeoutError as e:- await self.hooks['on_error'](e)- raise ConnectionTimeoutError(f"Request timed out: {str(e)}")-- except Exception as e:- await self.hooks['on_error'](e)- raise HTTPCrawlerError(f"HTTP request failed: {str(e)}")-- async def crawl(- self,- url: str,- config: Optional[CrawlerRunConfig] = None,- **kwargs- ) -> AsyncCrawlResponse:- config = config or CrawlerRunConfig.from_kwargs(kwargs)-- parsed = urlparse(url)- scheme = parsed.scheme.rstrip('/')-- if scheme not in self.VALID_SCHEMES:- raise ValueError(f"Unsupported URL scheme: {scheme}")-- try:- if scheme == 'file':- return await self._handle_file(parsed.path)- elif scheme == 'raw':- return await self._handle_raw(parsed.path)- else: # http or https- return await self._handle_http(url, config)-- except Exception as e:- if self.logger:- self.logger.error(- message="Crawl failed: {error}",- tag="CRAWL",- params={"error": str(e), "url": url}- )- raise\ No newline at end of filediff --git a/crawl4ai/async_crawler_strategy.py b/crawl4ai/async_crawler_strategy.pyindex b9de25f6..b3710b20 100644--- a/crawl4ai/async_crawler_strategy.py+++ b/crawl4ai/async_crawler_strategy.py@@ -1474,7 +1474,11 @@ class AsyncPlaywrightCrawlerStrategy(AsyncCrawlerStrategy):"""try:suggested_filename = download.suggested_filename- download_path = os.path.join(self.browser_config.downloads_path, suggested_filename)+ download_path = _safe_download_filepath(self.browser_config.downloads_path, suggested_filename)+ # Playwright's save_as performs the write itself (no O_NOFOLLOW+ # hook), so reject a symlink planted at the target before writing.+ if os.path.islink(download_path):+ raise ValueError(f"Refusing to write download through symlink: {download_path}")self.logger.info(message="Downloading {filename} to {path}",@@ -2413,6 +2417,35 @@ class AsyncPlaywrightCrawlerStrategy(AsyncCrawlerStrategy):# HTTP Crawler Strategy####################################################################################################+def _safe_download_filepath(downloads_path: str, filename: str) -> str:+ """Resolve a download destination confined to ``downloads_path``.++ The filename is derived from attacker-influenced input (a remote+ Content-Disposition header, or the browser's suggested filename), so it is+ reduced to a bare basename (dropping absolute paths and ``..`` traversal)+ and the resolved path is re-checked to live inside the downloads root,+ rejecting any pre-existing symlink that points outside. Raises ValueError+ on any escape. The final write must still use ``_nofollow_opener`` (or an+ equivalent ``O_NOFOLLOW`` / pre-write symlink check) to close the TOCTOU+ window between this check and the open.+ """+ safe_name = os.path.basename(filename or "")+ if not safe_name or safe_name in (".", ".."):+ safe_name = f"download_{hashlib.md5((filename or '').encode()).hexdigest()[:10]}"+ real_root = os.path.realpath(downloads_path)+ real_path = os.path.realpath(os.path.join(real_root, safe_name))+ if os.path.commonpath([real_root, real_path]) != real_root:+ raise ValueError(f"Unsafe download filename rejected: {filename!r}")+ return real_path+++def _nofollow_opener(path, flags):+ """Opener for ``open``/``aiofiles.open`` that refuses to follow a symlink at+ the final path component, closing the TOCTOU symlink-swap race after a path+ has been confined by ``_safe_download_filepath``."""+ return os.open(path, flags | os.O_NOFOLLOW)++class HTTPCrawlerError(Exception):"""Base error class for HTTP crawler specific exceptions"""pass@@ -2707,9 +2740,9 @@ class AsyncHTTPCrawlerStrategy(AsyncCrawlerStrategy):os.makedirs(downloads_path, exist_ok=True)filename = self._extract_filename(content_disposition, url, content_type)- filepath = os.path.join(downloads_path, filename)+ filepath = _safe_download_filepath(downloads_path, filename)- async with aiofiles.open(filepath, 'wb') as f:+ async with aiofiles.open(filepath, 'wb', opener=_nofollow_opener) as f:await f.write(raw_bytes)downloaded_files = [filepath]diff --git a/deploy/docker/MIGRATION.md b/deploy/docker/MIGRATION.mdnew file mode 100644index 00000000..75382306--- /dev/null+++ b/deploy/docker/MIGRATION.md@@ -0,0 +1,179 @@+# Migration Guide — Docker Server Hardening Release++This is a major, **secure-by-default** release of the Crawl4AI **Docker API+server** (`deploy/docker/`). Several defaults changed in breaking ways so the+out-of-the-box deployment is safe. The core pip library (SDK / in-process use)+is **unchanged** — these notes apply only to the self-hosted HTTP server.++How much you have to do scales with how much you drove through the API. A plain+"crawl these URLs with a normal config" user only does the two steps in+**Everyone**. The rest applies only if you used that specific feature.++> Upgrading from a self-hosted server? Read this first, then roll out behind a+> staging environment. See `SECURITY-VERIFY.md` for the deployment checklist.++---++## Everyone (2 steps)++### 1. Set an API token++The server no longer serves an unauthenticated API on `0.0.0.0`. It binds+loopback by default and will not expose itself without a credential.++```bash+export CRAWL4AI_API_TOKEN="$(openssl rand -hex 32)"+```++- With a token set, you may expose the server (put a TLS-terminating reverse+ proxy in front) and must send `Authorization: Bearer <token>` on every+ request except `GET /health`.+- With **no** token set, the server binds `127.0.0.1` only and prints a one-off+ token at startup for local use.++WebSocket clients (MCP, monitor) that can't set headers may pass `?token=...`.++### 2. Re-issue any tokens++The JWT implementation changed; tokens issued by older versions are no longer+valid. Re-mint via `POST /token` (which now requires the server to have an+`api_token` configured).++---++## Only if you used that feature++### Request bodies accept declarative options only++A crawl request body now carries scalar, declarative options only. The+following are **rejected with HTTP 400** when sent over the network; configure+them server-side or run a self-hosted in-process build (the SDK keeps full+control):++`js_code`, `js_code_before_wait`, `c4a_script`, `proxy` / `proxy_config`,+`extra_args`, `user_data_dir`, `cdp_url`, `cookies`, `headers`, `init_scripts`,+`base_url`, `deep_crawl_strategy`, `simulate_user`, `magic`,+`process_in_browser`, and nested LLM config objects.++Unknown fields are dropped; timeouts, viewport and scroll counts are clamped to+safe maximums.++### Hooks: declarative actions instead of code++`hooks.code` (Python strings) is replaced by a fixed set of declarative actions:++```jsonc+{+ "hooks": {+ "hooks": [+ {"action": "block_resources", "params": {"resource_types": ["image", "font"]}},+ {"action": "scroll_to_bottom", "params": {"max_steps": 10, "delay_ms": 500}}+ ]+ }+}+```++Available actions: `block_resources`, `add_cookies`, `set_headers`,+`scroll_to_bottom`, `wait_for_timeout`. Call `GET /hooks/info` for the parameter+schemas. Arbitrary hook code is available in a self-hosted in-process build.++### Screenshot / PDF: artifact id instead of `output_path`++`output_path` is removed. The server stores the result and returns an id + URL:++```jsonc+{"success": true, "screenshot": "<base64>",+ "artifact_id": "….", "url": "/artifacts/….", "mime": "image/png", "size": 12345}+```++Fetch the file with `GET /artifacts/{artifact_id}` (authenticated). Artifacts+have a TTL and a storage quota.++### LLM endpoints: provider by name++`base_url` is removed from `/md`, `/llm`, and `/llm/job`. Select a provider by+**name** only; the endpoint and key are configured server-side via env+(`OPENAI_BASE_URL` / `LLM_BASE_URL`) and `config.llm.allowed_providers`. A+provider outside the allowed family returns 400.++### Monitor actions need an admin token++`POST /monitor/actions/cleanup|kill_browser|restart_browser` and+`/monitor/stats/reset` require an **admin-scope** principal (the static+`CRAWL4AI_API_TOKEN` is admin; `/token`-issued JWTs are `data` scope).++### Browser / JS clients: allowlist your origin (CORS)++Cross-origin browser requests are denied unless allowlisted:++```yaml+security:+ cors_allow_origins: ["https://your-frontend.example"]+```++### TLS verification is on++Self-signed / internal TLS crawl targets now fail by default. For trusted+internal testing only: `CRAWL4AI_ALLOW_INSECURE_TLS=true`. Internal-network+crawling escape hatch: `CRAWL4AI_ALLOW_INTERNAL_URLS=true`.++### Webhook headers are validated++Custom webhook headers must be well-formed names with no control characters and+may not set hop-by-hop / sensitive headers (`Host`, `Content-Length`,+`Transfer-Encoding`, `Authorization`, `Cookie`, …). Invalid headers → 422.++### Redis requires a password++Redis runs in-container, loopback-only, password-protected, and its port is no+longer published. For an **external** redis, set `REDIS_PASSWORD`.++### Resource limits (all configurable; `0` = unbounded)++```yaml+limits:+ max_body_bytes: 10485760 # request body cap (413); 0 = unbounded+ wall_clock_s: 0 # per-crawl deadline (504); 0 = none+ queue:+ maxsize: 1000 # background job queue (503 when full); 0 = unbounded+ workers: 4+ per_principal: 0 # max concurrent jobs per caller (429); 0 = unlimited+```++To keep the previous behavior exactly, set the caps you don't want to `0`.++### Error responses are generic++5xx responses return `{"error": "Internal server error", "correlation_id": "…"}`.+Match the correlation id in the server logs for detail. Developer-facing 4xx+messages are unchanged.++---++## Defaults summary++| Setting | Old | New |+| --- | --- | --- |+| Bind | `0.0.0.0`, open | `127.0.0.1`; exposing requires a token |+| Auth | off by default | on by default |+| Security headers / CSP | off | on (strict on the API surface) |+| CORS | none | deny-by-default |+| TLS verification | disabled | enabled |+| Redis | no password, port published | password, loopback, not published |+| `output_path` | accepted | removed (artifact store) |+| LLM `base_url` in request | honored | removed |+| Hooks | Python code | declarative actions |+| Background jobs | unbounded | bounded queue (configurable, 0 = unbounded) |++## Operational notes++- **`--no-sandbox`** is still set by default (the container runs as non-root+ without a usable sandbox). To drop it, run the container with an unprivileged+ user namespace (`unprivileged_userns_clone=1`) or a seccomp profile, then set+ `CRAWL4AI_CHROMIUM_SANDBOX=true`. See `SECURITY-VERIFY.md`.+- The hardened `docker-compose.yml` uses `read_only: true` + tmpfs, `cap_drop:+ [ALL]`, `no-new-privileges`, and `shm_size` instead of a host `/dev/shm` bind.+ Mirror these in a custom compose file.+- The `/dashboard` and `/playground` UIs get baseline headers+ (`nosniff`, `X-Frame-Options: DENY`) and are auth-gated; a stricter CSP for+ the UIs is planned in a follow-up.diff --git a/deploy/docker/SECURITY-VERIFY.md b/deploy/docker/SECURITY-VERIFY.mdnew file mode 100644index 00000000..0ff9148c--- /dev/null+++ b/deploy/docker/SECURITY-VERIFY.md@@ -0,0 +1,153 @@+# Security Hardening — Build/Runtime Verification Runbook++The offline test suite (`pytest deploy/docker/tests/test_security_*.py`) covers+the logic of the hardening. A handful of items can only be confirmed with a real+`docker build` + boot or a browser. This runbook lists those, with exact+commands and expected results. Run it before relying on the hardened image.++Prereqs: Docker + docker compose, a checkout of this branch.++---++## 0. Offline suite (no Docker) — should already pass++```bash+python -m pip install -e . && pip install -r deploy/docker/requirements.txt pytest pytest-asyncio+pytest deploy/docker/tests/test_security_*.py -q+```+Expected: all pass, `1 xfailed` (the `--no-sandbox` posture test, see §3).++---++## 1. Build the hardened image++```bash+IMAGE=local-sec docker compose build+# or: docker build -t unclecode/crawl4ai:local-sec .+```+Expected: build succeeds. Note the `/app` dir is now root-owned + read-only and+the artifact dir `/var/lib/crawl4ai/outputs` is created 0700.++---++## 2. Boot + bind posture (entrypoint)++### 2a. No credential -> loopback only (refuses to expose)++```bash+docker run --rm -p 11235:11235 unclecode/crawl4ai:local-sec &+sleep 8+docker logs <id> 2>&1 | grep -i "binding loopback only" # expect this line+curl -fsS http://localhost:11235/health # expect: NOT reachable+```+Expected: entrypoint logs "no CRAWL4AI_API_TOKEN set; binding loopback only";+the mapped port is **not** reachable from the host (gunicorn bound 127.0.0.1+inside the container). This is the fail-closed default.++### 2b. With a credential -> may expose 0.0.0.0++```bash+TOKEN=$(openssl rand -hex 32)+docker run --rm -e CRAWL4AI_API_TOKEN=$TOKEN -p 11235:11235 unclecode/crawl4ai:local-sec &+sleep 8+curl -fsS http://localhost:11235/health # expect 200+curl -fsS http://localhost:11235/schema # expect 401+curl -fsS -H "Authorization: Bearer $TOKEN" http://localhost:11235/schema # expect 200+```++---++## 3. Chromium sandbox (`--no-sandbox`)++Default keeps `--no-sandbox` (works as today). To verify the hardened path:++### Option A — unprivileged user namespace (preferred)+Host: `sysctl -w kernel.unprivileged_userns_clone=1` (Debian/Ubuntu).+```bash+docker run --rm -e CRAWL4AI_API_TOKEN=$TOKEN -e CRAWL4AI_CHROMIUM_SANDBOX=true \+ -p 11235:11235 unclecode/crawl4ai:local-sec &+sleep 8+curl -fsS -X POST http://localhost:11235/crawl \+ -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \+ -d '{"urls":["https://example.com"]}'+```+Expected: a successful crawl (Chromium started sandboxed). If it fails to launch,+the host lacks userns — keep the default or use Option B.++### Option B — seccomp profile+Provide a Chrome seccomp profile and wire it in compose:+```yaml+security_opt:+ - seccomp=./seccomp-chrome.json+```+then set `CRAWL4AI_CHROMIUM_SANDBOX=true` and re-run the crawl above.++If verified, flip the default: remove `--no-sandbox` from `config.yml` and the+`test_no_no_sandbox_flag` xfail in `test_security_default_posture.py` becomes a+normal pass.++---++## 4. Read-only rootfs + tmpfs (compose)++```bash+docker compose up -d # uses read_only: true + tmpfs+sleep 8+# Writes outside tmpfs must fail:+docker compose exec crawl4ai sh -c 'echo x > /app/should_fail' ; echo "exit=$?" # expect non-zero+# Artifact write (tmpfs) must work via the API:+curl -fsS -X POST http://localhost:11235/screenshot \+ -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \+ -d '{"url":"https://example.com"}' | grep artifact_id+```+Expected: `/app` write fails (read-only), screenshot returns an `artifact_id`,+and `GET /artifacts/{id}` (with the token) returns the PNG.++---++## 5. Redis is loopback + password-protected, not exposed++```bash+docker compose exec crawl4ai sh -c 'redis-cli -p 6379 ping' # expect: NOAUTH / error+docker compose exec crawl4ai sh -c 'redis-cli -a "$REDIS_PASSWORD" ping' # expect: PONG+# From the host, the redis port must NOT be reachable (no EXPOSE / publish):+nc -z localhost 6379 ; echo "exit=$?" # expect non-zero+```++---++## 6. Browser egress proxy (DNS-rebinding control)++The browser is routed through the localhost pinning proxy. To confirm end to end:+```bash+# A normal public crawl works:+curl -fsS -X POST http://localhost:11235/crawl -H "Authorization: Bearer $TOKEN" \+ -H "Content-Type: application/json" -d '{"urls":["https://example.com"]}' | grep '"success": true'+# An internal target is refused up front (and the proxy would 403 a rebind):+curl -s -X POST http://localhost:11235/crawl -H "Authorization: Bearer $TOKEN" \+ -H "Content-Type: application/json" -d '{"urls":["http://169.254.169.254/"]}' # expect 400 blocked+```+(For a true rebinding test, point a host at a TTL-0 record that flips public->+internal and confirm the crawl never reaches the internal IP.)++---++## 7. Dashboard / playground (browser, CSP)++Open `http://localhost:11235/dashboard` and `/playground` in a browser (send the+token). Expected today: they load and work; response headers include+`X-Content-Type-Options: nosniff` and `X-Frame-Options: DENY`, but **no** strict+CSP (they still use inline scripts + CDN assets). Extending the strict CSP to+these mounts requires the externalization work noted in MIGRATION.md.++---++## Sign-off checklist++- [ ] §0 offline suite green (1 xfail)+- [ ] §2a loopback-only without a token; §2b exposed + gated with a token+- [ ] §3 Chromium starts sandboxed under userns/seccomp (if pursuing no-sandbox removal)+- [ ] §4 `/app` read-only; artifacts work on tmpfs+- [ ] §5 redis requires auth + not host-reachable+- [ ] §6 public crawl works; internal target blocked+- [ ] §7 dashboard/playground load with baseline headersdiff --git a/deploy/docker/api.py b/deploy/docker/api.pyindex 758b90fb..1756b925 100644--- a/deploy/docker/api.py+++ b/deploy/docker/api.py@@ -25,7 +25,45 @@ from crawl4ai import (RateLimiter,LLMConfig)+from crawl4ai.async_configs import Provenance, UntrustedConfigError+from hook_registry import build_declarative_hooks, HookValidationError+from llm_broker import LLMProviderNotAllowedfrom crawl4ai.utils import perform_completion_with_backoff+++def _enqueue_job(background_tasks, factory, principal=None):+ """Submit a background job to the bounded work queue (per-principal quota).++ Falls back to FastAPI BackgroundTasks when the queue isn't running (tests /+ no lifespan). Maps queue/quota limits to HTTP 503 / 429.+ """+ from work_queue import get_job_queue, QueueFull, QuotaExceeded+ q = get_job_queue()+ if q is None or not q.started:+ background_tasks.add_task(factory)+ return+ try:+ q.submit(factory, principal)+ except QuotaExceeded:+ raise HTTPException(status_code=429, detail="Too many concurrent jobs for this caller")+ except QueueFull:+ raise HTTPException(+ status_code=503, detail="Server busy, retry later",+ headers={"Retry-After": "5"},+ )+++def _attach_declarative_hooks(crawler, hooks_config: dict) -> dict:+ """Build and attach server-authored hooks from declarative specs.++ Raises HookValidationError on an unknown action / invalid params, which the+ handlers map to HTTP 400.+ """+ specs = hooks_config.get("hooks", []) or []+ hooks = build_declarative_hooks(specs)+ for hook_point, fn in hooks.items():+ crawler.crawler_strategy.set_hook(hook_point, fn)+ return {"status": "success", "attached": list(hooks.keys())}from crawl4ai.content_filter_strategy import (PruningContentFilter,BM25ContentFilter,@@ -47,8 +85,6 @@ from utils import (get_llm_base_url,get_redis_task_ttl,validate_url_destination,- validate_proxy_destination,- scrub_browser_extra_args,)from webhook import WebhookDeliveryService@@ -56,32 +92,6 @@ import psutil, timelogger = logging.getLogger(__name__)--def _enforce_proxy_safety(browser_config, crawler_config=None):- """Block SSRF via a caller-supplied proxy / proxy-redirecting browser flags.-- The crawl-target URL is validated elsewhere; this covers the other paths- that reach Chromium's egress: BrowserConfig.proxy, BrowserConfig.proxy_config- .server, CrawlerRunConfig.proxy_config.server, and proxy/DNS flags smuggled- via extra_args. Raises HTTPException(400) on a non-global proxy host."""- from fastapi import HTTPException- try:- if browser_config is not None:- if getattr(browser_config, "proxy", None):- validate_proxy_destination(browser_config.proxy)- pc = getattr(browser_config, "proxy_config", None)- if pc is not None and getattr(pc, "server", None):- validate_proxy_destination(pc.server)- if getattr(browser_config, "extra_args", None):- browser_config.extra_args = scrub_browser_extra_args(browser_config.extra_args)- if crawler_config is not None:- cpc = getattr(crawler_config, "proxy_config", None)- if cpc is not None and getattr(cpc, "server", None):- validate_proxy_destination(cpc.server)- except ValueError:- # opaque: do not echo the resolved internal address- raise HTTPException(status_code=400, detail="Proxy destination blocked (SSRF protection)")-# --- Helper to get memory ---def _get_memory_mb():try:@@ -133,6 +143,8 @@ async def handle_llm_qa(extra_args=cfg["crawler"]["browser"].get("extra_args", []),**cfg["crawler"]["browser"].get("kwargs", {}),)+ from egress_broker import enforce_egress+ enforce_egress(browser_cfg)crawler = await get_crawler(browser_cfg)result = await crawler.arun(url)if not result.success:@@ -151,19 +163,24 @@ async def handle_llm_qa(Answer:"""- resolved_provider = provider or config["llm"]["provider"]+ # Provider by name only; base_url/api_token are server-derived. A+ # request-supplied base_url is ignored (it was the key-exfil vector).+ from llm_broker import resolve_llm+ llm = resolve_llm(config, provider)response = perform_completion_with_backoff(- provider=resolved_provider,+ provider=llm["provider"],prompt_with_variables=prompt,- api_token=get_llm_api_key(config, resolved_provider),- temperature=temperature or get_llm_temperature(config, resolved_provider),- base_url=get_llm_base_url(config, resolved_provider), # ignore request base_url (key-exfil vector)+ api_token=llm["api_token"],+ temperature=temperature or llm["temperature"],+ base_url=llm["base_url"],base_delay=config["llm"].get("backoff_base_delay", 2),max_attempts=config["llm"].get("backoff_max_attempts", 3),exponential_factor=config["llm"].get("backoff_exponential_factor", 2))return response.choices[0].message.content+ except LLMProviderNotAllowed as e:+ raise HTTPException(status_code=400, detail=str(e))except Exception as e:logger.error(f"QA processing error: {str(e)}", exc_info=True)raise HTTPException(@@ -210,13 +227,15 @@ async def process_llm_extraction(error=error_msg)return- api_key = get_llm_api_key(config, provider) # Returns None to let litellm handle it+ # Provider by name only; base_url/api_token server-derived (no exfil).+ from llm_broker import resolve_llm+ _llm = resolve_llm(config, provider)llm_strategy = LLMExtractionStrategy(llm_config=LLMConfig(- provider=provider or config["llm"]["provider"],- api_token=api_key,- temperature=temperature or get_llm_temperature(config, provider),- base_url=get_llm_base_url(config, provider) # ignore request base_url (key-exfil vector)+ provider=_llm["provider"],+ api_token=_llm["api_token"],+ temperature=temperature or _llm["temperature"],+ base_url=_llm["base_url"],),instruction=instruction,schema=json.loads(schema) if schema else None,@@ -224,7 +243,19 @@ async def process_llm_extraction(cache_mode = CacheMode.ENABLED if cache == "1" else CacheMode.WRITE_ONLY- async with AsyncWebCrawler() as crawler:+ # Re-validate the destination at fetch time (the enqueue-time check is a+ # TOCTOU seed-only guard) and pin egress so the background fetch cannot+ # be rebound/redirected to an internal target.+ validate_url_destination(url)+ from utils import load_config as _load_config+ _wcfg = _load_config()+ worker_browser_cfg = BrowserConfig(+ extra_args=_wcfg["crawler"]["browser"].get("extra_args", []),+ **_wcfg["crawler"]["browser"].get("kwargs", {}),+ )+ from egress_broker import enforce_egress+ enforce_egress(worker_browser_cfg)+ async with AsyncWebCrawler(config=worker_browser_cfg) as crawler:result = await crawler.arun(url=url,config=CrawlerRunConfig(@@ -319,15 +350,18 @@ async def handle_markdown_request(if filter_type == FilterType.RAW:md_generator = DefaultMarkdownGenerator()else:+ # Provider by name only; base_url/api_token are server-derived.+ from llm_broker import resolve_llm+ _llm = resolve_llm(config, provider)content_filter = {FilterType.FIT: PruningContentFilter(),FilterType.BM25: BM25ContentFilter(user_query=query or ""),FilterType.LLM: LLMContentFilter(llm_config=LLMConfig(- provider=provider or config["llm"]["provider"],- api_token=get_llm_api_key(config, provider), # Returns None to let litellm handle it- temperature=temperature or get_llm_temperature(config, provider),- base_url=get_llm_base_url(config, provider) # ignore request base_url (key-exfil vector)+ provider=_llm["provider"],+ api_token=_llm["api_token"],+ temperature=temperature or _llm["temperature"],+ base_url=_llm["base_url"],),instruction=query or "Extract main content")@@ -343,6 +377,8 @@ async def handle_markdown_request(extra_args=_cfg["crawler"]["browser"].get("extra_args", []),**_cfg["crawler"]["browser"].get("kwargs", {}),)+ from egress_broker import enforce_egress+ enforce_egress(browser_cfg)crawler = await get_crawler(browser_cfg)result = await crawler.arun(url=decoded_url,@@ -363,6 +399,10 @@ async def handle_markdown_request(if filter_type == FilterType.RAWelse result.markdown.fit_markdown)+ except HTTPException:+ raise+ except LLMProviderNotAllowed as e:+ raise HTTPException(status_code=400, detail=str(e))except Exception as e:logger.error(f"Markdown error: {str(e)}", exc_info=True)raise HTTPException(@@ -385,15 +425,18 @@ async def handle_llm_request(provider: Optional[str] = None,webhook_config: Optional[Dict] = None,temperature: Optional[float] = None,- api_base_url: Optional[str] = None+ api_base_url: Optional[str] = None,+ requester: Optional[str] = None,+ is_admin: bool = False,) -> JSONResponse:"""Handle LLM extraction requests."""base_url = get_base_url(request)-+try:if is_task_id(input_path):return await handle_task_status(- redis, input_path, base_url+ redis, input_path, base_url,+ requester=requester, is_admin=is_admin,)if not query:@@ -419,9 +462,12 @@ async def handle_llm_request(provider,webhook_config,temperature,- api_base_url+ api_base_url,+ owner=requester,)+ except HTTPException:+ raise # 429/503 (queue/quota), 400, etc. - don't mask as 500except Exception as e:logger.error(f"LLM endpoint error: {str(e)}", exc_info=True)return JSONResponse({@@ -436,9 +482,16 @@ async def handle_task_status(task_id: str,base_url: str,*,- keep: bool = False+ keep: bool = False,+ requester: Optional[str] = None,+ is_admin: bool = False,) -> JSONResponse:- """Handle task status check requests."""+ """Handle task status check requests.++ Enforces ownership: a task records the `owner` (principal sub) that created+ it; a different requester gets 404 (not 403, so task existence is not+ revealed). Admin-scope principals may read any task.+ """task = await redis.hgetall(f"task:{task_id}")if not task:raise HTTPException(@@ -447,6 +500,15 @@ async def handle_task_status()task = decode_redis_hash(task)++ owner = task.get("owner")+ if owner and not is_admin and owner != requester:+ # Do not leak existence of someone else's task.+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail="Task not found"+ )+response = create_task_response(task, task_id, base_url)if task["status"] in [TaskStatus.COMPLETED, TaskStatus.FAILED]:@@ -467,7 +529,8 @@ async def create_new_task(provider: Optional[str] = None,webhook_config: Optional[Dict] = None,temperature: Optional[float] = None,- api_base_url: Optional[str] = None+ api_base_url: Optional[str] = None,+ owner: Optional[str] = None,) -> JSONResponse:"""Create and initialize a new task."""decoded_url = unquote(input_path)@@ -483,6 +546,8 @@ async def create_new_task("created_at": datetime.now().isoformat(),"url": decoded_url}+ if owner:+ task_data["owner"] = owner# Store webhook config if providedif webhook_config:@@ -490,20 +555,19 @@ async def create_new_task(await hset_with_ttl(redis, f"task:{task_id}", task_data, config)- background_tasks.add_task(- process_llm_extraction,- redis,- config,- task_id,- decoded_url,- query,- schema,- cache,- provider,- webhook_config,- temperature,- api_base_url- )+ try:+ _enqueue_job(+ background_tasks,+ lambda: process_llm_extraction(+ redis, config, task_id, decoded_url, query, schema, cache,+ provider, webhook_config, temperature, api_base_url,+ ),+ principal=owner,+ )+ except HTTPException:+ # Don't leave an orphan PROCESSING task if we refused to enqueue.+ await redis.delete(f"task:{task_id}")+ raisereturn JSONResponse({"task_id": task_id,@@ -569,6 +633,17 @@ async def stream_results(crawler: AsyncWebCrawler, results_gen: AsyncGenerator)if crawler:await release_crawler(crawler)++def _normalize_and_validate_seeds(urls: List[str]) -> List[str]:+ """Prefix bare hosts with https:// and SSRF-validate every seed URL's+ destination. Shared by the streaming and non-streaming crawl handlers so a+ new entry point cannot silently skip the destination check."""+ urls = [('https://' + url) if not url.startswith(('http://', 'https://')) and not url.startswith(("raw:", "raw://")) else url for url in urls]+ for url in urls:+ validate_url_destination(url)+ return urls++async def handle_crawl_request(urls: List[str],browser_config: dict,@@ -593,15 +668,15 @@ async def handle_crawl_request(start_time = time.time()mem_delta_mb = Nonepeak_mem_mb = start_mem_mb- hook_manager = Nonetry:- urls = [('https://' + url) if not url.startswith(('http://', 'https://')) and not url.startswith(("raw:", "raw://")) else url for url in urls]- for url in urls:- validate_url_destination(url)- browser_config = BrowserConfig.load(browser_config)- crawler_config = CrawlerRunConfig.load(crawler_config)- _enforce_proxy_safety(browser_config, crawler_config)+ urls = _normalize_and_validate_seeds(urls)+ browser_config = BrowserConfig.load(browser_config, provenance=Provenance.UNTRUSTED)+ crawler_config = CrawlerRunConfig.load(crawler_config, provenance=Provenance.UNTRUSTED)+ from egress_broker import enforce_egress+ enforce_egress(browser_config)+ from governor import clamp_deep_crawl+ clamp_deep_crawl(crawler_config)dispatcher = MemoryAdaptiveDispatcher(memory_threshold_percent=config["crawler"]["memory_threshold_percent"],@@ -613,17 +688,10 @@ async def handle_crawl_request(from crawler_pool import get_crawler, release_crawlercrawler = await get_crawler(browser_config)- # Attach hooks if provided+ # Attach declarative hooks if providedhooks_status = {}if hooks_config:- from hook_manager import attach_user_hooks_to_crawler, UserHookManager- hook_manager = UserHookManager(timeout=hooks_config.get('timeout', 30))- hooks_status, hook_manager = await attach_user_hooks_to_crawler(- crawler,- hooks_config.get('code', {}),- timeout=hooks_config.get('timeout', 30),- hook_manager=hook_manager- )+ hooks_status = _attach_declarative_hooks(crawler, hooks_config)logger.info(f"Hooks attachment status: {hooks_status['status']}")base_config = config["crawler"]["base_config"]@@ -631,7 +699,7 @@ async def handle_crawl_request(# Build the config(s) to pass to arun/arun_manyif crawler_configs and len(urls) > 1:# Per-URL config list: deserialize each and apply base_config- config_list = [CrawlerRunConfig.load(cc) for cc in crawler_configs]+ config_list = [CrawlerRunConfig.load(cc, provenance=Provenance.UNTRUSTED) for cc in crawler_configs]for cfg in config_list:for key, value in base_config.items():if hasattr(cfg, key):@@ -654,7 +722,13 @@ async def handle_crawl_request(urls[0] if len(urls) == 1 else urls,config=effective_config,dispatcher=dispatcher)- results = await partial_func()+ # Optional per-crawl wall-clock deadline (config limits.wall_clock_s; 0 = none).+ from governor import wall_clock_seconds+ _deadline = wall_clock_seconds(config)+ if _deadline and _deadline > 0:+ results = await asyncio.wait_for(partial_func(), timeout=_deadline)+ else:+ results = await partial_func()# Ensure results is always a listif not isinstance(results, list):@@ -721,33 +795,31 @@ async def handle_crawl_request(pass# Add hooks information if hooks were used- if hooks_config and hook_manager:- from hook_manager import UserHookManager- if isinstance(hook_manager, UserHookManager):- try:- # Ensure all hook data is JSON serializable- hook_data = {- "status": hooks_status,- "execution_log": hook_manager.execution_log,- "errors": hook_manager.errors,- "summary": hook_manager.get_summary()- }- # Test that it's serializable- json.dumps(hook_data)- response["hooks"] = hook_data- except (TypeError, ValueError) as e:- logger.error(f"Hook data not JSON serializable: {e}")- response["hooks"] = {- "status": {"status": "error", "message": "Hook data serialization failed"},- "execution_log": [],- "errors": [{"error": str(e)}],- "summary": {}- }-+ if hooks_config:+ response["hooks"] = hooks_status+return response+ except (UntrustedConfigError, HookValidationError) as e:+ # An untrusted request body tried to set a forbidden power-field,+ # construct a disallowed type, or specify an invalid hook. Client error.+ try:+ from monitor import get_monitor+ await get_monitor().track_request_end(+ request_id, success=False, error=str(e), status_code=400+ )+ except:+ pass+ raise HTTPException(status_code=400, detail=f"Rejected request: {e}")++ except asyncio.TimeoutError:+ # Per-crawl wall-clock deadline exceeded.+ raise HTTPException(status_code=504, detail="Crawl exceeded the time limit")+except HTTPException:- raise # client errors (e.g. blocked proxy 400) must not become 500+ # Deliberate status (e.g. 400 SSRF "URL blocked") must pass through+ # rather than be genericized to 500 by the handler below.+ raiseexcept Exception as e:logger.error(f"Crawl error: {str(e)}", exc_info=True)@@ -789,11 +861,18 @@ async def handle_stream_crawl_request(hooks_info = Nonecrawler = Nonetry:- browser_config = BrowserConfig.load(browser_config)+ # SSRF guard: validate every seed URL's destination before fetching,+ # mirroring handle_crawl_request. The streaming path previously skipped+ # this, leaving /crawl/stream (and /crawl with stream=true) unguarded.+ urls = _normalize_and_validate_seeds(urls)+ browser_config = BrowserConfig.load(browser_config, provenance=Provenance.UNTRUSTED)# browser_config.verbose = True # Set to False or remove for production stress testingbrowser_config.verbose = False- crawler_config = CrawlerRunConfig.load(crawler_config)- _enforce_proxy_safety(browser_config, crawler_config)+ from egress_broker import enforce_egress+ enforce_egress(browser_config)+ crawler_config = CrawlerRunConfig.load(crawler_config, provenance=Provenance.UNTRUSTED)+ from governor import clamp_deep_crawl+ clamp_deep_crawl(crawler_config)crawler_config.scraping_strategy = LXMLWebScrapingStrategy()crawler_config.stream = True@@ -810,19 +889,11 @@ async def handle_stream_crawl_request(from crawler_pool import get_crawler, release_crawlercrawler = await get_crawler(browser_config)- # Attach hooks if provided+ # Attach declarative hooks if providedif hooks_config:- from hook_manager import attach_user_hooks_to_crawler, UserHookManager- hook_manager = UserHookManager(timeout=hooks_config.get('timeout', 30))- hooks_status, hook_manager = await attach_user_hooks_to_crawler(- crawler,- hooks_config.get('code', {}),- timeout=hooks_config.get('timeout', 30),- hook_manager=hook_manager- )+ hooks_status = _attach_declarative_hooks(crawler, hooks_config)logger.info(f"Hooks attachment status for streaming: {hooks_status['status']}")- # Include hook manager in hooks_info for proper tracking- hooks_info = {'status': hooks_status, 'manager': hook_manager}+ hooks_info = {'status': hooks_status}# Deep crawl with single URL: use arun() which returns an async generator# mirroring the Python library's streaming behavior@@ -847,10 +918,17 @@ async def handle_stream_crawl_request(return crawler, results_gen, hooks_info+ except (UntrustedConfigError, HookValidationError) as e:+ if crawler:+ await release_crawler(crawler)+ raise HTTPException(status_code=400, detail=f"Rejected request: {e}")+except HTTPException:+ # Deliberate status (e.g. 400 SSRF "URL blocked") must pass through+ # rather than be genericized to 500 by the handler below.if crawler:await release_crawler(crawler)- raise # client errors (e.g. blocked proxy 400) must not become 500+ raiseexcept Exception as e:# Release crawler on setup error (for successful streams,@@ -872,6 +950,7 @@ async def handle_crawl_job(crawler_config: Dict,config: Dict,webhook_config: Optional[Dict] = None,+ owner: Optional[str] = None,) -> Dict:"""Fire-and-forget version of handle_crawl_request.@@ -888,6 +967,8 @@ async def handle_crawl_job("result": "","error": "",}+ if owner:+ task_data["owner"] = owner# Store webhook config if providedif webhook_config:@@ -921,7 +1002,6 @@ async def handle_crawl_job(result=result)- await asyncio.sleep(5) # Give Redis time to process the updateexcept Exception as exc:await hset_with_ttl(redis, f"task:{task_id}", {"status": TaskStatus.FAILED,@@ -938,5 +1018,9 @@ async def handle_crawl_job(error=str(exc))- background_tasks.add_task(_runner)+ try:+ _enqueue_job(background_tasks, _runner, principal=owner)+ except HTTPException:+ await redis.delete(f"task:{task_id}")+ raisereturn {"task_id": task_id}\ No newline at end of filediff --git a/deploy/docker/artifacts.py b/deploy/docker/artifacts.pynew file mode 100644index 00000000..a5aac1b5--- /dev/null+++ b/deploy/docker/artifacts.py@@ -0,0 +1,166 @@+"""+artifacts.py - sandboxed, opaque-ID artifact store.++The screenshot/PDF endpoints used to accept a caller-supplied `output_path` and+write to it. `validate_output_path` was string-only (no realpath / O_NOFOLLOW),+so a symlink or a sibling-prefix name (".../outputs-evil") bypassed it and gave+an arbitrary write -> root RCE (e.g. /etc/cron.d) since /app was writable.++The fix: callers never name a path. The server owns the directory, the names,+and the bytes. Each artifact gets a server-generated opaque id; writes are+O_EXCL|O_NOFOLLOW 0600 into a 0700 dir off /tmp, size-capped and dir-quota'd;+retrieval validates a 32-hex id, lstat()s a non-symlink regular file, and+enforces a TTL. A janitor reaps expired/over-quota files.+"""++from __future__ import annotations++import os+import re+import time+import uuid+from typing import Dict, Tuple++ARTIFACT_DIR = os.environ.get("CRAWL4AI_ARTIFACT_DIR", "/var/lib/crawl4ai/outputs")+MAX_ARTIFACT_BYTES = int(os.environ.get("CRAWL4AI_MAX_ARTIFACT_BYTES", str(50 * 1024 * 1024)))+ARTIFACT_QUOTA_BYTES = int(os.environ.get("CRAWL4AI_ARTIFACT_QUOTA_BYTES", str(2 * 1024 * 1024 * 1024)))+ARTIFACT_TTL_SECONDS = int(os.environ.get("CRAWL4AI_ARTIFACT_TTL_SECONDS", "3600"))++_HEX32 = re.compile(r"^[0-9a-f]{32}$")+_KIND = {+ "png": (".png", "image/png"),+ "pdf": (".pdf", "application/pdf"),+}+++class ArtifactError(Exception):+ pass+++class ArtifactTooLarge(ArtifactError):+ pass+++class QuotaExceeded(ArtifactError):+ pass+++class ArtifactNotFound(ArtifactError):+ pass+++def init_store() -> None:+ """Create the artifact dir 0700 (idempotent)."""+ os.makedirs(ARTIFACT_DIR, mode=0o700, exist_ok=True)+ try:+ os.chmod(ARTIFACT_DIR, 0o700)+ except OSError:+ pass+++def _dir_size() -> int:+ total = 0+ try:+ with os.scandir(ARTIFACT_DIR) as it:+ for entry in it:+ try:+ st = entry.stat(follow_symlinks=False)+ if os.path.stat.S_ISREG(st.st_mode):+ total += st.st_size+ except OSError:+ continue+ except FileNotFoundError:+ return 0+ return total+++def write_artifact(kind: str, data: bytes) -> Dict:+ """Write bytes under a server-generated opaque id. Returns metadata."""+ ext, mime = _KIND.get(kind, (".bin", "application/octet-stream"))+ if len(data) > MAX_ARTIFACT_BYTES:+ raise ArtifactTooLarge(f"artifact exceeds {MAX_ARTIFACT_BYTES} bytes")+ init_store()+ if _dir_size() + len(data) > ARTIFACT_QUOTA_BYTES:+ raise QuotaExceeded("artifact storage quota exceeded")++ artifact_id = uuid.uuid4().hex # 32 hex chars, unguessable+ path = os.path.join(ARTIFACT_DIR, artifact_id + ext)+ # O_EXCL: never follow/overwrite an existing entry; O_NOFOLLOW: refuse a+ # symlink at the final component. Server-chosen name => no traversal.+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)+ fd = os.open(path, flags, 0o600)+ with os.fdopen(fd, "wb") as f:+ f.write(data)+ return {"artifact_id": artifact_id, "mime": mime, "size": len(data)}+++def resolve_artifact(artifact_id: str) -> Tuple[str, str]:+ """Map an opaque id to (path, mime), enforcing hex-id, no-symlink, TTL.++ Raises ArtifactNotFound for an invalid id, a non-regular/symlink file, a+ missing file, or an expired artifact (so existence is never revealed).+ """+ if not isinstance(artifact_id, str) or not _HEX32.match(artifact_id):+ raise ArtifactNotFound()+ for ext, mime in _KIND.values():+ path = os.path.join(ARTIFACT_DIR, artifact_id + ext)+ try:+ st = os.lstat(path) # do NOT follow symlinks+ except FileNotFoundError:+ continue+ if not os.path.stat.S_ISREG(st.st_mode):+ raise ArtifactNotFound() # symlink / special file+ if time.time() - st.st_mtime > ARTIFACT_TTL_SECONDS:+ try:+ os.unlink(path)+ except OSError:+ pass+ raise ArtifactNotFound()+ return path, mime+ raise ArtifactNotFound()+++def janitor() -> int:+ """Reap expired artifacts; if still over quota, reap oldest first."""+ init_store()+ now = time.time()+ reaped = 0+ entries = []+ try:+ with os.scandir(ARTIFACT_DIR) as it:+ for entry in it:+ try:+ st = entry.stat(follow_symlinks=False)+ except OSError:+ continue+ if not os.path.stat.S_ISREG(st.st_mode):+ # remove anything that is not a regular file (e.g. a symlink)+ try:+ os.unlink(entry.path)+ reaped += 1+ except OSError:+ pass+ continue+ if now - st.st_mtime > ARTIFACT_TTL_SECONDS:+ try:+ os.unlink(entry.path)+ reaped += 1+ except OSError:+ pass+ continue+ entries.append((st.st_mtime, st.st_size, entry.path))+ except FileNotFoundError:+ return reaped++ total = sum(sz for _, sz, _ in entries)+ if total > ARTIFACT_QUOTA_BYTES:+ for _mtime, sz, path in sorted(entries): # oldest first+ if total <= ARTIFACT_QUOTA_BYTES:+ break+ try:+ os.unlink(path)+ total -= sz+ reaped += 1+ except OSError:+ pass+ return reapeddiff --git a/deploy/docker/auth.py b/deploy/docker/auth.pyindex 4a5f7332..3d7917b8 100644--- a/deploy/docker/auth.py+++ b/deploy/docker/auth.py@@ -1,104 +1,146 @@+"""+Authentication primitives for the Crawl4AI Docker server.++This module is PyJWT-only. The previous dual dependency on the GehirnInc `jwt`+package *and* `PyJWT` (both install a top-level `jwt` module) meant the meaning+of `import jwt` depended on install order, and the security tests could exercise+a different code path than production. We now depend on PyJWT exclusively.++Auth is decided in one place: the AuthGateMiddleware (auth_gate.py), which runs+as the outermost ASGI layer and fails closed. The helpers here are what that+gate (and the /token endpoint) call:++ * create_access_token - mint an HS256 JWT carrying a scope claim+ * decode_token - verify an HS256 JWT (algorithms passed as a LIST,+ which kills the substring-match bug and rejects+ alg:none / other algorithms)+ * constant_time_eq - timing-safe comparison for the static API token+ * resolve_secret_key - fail fast when a real secret is required but missing+"""++import hmac+import loggingimport os+import secrets as _secretsfrom datetime import datetime, timedelta, timezonefrom typing import Dict, Optional-from jwt import JWT, jwk_from_dict-from jwt.utils import get_int_from_datetime-from fastapi import Depends, HTTPException-from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials-from pydantic import EmailStr-from pydantic.main import BaseModel-import base64--instance = JWT()-security = HTTPBearer(auto_error=False)++import jwt+from fastapi import HTTPException, Request+from pydantic import BaseModel, EmailStr+ACCESS_TOKEN_EXPIRE_MINUTES = 60+ALGORITHM = "HS256"+_ALGORITHMS = [ALGORITHM] # a LIST on purpose: no substring matching, no alg:none_WEAK_SECRETS = {"mysecret", "secret", "password", "changeme", "test", "12345678"}+_MIN_SECRET_LEN = 32++_log = logging.getLogger("crawl4ai.security")-def _resolve_secret_key() -> str:- """Resolve SECRET_KEY: validate if set, auto-generate if JWT enabled but unset."""- import logging- import secrets as _secrets+def resolve_secret_key(*, required: bool) -> str:+ """Resolve and validate SECRET_KEY.++ required=True -> fail fast (RuntimeError) if unset/weak/short. Used when a+ real auth deployment is in effect; an ephemeral key would+ silently invalidate every issued token on restart.+ required=False -> auto-generate an ephemeral key (and warn) when unset, so+ loopback/dev still works. A set-but-weak key still fails.+ """key = os.environ.get("SECRET_KEY", "")if key:if key.lower() in _WEAK_SECRETS:raise RuntimeError(- "FATAL: SECRET_KEY is a known weak value. "- "Generate a strong one: python3 -c \"import secrets; print(secrets.token_hex(32))\""+ "FATAL: SECRET_KEY is a known weak value. Generate a strong one: "+ 'python3 -c "import secrets; print(secrets.token_hex(32))"')- if len(key) < 32:+ if len(key) < _MIN_SECRET_LEN:raise RuntimeError(- "FATAL: SECRET_KEY must be at least 32 characters. "- "Generate one: python3 -c \"import secrets; print(secrets.token_hex(32))\""+ f"FATAL: SECRET_KEY must be at least {_MIN_SECRET_LEN} characters. "+ 'Generate one: python3 -c "import secrets; print(secrets.token_hex(32))"')return key- # No key set -- auto-generate ephemeral key++ if required:+ raise RuntimeError(+ "FATAL: authentication is enabled but SECRET_KEY is not set. "+ 'Set it: SECRET_KEY=$(python3 -c "import secrets; print(secrets.token_hex(32))")'+ )+generated = _secrets.token_hex(32)- logging.getLogger("crawl4ai.security").warning(- "No SECRET_KEY set. Auto-generated ephemeral key (changes on restart). "- "Set SECRET_KEY env var for production."+ _log.warning(+ "No SECRET_KEY set. Auto-generated an ephemeral key (changes on restart, "+ "invalidating issued tokens). Set SECRET_KEY for any real deployment.")return generated-SECRET_KEY = _resolve_secret_key()--def get_jwk_from_secret(secret: str):- """Convert a secret string into a JWK object."""- secret_bytes = secret.encode('utf-8')- b64_secret = base64.urlsafe_b64encode(secret_bytes).rstrip(b'=').decode('utf-8')- return jwk_from_dict({"kty": "oct", "k": b64_secret})--def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:- """Create a JWT access token with an expiration."""- to_encode = data.copy()- expire = datetime.now(timezone.utc) + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))- to_encode.update({"exp": get_int_from_datetime(expire)})- signing_key = get_jwk_from_secret(SECRET_KEY)- return instance.encode(to_encode, signing_key, alg='HS256')--def verify_token(credentials: HTTPAuthorizationCredentials) -> Dict:- """Verify the JWT token from the Authorization header."""-- if not credentials or not credentials.credentials:- raise HTTPException(- status_code=401,- detail="No token provided",- headers={"WWW-Authenticate": "Bearer"}- )-- token = credentials.credentials- verifying_key = get_jwk_from_secret(SECRET_KEY)- try:- payload = instance.decode(token, verifying_key, do_time_check=True, algorithms='HS256')- return payload- except Exception as e:- raise HTTPException(- status_code=401,- detail=f"Invalid or expired token: {str(e)}",- headers={"WWW-Authenticate": "Bearer"}- )+# Module-level key, resolved leniently at import. The server's startup+# _resolve_auth() performs the fail-fast check when a real deployment is+# detected (credential set and/or non-loopback bind).+SECRET_KEY = resolve_secret_key(required=False)+++def create_access_token(+ data: dict,+ *,+ scope: str = "data",+ expires_delta: Optional[timedelta] = None,+) -> str:+ """Mint an HS256 JWT. `scope` is "data" (normal) or "admin"."""+ to_encode = dict(data)+ to_encode["scope"] = scope+ expire = datetime.now(timezone.utc) + (+ expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)+ )+ to_encode["exp"] = expire+ return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)+++def decode_token(token: str) -> Dict:+ """Verify an HS256 JWT and return its claims.++ Raises jwt.InvalidTokenError (incl. ExpiredSignatureError) on any failure.+ `algorithms` is a list, so alg:none and every non-HS256 algorithm are+ rejected outright.+ """+ return jwt.decode(token, SECRET_KEY, algorithms=_ALGORITHMS)+++def constant_time_eq(a: str, b: str) -> bool:+ """Timing-safe string comparison for the static API token."""+ return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8"))+++def get_principal(request: Request) -> Optional[Dict]:+ """The principal the AuthGateMiddleware already validated (or None)."""+ return getattr(request.state, "principal", None)def get_token_dependency(config: Dict):- """Return the token dependency if JWT is enabled, else a function that returns None."""-- if config.get("security", {}).get("jwt_enabled", False):- def jwt_required(credentials: HTTPAuthorizationCredentials = Depends(security)) -> Dict:- """Enforce JWT authentication when enabled."""- if credentials is None:- raise HTTPException(- status_code=401,- detail="Authentication required. Please provide a valid Bearer token.",- headers={"WWW-Authenticate": "Bearer"}- )- return verify_token(credentials)- return jwt_required- else:- return lambda: None+ """Backward-compatible dependency factory.++ Auth enforcement now lives in the AuthGateMiddleware (the outermost ASGI+ layer); by the time any route dependency runs, the request was already+ authenticated by the gate or rejected with 401. This dependency simply+ surfaces the validated principal to handlers that declared `_td`.+ """++ def _principal(request: Request) -> Optional[Dict]:+ return get_principal(request)++ return _principal+++def require_admin(request: Request) -> Dict:+ """Dependency: require an admin-scope principal (destructive actions)."""+ principal = get_principal(request)+ if not principal or principal.get("scope") != "admin":+ raise HTTPException(status_code=403, detail="Admin scope required")+ return principalclass TokenRequest(BaseModel):email: EmailStr- api_token: Optional[str] = None\ No newline at end of file+ api_token: Optional[str] = Nonediff --git a/deploy/docker/auth_gate.py b/deploy/docker/auth_gate.pynew file mode 100644index 00000000..2a037e50--- /dev/null+++ b/deploy/docker/auth_gate.py@@ -0,0 +1,119 @@+"""+AuthGateMiddleware - the single, fail-closed authentication boundary.++The previous design decided auth in a per-route FastAPI dependency that, when+`jwt_enabled` was false (the default), returned `lambda: None` - so every+`Depends(token_dep)` was decorative and the whole API was open. Static mounts,+the MCP transports and the Prometheus endpoint were never covered at all.++This middleware moves auth to the outermost ASGI layer so it covers EVERY+route, mount and sub-app (HTTP + WebSocket) uniformly, and it fails closed: a+request without a valid credential is rejected before it reaches any handler.++Accepted credentials:+ * the static operator API token (constant-time compared) -> admin scope, or+ * a valid HS256 JWT minted by this server -> the token's own scope claim.++Public paths (the health check and the token-issuing endpoint) pass through.+On failure: HTTP 401 JSON, or WebSocket close 4401.+On success: the validated principal is attached at scope["state"]["principal"]+(readable downstream as request.state.principal) for scope/ownership checks.+"""++from __future__ import annotations++import json+from typing import Callable, Dict, Iterable, Optional+from urllib.parse import parse_qs++import jwt++from auth import constant_time_eq, decode_token+++class AuthGateMiddleware:+ def __init__(+ self,+ app,+ *,+ token_provider: Callable[[], str],+ public_paths: Iterable[str] = (),+ ):+ self.app = app+ self._token_provider = token_provider+ self.public_paths = set(public_paths)++ # ─────────────────────────── ASGI entry ───────────────────────────+ async def __call__(self, scope, receive, send):+ if scope["type"] not in ("http", "websocket"):+ await self.app(scope, receive, send)+ return++ if scope.get("path", "") in self.public_paths:+ await self.app(scope, receive, send)+ return++ principal = self._authenticate(scope)+ if principal is None:+ await self._reject(scope, receive, send)+ return++ # Expose the principal to downstream handlers/dependencies.+ state = scope.setdefault("state", {})+ state["principal"] = principal+ await self.app(scope, receive, send)++ # ──────────────────────────── helpers ─────────────────────────────+ def _authenticate(self, scope) -> Optional[Dict]:+ token = self._extract_token(scope)+ if not token:+ return None++ # 1) static operator token -> admin scope+ static_token = self._token_provider() or ""+ if static_token and constant_time_eq(token, static_token):+ return {"sub": "operator", "scope": "admin", "via": "api_token"}++ # 2) HS256 JWT minted by this server+ try:+ claims = decode_token(token)+ except jwt.InvalidTokenError:+ return None+ claims.setdefault("scope", "data")+ return claims++ @staticmethod+ def _extract_token(scope) -> Optional[str]:+ # Authorization: Bearer <token>+ for name, value in scope.get("headers", []):+ if name == b"authorization":+ raw = value.decode("latin-1")+ if raw[:7].lower() == "bearer ":+ return raw[7:].strip()+ return None+ # WebSocket clients that cannot set headers may pass ?token=+ if scope["type"] == "websocket":+ qs = parse_qs(scope.get("query_string", b"").decode("latin-1"))+ vals = qs.get("token")+ if vals:+ return vals[0]+ return None++ async def _reject(self, scope, receive, send):+ if scope["type"] == "websocket":+ # Close before accept; 4401 = application "unauthorized".+ await send({"type": "websocket.close", "code": 4401})+ return+ body = json.dumps({"detail": "Authentication required"}).encode()+ await send(+ {+ "type": "http.response.start",+ "status": 401,+ "headers": [+ (b"content-type", b"application/json"),+ (b"www-authenticate", b"Bearer"),+ (b"content-length", str(len(body)).encode()),+ ],+ }+ )+ await send({"type": "http.response.body", "body": body})diff --git a/deploy/docker/config.yml b/deploy/docker/config.ymlindex 08af889c..614ac24d 100644--- a/deploy/docker/config.yml+++ b/deploy/docker/config.yml@@ -2,7 +2,10 @@app:title: "Crawl4AI API"version: "1.0.0"- host: "0.0.0.0"+ # Loopback by default. Exposing on 0.0.0.0 requires a credential+ # (CRAWL4AI_API_TOKEN); the startup auth guard refuses an open non-loopback+ # bind without one. Put a TLS-terminating reverse proxy in front for exposure.+ host: "127.0.0.1"port: 11235reload: Falseworkers: 1@@ -30,6 +33,18 @@ redis:ssl_certfile: Nonessl_keyfile: None+# Resource governance (DoS protection). Any limit set to 0 means "unbounded"+# (the pre-hardening behavior), so you can relax or disable each one.+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+ 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+ per_principal: 0 # max concurrent jobs per caller (429 over cap); 0 = unlimited+# Rate Limiting Configurationrate_limiting:enabled: True@@ -43,11 +58,12 @@ rate_limiting:# - Set SECRET_KEY environment variable to a secure random value# - Set CRAWL4AI_HOOKS_ENABLED=true only if you need hooks (RCE risk)security:- enabled: false+ enabled: truejwt_enabled: falseapi_token: "" # When set, /token endpoint requires this secret to issue JWTshttps_redirect: falsetrusted_hosts: ["*"]+ cors_allow_origins: [] # deny-by-default; list explicit origins to allow CORSheaders:x_content_type_options: "nosniff"x_frame_options: "DENY"@@ -74,13 +90,21 @@ crawler:text_mode: trueextra_args:# - "--single-process"+ # SECURITY: --no-sandbox disables the Chromium renderer sandbox (a renderer+ # exploit can then reach the container). It is required only because the+ # container runs as non-root without a usable sandbox. To remove it, run+ # the container with an unprivileged user namespace+ # (host: unprivileged_userns_clone=1) OR a verified seccomp profile+ # (compose: security_opt: seccomp=...), then delete this flag and confirm+ # Chromium still starts. Tracked as a build-gated hardening item.- "--no-sandbox"- "--disable-dev-shm-usage"- "--disable-gpu"- "--disable-software-rasterizer"# --disable-web-security removed for security (enables cross-origin access)- - "--allow-insecure-localhost"- - "--ignore-certificate-errors"+ # --allow-insecure-localhost / --ignore-certificate-errors removed: they+ # disabled TLS verification for every crawl (MITM / SSRF-to-internal-TLS).+ # Set CRAWL4AI_ALLOW_INSECURE_TLS=true only for trusted internal testing.# Logging Configurationlogging:diff --git a/deploy/docker/egress_broker.py b/deploy/docker/egress_broker.pynew file mode 100644index 00000000..873b6a12--- /dev/null+++ b/deploy/docker/egress_broker.py@@ -0,0 +1,209 @@+"""+egress_broker.py - the single rule and primitive for all outbound traffic.++Every SSRF defense before this was enumerate-badness (a hand-maintained list of+blocked CIDRs) and resolve-then-discard: the validator resolved a hostname,+checked the IP against the list, then threw the IP away and let the real+connection re-resolve (DNS rebinding / TOCTOU). It also missed whole families:+the IPv6 unspecified ::, NAT64 64:ff9b::/96, 6to4 2002::/16, and+host.docker.internal as anything but a literal prefix.++This module replaces the blocklist with one rule:++ reject any resolved IP where `not ip.is_global`++evaluated on every transition-embedded IPv4 form as well (v4-mapped, NAT64,+6to4, v4-compatible), and makes the entity that resolves DNS the same entity+that hands back the pinned IP to dial. `resolve_and_pin()` resolves once and+returns the exact IP to connect to; callers must dial that IP (Host/SNI+preserved) so a second, attacker-controlled resolution is never used.++Errors are opaque (`EgressBlocked.reason == "URL blocked"`) so the API never+leaks a resolved internal IP, hostname, or traceback (the old DNS oracle).+"""++from __future__ import annotations++import ipaddress+import os+import socket+from dataclasses import dataclass+from typing import List, Optional+from urllib.parse import urlparse++# Operator escape hatch for trusted internal deployments (off by default).+ALLOW_INTERNAL = os.environ.get("CRAWL4AI_ALLOW_INTERNAL_URLS", "false").lower() == "true"++_NAT64 = ipaddress.ip_network("64:ff9b::/96")+_V4COMPAT = ipaddress.ip_network("::/96")+_6TO4 = ipaddress.ip_network("2002::/16")++# Hostnames we refuse regardless of resolution (belt-and-suspenders; they also+# resolve to non-global addresses and would be caught anyway).+_BLOCKED_HOSTNAMES = {+ "localhost", "metadata.google.internal", "metadata",+ "kubernetes.default", "kubernetes.default.svc",+}+++class EgressBlocked(Exception):+ """Outbound target rejected. Carries an OPAQUE reason - never an IP/host."""++ def __init__(self, reason: str = "URL blocked"):+ self.reason = reason+ super().__init__(reason)+++@dataclass+class PinnedTarget:+ scheme: str+ host: str # original hostname (for Host header / SNI)+ port: int+ ip: str # the exact IP to dial - do NOT re-resolve `host`+++def _embedded_v4_forms(ip: ipaddress._BaseAddress) -> List[ipaddress._BaseAddress]:+ """The address plus any IPv4 embedded in a transition IPv6 form.++ Only the well-defined transition ranges are unwrapped, so a normal global+ IPv6 is never mis-derived into a bogus (and possibly non-global) IPv4.+ """+ forms: List[ipaddress._BaseAddress] = [ip]+ if isinstance(ip, ipaddress.IPv6Address):+ mapped = ip.ipv4_mapped+ if mapped is not None:+ forms.append(mapped)+ elif ip in _NAT64 or ip in _V4COMPAT:+ forms.append(ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF))+ elif ip in _6TO4:+ forms.append(ipaddress.IPv4Address((int(ip) >> 80) & 0xFFFFFFFF))+ return forms+++def is_forbidden_ip(ip_str: str) -> bool:+ """True if the IP (or any embedded transition form) is not globally routable."""+ try:+ ip = ipaddress.ip_address(ip_str)+ except ValueError:+ return True+ return any(not form.is_global for form in _embedded_v4_forms(ip))+++def _resolve(host: str, port: int):+ try:+ return socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)+ except socket.gaierror:+ raise EgressBlocked()+++def assert_host_allowed(host: str, port: int = 0) -> None:+ """Resolve `host` and reject if ANY answer is non-global. Opaque on failure."""+ if ALLOW_INTERNAL:+ return+ if not host:+ raise EgressBlocked()+ low = host.lower()+ if low in _BLOCKED_HOSTNAMES or low.startswith("host.docker.internal"):+ raise EgressBlocked()+ for *_, sockaddr in _resolve(host, port):+ if is_forbidden_ip(sockaddr[0]):+ raise EgressBlocked()+++def resolve_and_pin(url: str) -> PinnedTarget:+ """Resolve `url` once, reject if any answer is non-global, and pin one IP.++ The returned PinnedTarget.ip is the address the caller must dial; resolving+ `host` again at connect time would reopen the rebinding hole.+ """+ parsed = urlparse(str(url))+ scheme = (parsed.scheme or "").lower()+ if scheme not in ("http", "https"):+ raise EgressBlocked()+ host = parsed.hostname+ if not host:+ raise EgressBlocked()+ port = parsed.port or (443 if scheme == "https" else 80)++ if ALLOW_INTERNAL:+ # Still resolve so we can pin, but skip the global check.+ answers = _resolve(host, port)+ return PinnedTarget(scheme, host, port, answers[0][4][0])++ low = host.lower()+ if low in _BLOCKED_HOSTNAMES or low.startswith("host.docker.internal"):+ raise EgressBlocked()++ answers = _resolve(host, port)+ pinned = None+ for *_, sockaddr in answers:+ if is_forbidden_ip(sockaddr[0]):+ # Reject the host outright if ANY of its records is internal.+ raise EgressBlocked()+ if pinned is None:+ pinned = sockaddr[0]+ if pinned is None:+ raise EgressBlocked()+ return PinnedTarget(scheme, host, port, pinned)+++def check_redirect(location: str) -> PinnedTarget:+ """Re-validate (and pin) a redirect Location. Same rule as the initial hop."""+ return resolve_and_pin(location)+++ALLOW_INSECURE_TLS = os.environ.get("CRAWL4AI_ALLOW_INSECURE_TLS", "false").lower() == "true"++# URL of the localhost pinning forward-proxy (egress_proxy.py), set at boot.+# When present, enforce_egress routes the browser through it so Chromium never+# resolves the target itself (closes DNS rebinding on the browser path).+_EGRESS_PROXY_URL: Optional[str] = None+++def set_egress_proxy(url: Optional[str]) -> None:+ global _EGRESS_PROXY_URL+ _EGRESS_PROXY_URL = url+++def get_egress_proxy() -> Optional[str]:+ return _EGRESS_PROXY_URL++# Chromium flags that would re-route or weaken egress; scrubbed server-side.+_DANGEROUS_BROWSER_ARGS = (+ "--proxy-server", "--proxy-pac-url", "--proxy-bypass-list",+ "--host-resolver-rules", "--ignore-certificate-errors",+ "--allow-insecure-localhost",+)+++def enforce_egress(browser_config) -> None:+ """Server-side egress hardening applied to the effective browser config.++ R2 already forbids untrusted bodies from setting proxy/extra_args, so this+ is defense in depth that also covers server/SDK-built configs:+ - TLS verification ON (ignore_https_errors=False) unless the operator+ opts into CRAWL4AI_ALLOW_INSECURE_TLS;+ - no caller proxy (the key/SSRF redirect vector);+ - strip any proxy/TLS-weakening Chromium launch flags.+ """+ if browser_config is None:+ return+ if not ALLOW_INSECURE_TLS and hasattr(browser_config, "ignore_https_errors"):+ browser_config.ignore_https_errors = False+ # Drop any caller proxy, then route the browser through the pinning proxy so+ # Chromium never resolves the target host itself (DNS-rebinding control).+ for attr in ("proxy", "proxy_config"):+ if getattr(browser_config, attr, None) is not None:+ setattr(browser_config, attr, None)+ if _EGRESS_PROXY_URL and hasattr(browser_config, "proxy_config"):+ try:+ from crawl4ai import ProxyConfig+ browser_config.proxy_config = ProxyConfig(server=_EGRESS_PROXY_URL)+ except Exception:+ pass+ args = getattr(browser_config, "extra_args", None)+ if args:+ browser_config.extra_args = [+ a for a in args+ if not any(str(a).startswith(bad) for bad in _DANGEROUS_BROWSER_ARGS)+ ]diff --git a/deploy/docker/egress_proxy.py b/deploy/docker/egress_proxy.pynew file mode 100644index 00000000..4cdb56bd--- /dev/null+++ b/deploy/docker/egress_proxy.py@@ -0,0 +1,212 @@+"""+egress_proxy.py - localhost pinning forward-proxy for the browser.++context.route() sees URLs, not IPs, so it cannot stop DNS rebinding: Chromium+resolves the target host itself at connect time, and an attacker can answer+"public" to our up-front validation and "169.254.169.254" to the browser.++This proxy is the real control. Chromium is pointed at it (proxy_config), so it+never resolves the target itself - it asks us to CONNECT host:port. We run the+single egress rule (egress_broker.resolve_and_pin: resolve once, reject any+non-global IP, pin one IP), dial the PINNED IP ourselves, and splice raw bytes.+TLS stays end-to-end (we tunnel ciphertext; Chromium verifies the cert/SNI+against the real host - no MITM).++Bound to 127.0.0.1 on an ephemeral port; started at server boot.+"""++from __future__ import annotations++import asyncio+import logging+from urllib.parse import urlsplit++from egress_broker import EgressBlocked, resolve_and_pin++logger = logging.getLogger("crawl4ai.egress")++_CONNECT_OK = b"HTTP/1.1 200 Connection established\r\n\r\n"+_BLOCKED = b"HTTP/1.1 403 Forbidden\r\nContent-Length: 11\r\n\r\nURL blocked"+_BAD = b"HTTP/1.1 400 Bad Request\r\nContent-Length: 11\r\n\r\nBad Request"+_MAX_HEADER_BYTES = 64 * 1024+++class PinningProxy:+ """Async HTTP forward-proxy that connects only to pinned, global IPs."""++ def __init__(self, host: str = "127.0.0.1", port: int = 0):+ self._host = host+ self._port = port+ self._server: asyncio.AbstractServer | None = None+ self.bound_host: str | None = None+ self.bound_port: int | None = None++ @property+ def url(self) -> str | None:+ if self.bound_port is None:+ return None+ return f"http://{self.bound_host}:{self.bound_port}"++ async def start(self) -> str:+ self._server = await asyncio.start_server(self._handle, self._host, self._port)+ sock = self._server.sockets[0]+ self.bound_host, self.bound_port = sock.getsockname()[:2]+ logger.info("egress pinning proxy listening on %s", self.url)+ return self.url++ async def stop(self) -> None:+ if self._server is not None:+ self._server.close()+ try:+ await self._server.wait_closed()+ except Exception:+ pass++ # ─────────────────────────── connection handling ───────────────────────────+ async def _handle(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):+ try:+ request_line = await asyncio.wait_for(reader.readline(), timeout=30)+ if not request_line:+ return+ parts = request_line.split()+ if len(parts) < 3:+ await self._reply(writer, _BAD)+ return+ method = parts[0].decode("latin-1", "replace").upper()+ target = parts[1].decode("latin-1", "replace")++ if method == "CONNECT":+ await self._handle_connect(target, reader, writer)+ else:+ await self._handle_absolute(method, target, request_line, reader, writer)+ except asyncio.TimeoutError:+ await self._reply(writer, _BAD)+ except Exception as e:+ logger.debug("proxy connection error: %s", e)+ await self._safe_close(writer)++ async def _handle_connect(self, target, client_reader, client_writer):+ # target is "host:port"+ host, _, port_s = target.rpartition(":")+ if not host or not port_s.isdigit():+ await self._reply(client_writer, _BAD)+ return+ try:+ pin = resolve_and_pin(f"https://{host}:{port_s}")+ except EgressBlocked:+ await self._reply(client_writer, _BLOCKED)+ return++ # Drain the rest of the client's CONNECT headers.+ await self._drain_headers(client_reader)++ try:+ up_reader, up_writer = await asyncio.wait_for(+ asyncio.open_connection(pin.ip, int(port_s)), timeout=30+ )+ except Exception:+ await self._reply(client_writer, _BLOCKED)+ return++ client_writer.write(_CONNECT_OK)+ await client_writer.drain()+ await self._splice(client_reader, client_writer, up_reader, up_writer)++ async def _handle_absolute(self, method, target, request_line, client_reader, client_writer):+ # Plain HTTP proxying: target is an absolute URI "http://host/path".+ sp = urlsplit(target)+ if sp.scheme != "http" or not sp.hostname:+ await self._reply(client_writer, _BAD)+ return+ port = sp.port or 80+ try:+ pin = resolve_and_pin(f"http://{sp.hostname}:{port}")+ except EgressBlocked:+ await self._reply(client_writer, _BLOCKED)+ return++ headers = await self._read_headers(client_reader)+ path = sp.path or "/"+ if sp.query:+ path += "?" + sp.query+ try:+ up_reader, up_writer = await asyncio.wait_for(+ asyncio.open_connection(pin.ip, port), timeout=30+ )+ except Exception:+ await self._reply(client_writer, _BLOCKED)+ return+ # Re-issue in origin form with Host preserved.+ out = f"{method} {path} HTTP/1.1\r\n".encode("latin-1")+ out += b"Host: " + sp.hostname.encode("latin-1")+ if sp.port:+ out += f":{sp.port}".encode("latin-1")+ out += b"\r\n" + headers + b"\r\n"+ up_writer.write(out)+ await up_writer.drain()+ await self._splice(client_reader, client_writer, up_reader, up_writer)++ # ─────────────────────────── helpers ───────────────────────────+ async def _drain_headers(self, reader):+ read = 0+ while True:+ line = await asyncio.wait_for(reader.readline(), timeout=30)+ read += len(line)+ if line in (b"\r\n", b"\n", b""):+ return+ if read > _MAX_HEADER_BYTES:+ return++ async def _read_headers(self, reader) -> bytes:+ buf = b""+ while True:+ line = await asyncio.wait_for(reader.readline(), timeout=30)+ if line in (b"\r\n", b"\n", b""):+ break+ buf += line+ if len(buf) > _MAX_HEADER_BYTES:+ break+ # strip any proxy-only / connection headers+ kept = []+ for ln in buf.split(b"\r\n"):+ name = ln.split(b":", 1)[0].strip().lower()+ if name in (b"proxy-connection", b"proxy-authorization", b"host"):+ continue+ if ln:+ kept.append(ln)+ return (b"\r\n".join(kept) + b"\r\n") if kept else b""++ async def _splice(self, c_reader, c_writer, u_reader, u_writer):+ async def pipe(src, dst):+ try:+ while True:+ data = await src.read(65536)+ if not data:+ break+ dst.write(data)+ await dst.drain()+ except Exception:+ pass+ finally:+ await self._safe_close(dst)++ await asyncio.gather(+ pipe(c_reader, u_writer),+ pipe(u_reader, c_writer),+ )++ async def _reply(self, writer, payload: bytes):+ try:+ writer.write(payload)+ await writer.drain()+ except Exception:+ pass+ await self._safe_close(writer)++ @staticmethod+ async def _safe_close(writer):+ try:+ if not writer.is_closing():+ writer.close()+ except Exception:+ passdiff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.shnew file mode 100644index 00000000..1b403c72--- /dev/null+++ b/deploy/docker/entrypoint.sh@@ -0,0 +1,37 @@+#!/usr/bin/env bash+# entrypoint.sh - resolve the socket-level egress/auth posture before supervisord.+#+# This is the authoritative socket-level guard (gunicorn binds the socket, not+# Python). It must agree with the in-process _resolve_auth() check in server.py.+set -euo pipefail++# --- Redis password: prefer a mounted secret, else an existing env var. ------+if [[ -z "${REDIS_PASSWORD:-}" && -f /run/secrets/redis_password ]]; then+ REDIS_PASSWORD="$(cat /run/secrets/redis_password)"+fi+if [[ -z "${REDIS_PASSWORD:-}" ]]; then+ # Generate an ephemeral in-container password so redis is never open even+ # if the operator forgot to mount one. (Loopback + requirepass.)+ REDIS_PASSWORD="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"+ echo "entrypoint: no REDIS_PASSWORD provided; generated an ephemeral one." >&2+fi+export REDIS_PASSWORD++# --- API token: prefer a mounted secret, else an existing env var. -----------+if [[ -z "${CRAWL4AI_API_TOKEN:-}" && -f /run/secrets/api_token ]]; then+ export CRAWL4AI_API_TOKEN="$(cat /run/secrets/api_token)"+fi++# --- Bind resolution: loopback unless a credential is present. ---------------+PORT="${CRAWL4AI_PORT:-11235}"+if [[ -n "${CRAWL4AI_API_TOKEN:-}" || "${CRAWL4AI_JWT_ENABLED:-false}" == "true" ]]; then+ # A credential is configured -> the operator may expose all interfaces.+ GUNICORN_BIND="${GUNICORN_BIND:-[::]:${PORT}}"+else+ # No credential -> refuse to expose; serve loopback only.+ GUNICORN_BIND="127.0.0.1:${PORT}"+ echo "entrypoint: no CRAWL4AI_API_TOKEN set; binding loopback only (${GUNICORN_BIND})." >&2+fi+export GUNICORN_BIND++exec supervisord -c supervisord.confdiff --git a/deploy/docker/governor.py b/deploy/docker/governor.pynew file mode 100644index 00000000..73534e99--- /dev/null+++ b/deploy/docker/governor.py@@ -0,0 +1,111 @@+"""+governor.py - server-enforced resource governance (R5).++The deep-crawl DoS via a client-supplied unbounded max_pages is already closed+upstream: R2 forbids `deep_crawl_strategy` on an untrusted request body, and the+`urls` list is capped at 100 by the request schema. This module adds the two+remaining verifiable chokepoints:++ * a request body-size limit (ASGI middleware) so a giant body / inline `raw:`+ HTML cannot be buffered and processed in-process -> 413;+ * clamp_deep_crawl(): defense in depth for any *trusted* / server-built config+ that still carries a deep_crawl strategy with an unbounded page/depth count.++Heavier governance (bounded work queue replacing BackgroundTasks, per-principal+Redis quotas, wall-clock deadlines, stream decoupling) is left for the+integration-tested pass; gunicorn --limit-request-* covers the transport layer.+"""++from __future__ import annotations++import json+import math++DEFAULT_MAX_BODY_BYTES = 10 * 1024 * 1024 # 10 MiB+DEFAULT_MAX_PAGES = 100+DEFAULT_MAX_DEPTH = 5+++class BodySizeLimitMiddleware:+ """Reject HTTP requests whose declared Content-Length exceeds the limit.++ (Chunked/unknown-length bodies are additionally bounded at the transport by+ gunicorn --limit-request-* in the hardened deployment.)+ """++ def __init__(self, app, max_bytes: int = DEFAULT_MAX_BODY_BYTES):+ self.app = app+ self.max_bytes = max_bytes++ async def __call__(self, scope, receive, send):+ if scope["type"] == "http":+ for name, value in scope.get("headers", []):+ if name == b"content-length":+ try:+ if int(value) > self.max_bytes:+ await self._reject(send)+ return+ except ValueError:+ pass+ break+ await self.app(scope, receive, send)++ async def _reject(self, send):+ body = json.dumps({"detail": "Request body too large"}).encode()+ await send({+ "type": "http.response.start",+ "status": 413,+ "headers": [+ (b"content-type", b"application/json"),+ (b"content-length", str(len(body)).encode()),+ ],+ })+ await send({"type": "http.response.body", "body": body})+++def clamp_deep_crawl(crawler_config, *, max_pages: int = DEFAULT_MAX_PAGES,+ max_depth: int = DEFAULT_MAX_DEPTH) -> None:+ """Clamp an attached deep-crawl strategy's page/depth budget in place.++ Defense in depth: untrusted bodies cannot set deep_crawl_strategy at all+ (R2), but a server/base config might, and the library default for max_pages+ is infinity.+ """+ dc = getattr(crawler_config, "deep_crawl_strategy", None)+ if dc is None:+ return+ mp = getattr(dc, "max_pages", None)+ if mp is None or (isinstance(mp, float) and math.isinf(mp)) or mp > max_pages:+ try:+ dc.max_pages = max_pages+ except Exception:+ pass+ md = getattr(dc, "max_depth", None)+ if md is None or md > max_depth:+ try:+ dc.max_depth = max_depth+ except Exception:+ pass+++def max_body_bytes_from_config(config: dict) -> int:+ return int((config.get("limits", {}) or {}).get("max_body_bytes", DEFAULT_MAX_BODY_BYTES))+++def _limits(config: dict) -> dict:+ return config.get("limits", {}) or {}+++def wall_clock_seconds(config: dict) -> float:+ """Per-crawl wall-clock deadline in seconds; 0 (default) => no deadline."""+ return float(_limits(config).get("wall_clock_s", 0) or 0)+++def job_queue_caps(config: dict) -> dict:+ """Bounded-job-queue settings; 0 => unbounded/unlimited (current behavior)."""+ q = _limits(config).get("queue", {}) or {}+ return {+ "maxsize": int(q.get("maxsize", 1000) or 0),+ "workers": int(q.get("workers", 4) or 1),+ "per_principal": int(q.get("per_principal", 0) or 0),+ }diff --git a/deploy/docker/hook_manager.py b/deploy/docker/hook_manager.pydeleted file mode 100644index 7c93e278..00000000--- a/deploy/docker/hook_manager.py+++ /dev/null@@ -1,548 +0,0 @@-"""-Hook Manager for User-Provided Hook Functions-Handles validation, compilation, and safe execution of user-provided hook code-"""--import ast-import asyncio-import traceback-from typing import Dict, Callable, Optional, Tuple, List, Any-import logging--logger = logging.getLogger(__name__)---class UserHookManager:- """Manages user-provided hook functions with error isolation"""-- # Expected signatures for each hook point- HOOK_SIGNATURES = {- "on_browser_created": ["browser"],- "on_page_context_created": ["page", "context"],- "before_goto": ["page", "context", "url"],- "after_goto": ["page", "context", "url", "response"],- "on_user_agent_updated": ["page", "context", "user_agent"],- "on_execution_started": ["page", "context"],- "before_retrieve_html": ["page", "context"],- "before_return_html": ["page", "context", "html"]- }-- # Default timeout for hook execution (in seconds)- DEFAULT_TIMEOUT = 30-- def __init__(self, timeout: int = DEFAULT_TIMEOUT):- self.timeout = timeout- self.errors: List[Dict[str, Any]] = []- self.compiled_hooks: Dict[str, Callable] = {}- self.execution_log: List[Dict[str, Any]] = []-- def validate_hook_structure(self, hook_code: str, hook_point: str) -> Tuple[bool, str]:- """- Validate the structure of user-provided hook code-- Args:- hook_code: The Python code string containing the hook function- hook_point: The hook point name (e.g., 'on_page_context_created')-- Returns:- Tuple of (is_valid, error_message)- """- try:- # Parse the code- tree = ast.parse(hook_code)-- # Check if it's empty- if not tree.body:- return False, "Hook code is empty"-- # Find the function definition- func_def = None- for node in tree.body:- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):- func_def = node- break-- if not func_def:- return False, "Hook must contain a function definition (def or async def)"-- # Check if it's async (all hooks should be async)- if not isinstance(func_def, ast.AsyncFunctionDef):- return False, f"Hook function must be async (use 'async def' instead of 'def')"-- # Get function name for better error messages- func_name = func_def.name-- # Validate parameters- expected_params = self.HOOK_SIGNATURES.get(hook_point, [])- if not expected_params:- return False, f"Unknown hook point: {hook_point}"-- func_params = [arg.arg for arg in func_def.args.args]-- # Check if it has **kwargs for flexibility- has_kwargs = func_def.args.kwarg is not None-- # Must have at least the expected parameters- missing_params = []- for expected in expected_params:- if expected not in func_params:- missing_params.append(expected)-- if missing_params and not has_kwargs:- return False, f"Hook function '{func_name}' must accept parameters: {', '.join(expected_params)} (missing: {', '.join(missing_params)})"-- # Check if it returns something (should return page or browser)- has_return = any(isinstance(node, ast.Return) for node in ast.walk(func_def))- if not has_return:- # Warning, not error - we'll handle this- logger.warning(f"Hook function '{func_name}' should return the {expected_params[0]} object")-- return True, "Valid"-- except SyntaxError as e:- return False, f"Syntax error at line {e.lineno}: {str(e)}"- except Exception as e:- return False, f"Failed to parse hook code: {str(e)}"-- def compile_hook(self, hook_code: str, hook_point: str) -> Optional[Callable]:- """- Compile user-provided hook code into a callable function-- Args:- hook_code: The Python code string- hook_point: The hook point name-- Returns:- Compiled function or None if compilation failed- """- try:- # Create a safe namespace for the hook- # SECURITY: No __import__ to prevent arbitrary module imports (RCE risk)- import builtins- safe_builtins = {}-- # Add safe built-in functions (no __import__ for security)- # SECURITY: Minimal builtins only. Removed:- # - getattr/setattr: sandbox escape via attribute access- # - type: enables __subclasses__() MRO chain attacks- # - __build_class__: enables malicious __init_subclass__- # - hasattr: information disclosure- allowed_builtins = [- 'print', 'len', 'str', 'int', 'float', 'bool',- 'list', 'dict', 'set', 'tuple', 'range', 'enumerate',- 'zip', 'map', 'filter', 'any', 'all', 'sum', 'min', 'max',- 'sorted', 'reversed', 'abs', 'round', 'isinstance',- 'callable', 'iter', 'next',- ]-- for name in allowed_builtins:- if hasattr(builtins, name):- safe_builtins[name] = getattr(builtins, name)-- namespace = {- '__name__': f'user_hook_{hook_point}',- '__builtins__': safe_builtins- }-- # Inject commonly needed modules into hook namespace.- # NOTE: We import here (in hook_manager's own scope) and inject- # the objects directly. Using exec("import X", namespace) does NOT- # work because namespace's __builtins__ lacks __import__.- import asyncio as _asyncio_mod- import json as _json_mod- import re as _re_mod- from typing import Dict as _Dict, List as _List, Optional as _Optional-- # SECURITY: Create safe module proxies that strip __builtins__- # and dangerous sub-modules. Without this, hook code can reach- # real __import__ via e.g. asyncio.__builtins__['__import__'].- import types-- def _safe_module(mod, exclude_attrs=None):- """Create a proxy module without __builtins__ or dangerous attrs."""- proxy = types.ModuleType(mod.__name__)- skip = {"__builtins__", "__loader__", "__spec__"}- if exclude_attrs:- skip.update(exclude_attrs)- for attr in dir(mod):- if attr in skip:- continue- try:- setattr(proxy, attr, getattr(mod, attr))- except (AttributeError, TypeError):- pass- return proxy-- namespace["asyncio"] = _safe_module(_asyncio_mod, {- "subprocess", "create_subprocess_exec", "create_subprocess_shell"- })- namespace["json"] = _safe_module(_json_mod)- namespace["re"] = _safe_module(_re_mod)- namespace["Dict"] = _Dict- namespace["List"] = _List- namespace["Optional"] = _Optional-- # Execute the code to define the function- exec(hook_code, namespace)-- # Find the async function in the namespace- for name, obj in namespace.items():- if callable(obj) and not name.startswith('_') and asyncio.iscoroutinefunction(obj):- return obj-- # If no async function found, look for any function- for name, obj in namespace.items():- if callable(obj) and not name.startswith('_'):- logger.warning(f"Found non-async function '{name}' - wrapping it")- # Wrap sync function in async- async def async_wrapper(*args, **kwargs):- return obj(*args, **kwargs)- return async_wrapper-- raise ValueError("No callable function found in hook code")-- except Exception as e:- error = {- 'hook_point': hook_point,- 'error': f"Failed to compile hook: {str(e)}",- 'type': 'compilation_error',- 'traceback': traceback.format_exc()- }- self.errors.append(error)- logger.error(f"Hook compilation failed for {hook_point}: {str(e)}")- return None-- async def execute_hook_safely(- self,- hook_func: Callable,- hook_point: str,- *args,- **kwargs- ) -> Tuple[Any, Optional[Dict]]:- """- Execute a user hook with error isolation and timeout-- Args:- hook_func: The compiled hook function- hook_point: The hook point name- *args, **kwargs: Arguments to pass to the hook-- Returns:- Tuple of (result, error_dict)- """- start_time = asyncio.get_event_loop().time()-- try:- # Add timeout to prevent infinite loops- result = await asyncio.wait_for(- hook_func(*args, **kwargs),- timeout=self.timeout- )-- # Log successful execution- execution_time = asyncio.get_event_loop().time() - start_time- self.execution_log.append({- 'hook_point': hook_point,- 'status': 'success',- 'execution_time': execution_time,- 'timestamp': start_time- })-- return result, None-- except asyncio.TimeoutError:- error = {- 'hook_point': hook_point,- 'error': f'Hook execution timed out ({self.timeout}s limit)',- 'type': 'timeout',- 'execution_time': self.timeout- }- self.errors.append(error)- self.execution_log.append({- 'hook_point': hook_point,- 'status': 'timeout',- 'error': error['error'],- 'execution_time': self.timeout,- 'timestamp': start_time- })- # Return the first argument (usually page/browser) to continue- return args[0] if args else None, error-- except Exception as e:- execution_time = asyncio.get_event_loop().time() - start_time- error = {- 'hook_point': hook_point,- 'error': str(e),- 'type': type(e).__name__,- 'traceback': traceback.format_exc(),- 'execution_time': execution_time- }- self.errors.append(error)- self.execution_log.append({- 'hook_point': hook_point,- 'status': 'failed',- 'error': str(e),- 'error_type': type(e).__name__,- 'execution_time': execution_time,- 'timestamp': start_time- })- # Return the first argument (usually page/browser) to continue- return args[0] if args else None, error-- def get_summary(self) -> Dict[str, Any]:- """Get a summary of hook execution"""- total_hooks = len(self.execution_log)- successful = sum(1 for log in self.execution_log if log['status'] == 'success')- failed = sum(1 for log in self.execution_log if log['status'] == 'failed')- timed_out = sum(1 for log in self.execution_log if log['status'] == 'timeout')-- return {- 'total_executions': total_hooks,- 'successful': successful,- 'failed': failed,- 'timed_out': timed_out,- 'success_rate': (successful / total_hooks * 100) if total_hooks > 0 else 0,- 'total_errors': len(self.errors)- }---class IsolatedHookWrapper:- """Wraps user hooks with error isolation and reporting"""-- def __init__(self, hook_manager: UserHookManager):- self.hook_manager = hook_manager-- def create_hook_wrapper(self, user_hook: Callable, hook_point: str) -> Callable:- """- Create a wrapper that isolates hook errors from main process-- Args:- user_hook: The compiled user hook function- hook_point: The hook point name-- Returns:- Wrapped async function that handles errors gracefully- """-- async def wrapped_hook(*args, **kwargs):- """Wrapped hook with error isolation"""- # Get the main return object (page/browser)- # This ensures we always have something to return- return_obj = None- if args:- return_obj = args[0]- elif 'page' in kwargs:- return_obj = kwargs['page']- elif 'browser' in kwargs:- return_obj = kwargs['browser']-- try:- # Execute user hook with safety- result, error = await self.hook_manager.execute_hook_safely(- user_hook,- hook_point,- *args,- **kwargs- )-- if error:- # Hook failed but we continue with original object- logger.warning(f"User hook failed at {hook_point}: {error['error']}")- return return_obj-- # Hook succeeded - return its result or the original object- if result is None:- logger.debug(f"Hook at {hook_point} returned None, using original object")- return return_obj-- return result-- except Exception as e:- # This should rarely happen due to execute_hook_safely- logger.error(f"Unexpected error in hook wrapper for {hook_point}: {e}")- return return_obj-- # Set function name for debugging- wrapped_hook.__name__ = f"wrapped_{hook_point}"- return wrapped_hook---async def process_user_hooks(- hooks_input: Dict[str, str],- timeout: int = 30-) -> Tuple[Dict[str, Callable], List[Dict], UserHookManager]:- """- Process and compile user-provided hook functions-- Args:- hooks_input: Dictionary mapping hook points to code strings- timeout: Timeout for each hook execution-- Returns:- Tuple of (compiled_hooks, validation_errors, hook_manager)- """-- hook_manager = UserHookManager(timeout=timeout)- wrapper = IsolatedHookWrapper(hook_manager)- compiled_hooks = {}- validation_errors = []-- for hook_point, hook_code in hooks_input.items():- # Skip empty hooks- if not hook_code or not hook_code.strip():- continue-- # Validate hook point- if hook_point not in UserHookManager.HOOK_SIGNATURES:- validation_errors.append({- 'hook_point': hook_point,- 'error': f'Unknown hook point. Valid points: {", ".join(UserHookManager.HOOK_SIGNATURES.keys())}',- 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code- })- continue-- # Validate structure- is_valid, message = hook_manager.validate_hook_structure(hook_code, hook_point)- if not is_valid:- validation_errors.append({- 'hook_point': hook_point,- 'error': message,- 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code- })- continue-- # Compile the hook- hook_func = hook_manager.compile_hook(hook_code, hook_point)- if hook_func:- # Wrap with error isolation- wrapped_hook = wrapper.create_hook_wrapper(hook_func, hook_point)- compiled_hooks[hook_point] = wrapped_hook- logger.info(f"Successfully compiled hook for {hook_point}")- else:- validation_errors.append({- 'hook_point': hook_point,- 'error': 'Failed to compile hook function - check syntax and structure',- 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code- })-- return compiled_hooks, validation_errors, hook_manager---async def process_user_hooks_with_manager(- hooks_input: Dict[str, str],- hook_manager: UserHookManager-) -> Tuple[Dict[str, Callable], List[Dict]]:- """- Process and compile user-provided hook functions with existing manager-- Args:- hooks_input: Dictionary mapping hook points to code strings- hook_manager: Existing UserHookManager instance-- Returns:- Tuple of (compiled_hooks, validation_errors)- """-- wrapper = IsolatedHookWrapper(hook_manager)- compiled_hooks = {}- validation_errors = []-- for hook_point, hook_code in hooks_input.items():- # Skip empty hooks- if not hook_code or not hook_code.strip():- continue-- # Validate hook point- if hook_point not in UserHookManager.HOOK_SIGNATURES:- validation_errors.append({- 'hook_point': hook_point,- 'error': f'Unknown hook point. Valid points: {", ".join(UserHookManager.HOOK_SIGNATURES.keys())}',- 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code- })- continue-- # Validate structure- is_valid, message = hook_manager.validate_hook_structure(hook_code, hook_point)- if not is_valid:- validation_errors.append({- 'hook_point': hook_point,- 'error': message,- 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code- })- continue-- # Compile the hook- hook_func = hook_manager.compile_hook(hook_code, hook_point)- if hook_func:- # Wrap with error isolation- wrapped_hook = wrapper.create_hook_wrapper(hook_func, hook_point)- compiled_hooks[hook_point] = wrapped_hook- logger.info(f"Successfully compiled hook for {hook_point}")- else:- validation_errors.append({- 'hook_point': hook_point,- 'error': 'Failed to compile hook function - check syntax and structure',- 'code_preview': hook_code[:100] + '...' if len(hook_code) > 100 else hook_code- })-- return compiled_hooks, validation_errors---async def attach_user_hooks_to_crawler(- crawler, # AsyncWebCrawler instance- user_hooks: Dict[str, str],- timeout: int = 30,- hook_manager: Optional[UserHookManager] = None-) -> Tuple[Dict[str, Any], UserHookManager]:- """- Attach user-provided hooks to crawler with full error reporting-- Args:- crawler: AsyncWebCrawler instance- user_hooks: Dictionary mapping hook points to code strings- timeout: Timeout for each hook execution- hook_manager: Optional existing UserHookManager instance-- Returns:- Tuple of (status_dict, hook_manager)- """-- # Use provided hook_manager or create a new one- if hook_manager is None:- hook_manager = UserHookManager(timeout=timeout)-- # Process hooks with the hook_manager- compiled_hooks, validation_errors = await process_user_hooks_with_manager(- user_hooks, hook_manager- )-- # Log validation errors- if validation_errors:- logger.warning(f"Hook validation errors: {validation_errors}")-- # Attach successfully compiled hooks- attached_hooks = []- for hook_point, wrapped_hook in compiled_hooks.items():- try:- crawler.crawler_strategy.set_hook(hook_point, wrapped_hook)- attached_hooks.append(hook_point)- logger.info(f"Attached hook to {hook_point}")- except Exception as e:- logger.error(f"Failed to attach hook to {hook_point}: {e}")- validation_errors.append({- 'hook_point': hook_point,- 'error': f'Failed to attach hook: {str(e)}'- })-- status = 'success' if not validation_errors else ('partial' if attached_hooks else 'failed')-- status_dict = {- 'status': status,- 'attached_hooks': attached_hooks,- 'validation_errors': validation_errors,- 'total_hooks_provided': len(user_hooks),- 'successfully_attached': len(attached_hooks),- 'failed_validation': len(validation_errors)- }-- return status_dict, hook_manager\ No newline at end of filediff --git a/deploy/docker/hook_registry.py b/deploy/docker/hook_registry.pynew file mode 100644index 00000000..c20e256d--- /dev/null+++ b/deploy/docker/hook_registry.py@@ -0,0 +1,244 @@+"""+Declarative hook registry - the safe replacement for the exec-based hook system.++The old hook_manager.py compiled and exec()'d user-supplied Python at crawl hook+points. Its sandbox was unsound (escapable via __subclasses__ MRO walks, injected+module __globals__, frame inspection), giving unauthenticated RCE when hooks were+enabled. There is no safe way to run attacker Python in-process.++Instead, a request may only choose from a fixed set of declarative ACTIONS whose+parameters are schema-validated scalars. Each action maps to a server-authored+async function that calls exactly one specific Playwright API - no user string+ever reaches an interpreter. This covers the documented hook use cases (block+assets, inject auth cookies/headers, scroll for lazy content, wait).++Power users who genuinely need arbitrary hook code use a self-hosted in-process+build where crawler_strategy.set_hook(...) remains available and trusted.+"""++from __future__ import annotations++import re+from typing import Any, Callable, Dict, List++from pydantic import BaseModel, Field, field_validator+++class HookValidationError(ValueError):+ """A declarative hook spec was invalid. The Docker layer maps this to 400."""+++_HEADER_NAME_RE = re.compile(r"^[A-Za-z0-9-]{1,64}$")+_ALLOWED_RESOURCE_TYPES = {"image", "stylesheet", "font", "media"}+_MAX_SCROLL_STEPS = 50+_MAX_SCROLL_DELAY_MS = 5000+_MAX_WAIT_MS = 60_000+_MAX_COOKIES = 20+_MAX_HEADERS = 20+++# ───────────────────────── per-action parameter schemas ─────────────────────────+class BlockResourcesParams(BaseModel):+ resource_types: List[str] = Field(..., min_length=1)++ @field_validator("resource_types")+ @classmethod+ def _check(cls, v):+ bad = sorted(set(v) - _ALLOWED_RESOURCE_TYPES)+ if bad:+ raise ValueError(f"unsupported resource_types {bad}; allowed: {sorted(_ALLOWED_RESOURCE_TYPES)}")+ return v+++class _Cookie(BaseModel):+ name: str = Field(..., min_length=1, max_length=256)+ value: str = Field(..., max_length=4096)+ domain: str = Field(..., min_length=1, max_length=253)+ path: str = "/"+ secure: bool = True+ httpOnly: bool = False+++class AddCookiesParams(BaseModel):+ cookies: List[_Cookie] = Field(..., min_length=1, max_length=_MAX_COOKIES)+++class SetHeadersParams(BaseModel):+ headers: Dict[str, str]++ @field_validator("headers")+ @classmethod+ def _check(cls, v):+ if len(v) > _MAX_HEADERS:+ raise ValueError(f"too many headers (max {_MAX_HEADERS})")+ for name, value in v.items():+ if not _HEADER_NAME_RE.match(name):+ raise ValueError(f"invalid header name {name!r}")+ if any(c in value for c in "\r\n\x00"):+ raise ValueError(f"control characters in value for header {name!r}")+ return v+++class ScrollToBottomParams(BaseModel):+ max_steps: int = Field(10, ge=1, le=_MAX_SCROLL_STEPS)+ delay_ms: int = Field(500, ge=0, le=_MAX_SCROLL_DELAY_MS)+++class WaitForTimeoutParams(BaseModel):+ timeout_ms: int = Field(..., ge=0, le=_MAX_WAIT_MS)+++# ───────────────────────── server-authored hook factories ─────────────────────────+def _factory_block_resources(p: BlockResourcesParams):+ types = set(p.resource_types)++ async def hook(page, **kwargs):+ context = kwargs.get("context")++ async def _route(route):+ try:+ if route.request.resource_type in types:+ await route.abort()+ else:+ await route.continue_()+ except Exception:+ # never let a routing decision crash the crawl+ await route.continue_()++ if context is not None:+ await context.route("**/*", _route)+ return page++ return hook+++def _factory_add_cookies(p: AddCookiesParams):+ cookies = [c.model_dump() for c in p.cookies]++ async def hook(page, **kwargs):+ context = kwargs.get("context")+ if context is not None:+ await context.add_cookies(cookies)+ return page++ return hook+++def _factory_set_headers(p: SetHeadersParams):+ headers = dict(p.headers)++ async def hook(page, **kwargs):+ await page.set_extra_http_headers(headers)+ return page++ return hook+++def _factory_scroll_to_bottom(p: ScrollToBottomParams):+ max_steps, delay_ms = p.max_steps, p.delay_ms++ async def hook(page, **kwargs):+ for _ in range(max_steps):+ await page.evaluate("window.scrollTo(0, document.body.scrollHeight)")+ if delay_ms:+ await page.wait_for_timeout(delay_ms)+ return page++ return hook+++def _factory_wait_for_timeout(p: WaitForTimeoutParams):+ timeout_ms = p.timeout_ms++ async def hook(page, **kwargs):+ await page.wait_for_timeout(timeout_ms)+ return page++ return hook+++# action name -> (hook_point, params model, factory, human description)+HOOK_REGISTRY: Dict[str, dict] = {+ "block_resources": {+ "hook_point": "on_page_context_created",+ "params_model": BlockResourcesParams,+ "factory": _factory_block_resources,+ "description": "Abort matching resource types (image/stylesheet/font/media).",+ },+ "add_cookies": {+ "hook_point": "on_page_context_created",+ "params_model": AddCookiesParams,+ "factory": _factory_add_cookies,+ "description": "Add cookies to the browser context before navigation (auth).",+ },+ "set_headers": {+ "hook_point": "before_goto",+ "params_model": SetHeadersParams,+ "factory": _factory_set_headers,+ "description": "Set extra HTTP request headers before navigating.",+ },+ "scroll_to_bottom": {+ "hook_point": "before_retrieve_html",+ "params_model": ScrollToBottomParams,+ "factory": _factory_scroll_to_bottom,+ "description": "Scroll to the page bottom in bounded steps (lazy-load).",+ },+ "wait_for_timeout": {+ "hook_point": "before_retrieve_html",+ "params_model": WaitForTimeoutParams,+ "factory": _factory_wait_for_timeout,+ "description": "Wait a bounded number of milliseconds before retrieving HTML.",+ },+}+++def build_declarative_hooks(specs: List[Any]) -> Dict[str, Callable]:+ """Validate declarative hook specs and return {hook_point: composed async hook}.++ Each spec is an object/dict with `action` and `params`. Multiple specs that+ target the same hook point are composed and run in order. Raises+ HookValidationError on an unknown action or invalid params.+ """+ if not specs:+ return {}+ if len(specs) > 10:+ raise HookValidationError("too many hooks (max 10)")++ grouped: Dict[str, List[Callable]] = {}+ for spec in specs:+ action = spec.get("action") if isinstance(spec, dict) else getattr(spec, "action", None)+ raw_params = (spec.get("params", {}) if isinstance(spec, dict) else getattr(spec, "params", {})) or {}+ entry = HOOK_REGISTRY.get(action)+ if entry is None:+ raise HookValidationError(+ f"unknown hook action {action!r}; allowed: {sorted(HOOK_REGISTRY)}"+ )+ try:+ params = entry["params_model"](**raw_params)+ except Exception as e:+ raise HookValidationError(f"invalid params for hook '{action}': {e}")+ sub_hook = entry["factory"](params)+ grouped.setdefault(entry["hook_point"], []).append(sub_hook)++ hooks: Dict[str, Callable] = {}+ for hook_point, sub_hooks in grouped.items():+ def _compose(sub_hooks):+ async def composed(page, **kwargs):+ for fn in sub_hooks:+ await fn(page, **kwargs)+ return page+ return composed+ hooks[hook_point] = _compose(sub_hooks)+ return hooks+++def describe_registry() -> dict:+ """Enumerate the available declarative actions for /hooks/info."""+ return {+ action: {+ "hook_point": entry["hook_point"],+ "description": entry["description"],+ "params_schema": entry["params_model"].model_json_schema(),+ }+ for action, entry in HOOK_REGISTRY.items()+ }diff --git a/deploy/docker/job.py b/deploy/docker/job.pyindex 51f49a59..5ad1a123 100644--- a/deploy/docker/job.py+++ b/deploy/docker/job.py@@ -12,6 +12,7 @@ from api import (handle_crawl_job,handle_task_status,)+from auth import get_principalfrom schemas import WebhookConfig# ------------- dependency placeholders -------------@@ -23,6 +24,19 @@ _token_dep: Callable = lambda: None # dummy until injectedrouter = APIRouter()+def _principal_dep(request: Request) -> Optional[Dict]:+ """The principal the AuthGateMiddleware already validated for this request."""+ return get_principal(request)+++def _owner_of(principal: Optional[Dict]) -> Optional[str]:+ return principal.get("sub") if principal else None+++def _is_admin(principal: Optional[Dict]) -> bool:+ return bool(principal) and principal.get("scope") == "admin"++# === init hook called by server.py =========================================def init_job_router(redis, config, token_dep) -> APIRouter:"""Inject shared singletons and return the router for mounting."""@@ -40,7 +54,7 @@ class LlmJobPayload(BaseModel):provider: Optional[str] = Nonewebhook_config: Optional[WebhookConfig] = Nonetemperature: Optional[float] = None- base_url: Optional[str] = None+ # base_url removed: server-derived LLM endpoint only (key-exfil vector).class CrawlJobPayload(BaseModel):@@ -56,7 +70,7 @@ async def llm_job_enqueue(payload: LlmJobPayload,background_tasks: BackgroundTasks,request: Request,- _td: Dict = Depends(lambda: _token_dep()), # late-bound dep+ _td: Optional[Dict] = Depends(_principal_dep),):webhook_config = Noneif payload.webhook_config:@@ -79,7 +93,8 @@ async def llm_job_enqueue(provider=payload.provider,webhook_config=webhook_config,temperature=payload.temperature,- api_base_url=payload.base_url,+ requester=_owner_of(_td),+ is_admin=_is_admin(_td),)@@ -87,9 +102,12 @@ async def llm_job_enqueue(async def llm_job_status(request: Request,task_id: str,- _td: Dict = Depends(lambda: _token_dep())+ _td: Optional[Dict] = Depends(_principal_dep),):- return await handle_task_status(_redis, task_id, base_url=str(request.base_url))+ return await handle_task_status(+ _redis, task_id, base_url=str(request.base_url),+ requester=_owner_of(_td), is_admin=_is_admin(_td),+ )# ---------- CRAWL job -------------------------------------------------------@@ -97,7 +115,7 @@ async def llm_job_status(async def crawl_job_enqueue(payload: CrawlJobPayload,background_tasks: BackgroundTasks,- _td: Dict = Depends(lambda: _token_dep()),+ _td: Optional[Dict] = Depends(_principal_dep),):webhook_config = Noneif payload.webhook_config:@@ -116,6 +134,7 @@ async def crawl_job_enqueue(payload.crawler_config,config=_config,webhook_config=webhook_config,+ owner=_owner_of(_td),)@@ -123,6 +142,9 @@ async def crawl_job_enqueue(async def crawl_job_status(request: Request,task_id: str,- _td: Dict = Depends(lambda: _token_dep())+ _td: Optional[Dict] = Depends(_principal_dep),):- return await handle_task_status(_redis, task_id, base_url=str(request.base_url))+ return await handle_task_status(+ _redis, task_id, base_url=str(request.base_url),+ requester=_owner_of(_td), is_admin=_is_admin(_td),+ )diff --git a/deploy/docker/llm_broker.py b/deploy/docker/llm_broker.pynew file mode 100644index 00000000..20c26334--- /dev/null+++ b/deploy/docker/llm_broker.py@@ -0,0 +1,64 @@+"""+llm_broker.py - server-side LLM provider resolution.++The credential-exfil gadget (reported by Geo): a request could pass its own+`base_url` (and/or `provider`), and the server would happily send the+configured provider API key to that attacker-controlled endpoint, leaking+*every* provider key the server holds.++The fix: a request may select a provider BY NAME only (and only from an+allowlisted family). The `base_url` and `api_token` are ALWAYS derived+server-side from config/environment and are never taken from the request, so a+key can never be redirected to an attacker host.+"""++from __future__ import annotations++from typing import Dict, Optional+++class LLMProviderNotAllowed(ValueError):+ """The requested LLM provider is not in the server's allowlist (-> HTTP 400)."""+++def _family(provider: Optional[str]) -> str:+ return (provider or "").split("/")[0].lower()+++def allowed_provider_families(config: Dict) -> set:+ """Provider families a request may select.++ Sourced from config.llm.allowed_providers plus the default provider's+ family. Empty set => unrestricted family selection (base_url/key are still+ server-only, so the exfil path stays closed); set a non-empty+ allowed_providers to lock it down further.+ """+ cfg = config.get("llm", {}) or {}+ fams = {_family(p) for p in (cfg.get("allowed_providers") or [])}+ if cfg.get("provider"):+ fams.add(_family(cfg["provider"]))+ return {f for f in fams if f}+++def resolve_llm(config: Dict, requested_provider: Optional[str] = None) -> Dict:+ """Resolve the LLM call parameters fully server-side.++ A request-supplied base_url/api_token is intentionally NOT a parameter here:+ callers pass only the provider *name*. Returns {provider, base_url,+ api_token, temperature}, all server-derived.+ """+ from utils import get_llm_api_key, get_llm_base_url, get_llm_temperature++ default = config["llm"]["provider"]+ provider = requested_provider or default++ fams = allowed_provider_families(config)+ if fams and _family(provider) not in fams:+ raise LLMProviderNotAllowed("LLM provider not allowed")++ return {+ "provider": provider,+ "base_url": get_llm_base_url(config, provider), # canonical, never from request+ "api_token": get_llm_api_key(config, provider), # server credential+ "temperature": get_llm_temperature(config, provider),+ }diff --git a/deploy/docker/mcp_bridge.py b/deploy/docker/mcp_bridge.pyindex 7cae2dc6..653bc368 100644--- a/deploy/docker/mcp_bridge.py+++ b/deploy/docker/mcp_bridge.py@@ -36,6 +36,22 @@ def mcp_tool(name: str | None = None):return deco# ── HTTP‑proxy helper for FastAPI endpoints ─────────────────────+def _service_auth_headers() -> dict:+ """Authenticate the internal loopback call to our own gated endpoints.++ The MCP transport is now behind the AuthGateMiddleware, so by the time a+ tool is invoked the MCP client is already authenticated. The loopback HTTP+ call this proxy makes must therefore carry a credential too, or the gate+ would 401 it. We mint a short-lived, data-scope service token: MCP exposes+ only data-plane tools (no admin/monitor actions), so this grants no+ privilege escalation. (Requires a shared SECRET_KEY across workers, which+ the auth startup check already mandates for any real deployment.)+ """+ from auth import create_access_token+ token = create_access_token({"sub": "mcp-service"}, scope="data")+ return {"Authorization": f"Bearer {token}"}++def _make_http_proxy(base_url: str, route, *, timeout: float | None = None):method = list(route.methods - {"HEAD", "OPTIONS"})[0]async def proxy(**kwargs):@@ -48,12 +64,13 @@ def _make_http_proxy(base_url: str, route, *, timeout: float | None = None):kwargs.pop(k)url = base_url.rstrip("/") + path+ headers = _service_auth_headers()async with httpx.AsyncClient(timeout=timeout) as client:try:r = (- await client.get(url, params=kwargs)+ await client.get(url, params=kwargs, headers=headers)if method == "GET"- else await client.request(method, url, json=kwargs)+ else await client.request(method, url, json=kwargs, headers=headers))r.raise_for_status()return r.text if method == "GET" else r.json()diff --git a/deploy/docker/monitor_routes.py b/deploy/docker/monitor_routes.pyindex d77f47c1..5faf33d6 100644--- a/deploy/docker/monitor_routes.py+++ b/deploy/docker/monitor_routes.py@@ -1,8 +1,9 @@# monitor_routes.py - Monitor API endpoints-from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect+from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect, Dependsfrom pydantic import BaseModelfrom typing import Optionalfrom monitor import get_monitor+from auth import require_adminimport loggingimport asyncioimport json@@ -153,7 +154,7 @@ class KillBrowserRequest(BaseModel):sig: str[email protected]("/actions/cleanup")[email protected]("/actions/cleanup", dependencies=[Depends(require_admin)])async def force_cleanup():"""Force immediate janitor cleanup (kills idle cold pool browsers)."""try:@@ -184,7 +185,7 @@ async def force_cleanup():raise HTTPException(500, str(e))[email protected]("/actions/kill_browser")[email protected]("/actions/kill_browser", dependencies=[Depends(require_admin)])async def kill_browser(req: KillBrowserRequest):"""Kill a specific browser by signature (hot or cold only).@@ -253,7 +254,7 @@ async def kill_browser(req: KillBrowserRequest):raise HTTPException(500, str(e))[email protected]("/actions/restart_browser")[email protected]("/actions/restart_browser", dependencies=[Depends(require_admin)])async def restart_browser(req: KillBrowserRequest):"""Restart a browser (kill + recreate). Works for permanent too.@@ -336,7 +337,7 @@ async def restart_browser(req: KillBrowserRequest):raise HTTPException(500, str(e))[email protected]("/stats/reset")[email protected]("/stats/reset", dependencies=[Depends(require_admin)])async def reset_stats():"""Reset today's endpoint counters."""try:@@ -360,15 +361,9 @@ async def websocket_endpoint(websocket: WebSocket):- Browser pool status- Timeline data"""- # WebSocket endpoints don't inherit router dependencies in FastAPI.- # Validate token from query params if auth is configured.- import os- expected_token = os.environ.get("CRAWL4AI_API_TOKEN", "")- if expected_token:- token = websocket.query_params.get("token", "")- if token != expected_token:- await websocket.close(code=4003, reason="Authentication required")- return+ # Auth is enforced by the AuthGateMiddleware (outermost ASGI layer), which+ # validates the ?token= query param / Authorization header for this+ # WebSocket and closes 4401 before we are reached. No bespoke check here.await websocket.accept()logger.info("WebSocket client connected")diff --git a/deploy/docker/requirements.txt b/deploy/docker/requirements.txtindex b33c081f..6ce2290b 100644--- a/deploy/docker/requirements.txt+++ b/deploy/docker/requirements.txt@@ -4,7 +4,6 @@ gunicorn>=23.0.0slowapi==0.1.9prometheus-fastapi-instrumentator>=7.1.0redis>=5.2.1-jwt>=1.3.1dnspython>=2.7.0email-validator==2.2.0sse-starlette==2.2.1diff --git a/deploy/docker/schemas.py b/deploy/docker/schemas.pyindex dd561bb2..f066e5c8 100644--- a/deploy/docker/schemas.py+++ b/deploy/docker/schemas.py@@ -1,4 +1,4 @@-from typing import List, Optional, Dict+from typing import Any, List, Optional, Dictfrom enum import Enumfrom pydantic import BaseModel, Field, HttpUrl, field_validatorfrom utils import FilterType@@ -18,38 +18,39 @@ class CrawlRequest(BaseModel):)+class HookSpec(BaseModel):+ """A single declarative hook: a fixed action plus schema-validated params.++ Arbitrary Python (the old `code` map) is no longer accepted - it was an+ exec()-based RCE surface. Available actions are enumerated by GET /hooks/info+ and validated server-side by hook_registry.py.+ """+ action: str = Field(..., description="One of the registered hook actions")+ params: Dict[str, Any] = Field(default_factory=dict, description="Action parameters")++class HookConfig(BaseModel):- """Configuration for user-provided hooks"""- code: Dict[str, str] = Field(- default_factory=dict,- description="Map of hook points to Python code strings"+ """Configuration for declarative hooks."""+ hooks: List[HookSpec] = Field(+ default_factory=list,+ max_length=10,+ description="Declarative hook specs (action + params), max 10",)timeout: int = Field(default=30,ge=1,le=120,- description="Timeout in seconds for each hook execution"+ description="Timeout in seconds for each hook execution",)-+class Config:- schema_extra = {+ json_schema_extra = {"example": {- "code": {- "on_page_context_created": """-async def hook(page, context, **kwargs):- # Block images to speed up crawling- await context.route("**/*.{png,jpg,jpeg,gif}", lambda route: route.abort())- return page-""",- "before_retrieve_html": """-async def hook(page, context, **kwargs):- # Scroll to load lazy content- await page.evaluate("window.scrollTo(0, document.body.scrollHeight)")- await page.wait_for_timeout(2000)- return page-"""- },- "timeout": 30+ "hooks": [+ {"action": "block_resources", "params": {"resource_types": ["image", "font"]}},+ {"action": "scroll_to_bottom", "params": {"max_steps": 10, "delay_ms": 500}},+ ],+ "timeout": 30,}}@@ -69,7 +70,8 @@ class MarkdownRequest(BaseModel):c: Optional[str] = Field("0", description="Cache‑bust / revision counter")provider: Optional[str] = Field(None, description="LLM provider override (e.g., 'anthropic/claude-3-opus')")temperature: Optional[float] = Field(None, description="LLM temperature override (0.0-2.0)")- base_url: Optional[str] = Field(None, description="LLM API base URL override")+ # base_url removed: a request-supplied LLM endpoint was a credential-exfil+ # vector. The endpoint is derived server-side from the provider name.class RawCode(BaseModel):@@ -82,29 +84,14 @@ class ScreenshotRequest(BaseModel):url: strscreenshot_wait_for: Optional[float] = 2wait_for_images: Optional[bool] = False- output_path: Optional[str] = None+ # output_path removed: callers never name a filesystem path (it was an+ # arbitrary-write -> RCE vector). The server writes to the sandboxed+ # artifact store and returns an opaque artifact_id.- @field_validator("output_path")- @classmethod- def reject_traversal(cls, v):- if v is None:- return v- if ".." in v.replace("\\", "/").split("/"):- raise ValueError("output_path must not contain path traversal sequences")- return vclass PDFRequest(BaseModel):url: str- output_path: Optional[str] = None-- @field_validator("output_path")- @classmethod- def reject_traversal(cls, v):- if v is None:- return v- if ".." in v.replace("\\", "/").split("/"):- raise ValueError("output_path must not contain path traversal sequences")- return v+ # output_path removed (see ScreenshotRequest).class JSEndpointRequest(BaseModel):diff --git a/deploy/docker/server.py b/deploy/docker/server.pyindex e984ff62..1bc05d83 100644--- a/deploy/docker/server.py+++ b/deploy/docker/server.py@@ -9,8 +9,13 @@ Crawl4AI FastAPI entry‑point# ── stdlib & 3rd‑party imports ───────────────────────────────from crawler_pool import get_crawler, release_crawler, close_all, janitorfrom crawl4ai import AsyncWebCrawler, BrowserConfig, CrawlerRunConfig+from crawl4ai.async_configs import Provenance, UntrustedConfigErrorfrom crawl4ai.__version__ import __version__-from auth import create_access_token, get_token_dependency, TokenRequest+from auth import (+ create_access_token, get_token_dependency, TokenRequest,+ constant_time_eq, resolve_secret_key,+)+from auth_gate import AuthGateMiddlewarefrom pydantic import BaseModelfrom typing import Optional, List, Dictfrom fastapi import Request, Depends@@ -36,7 +41,7 @@ from schemas import (from utils import (FilterType, load_config, setup_logging, verify_email_domain,- validate_output_path, write_output_file, validate_webhook_url, validate_url_destination,+ validate_webhook_url, validate_url_destination,)import osimport sys@@ -88,6 +93,13 @@ HOOKS_ENABLED = os.environ.get("CRAWL4AI_HOOKS_ENABLED", "false").lower() == "tr# /execute_js disabled by default (arbitrary JS + SSRF risk). Set to "true" to enable.EXECUTE_JS_ENABLED = os.environ.get("CRAWL4AI_EXECUTE_JS_ENABLED", "false").lower() == "true"+# Chromium renderer sandbox. --no-sandbox is kept by default because the+# container runs as non-root without a usable sandbox. On a host that provides+# an unprivileged user namespace (unprivileged_userns_clone=1) or a seccomp+# profile, set CRAWL4AI_CHROMIUM_SANDBOX=true to drop --no-sandbox and run the+# renderer sandboxed. Verify Chromium still starts after flipping it.+CHROMIUM_SANDBOX = os.environ.get("CRAWL4AI_CHROMIUM_SANDBOX", "false").lower() == "true"+# Warn loudly if API token is not set (all endpoints unauthenticated)_api_token = config.get("security", {}).get("api_token", "") or os.environ.get("CRAWL4AI_API_TOKEN", "")if not _api_token:@@ -98,12 +110,30 @@ if not _api_token:)# ── default browser config helper ─────────────────────────────+def _browser_extra_args() -> list:+ """Effective Chromium launch flags. Drops --no-sandbox when the operator+ opts into the renderer sandbox (CRAWL4AI_CHROMIUM_SANDBOX=true)."""+ args = list(config["crawler"]["browser"].get("extra_args", []))+ if CHROMIUM_SANDBOX:+ args = [a for a in args if a != "--no-sandbox"]+ return args++def get_default_browser_config() -> BrowserConfig:- """Get default BrowserConfig from config.yml."""- return BrowserConfig(- extra_args=config["crawler"]["browser"].get("extra_args", []),+ """Get default BrowserConfig from config.yml.++ Egress hardening (TLS-verify on, pinning proxy so Chromium never resolves+ the target itself) is applied here so every endpoint that fetches through+ the default config (/html, /screenshot, /pdf, /execute_js) gets the same+ DNS-rebinding / redirect-to-internal protection as /crawl, rather than+ relying on each handler to remember it."""+ bc = BrowserConfig(+ extra_args=_browser_extra_args(),**config["crawler"]["browser"].get("kwargs", {}),)+ from egress_broker import enforce_egress+ enforce_egress(bc)+ return bc# import logging# page_log = logging.getLogger("page_cap")@@ -134,6 +164,28 @@ async def lifespan(_: FastAPI):from monitor import MonitorStatsimport monitor as monitor_module+ # Enforce auth posture before serving any traffic.+ _resolve_auth()++ # Initialize the sandboxed artifact store + reaper.+ from artifacts import init_store+ init_store()+ app.state.artifact_janitor = asyncio.create_task(_artifact_janitor())++ # Start the localhost pinning forward-proxy and route the browser through it.+ from egress_proxy import PinningProxy+ from egress_broker import set_egress_proxy+ app.state.egress_proxy = PinningProxy()+ set_egress_proxy(await app.state.egress_proxy.start())++ # Bounded background-job queue (per-principal quotas optional).+ from work_queue import WorkQueue, set_job_queue+ from governor import job_queue_caps+ _caps = job_queue_caps(config)+ app.state.job_queue = WorkQueue(**_caps)+ await app.state.job_queue.start()+ set_job_queue(app.state.job_queue)+# Initialize monitormonitor_module.monitor_stats = MonitorStats(redis)await monitor_module.monitor_stats.load_from_redis()@@ -141,7 +193,7 @@ async def lifespan(_: FastAPI):# Initialize browser poolawait init_permanent(BrowserConfig(- extra_args=config["crawler"]["browser"].get("extra_args", []),+ extra_args=_browser_extra_args(),**config["crawler"]["browser"].get("kwargs", {}),))@@ -154,6 +206,15 @@ async def lifespan(_: FastAPI):# Cleanupapp.state.janitor.cancel()app.state.timeline_updater.cancel()+ app.state.artifact_janitor.cancel()+ try:+ await app.state.egress_proxy.stop()+ except Exception:+ pass+ try:+ await app.state.job_queue.stop()+ except Exception:+ pass# Monitor cleanup (persist stats and stop workers)from monitor import get_monitor@@ -164,6 +225,16 @@ async def lifespan(_: FastAPI):await close_all()+async def _artifact_janitor():+ """Periodically reap expired / over-quota artifacts."""+ from artifacts import janitor as _reap+ while True:+ await asyncio.sleep(300)+ try:+ _reap()+ except Exception as e:+ logger.warning(f"Artifact janitor error: {e}")+async def _timeline_updater():"""Update timeline data every 5 seconds."""from monitor import get_monitor@@ -240,13 +311,31 @@ limiter = Limiter(def _setup_security(app_: FastAPI):sec = config["security"]- if not sec["enabled"]:- returnif sec.get("https_redirect"):app_.add_middleware(HTTPSRedirectMiddleware)- if sec.get("trusted_hosts", []) != ["*"]:+ # Apply the Host guard whenever real hostnames are configured, independent+ # of `security.enabled` (the old code silently skipped it when disabled).+ trusted = sec.get("trusted_hosts", ["*"])+ if trusted and trusted != ["*"]:+ app_.add_middleware(TrustedHostMiddleware, allowed_hosts=trusted)+ elif config["app"]["host"] not in ("127.0.0.1", "localhost", "::1"):+ logging.getLogger("crawl4ai.security").warning(+ "trusted_hosts is ['*'] on a non-loopback bind (%s): the Host guard "+ "is disabled. Set security.trusted_hosts to your real hostname(s).",+ config["app"]["host"],+ )++ # Deny-by-default CORS: only explicitly allowlisted origins; never '*' with+ # credentials.+ origins = [o for o in (sec.get("cors_allow_origins") or []) if o and o != "*"]+ if origins:+ from fastapi.middleware.cors import CORSMiddlewareapp_.add_middleware(- TrustedHostMiddleware, allowed_hosts=sec["trusted_hosts"]+ CORSMiddleware,+ allow_origins=origins,+ allow_credentials=True,+ allow_methods=["*"],+ allow_headers=["*"],)@@ -257,14 +346,104 @@ if config["observability"]["prometheus"]["enabled"]:token_dep = get_token_dependency(config)+# ── security response headers (unconditional, strict-by-default) ──────+SECURITY_BASELINE_HEADERS = {+ "X-Content-Type-Options": "nosniff",+ "X-Frame-Options": "DENY",+ "Referrer-Policy": "no-referrer",+ "Cross-Origin-Opener-Policy": "same-origin",+ "Cross-Origin-Resource-Policy": "same-origin",+}+# Strict CSP for the API / error surface (the injection-reflection paths).+STRICT_CSP = (+ "default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; "+ "img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; "+ "base-uri 'none'; form-action 'none'"+)+# The dashboard/playground still ship inline scripts/styles; until they are+# externalized (CSP-compat refactor) they must not receive the strict CSP or+# they break. They still get the baseline headers (nosniff, frame DENY).+_UI_PREFIXES = ("/dashboard", "/playground", "/static")+@app.middleware("http")async def add_security_headers(request: Request, call_next):resp = await call_next(request)- if config["security"]["enabled"]:- resp.headers.update(config["security"]["headers"])+ for k, v in SECURITY_BASELINE_HEADERS.items():+ resp.headers.setdefault(k, v)+ path = request.url.path+ if not any(path.startswith(p) for p in _UI_PREFIXES):+ resp.headers.setdefault("Content-Security-Policy", STRICT_CSP)+ if config["security"].get("https_redirect"):+ resp.headers.setdefault(+ "Strict-Transport-Security", "max-age=63072000; includeSubDomains"+ )return resp++# ── authentication gate (outermost ASGI layer, fails closed) ──────────+# The single place auth is decided: covers every route, static mount, the MCP+# transports and the metrics endpoint, for HTTP and WebSocket alike. Only the+# health check and the token-issuing endpoint are public.+HEALTH_PATH = config["observability"]["health_check"]["endpoint"]+++def _current_api_token() -> str:+ """The effective static operator token (config or environment)."""+ return (+ config.get("security", {}).get("api_token", "")+ or os.environ.get("CRAWL4AI_API_TOKEN", "")+ )+++app.add_middleware(+ AuthGateMiddleware,+ token_provider=_current_api_token,+ public_paths={HEALTH_PATH, "/token"},+)++# ── request body-size limit (DoS) ─────────────────────────────────────+from governor import BodySizeLimitMiddleware, max_body_bytes_from_config+app.add_middleware(BodySizeLimitMiddleware, max_bytes=max_body_bytes_from_config(config))+++def _resolve_auth():+ """Runtime auth-posture guard. Runs at startup (lifespan), not import, so+ the behavioral test harness can import the app without a hard exit.++ - credential configured -> enforce (fail fast on jwt_enabled w/o SECRET_KEY)+ - none + non-loopback bind -> refuse to start (would be open to the network)+ - none + loopback bind -> generate a one-off token and print it+ """+ host = config["app"]["host"]+ loopback = host in ("127.0.0.1", "localhost", "::1")+ api_token = _current_api_token()+ jwt_enabled = config.get("security", {}).get("jwt_enabled", False)++ if api_token or jwt_enabled:+ if jwt_enabled:+ resolve_secret_key(required=True) # fail fast: no ephemeral secret+ logger.info("Auth gate active (credential configured).")+ return++ if not loopback:+ logger.critical(+ "Refusing to start: binding %s with no CRAWL4AI_API_TOKEN and "+ "jwt_enabled=false would expose an unauthenticated API. Set "+ "CRAWL4AI_API_TOKEN=$(openssl rand -hex 32), enable jwt, or bind loopback.",+ host,+ )+ sys.exit(1)++ import secrets as _secrets+ gen = _secrets.token_hex(32)+ os.environ["CRAWL4AI_API_TOKEN"] = gen+ logger.warning(+ "No CRAWL4AI_API_TOKEN set; generated an ephemeral token for this "+ "loopback session:\n CRAWL4AI_API_TOKEN=%s",+ gen,+ )+# ───────────────── URL validation helper ─────────────────ALLOWED_URL_SCHEMES = ("http://", "https://")ALLOWED_URL_SCHEMES_WITH_RAW = ("http://", "https://", "raw:", "raw://")@@ -287,14 +466,19 @@ ALLOWED_TYPES = {def _config_from_json(data: dict) -> dict:- """Create CrawlerRunConfig or BrowserConfig from JSON {type, params}.- No eval() -- uses Pydantic constructors directly."""+ """Validate a {type, params} config under the untrusted trust boundary and+ echo the normalized result.++ This endpoint is no longer a gadget-construction oracle: only the gated,+ side-effect-free CrawlerRunConfig/BrowserConfig types may be validated, the+ untrusted gate raises on forbidden power-fields and disallowed nested types+ (LLM*, proxy, deep-crawl - which is what would read env/secrets), drops+ unknown fields, and clamps quantities."""config_type = data.get("type")- params = data.get("params", {})if config_type == "CrawlerRunConfig":- obj = CrawlerRunConfig(**params)+ obj = CrawlerRunConfig.load(data, provenance=Provenance.UNTRUSTED)elif config_type == "BrowserConfig":- obj = BrowserConfig(**params)+ obj = BrowserConfig.load(data, provenance=Provenance.UNTRUSTED)else:raise ValueError("type must be 'CrawlerRunConfig' or 'BrowserConfig'")return obj.dump()@@ -309,11 +493,57 @@ app.include_router(monitor_router, dependencies=[Depends(token_dep)])logger = logging.getLogger(__name__)++# ── central exception handling (no internal detail leaks) ─────────────+# 16 sites used to return raw str(e) to clients, leaking paths, dependency+# versions, resolved internal IPs and sometimes secrets. Centralize: 5xx+# responses are generic + carry a correlation id; the full detail is logged+# server-side. 4xx developer messages are preserved.+import uuid as _uuid+from starlette.exceptions import HTTPException as _StarletteHTTPException++[email protected]_handler(_StarletteHTTPException)+async def _http_exception_handler(request: Request, exc: _StarletteHTTPException):+ # 500 is the raw-str(e) leak vector -> genericize with a correlation id.+ # Deliberate operational statuses (502/503/504, with their own short+ # messages + headers like Retry-After) pass through, as do 4xx.+ if exc.status_code == 500:+ cid = _uuid.uuid4().hex[:12]+ logger.error("server error 500 [cid=%s]: %s", cid, exc.detail)+ return JSONResponse(+ {"error": "Internal server error", "correlation_id": cid},+ status_code=500,+ )+ return JSONResponse(+ {"detail": exc.detail},+ status_code=exc.status_code,+ headers=getattr(exc, "headers", None),+ )++[email protected]_handler(Exception)+async def _unhandled_exception_handler(request: Request, exc: Exception):+ cid = _uuid.uuid4().hex[:12]+ logger.exception("unhandled exception [cid=%s]", cid)+ return JSONResponse(+ {"error": "Internal server error", "correlation_id": cid},+ status_code=500,+ )++# ──────────────────────── Endpoints ──────────────────────────@app.post("/token")async def get_token(req: TokenRequest):expected_token = config.get("security", {}).get("api_token", "")- if expected_token and req.api_token != expected_token:+ if not expected_token:+ # Fail closed: without a configured api_token the old behavior minted a+ # JWT to anyone whose email merely had an MX record. Refuse instead.+ raise HTTPException(+ 403,+ "Token issuance is disabled: no api_token is configured on the server.",+ )+ if not req.api_token or not constant_time_eq(req.api_token, expected_token):raise HTTPException(401, "Invalid or missing api_token")if not verify_email_domain(req.email):raise HTTPException(400, "Invalid email domain")@@ -354,9 +584,11 @@ async def get_markdown(if not body.url.startswith(("http://", "https://")) and not body.url.startswith(("raw:", "raw://")):raise HTTPException(400, "Invalid URL format. Must start with http://, https://, or for raw HTML (raw:, raw://)")+ # base_url is intentionally not accepted from the request (key-exfil vector);+ # the LLM endpoint is server-derived from the provider name only.markdown = await handle_markdown_request(body.url, body.f, body.q, body.c, config, body.provider,- body.temperature, body.base_url+ body.temperature)return JSONResponse({"url": body.url,@@ -399,6 +631,35 @@ async def generate_html(if crawler:await release_crawler(crawler)+# ── artifact store helpers ───────────────────────────────────+def _store_artifact(kind: str, data: bytes) -> dict:+ """Write to the sandboxed store; map quota/size errors to HTTP codes."""+ from artifacts import write_artifact, ArtifactTooLarge, QuotaExceeded+ try:+ meta = write_artifact(kind, data)+ except ArtifactTooLarge:+ raise HTTPException(413, "Artifact too large")+ except QuotaExceeded:+ raise HTTPException(507, "Artifact storage quota exceeded")+ return {+ "artifact_id": meta["artifact_id"],+ "url": f"/artifacts/{meta['artifact_id']}",+ "mime": meta["mime"],+ "size": meta["size"],+ }++[email protected]("/artifacts/{artifact_id}")+async def get_artifact(artifact_id: str, _td: Dict = Depends(token_dep)):+ """Fetch a previously generated artifact by its opaque id (authed)."""+ from artifacts import resolve_artifact, ArtifactNotFound+ try:+ path, mime = resolve_artifact(artifact_id)+ except ArtifactNotFound:+ raise HTTPException(404, "Artifact not found")+ return FileResponse(path, media_type=mime, headers={"X-Content-Type-Options": "nosniff"})++# Screenshot endpoint@@ -411,9 +672,9 @@ async def generate_screenshot(_td: Dict = Depends(token_dep),):"""- Capture a full-page PNG screenshot of the specified URL, waiting an optional delay before capture,- Use when you need an image snapshot of the rendered page. Its recommened to provide an output path to save the screenshot.- Then in result instead of the screenshot you will get a path to the saved file.+ Capture a full-page PNG screenshot of the specified URL, waiting an optional delay before capture.+ Use when you need an image snapshot of the rendered page. The image is also written to the+ sandboxed artifact store; the response includes an `artifact_id` and a `url` to fetch it."""validate_url_scheme(body.url)crawler = None@@ -424,11 +685,10 @@ async def generate_screenshot(if not results[0].success:raise HTTPException(500, detail=results[0].error_message or "Crawl failed")screenshot_data = results[0].screenshot- if body.output_path:- abs_path = validate_output_path(body.output_path)- write_output_file(abs_path, base64.b64decode(screenshot_data))- return {"success": True, "path": abs_path}- return {"success": True, "screenshot": screenshot_data}+ art = _store_artifact("png", base64.b64decode(screenshot_data))+ return {"success": True, "screenshot": screenshot_data, **art}+ except HTTPException:+ raiseexcept Exception as e:raise HTTPException(500, detail=str(e))finally:@@ -447,9 +707,9 @@ async def generate_pdf(_td: Dict = Depends(token_dep),):"""- Generate a PDF document of the specified URL,- Use when you need a printable or archivable snapshot of the page. It is recommended to provide an output path to save the PDF.- Then in result instead of the PDF you will get a path to the saved file.+ Generate a PDF document of the specified URL.+ Use when you need a printable or archivable snapshot of the page. The PDF is also written to the+ sandboxed artifact store; the response includes an `artifact_id` and a `url` to fetch it."""validate_url_scheme(body.url)crawler = None@@ -460,11 +720,10 @@ async def generate_pdf(if not results[0].success:raise HTTPException(500, detail=results[0].error_message or "Crawl failed")pdf_data = results[0].pdf- if body.output_path:- abs_path = validate_output_path(body.output_path)- write_output_file(abs_path, pdf_data)- return {"success": True, "path": abs_path}- return {"success": True, "pdf": base64.b64encode(pdf_data).decode()}+ art = _store_artifact("pdf", pdf_data)+ return {"success": True, "pdf": base64.b64encode(pdf_data).decode(), **art}+ except HTTPException:+ raiseexcept Exception as e:raise HTTPException(500, detail=str(e))finally:@@ -556,14 +815,15 @@ async def llm_endpoint(q: str = Query(...),provider: Optional[str] = Query(None, description="LLM provider override, e.g. 'openai/gpt-4o-mini'"),temperature: Optional[float] = Query(None, description="LLM temperature override"),- base_url: Optional[str] = Query(None, description="LLM API base URL override"),_td: Dict = Depends(token_dep),):+ # base_url is intentionally not accepted (key-exfil vector); the endpoint is+ # derived server-side from the provider name only.if not q:raise HTTPException(400, "Query parameter 'q' is required")if not url.startswith(("http://", "https://")) and not url.startswith(("raw:", "raw://")):url = "https://" + url- answer = await handle_llm_qa(url, q, config, provider=provider, temperature=temperature, base_url=base_url)+ answer = await handle_llm_qa(url, q, config, provider=provider, temperature=temperature)return JSONResponse({"answer": answer})@@ -576,68 +836,23 @@ async def get_schema():@app.get("/hooks/info")async def get_hooks_info():- """Get information about available hook points and their signatures"""- from hook_manager import UserHookManager-- hook_info = {}- for hook_point, params in UserHookManager.HOOK_SIGNATURES.items():- hook_info[hook_point] = {- "parameters": params,- "description": get_hook_description(hook_point),- "example": get_hook_example(hook_point)- }-- return JSONResponse({- "available_hooks": hook_info,- "timeout_limits": {- "min": 1,- "max": 120,- "default": 30- }- })+ """Enumerate the available declarative hook actions and their parameter schemas.+ Arbitrary hook code is no longer accepted (it was an exec()-based RCE+ surface). Each action maps to a server-authored, single-purpose Playwright+ operation; clients select an action and supply schema-validated params.+ """+ from hook_registry import describe_registry-def get_hook_description(hook_point: str) -> str:- """Get description for each hook point"""- descriptions = {- "on_browser_created": "Called after browser instance is created",- "on_page_context_created": "Called after page and context are created - ideal for authentication",- "before_goto": "Called before navigating to the target URL",- "after_goto": "Called after navigation is complete",- "on_user_agent_updated": "Called when user agent is updated",- "on_execution_started": "Called when custom JavaScript execution begins",- "before_retrieve_html": "Called before retrieving the final HTML - ideal for scrolling",- "before_return_html": "Called just before returning the HTML content"- }- return descriptions.get(hook_point, "")---def get_hook_example(hook_point: str) -> str:- """Get example code for each hook point"""- examples = {- "on_page_context_created": """async def hook(page, context, **kwargs):- # Add authentication cookie- await context.add_cookies([{- 'name': 'session',- 'value': 'my-session-id',- 'domain': '.example.com'- }])- return page""",-- "before_retrieve_html": """async def hook(page, context, **kwargs):- # Scroll to load lazy content- await page.evaluate("window.scrollTo(0, document.body.scrollHeight)")- await page.wait_for_timeout(2000)- return page""",-- "before_goto": """async def hook(page, context, url, **kwargs):- # Set custom headers- await page.set_extra_http_headers({- 'X-Custom-Header': 'value'+ return JSONResponse({+ "available_actions": describe_registry(),+ "usage": {+ "field": "hooks",+ "shape": [{"action": "<action>", "params": {"...": "..."}}],+ "max_hooks": 10,+ },+ "timeout_limits": {"min": 1, "max": 120, "default": 30},})- return page"""- }- return examples.get(hook_point, "# Implement your hook logic here\nreturn page")@app.get(config["observability"]["health_check"]["endpoint"])@@ -668,7 +883,12 @@ async def crawl(if crawl_request.hooks and not HOOKS_ENABLED:raise HTTPException(403, "Hooks are disabled. Set CRAWL4AI_HOOKS_ENABLED=true to enable.")# Check whether it is a redirection for a streaming request- crawler_config = CrawlerRunConfig.load(crawl_request.crawler_config)+ try:+ crawler_config = CrawlerRunConfig.load(+ crawl_request.crawler_config, provenance=Provenance.UNTRUSTED+ )+ except UntrustedConfigError as e:+ raise HTTPException(400, f"Rejected config: {e}")if crawler_config.stream:return await stream_process(crawl_request=crawl_request)@@ -676,7 +896,7 @@ async def crawl(hooks_config = Noneif crawl_request.hooks:hooks_config = {- 'code': crawl_request.hooks.code,+ 'hooks': crawl_request.hooks.hooks,'timeout': crawl_request.hooks.timeout}@@ -714,7 +934,7 @@ async def stream_process(crawl_request: CrawlRequestWithHooks):hooks_config = Noneif crawl_request.hooks:hooks_config = {- 'code': crawl_request.hooks.code,+ 'hooks': crawl_request.hooks.hooks,'timeout': crawl_request.hooks.timeout}@@ -873,7 +1093,10 @@ async def get_context(print(f"MCP server running on {config['app']['host']}:{config['app']['port']}")attach_mcp(app,- base_url=f"http://{config['app']['host']}:{config['app']['port']}"+ # Internal MCP tool calls go over loopback to our own gated endpoints,+ # carrying a service token. Pin to 127.0.0.1 (config host may be 0.0.0.0,+ # which is a bind address, not a valid connect target).+ base_url=f"http://127.0.0.1:{config['app']['port']}")# ────────────────────────── cli ──────────────────────────────diff --git a/deploy/docker/supervisord.conf b/deploy/docker/supervisord.confindex 198a78de..b99f8a0b 100644--- a/deploy/docker/supervisord.conf+++ b/deploy/docker/supervisord.conf@@ -4,7 +4,9 @@ logfile=/dev/null ; Log supervisord output to stdout/stderrlogfile_maxbytes=0[program:redis]-command=/usr/bin/redis-server --loglevel notice ; Path to redis-server on Alpine+; Loopback-only and password-protected. REDIS_PASSWORD is exported by+; entrypoint.sh from the mounted secret; the app must supply it to connect.+command=/usr/bin/redis-server --loglevel notice --bind 127.0.0.1 ::1 --requirepass "%(ENV_REDIS_PASSWORD)s"user=appuser ; Run redis as our non-root userautorestart=truepriority=10@@ -14,7 +16,11 @@ stderr_logfile=/dev/stderr ; Redirect redis stderr to container stderrstderr_logfile_maxbytes=0[program:gunicorn]-command=/usr/local/bin/gunicorn --bind [::]:11235 --workers 1 --threads 4 --timeout 1800 --graceful-timeout 30 --keep-alive 300 --log-level info --worker-class uvicorn.workers.UvicornWorker server:app+; Bind is resolved by entrypoint.sh into GUNICORN_BIND: loopback unless a+; credential (CRAWL4AI_API_TOKEN) is present, in which case the operator may+; expose 0.0.0.0. gunicorn is the authoritative socket-level guard; the Python+; _resolve_auth() check is the in-process guard - both must agree.+command=/usr/local/bin/gunicorn --bind "%(ENV_GUNICORN_BIND)s" --workers 1 --threads 4 --timeout 1800 --graceful-timeout 30 --keep-alive 300 --log-level info --limit-request-line 8190 --limit-request-fields 100 --worker-class uvicorn.workers.UvicornWorker server:appdirectory=/app ; Working directory for the appuser=appuser ; Run gunicorn as our non-root userautorestart=truediff --git a/deploy/docker/tests/conftest.py b/deploy/docker/tests/conftest.pynew file mode 100644index 00000000..80046645--- /dev/null+++ b/deploy/docker/tests/conftest.py@@ -0,0 +1,168 @@+"""+Shared fixtures for the Crawl4AI Docker server *behavioral* security tests.++Unlike the legacy `test_security_*.py` suites (which grep the source text and+pass even when the running server is wide open), these fixtures boot the real+FastAPI application via Starlette's TestClient and exercise it as a client+would. That makes the tests behavioral: they assert what the server actually+*does*, not what the source happens to contain.++Design notes+------------+* The app is imported once per session. `deploy/docker` is put on `sys.path`+ first, because `server.py` does `from crawler_pool import ...` at module top,+ before its own `sys.path.append`.+* The TestClient is created *without* the `with` context-manager form on+ purpose: that skips the FastAPI lifespan, so no Chromium is launched and no+ Redis connection is opened at startup. Authentication is decided by a+ dependency/middleware that runs before any route handler, so auth-posture+ assertions resolve before the app ever needs a browser or Redis.+* `offline_dns` / `rebinding_dns` monkeypatch name resolution so the SSRF /+ egress behavioral tests (R3) run fully offline and can model DNS-rebinding+ (resolve-then-reconnect TOCTOU) deterministically.+"""++import importlib+import socket+import sys+from pathlib import Path++import pytest++# deploy/docker (the dir that holds server.py, auth.py, ...) must be importable+# before we import `server`, since server.py imports its siblings by bare name.+DOCKER_DIR = Path(__file__).resolve().parents[1]+if str(DOCKER_DIR) not in sys.path:+ sys.path.insert(0, str(DOCKER_DIR))+++def pytest_configure(config):+ config.addinivalue_line(+ "markers",+ "posture: the secure-by-default acceptance gate (expected RED until R1-R7 land)",+ )+ config.addinivalue_line(+ "markers", "cve: regression test for a specific reported vulnerability"+ )++[email protected](scope="session")+def server_module():+ """Import the Docker server app once for the whole test session.++ Returns the imported `server` module so tests can introspect the loaded+ config, the redis-url builder, feature flags, etc.+ """+ # Import fresh; if a previous test mutated it we still want the real module.+ if "server" in sys.modules:+ return sys.modules["server"]+ return importlib.import_module("server")+++def stock_client(server_module):+ """A TestClient bound to the app as shipped (config.yml defaults).++ No lifespan => no real browser, no Redis connect. Auth/headers/routing are+ all exercised normally because they sit in front of the route handlers.+ """+ from starlette.testclient import TestClient++ # raise_server_exceptions=False so an un-gated handler that blows up on a+ # missing pool/redis surfaces as a 500 response (which our posture test+ # treats as "not 401" => still a finding) instead of bubbling out of the+ # test client as an exception.+ return TestClient(server_module.app, raise_server_exceptions=False)+++def effective_config(server_module):+ """The configuration dict the running app actually loaded."""+ return server_module.config+++def effective_browser_args(effective_config):+ """The Chromium launch flags the app will pass to every browser."""+ return list(effective_config["crawler"]["browser"].get("extra_args", []))+++def effective_redis_url(server_module):+ """The Redis URL the app builds from config + environment."""+ return server_module._build_redis_url(server_module.config)+++# ─────────────────────── offline DNS control ────────────────────────+# These let SSRF/egress tests run without touching the network and let us+# model DNS rebinding precisely.++class _FakeResolver:+ """Drop-in for socket.getaddrinfo with a controllable host->IP map.++ Unknown hosts resolve to a stable public-ish default so accidental real+ lookups never escape the test process.+ """++ DEFAULT_IP = "93.184.216.34" # documentation/example address space++ def __init__(self):+ self.map = {} # host -> ip (single answer)++ def set(self, host, ip):+ self.map[host] = ip++ def getaddrinfo(self, host, port, *args, **kwargs):+ ip = self.map.get(host, self.DEFAULT_IP)+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port or 0))]+++def offline_dns(monkeypatch):+ """Patch socket.getaddrinfo with a controllable, offline resolver.++ Usage:+ offline_dns.set("evil.example", "169.254.169.254")+ """+ resolver = _FakeResolver()+ monkeypatch.setattr(socket, "getaddrinfo", resolver.getaddrinfo)+ return resolver+++class _RebindingResolver:+ """Returns a *different* answer on the second+ lookup of the same host.++ Models the resolve-then-discard TOCTOU: validation sees a public IP, the+ later real connection re-resolves to an internal IP. A correct egress+ broker resolves once and pins, so the second (internal) answer is never+ dialed.+ """++ def __init__(self, host, first_ip, second_ip):+ self.host = host+ self.first_ip = first_ip+ self.second_ip = second_ip+ self.calls = 0++ def getaddrinfo(self, host, port, *args, **kwargs):+ if host == self.host:+ self.calls += 1+ ip = self.first_ip if self.calls == 1 else self.second_ip+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port or 0))]+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", port or 0))]+++def rebinding_dns(monkeypatch):+ """Factory that installs a DNS-rebinding resolver.++ Usage:+ r = rebinding_dns("rebind.example", "93.184.216.34", "169.254.169.254")+ ... # first lookup public, every later lookup internal+ """+ def _install(host, first_ip, second_ip):+ resolver = _RebindingResolver(host, first_ip, second_ip)+ monkeypatch.setattr(socket, "getaddrinfo", resolver.getaddrinfo)+ return resolver++ return _installdiff --git a/deploy/docker/tests/test_security_0_8_8.py b/deploy/docker/tests/test_security_0_8_8.pydeleted file mode 100644index 468ac584..00000000--- a/deploy/docker/tests/test_security_0_8_8.py+++ /dev/null@@ -1,158 +0,0 @@-"""-Behavioral tests for the 0.8.8 non-breaking security patch.--Each fix here is backward-compatible: features keep working, only the unsafe-behavior is closed. (The full secure-by-default redesign is the later major.)--Covers:- - SSRF blocklist gaps closed (NAT64 / 6to4 / :: / v4-mapped, not-is_global)- + opaque error (no resolved IP leak)- - output_path symlink/TOCTOU hardening (realpath containment + O_NOFOLLOW)- with the feature kept- - request-supplied LLM base_url ignored (key-exfil vector)- - env:SECRET_KEY exfil gadget blocked in LLMConfig (provider keys still work)- - CRLF-safe logging- - webhook header sanitization-"""--import os-import socket-import sys--import pytest--DOCKER_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))-if DOCKER_DIR not in sys.path:- sys.path.insert(0, DOCKER_DIR)---def _patch_dns(monkeypatch, ip):- def fake(host, port=None, *a, **k):- return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port or 0))]- monkeypatch.setattr(socket, "getaddrinfo", fake)---class TestSsrfGapsClosed:- @pytest.mark.parametrize("ip", [- "169.254.169.254", # metadata- "127.0.0.1", "10.0.0.5", "192.168.1.1", "100.64.0.1",- "::1", "::", # v6 loopback + unspecified (was a gap)- "::ffff:169.254.169.254", # v4-mapped metadata- "64:ff9b::a9fe:a9fe", # NAT64 -> 169.254.169.254 (was a gap)- "2002:a9fe:a9fe::1", # 6to4 embedding 169.254.169.254 (was a gap)- ])- def test_internal_blocked(self, monkeypatch, ip):- import utils- _patch_dns(monkeypatch, ip)- with pytest.raises(ValueError):- utils.validate_webhook_url("http://target.example/cb")-- @pytest.mark.parametrize("ip", ["8.8.8.8", "1.1.1.1"])- def test_public_allowed(self, monkeypatch, ip):- import utils- _patch_dns(monkeypatch, ip)- utils.validate_webhook_url("http://target.example/cb") # no raise-- def test_error_is_opaque(self, monkeypatch):- import utils- _patch_dns(monkeypatch, "169.254.169.254")- with pytest.raises(ValueError) as e:- utils.validate_webhook_url("http://target.example/")- assert "169.254" not in str(e.value) # no resolved-IP leak---class TestOutputPathHardening:- def test_symlink_escape_rejected(self, monkeypatch, tmp_path):- import utils- allowed = tmp_path / "outputs"- allowed.mkdir()- monkeypatch.setattr(utils, "ALLOWED_OUTPUT_DIR", str(allowed))- # Plant a symlinked subdir that points outside the allowed dir.- outside = tmp_path / "outside"- outside.mkdir()- (allowed / "evil").symlink_to(outside)- from fastapi import HTTPException- with pytest.raises(HTTPException):- utils.validate_output_path("evil/pwned.png") # realpath escapes-- def test_normal_path_ok(self, monkeypatch, tmp_path):- import utils- allowed = tmp_path / "outputs"- allowed.mkdir()- monkeypatch.setattr(utils, "ALLOWED_OUTPUT_DIR", str(allowed))- p = utils.validate_output_path("sub/shot.png")- assert p.startswith(str(allowed))-- def test_write_refuses_symlink_final_component(self, monkeypatch, tmp_path):- import utils- allowed = tmp_path / "outputs"- allowed.mkdir()- target = allowed / "shot.png"- # Pre-plant a symlink at the final path pointing at a secret.- secret = tmp_path / "secret"- secret.write_text("SECRET")- target.symlink_to(secret)- with pytest.raises(OSError):- utils.write_output_file(str(target), b"data") # O_NOFOLLOW refuses---class TestLlmBaseUrlIgnored:- def test_request_base_url_not_honored_in_source(self):- # base_url from the request must never be passed to the LLM call.- with open(os.path.join(DOCKER_DIR, "api.py")) as f:- src = f.read()- assert "base_url or get_llm_base_url" not in src- assert "base_url=get_llm_base_url(config" in src---class TestEnvSecretGuard:- def test_env_secret_key_blocked(self):- from crawl4ai.async_configs import LLMConfig- with pytest.raises(ValueError):- LLMConfig(api_token="env:SECRET_KEY")-- @pytest.mark.parametrize("name", ["REDIS_PASSWORD", "CRAWL4AI_API_TOKEN", "MY_PRIVATE_KEY"])- def test_other_secrets_blocked(self, name):- from crawl4ai.async_configs import LLMConfig- with pytest.raises(ValueError):- LLMConfig(api_token=f"env:{name}")-- def test_provider_key_still_works(self, monkeypatch):- from crawl4ai.async_configs import LLMConfig- monkeypatch.setenv("OPENAI_API_KEY", "sk-test-123")- cfg = LLMConfig(provider="openai/gpt-4o-mini", api_token="env:OPENAI_API_KEY")- assert cfg.api_token == "sk-test-123" # normal provider key unaffected---class TestCRLFSafeLogging:- def test_crlf_stripped(self):- import logging- from utils import CRLFSafeFilter- rec = logging.LogRecord("t", logging.INFO, __file__, 1,- "url=http://x/\r\nINJECTED login ok", None, None)- CRLFSafeFilter().filter(rec)- msg = rec.getMessage()- assert "\r" not in msg and "\n" not in msg and "INJECTED" in msg---class TestWebhookHeaderSanitization:- def test_crlf_value_rejected(self):- from webhook import sanitize_webhook_headers- with pytest.raises(ValueError):- sanitize_webhook_headers({"X-Foo": "bar\r\nInjected: 1"})-- @pytest.mark.parametrize("bad", ["Host", "Content-Length", "Authorization", "Cookie"])- def test_hop_by_hop_denied(self, bad):- from webhook import sanitize_webhook_headers- with pytest.raises(ValueError):- sanitize_webhook_headers({bad: "x"})-- def test_good_header_passes(self):- from webhook import sanitize_webhook_headers- assert sanitize_webhook_headers({"X-Trace-Id": "abc"}) == {"X-Trace-Id": "abc"}-- def test_schema_rejects_early(self):- from schemas import WebhookConfig- import pydantic- with pytest.raises(pydantic.ValidationError):- WebhookConfig(webhook_url="https://example.com/cb", webhook_headers={"Host": "evil"})diff --git a/deploy/docker/tests/test_security_0_8_9.py b/deploy/docker/tests/test_security_0_8_9.pydeleted file mode 100644index 2535b505..00000000--- a/deploy/docker/tests/test_security_0_8_9.py+++ /dev/null@@ -1,119 +0,0 @@-"""-Behavioral tests for the 0.8.9 non-breaking security patch.--Closes the proxy-injection SSRF class in the Docker server: an unauthenticated-/crawl could set a proxy (or proxy-redirecting Chromium flag) pointing at an-internal IP and route the browser through it, reaching internal services and-cloud metadata. The crawl-target URL was validated; the proxy address was not.--All fixes are backward compatible: a legitimate public proxy still works; only-non-global proxy hosts are rejected and dangerous --proxy/--host-resolver flags-are stripped from extra_args.-"""--import os-import sys--import pytest--DOCKER_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))-if DOCKER_DIR not in sys.path:- sys.path.insert(0, DOCKER_DIR)---class TestValidateProxyDestination:- # IP literals so getaddrinfo is numeric (no network needed).- @pytest.mark.parametrize("server", [- "http://169.254.169.254:8080", # cloud metadata- "http://127.0.0.1:8888",- "http://10.0.0.5:3128",- "http://192.168.1.10:3128",- "169.254.169.254:8080", # bare host:port (no scheme)- "socks5://10.1.2.3:1080",- "http://[::1]:8080", # ipv6 loopback- "http://[::ffff:169.254.169.254]:80", # v4-mapped metadata- ])- def test_internal_proxy_rejected(self, server):- import utils- with pytest.raises(ValueError):- utils.validate_proxy_destination(server)-- @pytest.mark.parametrize("server", [- "http://8.8.8.8:3128",- "https://1.1.1.1:443",- "8.8.8.8:3128",- ])- def test_public_proxy_allowed(self, server):- import utils- utils.validate_proxy_destination(server) # no raise-- def test_empty_is_noop(self):- import utils- utils.validate_proxy_destination("") # no raise- utils.validate_proxy_destination(None) # no raise---class TestScrubExtraArgs:- def test_strips_dangerous_flags(self):- import utils- args = [- "--headless",- "--proxy-server=http://10.0.0.1:3128",- "--host-resolver-rules=MAP * 169.254.169.254",- "--proxy-bypass-list=*",- "--proxy-pac-url=http://evil/p.pac",- "--disable-gpu",- ]- out = utils.scrub_browser_extra_args(args)- assert out == ["--headless", "--disable-gpu"]-- def test_keeps_benign(self):- import utils- args = ["--headless", "--no-sandbox", "--disable-dev-shm-usage"]- assert utils.scrub_browser_extra_args(args) == args-- def test_empty(self):- import utils- assert utils.scrub_browser_extra_args([]) == []- assert utils.scrub_browser_extra_args(None) is None---class TestEnforceProxySafety:- def test_browser_proxy_config_internal_400(self):- import api- from fastapi import HTTPException- from crawl4ai import BrowserConfig, ProxyConfig- b = BrowserConfig(proxy_config=ProxyConfig(server="http://169.254.169.254:8080"))- with pytest.raises(HTTPException) as e:- api._enforce_proxy_safety(b, None)- assert e.value.status_code == 400- assert "169.254" not in str(e.value.detail) # opaque-- def test_deprecated_proxy_field_internal_400(self):- import api- from fastapi import HTTPException- from crawl4ai import BrowserConfig- b = BrowserConfig(proxy="http://10.0.0.9:3128")- with pytest.raises(HTTPException):- api._enforce_proxy_safety(b, None)-- def test_crawler_proxy_config_internal_400(self):- import api- from fastapi import HTTPException- from crawl4ai import BrowserConfig, CrawlerRunConfig, ProxyConfig- c = CrawlerRunConfig(proxy_config=ProxyConfig(server="http://192.168.0.2:3128"))- with pytest.raises(HTTPException):- api._enforce_proxy_safety(BrowserConfig(), c)-- def test_extra_args_proxy_scrubbed(self):- import api- from crawl4ai import BrowserConfig- b = BrowserConfig(extra_args=["--proxy-server=http://10.0.0.1", "--headless"])- api._enforce_proxy_safety(b, None) # no raise (scrub, not block)- assert b.extra_args == ["--headless"]-- def test_public_proxy_passes(self):- import api- from crawl4ai import BrowserConfig, ProxyConfig- b = BrowserConfig(proxy_config=ProxyConfig(server="http://8.8.8.8:3128"))- api._enforce_proxy_safety(b, None) # no raisediff --git a/deploy/docker/tests/test_security_2026_04.py b/deploy/docker/tests/test_security_2026_04.pyindex e7ecebdd..9e00115a 100644--- a/deploy/docker/tests/test_security_2026_04.py+++ b/deploy/docker/tests/test_security_2026_04.py@@ -81,60 +81,55 @@ DEPLOY_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")# VULN 1: Arbitrary File Write - Path Traversal# ============================================================================-class TestPathTraversalBlocked(unittest.TestCase):- """Test validate_output_path blocks all traversal attempts."""+class TestOutputPathRemoved(unittest.TestCase):+ """output_path is gone; the server owns paths via the artifact store.++ The old string-only validate_output_path was bypassable (symlink/TOCTOU,+ sibling-prefix '...-evil') -> arbitrary write -> RCE. The fix is to never+ accept a caller path at all. Behavioral artifact-store coverage (O_NOFOLLOW,+ O_EXCL, hex id, TTL, quota) lives in test_security_artifact_store.py.+ """++ def test_screenshot_request_has_no_output_path(self):+ sys.path.insert(0, DEPLOY_DIR)+ from schemas import ScreenshotRequest+ self.assertNotIn("output_path", ScreenshotRequest.model_fields)++ def test_pdf_request_has_no_output_path(self):+ sys.path.insert(0, DEPLOY_DIR)+ from schemas import PDFRequest+ self.assertNotIn("output_path", PDFRequest.model_fields)++ def test_validate_output_path_deleted(self):+ sys.path.insert(0, DEPLOY_DIR)+ import utils+ self.assertFalse(+ hasattr(utils, "validate_output_path"),+ "validate_output_path must be deleted (caller paths no longer accepted)",+ )- def test_absolute_path_gets_jailed(self):- """Absolute paths get stripped and jailed inside allowed dir."""- result = validate_output_path("/app/server.py")- self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))- self.assertNotEqual(result, "/app/server.py")- def test_absolute_etc_passwd_gets_jailed(self):- result = validate_output_path("/etc/passwd")- self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))- self.assertNotEqual(result, "/etc/passwd")-- def test_relative_traversal_simple(self):- with self.assertRaises(ValueError):- validate_output_path("../../etc/passwd")-- def test_relative_traversal_deep(self):- with self.assertRaises(ValueError):- validate_output_path("foo/../../bar/../../../app/evil.py")-- def test_absolute_path_home_gets_jailed(self):- result = validate_output_path("/home/appuser/.bashrc")- self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))-- def test_absolute_path_tmp_outside_gets_jailed(self):- result = validate_output_path("/tmp/other-dir/evil.py")- self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))-- def test_simple_filename(self):- result = validate_output_path("test.png")- self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))- self.assertTrue(result.endswith("test.png"))-- def test_subdirectory(self):- result = validate_output_path("subdir/deep/test.png")- self.assertTrue(result.startswith(ALLOWED_OUTPUT_DIR))-- def test_filename_with_dots(self):- result = validate_output_path("my.screenshot.2024.png")- self.assertTrue(result.endswith("my.screenshot.2024.png"))+class TestPydanticPathValidator(unittest.TestCase):+ """output_path (and its traversal validator) are gone entirely.+ Traversal rejection used to be the mitigation; the real fix is that no+ caller path is accepted at all, so there is nothing to traverse. The+ sandboxed artifact store owns all paths now.+ """-class TestPydanticPathValidator(unittest.TestCase):- """Verify schemas.py has traversal rejection on output_path."""+ def test_no_output_path_field_on_request_models(self):+ sys.path.insert(0, DEPLOY_DIR)+ from schemas import ScreenshotRequest, PDFRequest+ self.assertNotIn("output_path", ScreenshotRequest.model_fields)+ self.assertNotIn("output_path", PDFRequest.model_fields)- def test_schemas_has_validator(self):- with open(os.path.join(DEPLOY_DIR, "schemas.py")) as f:- source = f.read()- self.assertIn("reject_traversal", source,- "schemas.py must have reject_traversal validator on output_path")- self.assertIn('".."', source,- "Validator must check for '..' traversal")+ def test_traversal_validator_removed(self):+ # No reject_traversal validator should remain registered on the models.+ sys.path.insert(0, DEPLOY_DIR)+ from schemas import ScreenshotRequest, PDFRequest+ for model in (ScreenshotRequest, PDFRequest):+ names = set(getattr(model, "__pydantic_decorators__").field_validators)+ self.assertNotIn("reject_traversal", names)# ============================================================================@@ -154,13 +149,30 @@ class TestMonitorAuthStructural(unittest.TestCase):returnself.fail("Could not find monitor_router include_router line")- def test_websocket_has_token_check(self):+ def test_websocket_auth_enforced_by_gate(self):+ """The monitor WS is gated by the AuthGateMiddleware (behavioral).++ Auth moved out of the route's bespoke, timing-unsafe env-token check+ and into the outermost ASGI gate, which closes an unauthenticated+ WebSocket before it is accepted.+ """+ import sys+ sys.path.insert(0, DEPLOY_DIR)+ import server+ from starlette.testclient import TestClient++ client = TestClient(server.app)+ # Unauthenticated connect must be rejected by the gate.+ with self.assertRaises(Exception):+ with client.websocket_connect("/monitor/ws") as ws:+ ws.receive_text()++ # The old in-route check must be gone (it read a different secret than+ # the REST path and compared with a timing-unsafe `!=`).with open(os.path.join(DEPLOY_DIR, "monitor_routes.py")) as f:source = f.read()- self.assertIn("CRAWL4AI_API_TOKEN", source,- "WebSocket endpoint must check CRAWL4AI_API_TOKEN")- self.assertIn("websocket.close", source,- "WebSocket must close connection on auth failure")+ self.assertNotIn('os.environ.get("CRAWL4AI_API_TOKEN"', source,+ "bespoke WS token check must be removed; the gate owns WS auth")# ============================================================================@@ -271,15 +283,20 @@ class TestSSRFBlocked(unittest.TestCase):class TestWebhookSourceChecks(unittest.TestCase):- def test_follow_redirects_disabled(self):+ def test_redirects_not_auto_followed(self):+ # Redirects are followed manually and re-validated per hop, never+ # auto-followed (which would skip the SSRF re-check).with open(os.path.join(DEPLOY_DIR, "webhook.py")) as f:source = f.read()- self.assertIn("follow_redirects=False", source)+ self.assertIn("allow_redirects=False", source)+ self.assertIn("check_redirect", source) # each hop re-validateddef test_webhook_validates_at_send_time(self):+ # Validation happens at send time via the egress broker (resolve_and_pin+ # rejects non-global targets); the connection is also pinned to that IP.with open(os.path.join(DEPLOY_DIR, "webhook.py")) as f:source = f.read()- self.assertIn("validate_webhook_url", source)+ self.assertIn("resolve_and_pin", source)def test_job_validates_webhook(self):with open(os.path.join(DEPLOY_DIR, "job.py")) as f:diff --git a/deploy/docker/tests/test_security_2026_04_b2.py b/deploy/docker/tests/test_security_2026_04_b2.pyindex 47e701b5..d6e2cbb2 100644--- a/deploy/docker/tests/test_security_2026_04_b2.py+++ b/deploy/docker/tests/test_security_2026_04_b2.py@@ -15,6 +15,7 @@ import astimport unittestimport builtinsimport types+from unittest import mockDEPLOY_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")@@ -35,13 +36,26 @@ class TestJWTSecretHardened(unittest.TestCase):"auth.py must not use 'mysecret' as env var default")def test_weak_secret_validation_exists(self):- """auth.py must validate against known weak secrets."""- with open(os.path.join(DEPLOY_DIR, "auth.py")) as f:- source = f.read()- self.assertIn("_WEAK_SECRETS", source,- "auth.py must have weak secrets blocklist")- self.assertIn("< 32", source,- "auth.py must enforce minimum key length")+ """auth.py must reject weak and too-short SECRET_KEY values (behavioral)."""+ import importlib+ import sys+ sys.path.insert(0, DEPLOY_DIR)+ auth = importlib.import_module("auth")++ # A known-weak secret must be rejected.+ with mock.patch.dict(os.environ, {"SECRET_KEY": "mysecret"}):+ with self.assertRaises(RuntimeError):+ auth.resolve_secret_key(required=True)++ # A too-short secret (< 32 chars) must be rejected.+ with mock.patch.dict(os.environ, {"SECRET_KEY": "short"}):+ with self.assertRaises(RuntimeError):+ auth.resolve_secret_key(required=True)++ # A strong secret must be accepted and returned unchanged.+ strong = "a" * 32+ with mock.patch.dict(os.environ, {"SECRET_KEY": strong}):+ self.assertEqual(auth.resolve_secret_key(required=True), strong)def test_mysecret_in_weak_list(self):"""'mysecret' must be in the weak secrets blocklist."""@@ -165,194 +179,69 @@ class TestExecuteJsDisabled(unittest.TestCase):# ============================================================================-# B2-V4: Hook Sandbox __builtins__ Escape-# ============================================================================--class TestHookSandboxBugreport(unittest.TestCase):- """Test the specific __builtins__ escape vector reported by by111."""-- @classmethod- def setUpClass(cls):- """Build hook sandbox exactly as hook_manager does."""- safe_builtins = {}- allowed_builtins = [- 'print', 'len', 'str', 'int', 'float', 'bool',- 'list', 'dict', 'set', 'tuple', 'range', 'enumerate',- 'zip', 'map', 'filter', 'any', 'all', 'sum', 'min', 'max',- 'sorted', 'reversed', 'abs', 'round', 'isinstance',- 'callable', 'iter', 'next',- ]- for name in allowed_builtins:- if hasattr(builtins, name):- safe_builtins[name] = getattr(builtins, name)- cls.safe_builtins = safe_builtins-- def _make_namespace(self):- import asyncio as _asyncio_mod- import json as _json_mod- import re as _re_mod- from typing import Dict, List, Optional-- def _safe_module(mod, exclude_attrs=None):- proxy = types.ModuleType(mod.__name__)- skip = {"__builtins__", "__loader__", "__spec__"}- if exclude_attrs:- skip.update(exclude_attrs)- for attr in dir(mod):- if attr in skip:- continue- try:- setattr(proxy, attr, getattr(mod, attr))- except (AttributeError, TypeError):- pass- return proxy-- namespace = {- '__name__': 'test_hook',- '__builtins__': dict(self.safe_builtins),- }- namespace["asyncio"] = _safe_module(_asyncio_mod, {- "subprocess", "create_subprocess_exec", "create_subprocess_shell"- })- namespace["json"] = _safe_module(_json_mod)- namespace["re"] = _safe_module(_re_mod)- namespace["Dict"] = Dict- namespace["List"] = List- namespace["Optional"] = Optional- return namespace-- # -- The exact attack from by111's report ---- def test_asyncio_builtins_import_blocked(self):- """asyncio.__builtins__['__import__'] must not be accessible."""- ns = self._make_namespace()- self.assertFalse(hasattr(ns["asyncio"], "__builtins__"),- "asyncio proxy must not have __builtins__")-- def test_json_builtins_import_blocked(self):- """json.__builtins__['__import__'] must not be accessible."""- ns = self._make_namespace()- self.assertFalse(hasattr(ns["json"], "__builtins__"),- "json proxy must not have __builtins__")-- def test_re_builtins_import_blocked(self):- """re.__builtins__['__import__'] must not be accessible."""- ns = self._make_namespace()- self.assertFalse(hasattr(ns["re"], "__builtins__"),- "re proxy must not have __builtins__")-- def test_module_loader_not_copied(self):- """Real module's __loader__ must not be copied to proxy."""- import asyncio as real_asyncio- ns = self._make_namespace()- # Proxy may have a default __loader__ from types.ModuleType,- # but it must NOT be the real module's loader- proxy_loader = getattr(ns["asyncio"], "__loader__", None)- real_loader = getattr(real_asyncio, "__loader__", None)- if proxy_loader is not None and real_loader is not None:- self.assertIsNot(proxy_loader, real_loader,- "Proxy must not have the real module's __loader__")-- def test_module_spec_not_copied(self):- """Real module's __spec__ must not be copied to proxy."""- import asyncio as real_asyncio- ns = self._make_namespace()- proxy_spec = getattr(ns["asyncio"], "__spec__", None)- real_spec = getattr(real_asyncio, "__spec__", None)- if proxy_spec is not None and real_spec is not None:- self.assertIsNot(proxy_spec, real_spec,- "Proxy must not have the real module's __spec__")-- def test_by111_exploit_via_asyncio(self):- """Exact exploit from by111: asyncio.__builtins__['__import__']('os')."""- ns = self._make_namespace()- code = '''-async def hook(page, **kw):- real_import = asyncio.__builtins__['__import__']- os = real_import('os')- return os.system('id')-'''- with self.assertRaises((AttributeError, KeyError, TypeError)):- exec(code, ns)- import asyncio- asyncio.get_event_loop().run_until_complete(ns['hook'](None))-- def test_getattr_not_in_builtins(self):- """getattr must not be available (enables attribute-based escape)."""- ns = self._make_namespace()- self.assertNotIn('getattr', ns['__builtins__'])-- def test_type_not_in_builtins(self):- """type must not be available (enables __subclasses__ MRO chain)."""- ns = self._make_namespace()- self.assertNotIn('type', ns['__builtins__'])-- def test_build_class_not_in_builtins(self):- """__build_class__ must not be available."""- ns = self._make_namespace()- self.assertNotIn('__build_class__', ns['__builtins__'])-- def test_hasattr_not_in_builtins(self):- """hasattr must not be available (information disclosure)."""- ns = self._make_namespace()- self.assertNotIn('hasattr', ns['__builtins__'])-- # -- asyncio still works for legitimate hooks ---- def test_asyncio_sleep_works(self):- ns = self._make_namespace()- self.assertTrue(hasattr(ns["asyncio"], "sleep"))-- def test_asyncio_gather_works(self):- ns = self._make_namespace()- self.assertTrue(hasattr(ns["asyncio"], "gather"))-- def test_json_loads_works(self):- ns = self._make_namespace()- self.assertTrue(hasattr(ns["json"], "loads"))-- def test_re_compile_works(self):- ns = self._make_namespace()- self.assertTrue(hasattr(ns["re"], "compile"))---# ============================================================================-# Source-level verification for hook_manager.py+# B2-V4: exec-based hook system removed (replaced by declarative registry)# ============================================================================-class TestHookManagerSourceClean(unittest.TestCase):- """Verify hook_manager.py source has all dangerous builtins removed."""-- def test_getattr_removed(self):- with open(os.path.join(DEPLOY_DIR, "hook_manager.py")) as f:- source = f.read()- tree = ast.parse(source)- for node in ast.walk(tree):- if isinstance(node, ast.Assign):- for target in node.targets:- if isinstance(target, ast.Name) and target.id == "allowed_builtins":- if isinstance(node.value, ast.List):- vals = [e.value for e in node.value.elts if isinstance(e, ast.Constant)]- self.assertNotIn("getattr", vals)- self.assertNotIn("setattr", vals)- self.assertNotIn("hasattr", vals)- self.assertNotIn("type", vals)- self.assertNotIn("__build_class__", vals)- return- self.fail("Could not find allowed_builtins in hook_manager.py")-- def test_safe_module_strips_builtins(self):- """_safe_module function must skip __builtins__."""- with open(os.path.join(DEPLOY_DIR, "hook_manager.py")) as f:- source = f.read()- self.assertIn("__builtins__", source)- self.assertIn("__loader__", source)- self.assertIn("__spec__", source)+class TestHookExecPathRemoved(unittest.TestCase):+ """The exec()/compile() hook system is gone; hooks are now declarative.++ No sandbox survives attacker Python in-process, so hook_manager.py was+ deleted and replaced by hook_registry.py (a fixed set of server-authored+ actions selected by name with schema-validated scalar params).+ """++ def test_hook_manager_module_deleted(self):+ self.assertFalse(+ os.path.exists(os.path.join(DEPLOY_DIR, "hook_manager.py")),+ "hook_manager.py (the exec-based hook system) must be deleted",+ )++ def test_no_exec_compile_eval_in_docker_layer(self):+ """The RCE primitives must be absent from the docker server code.++ Uses AST so it flags only bare-builtin calls (exec/eval/compile), not+ attribute calls like re.compile(...) or the words in comments/docstrings.+ """+ import ast+ import glob+ offenders = []+ for path in glob.glob(os.path.join(DEPLOY_DIR, "*.py")):+ with open(path) as f:+ tree = ast.parse(f.read(), filename=path)+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id in {"exec", "eval", "compile"}+ ):+ offenders.append((os.path.basename(path), node.func.id, node.lineno))+ self.assertEqual(offenders, [], f"bare exec/eval/compile call found: {offenders}")++ def test_registry_rejects_unknown_action(self):+ sys.path.insert(0, DEPLOY_DIR)+ from hook_registry import build_declarative_hooks, HookValidationError+ with self.assertRaises(HookValidationError):+ build_declarative_hooks([{"action": "run_python", "params": {"code": "x"}}])++ def test_registry_rejects_bad_params(self):+ sys.path.insert(0, DEPLOY_DIR)+ from hook_registry import build_declarative_hooks, HookValidationError+ with self.assertRaises(HookValidationError):+ build_declarative_hooks([{"action": "block_resources", "params": {"resource_types": ["script"]}}])++ def test_registry_builds_valid_hooks(self):+ sys.path.insert(0, DEPLOY_DIR)+ from hook_registry import build_declarative_hooks+ hooks = build_declarative_hooks([+ {"action": "block_resources", "params": {"resource_types": ["image"]}},+ {"action": "scroll_to_bottom", "params": {"max_steps": 5}},+ ])+ # block_resources -> on_page_context_created, scroll -> before_retrieve_html+ self.assertIn("on_page_context_created", hooks)+ self.assertIn("before_retrieve_html", hooks)+ for fn in hooks.values():+ self.assertTrue(callable(fn))if __name__ == "__main__":- print("=" * 70)- print("Crawl4AI Security Tests - Batch 2 (2026-04-14)")- print("=" * 70)- print()- unittest.main(verbosity=2)+ unittest.main()diff --git a/deploy/docker/tests/test_security_artifact_store.py b/deploy/docker/tests/test_security_artifact_store.pynew file mode 100644index 00000000..80b095dc--- /dev/null+++ b/deploy/docker/tests/test_security_artifact_store.py@@ -0,0 +1,108 @@+"""+R4 artifact-store behavioral tests: the server owns the directory, names and+bytes. Writes are O_EXCL|O_NOFOLLOW 0600; retrieval requires a 32-hex id,+refuses symlinks/non-regular files, and enforces a TTL.+"""++import os+import time++import pytest+++def store(tmp_path, monkeypatch):+ """Point the artifact store at an isolated temp dir and reload it."""+ monkeypatch.setenv("CRAWL4AI_ARTIFACT_DIR", str(tmp_path / "art"))+ monkeypatch.setenv("CRAWL4AI_MAX_ARTIFACT_BYTES", "1024")+ monkeypatch.setenv("CRAWL4AI_ARTIFACT_QUOTA_BYTES", "4096")+ monkeypatch.setenv("CRAWL4AI_ARTIFACT_TTL_SECONDS", "3600")+ import importlib+ import artifacts+ importlib.reload(artifacts)+ artifacts.init_store()+ yield artifacts+ importlib.reload(artifacts) # restore defaults for other tests+++pytestmark = pytest.mark.posture+++class TestWrite:+ def test_write_returns_hex_id_and_meta(self, store):+ meta = store.write_artifact("png", b"\x89PNG data")+ assert len(meta["artifact_id"]) == 32 and all(c in "0123456789abcdef" for c in meta["artifact_id"])+ assert meta["mime"] == "image/png" and meta["size"] == len(b"\x89PNG data")++ def test_dir_is_0700_and_file_0600(self, store):+ meta = store.write_artifact("pdf", b"%PDF-1.4")+ assert oct(os.stat(store.ARTIFACT_DIR).st_mode)[-3:] == "700"+ path, _ = store.resolve_artifact(meta["artifact_id"])+ assert oct(os.stat(path).st_mode)[-3:] == "600"++ def test_oversize_rejected(self, store):+ with pytest.raises(store.ArtifactTooLarge):+ store.write_artifact("png", b"x" * 2048) # cap is 1024++ def test_quota_enforced(self, store):+ for _ in range(4):+ store.write_artifact("png", b"x" * 1000)+ with pytest.raises(store.QuotaExceeded):+ store.write_artifact("png", b"x" * 1000) # would exceed 4096+++class TestResolve:+ def test_roundtrip(self, store):+ meta = store.write_artifact("png", b"hello")+ path, mime = store.resolve_artifact(meta["artifact_id"])+ assert mime == "image/png"+ with open(path, "rb") as f:+ assert f.read() == b"hello"++ @pytest.mark.parametrize("bad", ["../etc/passwd", "..", "g" * 32, "abc", "/etc/passwd", "a" * 31])+ def test_non_hex_or_traversal_404(self, store, bad):+ with pytest.raises(store.ArtifactNotFound):+ store.resolve_artifact(bad)++ def test_symlink_not_followed(self, store):+ # Plant a symlink named like a valid artifact pointing at a secret.+ secret = os.path.join(store.ARTIFACT_DIR, "secret.txt")+ with open(secret, "wb") as f:+ f.write(b"TOPSECRET")+ fake_id = "a" * 32+ link = os.path.join(store.ARTIFACT_DIR, fake_id + ".png")+ os.symlink(secret, link)+ with pytest.raises(store.ArtifactNotFound):+ store.resolve_artifact(fake_id) # lstat sees a symlink -> refuse++ def test_ttl_expired_404_and_reaped(self, store):+ meta = store.write_artifact("png", b"old")+ path, _ = store.resolve_artifact(meta["artifact_id"])+ old = time.time() - 7200 # 2h ago, TTL is 1h+ os.utime(path, (old, old))+ with pytest.raises(store.ArtifactNotFound):+ store.resolve_artifact(meta["artifact_id"])+ assert not os.path.exists(path) # resolve reaped it+++class TestWriteIsExclusiveAndNoFollow:+ def test_write_uses_oexcl_nofollow(self, store):+ import inspect+ src = inspect.getsource(store.write_artifact)+ assert "O_EXCL" in src and "O_NOFOLLOW" in src+++class TestJanitor:+ def test_janitor_removes_symlinks_and_expired(self, store):+ meta = store.write_artifact("png", b"keep")+ # expired regular file+ old_meta = store.write_artifact("pdf", b"old")+ op, _ = store.resolve_artifact(old_meta["artifact_id"])+ past = time.time() - 7200+ os.utime(op, (past, past))+ # a planted symlink+ os.symlink("/etc/passwd", os.path.join(store.ARTIFACT_DIR, "deadbeef" * 4 + ".png"))+ reaped = store.janitor()+ assert reaped >= 2+ # the fresh one survives+ store.resolve_artifact(meta["artifact_id"])diff --git a/deploy/docker/tests/test_security_authz.py b/deploy/docker/tests/test_security_authz.pynew file mode 100644index 00000000..0c0da4ee--- /dev/null+++ b/deploy/docker/tests/test_security_authz.py@@ -0,0 +1,116 @@+"""+Behavioral authorization tests for R1 (beyond the blanket default-deny gate):++ * admin scope - monitor destructive actions require an admin principal;+ a valid data-scope token is allowed past the gate but+ rejected (403) by require_admin.+ * MCP no-laundering - the MCP tool proxy authenticates its internal loopback+ call (it no longer relies on the endpoints being open).+ * job ownership - a task records its owner; a different requester gets 404+ (not 403), and an admin can read any task.++These exercise the running app, not its source text.+"""++import pytest++pytestmark = pytest.mark.posture++from auth import create_access_token # noqa: E402+++def _bearer(token: str) -> dict:+ return {"Authorization": f"Bearer {token}"}+++# ───────────────────────────── admin scope ─────────────────────────────+class TestAdminScope:+ def test_data_scope_cannot_reset_stats(self, stock_client):+ data_tok = create_access_token({"sub": "[email protected]"}, scope="data")+ r = stock_client.post("/monitor/stats/reset", headers=_bearer(data_tok))+ assert r.status_code == 403, f"data-scope reached admin action: {r.status_code}"++ def test_data_scope_cannot_kill_browser(self, stock_client):+ data_tok = create_access_token({"sub": "[email protected]"}, scope="data")+ r = stock_client.post(+ "/monitor/actions/kill_browser", json={"sig": "abc"}, headers=_bearer(data_tok)+ )+ assert r.status_code == 403++ def test_admin_scope_passes_require_admin(self, stock_client):+ admin_tok = create_access_token({"sub": "[email protected]"}, scope="admin")+ r = stock_client.post("/monitor/stats/reset", headers=_bearer(admin_tok))+ # Past require_admin: not a 401/403. (500 acceptable here: no monitor+ # singleton without a lifespan — the point is authz let it through.)+ assert r.status_code not in (401, 403), f"admin blocked: {r.status_code}"++ def test_unauthenticated_admin_action_is_401(self, stock_client):+ r = stock_client.post("/monitor/stats/reset")+ assert r.status_code == 401+++# ────────────────────────── MCP no-laundering ──────────────────────────+class TestMcpNoLaundering:+ def test_mcp_proxy_attaches_service_credential(self):+ """The internal loopback proxy must carry a valid, data-scope token."""+ import mcp_bridge+ from auth import decode_token++ headers = mcp_bridge._service_auth_headers()+ assert "Authorization" in headers+ scheme, _, token = headers["Authorization"].partition(" ")+ assert scheme == "Bearer" and token+ claims = decode_token(token)+ assert claims["scope"] == "data", "MCP service token must not be admin-scoped"++ def test_mcp_base_url_is_loopback(self, server_module):+ """The MCP proxy must target loopback, never the 0.0.0.0 bind address."""+ import inspect+ src = inspect.getsource(server_module)+ assert "http://127.0.0.1:" in src+ assert 'base_url=f"http://{config' not in src+++# ─────────────────────────── job ownership ─────────────────────────────+class _FakeRedis:+ """Minimal async Redis stub holding one task hash."""++ def __init__(self, task):+ # Real redis returns bytes keys/values; decode_redis_hash expects that.+ self._task = {k.encode(): str(v).encode() for k, v in task.items()}++ async def hgetall(self, key):+ return dict(self._task)++ async def delete(self, key):+ self._task = {}+++class TestJobOwnership:+ async def _status(self, task, **kw):+ import api+ redis = _FakeRedis(task)+ return await api.handle_task_status(+ redis, "crawl_abc", base_url="http://t/", keep=True, **kw+ )++ async def test_owner_can_read_own_task(self):+ task = {"status": "completed", "created_at": "2026-01-01T00:00:00",+ "url": "[]", "result": "{}", "owner": "[email protected]"}+ resp = await self._status(task, requester="[email protected]", is_admin=False)+ assert resp.status_code == 200++ async def test_other_requester_gets_404_not_403(self):+ from fastapi import HTTPException+ task = {"status": "completed", "created_at": "2026-01-01T00:00:00",+ "url": "[]", "result": "{}", "owner": "[email protected]"}+ with pytest.raises(HTTPException) as exc:+ await self._status(task, requester="[email protected]", is_admin=False)+ assert exc.value.status_code == 404 # not 403: don't reveal existence++ async def test_admin_can_read_any_task(self):+ task = {"status": "completed", "created_at": "2026-01-01T00:00:00",+ "url": "[]", "result": "{}", "owner": "[email protected]"}+ resp = await self._status(task, requester="[email protected]", is_admin=True)+ assert resp.status_code == 200diff --git a/deploy/docker/tests/test_security_container_posture.py b/deploy/docker/tests/test_security_container_posture.pynew file mode 100644index 00000000..46c032db--- /dev/null+++ b/deploy/docker/tests/test_security_container_posture.py@@ -0,0 +1,114 @@+"""+R7 container/deployment posture - static parse of the deployment artifacts.++These assert the hardening is declared in the Dockerfile / docker-compose.yml /+supervisord.conf. The RUNTIME acceptance gate (the hardened image builds,+Chromium starts without --no-sandbox under userns/seccomp, the read-only rootfs++ tmpfs work, redis truly requires auth) needs an actual `docker build` + boot+and is tracked as build-gated; it is out of scope for this offline suite.+"""++import os+import re++import pytest++pytestmark = pytest.mark.posture++REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", ".."))+DOCKER_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))+++def _read(path):+ with open(path) as f:+ return f.read()++[email protected](scope="module")+def dockerfile():+ return _read(os.path.join(REPO_ROOT, "Dockerfile"))++[email protected](scope="module")+def compose():+ return _read(os.path.join(REPO_ROOT, "docker-compose.yml"))++[email protected](scope="module")+def supervisord():+ return _read(os.path.join(DOCKER_DIR, "supervisord.conf"))+++class TestDockerfile:+ def test_no_redis_expose(self, dockerfile):+ # No active EXPOSE 6379 line (commented references are fine).+ for line in dockerfile.splitlines():+ stripped = line.strip()+ if stripped.startswith("#"):+ continue+ assert not re.match(r"EXPOSE\s+.*\b6379\b", stripped), \+ "redis port 6379 must not be EXPOSEd"++ def test_app_dir_root_owned_readonly(self, dockerfile):+ assert "chown -R root:root ${APP_HOME}" in dockerfile+ assert "chmod -R a-w ${APP_HOME}" in dockerfile++ def test_artifact_dir_created_0700(self, dockerfile):+ assert "/var/lib/crawl4ai/outputs" in dockerfile+ assert "chmod 700 /var/lib/crawl4ai/outputs" in dockerfile++ def test_runs_as_non_root(self, dockerfile):+ assert re.search(r"^USER\s+appuser", dockerfile, re.MULTILINE)+++class TestSupervisord:+ def test_redis_requires_password(self, supervisord):+ assert "--requirepass" in supervisord++ def test_redis_bound_loopback(self, supervisord):+ assert "--bind 127.0.0.1" in supervisord++ def test_gunicorn_bind_is_env_driven(self, supervisord):+ # entrypoint.sh resolves GUNICORN_BIND (loopback unless a credential).+ assert "ENV_GUNICORN_BIND" in supervisord++ def test_gunicorn_request_limits(self, supervisord):+ assert "--limit-request-line" in supervisord+++class TestCompose:+ def test_cap_drop_all(self, compose):+ assert "cap_drop" in compose and "ALL" in compose++ def test_no_new_privileges(self, compose):+ assert "no-new-privileges:true" in compose++ def test_read_only_rootfs(self, compose):+ assert re.search(r"read_only:\s*true", compose)++ def test_no_host_dev_shm_bind(self, compose):+ assert "/dev/shm:/dev/shm" not in compose+ assert "shm_size" in compose++ def test_pids_limit(self, compose):+ assert "pids_limit" in compose+++class TestEntrypoint:+ def test_entrypoint_exists_and_resolves_bind(self):+ src = _read(os.path.join(DOCKER_DIR, "entrypoint.sh"))+ assert "GUNICORN_BIND" in src and "REDIS_PASSWORD" in src+ assert "127.0.0.1" in src # loopback default when no credential+++class TestSandboxOptOut:+ def test_default_keeps_no_sandbox(self, server_module, monkeypatch):+ monkeypatch.setattr(server_module, "CHROMIUM_SANDBOX", False)+ assert "--no-sandbox" in server_module._browser_extra_args()++ def test_opt_in_drops_no_sandbox(self, server_module, monkeypatch):+ # CRAWL4AI_CHROMIUM_SANDBOX=true -> run the renderer sandboxed.+ monkeypatch.setattr(server_module, "CHROMIUM_SANDBOX", True)+ assert "--no-sandbox" not in server_module._browser_extra_args()+ # other flags are preserved+ assert "--disable-dev-shm-usage" in server_module._browser_extra_args()diff --git a/deploy/docker/tests/test_security_default_posture.py b/deploy/docker/tests/test_security_default_posture.pynew file mode 100644index 00000000..4020548e--- /dev/null+++ b/deploy/docker/tests/test_security_default_posture.py@@ -0,0 +1,195 @@+"""+HEADLINE SECURITY POSTURE GATE — test_security_default_posture++This is the acceptance gate for the Docker-server security hardening+(root causes R1-R7). It boots the server *with the shipped config.yml* and+asserts the secure-by-default end state:++ - every mutating + read endpoint, static mount, and MCP transport requires+ auth out of the box (R1); only the health check is public,+ - the token endpoint will not freely mint credentials when no api_token /+ secret is configured (R1),+ - strong security headers + a strict CSP are present on every response even+ when `security.enabled` is false (R6),+ - the effective browser launch flags carry no `--no-sandbox` and no+ TLS-verification-disabling flags (R3/R7),+ - Redis requires a password and security is on by default (R7),+ - dangerous request->code features are off by default (R2).++IT IS EXPECTED TO BE RED TODAY. Each failing assertion names one gap the+hardening must close. As R1-R7 land, methods flip green; when the whole class+is green, the default Docker deploy is safe and CI can gate on it.++Run: pytest deploy/docker/tests/test_security_default_posture.py -v+"""++import pytest++pytestmark = pytest.mark.posture++HEALTH = "/health"++# (method, path, json-body-or-None) for every endpoint that must NOT be+# reachable without authentication. Bodies are intentionally minimal/invalid so+# that in the *current* (open) state the request fails fast at validation+# rather than launching a real crawl — the assertion (== 401) still fails,+# which is the RED signal we want, with no browser/network side effects.+PROTECTED_ENDPOINTS = [+ # mutating / action endpoints+ ("post", "/crawl", {}),+ ("post", "/crawl/stream", {}),+ ("post", "/md", {}),+ ("post", "/html", {}),+ ("post", "/screenshot", {}),+ ("post", "/pdf", {}),+ ("post", "/execute_js", {}),+ ("post", "/config/dump", {}),+ ("post", "/crawl/job", {}),+ ("post", "/llm/job", {}),+ # monitor mutating actions (must additionally require *admin* scope; here we+ # only assert they are not anonymously reachable). Pools are empty without a+ # lifespan, so probing these performs no destructive action.+ ("post", "/monitor/actions/cleanup", {}),+ ("post", "/monitor/actions/kill_browser", {}),+ ("post", "/monitor/actions/restart_browser", {}),+ ("post", "/monitor/stats/reset", {}),+ # read / info endpoints that currently have NO auth dependency at all+ ("get", "/schema", None),+ ("get", "/hooks/info", None),+ ("get", "/ask", None),+ ("get", "/metrics", None),+ ("get", "/llm/example.com", None), # no `q` -> fast 400 today, must be 401+ ("get", "/monitor/health", None),+ ("get", "/monitor/requests", None),+ ("get", "/monitor/browsers", None),+ ("get", "/monitor/endpoints/stats", None),+ ("get", "/monitor/timeline", None),+ # MCP transport (must be gated; today it is open AND launders credentials)+ ("get", "/mcp/schema", None),+ # static mounts (dashboard / playground served unauthenticated today)+ ("get", "/dashboard/", None),+ ("get", "/playground/", None),+]+++def _call(client, method, path, body):+ fn = getattr(client, method)+ if body is not None:+ return fn(path, json=body)+ return fn(path)+++class TestDefaultDeployIsSafe:+ """The shipped Docker image must be secure with an empty/default config."""++ # ───────────────────────── R1: authentication ─────────────────────────++ def test_health_check_is_public(self, stock_client):+ """The health endpoint is the one intentionally public route."""+ r = stock_client.get(HEALTH)+ assert r.status_code == 200++ @pytest.mark.parametrize(+ "method,path,body",+ PROTECTED_ENDPOINTS,+ ids=[f"{m.upper()} {p}" for m, p, _ in PROTECTED_ENDPOINTS],+ )+ def test_endpoint_requires_auth_by_default(self, stock_client, method, path, body):+ """Without a credential, every non-health route must refuse (401)."""+ r = _call(stock_client, method, path, body)+ assert r.status_code == 401, (+ f"{method.upper()} {path} returned {r.status_code} unauthenticated; "+ f"expected 401. Endpoint is reachable without a credential."+ )++ def test_token_endpoint_does_not_freely_mint(self, stock_client, server_module, monkeypatch):+ """With no api_token configured, /token must not hand a JWT to anyone.++ Force the email-domain MX check to pass so the test exercises the real+ vulnerability (anonymous token minting) rather than passing for the+ wrong reason when offline.+ """+ monkeypatch.setattr(server_module, "verify_email_domain", lambda email: True)+ r = stock_client.post("/token", json={"email": "[email protected]"})+ if r.status_code == 200:+ assert "access_token" not in r.json(), (+ "/token minted a credential for an anonymous caller with no "+ "api_token configured — anyone can self-issue a valid JWT."+ )++ # ─────────────────────── R6: headers / CSP / framing ──────────────────++ def test_security_headers_present_by_default(self, stock_client):+ """Baseline security headers must be emitted even when security.enabled is false."""+ r = stock_client.get(HEALTH)+ h = {k.lower(): v for k, v in r.headers.items()}+ assert h.get("x-content-type-options") == "nosniff"+ assert h.get("x-frame-options", "").upper() == "DENY"+ assert "content-security-policy" in h, "no CSP header on a default response"++ def test_csp_is_strict(self, stock_client):+ """CSP must lock script execution to self and forbid inline/unsafe + framing."""+ r = stock_client.get(HEALTH)+ csp = r.headers.get("content-security-policy", "")+ assert "script-src 'self'" in csp, f"CSP missing strict script-src: {csp!r}"+ assert "frame-ancestors 'none'" in csp, f"CSP allows framing: {csp!r}"+ assert "unsafe-inline" not in csp, f"CSP permits unsafe-inline: {csp!r}"++ # ─────────────────── R3 / R7: browser & TLS launch flags ───────────────++ @pytest.mark.xfail(+ reason="build-gated: --no-sandbox stays until the container runs with an "+ "unprivileged userns or a verified seccomp profile and a docker build "+ "confirms Chromium still starts. Tracked, not yet done.",+ strict=False,+ )+ def test_no_no_sandbox_flag(self, effective_browser_args):+ """Chromium must not run with --no-sandbox by default (renderer escape)."""+ assert "--no-sandbox" not in effective_browser_args, (+ "default config launches Chromium with --no-sandbox"+ )++ def test_tls_verification_not_disabled(self, effective_browser_args):+ """TLS verification must not be disabled by default."""+ assert "--ignore-certificate-errors" not in effective_browser_args+ assert "--allow-insecure-localhost" not in effective_browser_args++ # ───────────────────────── R7: deploy posture ─────────────────────────++ def test_security_enabled_by_default(self, effective_config):+ """The security middleware block must be on out of the box."""+ assert effective_config["security"]["enabled"] is True++ def test_redis_is_not_network_exposed(self, effective_redis_url, effective_config):+ """Redis must not be open on the network: loopback host or a password.++ The container runs redis loopback-only with --requirepass (supervisord)+ and no EXPOSE (asserted in the container-posture suite); a password also+ satisfies this for an external redis.+ """+ rc = effective_config.get("redis", {})+ host = str(rc.get("host", "localhost")).lower()+ pw = rc.get("password", "") or ""+ loopback = host in ("localhost", "127.0.0.1", "::1")+ assert loopback or pw, (+ "redis is neither loopback-bound nor password-protected"+ )++ def test_trusted_hosts_not_wildcard_when_exposed(self, effective_config):+ """A wildcard trusted_hosts on a non-loopback bind silently disables the host guard."""+ host = effective_config["app"]["host"]+ trusted = effective_config["security"]["trusted_hosts"]+ exposed = host not in ("127.0.0.1", "localhost", "::1")+ assert not (exposed and trusted == ["*"]), (+ f"app binds {host} but trusted_hosts is {trusted} (host guard disabled)"+ )++ # ───────────────────── R2: dangerous features off by default ───────────++ def test_hooks_disabled_by_default(self, server_module):+ """User-supplied hook code (exec path) must be off unless explicitly enabled."""+ assert server_module.HOOKS_ENABLED is False++ def test_execute_js_disabled_by_default(self, server_module):+ """Arbitrary JS execution endpoint must be off unless explicitly enabled."""+ assert server_module.EXECUTE_JS_ENABLED is Falsediff --git a/deploy/docker/tests/test_security_download_traversal.py b/deploy/docker/tests/test_security_download_traversal.pynew file mode 100644index 00000000..9af745a0--- /dev/null+++ b/deploy/docker/tests/test_security_download_traversal.py@@ -0,0 +1,100 @@+"""Path-traversal regression tests for crawler file downloads.++Y4tacker reported an arbitrary-file-write -> RCE: a download filename taken+from an attacker-controlled Content-Disposition header (HTTP strategy) or the+browser's suggested filename (Playwright strategy) was joined to the downloads+dir with no confinement, so an absolute path or ``../`` sequence escaped it.++Both call sites now route through ``_safe_download_filepath``, which reduces+the name to a bare basename and re-checks containment. These tests exercise+that helper directly (offline, no network/browser).+"""++import os+import tempfile++import pytest++from crawl4ai.async_crawler_strategy import _safe_download_filepath, _nofollow_opener++pytestmark = pytest.mark.posture+++def downloads_dir():+ with tempfile.TemporaryDirectory() as d:+ yield d+++class TestDownloadPathConfinement:+ def test_plain_filename_kept(self, downloads_dir):+ p = _safe_download_filepath(downloads_dir, "report.pdf")+ assert p == os.path.join(os.path.realpath(downloads_dir), "report.pdf")++ @pytest.mark.parametrize(+ "evil",+ [+ "/etc/cron.d/evil",+ "/tmp/pwned_absolute.sh",+ "../../../.bashrc",+ "../../.ssh/authorized_keys",+ "../../../../etc/passwd",+ "..",+ ".",+ "",+ "foo/../../bar",+ ],+ )+ def test_escape_attempts_confined(self, downloads_dir, evil):+ """No input may produce a path outside the downloads root."""+ root = os.path.realpath(downloads_dir)+ p = _safe_download_filepath(downloads_dir, evil)+ assert os.path.commonpath([root, p]) == root+ # The resolved file sits directly inside the root (basename only).+ assert os.path.dirname(p) == root++ def test_absolute_path_does_not_win(self, downloads_dir):+ p = _safe_download_filepath(downloads_dir, "/etc/cron.d/evil")+ assert not p.startswith("/etc/")+ assert p.startswith(os.path.realpath(downloads_dir))++ def test_symlink_escape_rejected(self, downloads_dir):+ """If the basename is an existing symlink in the root pointing out,+ realpath resolves outside the root and the write must be rejected."""+ root = os.path.realpath(downloads_dir)+ outside_dir = tempfile.mkdtemp()+ outside_file = os.path.join(outside_dir, "target")+ link = os.path.join(root, "evil")+ os.symlink(outside_file, link)+ # filename "evil" -> root/evil is a symlink to outside -> rejected.+ with pytest.raises(ValueError):+ _safe_download_filepath(downloads_dir, "evil")+++class TestNoFollowOpener:+ """The write must refuse to follow a symlink swapped in after path+ confinement (the TOCTOU window between realpath-check and open)."""++ def test_open_refuses_symlink_target(self, downloads_dir):+ import os+ outside = tempfile.mkdtemp()+ outside_file = os.path.join(outside, "secret")+ with open(outside_file, "w") as f:+ f.write("original")+ # Attacker swaps the confined target for a symlink pointing outside.+ target = os.path.join(downloads_dir, "report.pdf")+ os.symlink(outside_file, target)+ with pytest.raises(OSError): # ELOOP from O_NOFOLLOW+ with open(target, "wb", opener=_nofollow_opener) as f:+ f.write(b"pwned")+ # The outside file was not overwritten through the symlink.+ with open(outside_file) as f:+ assert f.read() == "original"++ def test_open_writes_normal_file(self, downloads_dir):+ import os+ target = os.path.join(downloads_dir, "ok.bin")+ with open(target, "wb", opener=_nofollow_opener) as f:+ f.write(b"data")+ with open(target, "rb") as f:+ assert f.read() == b"data"diff --git a/deploy/docker/tests/test_security_egress_proxy.py b/deploy/docker/tests/test_security_egress_proxy.pynew file mode 100644index 00000000..03ebae1e--- /dev/null+++ b/deploy/docker/tests/test_security_egress_proxy.py@@ -0,0 +1,132 @@+"""+R3 browser egress-proxy tests (real loopback sockets, fully offline).++The pinning proxy is what actually stops DNS rebinding on the browser path:+Chromium is pointed at it, so it asks the proxy to CONNECT host:port; the proxy+resolves-and-pins (egress_broker.resolve_and_pin) and dials only the pinned,+global IP. We drive it with a raw asyncio client + a fake upstream, and stub+resolve_and_pin so a "public" host pins to the loopback upstream while an+"internal" host is refused. (The not-is_global rule itself is covered in+test_security_ssrf_egress.py.)+"""++import asyncio++import pytest++import egress_proxy+from egress_broker import EgressBlocked, PinnedTarget+from egress_proxy import PinningProxy++pytestmark = pytest.mark.posture+++async def _fake_upstream():+ async def handle(reader, writer):+ await reader.read(65536)+ writer.write(b"UPSTREAM-OK")+ await writer.drain()+ writer.close()+ server = await asyncio.start_server(handle, "127.0.0.1", 0)+ return server, server.sockets[0].getsockname()[1]+++class TestPinningProxy:+ async def test_connect_to_global_host_tunnels(self, monkeypatch):+ up, up_port = await _fake_upstream()++ # Pin "good.example" to the loopback upstream (stand-in for a global IP).+ def fake_pin(url):+ return PinnedTarget("https", "good.example", up_port, "127.0.0.1")+ monkeypatch.setattr(egress_proxy, "resolve_and_pin", fake_pin)++ proxy = PinningProxy()+ await proxy.start()+ try:+ r, w = await asyncio.open_connection(proxy.bound_host, proxy.bound_port)+ w.write(f"CONNECT good.example:{up_port} HTTP/1.1\r\n\r\n".encode())+ await w.drain()+ status = await asyncio.wait_for(r.readline(), timeout=5)+ assert b"200" in status+ await r.readline() # blank line after the 200+ w.write(b"hello")+ await w.drain()+ body = await asyncio.wait_for(r.read(100), timeout=5)+ assert b"UPSTREAM-OK" in body+ w.close()+ finally:+ await proxy.stop()+ up.close()++ async def test_connect_to_internal_host_blocked(self, monkeypatch):+ def fake_pin(url):+ raise EgressBlocked()+ monkeypatch.setattr(egress_proxy, "resolve_and_pin", fake_pin)++ proxy = PinningProxy()+ await proxy.start()+ try:+ r, w = await asyncio.open_connection(proxy.bound_host, proxy.bound_port)+ w.write(b"CONNECT evil.example:443 HTTP/1.1\r\n\r\n")+ await w.drain()+ status = await asyncio.wait_for(r.readline(), timeout=5)+ assert b"403" in status+ w.close()+ finally:+ await proxy.stop()++ async def test_proxy_dials_pinned_ip_not_requested_host(self, monkeypatch):+ # resolve_and_pin returns a pinned ip distinct from the CONNECT host;+ # assert the proxy dials the pinned ip.+ dialed = {}+ up, up_port = await _fake_upstream()++ def fake_pin(url):+ return PinnedTarget("https", "rebind.example", up_port, "127.0.0.1")+ monkeypatch.setattr(egress_proxy, "resolve_and_pin", fake_pin)++ real_open = asyncio.open_connection++ async def spy_open(host, port, *a, **k):+ dialed["host"], dialed["port"] = host, port+ return await real_open(host, port, *a, **k)+ # patch only the name the proxy module uses+ monkeypatch.setattr(egress_proxy.asyncio, "open_connection", spy_open)++ proxy = PinningProxy()+ await proxy.start()+ try:+ r, w = await real_open(proxy.bound_host, proxy.bound_port)+ w.write(f"CONNECT rebind.example:{up_port} HTTP/1.1\r\n\r\n".encode())+ await w.drain()+ await asyncio.wait_for(r.readline(), timeout=5)+ assert dialed.get("host") == "127.0.0.1" # the pinned ip+ w.close()+ finally:+ await proxy.stop()+ up.close()++ async def test_malformed_connect_400(self):+ proxy = PinningProxy()+ await proxy.start()+ try:+ r, w = await asyncio.open_connection(proxy.bound_host, proxy.bound_port)+ w.write(b"CONNECT not-a-host-port HTTP/1.1\r\n\r\n")+ await w.drain()+ status = await asyncio.wait_for(r.readline(), timeout=5)+ assert b"400" in status+ w.close()+ finally:+ await proxy.stop()+++class TestEnforceEgressWiring:+ def test_enforce_egress_sets_proxy(self, monkeypatch):+ import egress_broker+ from crawl4ai import BrowserConfig+ monkeypatch.setattr(egress_broker, "_EGRESS_PROXY_URL", "http://127.0.0.1:9999")+ b = BrowserConfig()+ egress_broker.enforce_egress(b)+ assert b.proxy_config is not None+ assert b.proxy_config.server == "http://127.0.0.1:9999"diff --git a/deploy/docker/tests/test_security_fixes.py b/deploy/docker/tests/test_security_fixes.pyindex 1d31455a..c67507e9 100644--- a/deploy/docker/tests/test_security_fixes.py+++ b/deploy/docker/tests/test_security_fixes.py@@ -82,40 +82,23 @@ class TestURLValidation(unittest.TestCase):class TestHookBuiltins(unittest.TestCase):- """Test that dangerous builtins are removed from hooks."""-- def test_import_not_in_allowed_builtins(self):- """__import__ must NOT be in allowed_builtins."""- allowed_builtins = [- 'print', 'len', 'str', 'int', 'float', 'bool',- 'list', 'dict', 'set', 'tuple', 'range', 'enumerate',- 'zip', 'map', 'filter', 'any', 'all', 'sum', 'min', 'max',- 'sorted', 'reversed', 'abs', 'round', 'isinstance', 'type',- 'hasattr', 'callable', 'iter', 'next',- '__build_class__'- ]+ """Hooks are declarative now - there is no builtins sandbox to harden.- self.assertNotIn('__import__', allowed_builtins)- self.assertNotIn('eval', allowed_builtins)- self.assertNotIn('exec', allowed_builtins)- self.assertNotIn('compile', allowed_builtins)- self.assertNotIn('open', allowed_builtins)- # getattr/setattr are sandbox escape vectors - must not be present- self.assertNotIn('getattr', allowed_builtins)- self.assertNotIn('setattr', allowed_builtins)-- def test_build_class_in_allowed_builtins(self):- """__build_class__ must be in allowed_builtins (needed for class definitions)."""- allowed_builtins = [- 'print', 'len', 'str', 'int', 'float', 'bool',- 'list', 'dict', 'set', 'tuple', 'range', 'enumerate',- 'zip', 'map', 'filter', 'any', 'all', 'sum', 'min', 'max',- 'sorted', 'reversed', 'abs', 'round', 'isinstance', 'type',- 'hasattr', 'callable', 'iter', 'next',- '__build_class__'- ]+ The exec()-based hook system was removed (no in-process sandbox survives+ attacker Python). Hooks are a fixed registry of server-authored actions, so+ the relevant guarantee is simply that no action runs arbitrary code.+ """- self.assertIn('__build_class__', allowed_builtins)+ def test_registry_actions_are_fixed_and_codeless(self):+ from hook_registry import HOOK_REGISTRY+ # No action accepts/executes raw code.+ for action in HOOK_REGISTRY:+ self.assertNotIn("code", action.lower())+ self.assertNotIn("eval", action.lower())+ self.assertNotIn("exec", action.lower())+ # The documented safe actions are present.+ self.assertTrue({"block_resources", "add_cookies", "set_headers",+ "scroll_to_bottom", "wait_for_timeout"}.issubset(HOOK_REGISTRY))class TestHooksEnabled(unittest.TestCase):diff --git a/deploy/docker/tests/test_security_headers_xss.py b/deploy/docker/tests/test_security_headers_xss.pynew file mode 100644index 00000000..4ae8295a--- /dev/null+++ b/deploy/docker/tests/test_security_headers_xss.py@@ -0,0 +1,124 @@+"""+R6 headers / CSP / CORS behavioral tests.++Security headers are emitted unconditionally (independent of security.enabled).+The strict CSP applies to the API / error surface; the still-inline dashboard /+playground keep the baseline headers but not the strict CSP until they are+externalized (CSP-compat refactor - tracked separately). CORS is deny-by-default.+"""++import pytest++pytestmark = pytest.mark.posture+++class TestBaselineHeaders:+ def test_present_on_api_response(self, stock_client):+ r = stock_client.get("/health")+ h = {k.lower(): v for k, v in r.headers.items()}+ assert h.get("x-content-type-options") == "nosniff"+ assert h.get("x-frame-options", "").upper() == "DENY"+ assert h.get("referrer-policy") == "no-referrer"+ assert h.get("cross-origin-opener-policy") == "same-origin"++ def test_present_even_with_security_disabled(self, stock_client, server_module, monkeypatch):+ # Headers must be emitted independent of the security.enabled flag (the+ # old middleware only added them when enabled). Force it off and verify.+ monkeypatch.setitem(server_module.config["security"], "enabled", False)+ r = stock_client.get("/health")+ h = {k.lower() for k in r.headers}+ assert "content-security-policy" in h+ assert "x-content-type-options" in h++ def test_baseline_on_dashboard_mount(self, stock_client, server_module):+ from auth import create_access_token+ h = {"Authorization": f"Bearer {create_access_token({'sub': '[email protected]'}, scope='admin')}"}+ r = stock_client.get("/dashboard/", headers=h)+ hh = {k.lower(): v for k, v in r.headers.items()}+ assert hh.get("x-content-type-options") == "nosniff"+ assert hh.get("x-frame-options", "").upper() == "DENY"+++class TestStrictCsp:+ def test_api_csp_is_strict(self, stock_client):+ csp = stock_client.get("/health").headers.get("content-security-policy", "")+ assert "script-src 'self'" in csp+ assert "frame-ancestors 'none'" in csp+ assert "default-src 'none'" in csp+ assert "unsafe-inline" not in csp++ def test_ui_mount_not_given_strict_csp(self, stock_client, server_module):+ # The inline-script UI must not get the strict CSP yet (it would break).+ from auth import create_access_token+ h = {"Authorization": f"Bearer {create_access_token({'sub': '[email protected]'}, scope='admin')}"}+ csp = stock_client.get("/playground/", headers=h).headers.get("content-security-policy")+ assert csp is None+++class TestCorsDenyByDefault:+ def test_no_cors_allow_origin_by_default(self, stock_client):+ r = stock_client.get("/health", headers={"Origin": "https://evil.example"})+ assert "access-control-allow-origin" not in {k.lower() for k in r.headers}+++class TestErrorSanitization:+ def test_5xx_is_generic_with_correlation_id(self, stock_client, server_module):+ from auth import create_access_token+ h = {"Authorization": f"Bearer {create_access_token({'sub': '[email protected]'}, scope='admin')}"}+ # /monitor/stats/reset has no monitor singleton without a lifespan -> the+ # handler raises -> our central handler returns a sanitized 500.+ r = stock_client.post("/monitor/stats/reset", headers=h)+ assert r.status_code >= 500+ body = r.json()+ assert body.get("error") == "Internal server error"+ assert "correlation_id" in body+ # No internal detail (exception text / paths) leaked.+ assert "Traceback" not in r.text and "/home/" not in r.text++ def test_4xx_detail_preserved(self, stock_client):+ # /token is public; with no api_token configured it raises a 4xx, which+ # the central handler passes through with its developer-facing detail.+ r = stock_client.post("/token", json={"email": "[email protected]"})+ assert 400 <= r.status_code < 500+ assert "detail" in r.json() and r.json()["detail"]+++class TestWebhookHeaderSanitization:+ def test_crlf_in_value_rejected(self):+ from webhook import sanitize_webhook_headers+ with pytest.raises(ValueError):+ sanitize_webhook_headers({"X-Foo": "bar\r\nInjected: 1"})++ def test_hop_by_hop_denied(self):+ from webhook import sanitize_webhook_headers+ for bad in ("Host", "Content-Length", "Transfer-Encoding", "Authorization"):+ with pytest.raises(ValueError):+ sanitize_webhook_headers({bad: "x"})++ def test_bad_name_rejected(self):+ from webhook import sanitize_webhook_headers+ with pytest.raises(ValueError):+ sanitize_webhook_headers({"X Foo": "bar"})++ def test_good_headers_pass(self):+ from webhook import sanitize_webhook_headers+ assert sanitize_webhook_headers({"X-Trace-Id": "abc123"}) == {"X-Trace-Id": "abc123"}++ def test_schema_validator_rejects_early(self):+ from schemas import WebhookConfig+ import pydantic+ with pytest.raises(pydantic.ValidationError):+ WebhookConfig(webhook_url="https://example.com/cb",+ webhook_headers={"Host": "evil"})+++class TestCRLFSafeLogging:+ def test_crlf_stripped_from_log_message(self):+ import logging+ from utils import CRLFSafeFilter+ rec = logging.LogRecord("t", logging.INFO, __file__, 1,+ "url=http://x/\r\nINJECTED admin login", None, None)+ CRLFSafeFilter().filter(rec)+ msg = rec.getMessage()+ assert "\r" not in msg and "\n" not in msg+ assert "INJECTED" in msg # content kept, just de-fangeddiff --git a/deploy/docker/tests/test_security_llm_broker.py b/deploy/docker/tests/test_security_llm_broker.pynew file mode 100644index 00000000..fdb5f79e--- /dev/null+++ b/deploy/docker/tests/test_security_llm_broker.py@@ -0,0 +1,78 @@+"""+R3 LLM-broker tests: a request selects a provider BY NAME only; base_url and+api_token are always server-derived, so the configured provider key can never+be redirected to an attacker endpoint (the reported credential-exfil gadget).+"""++import pytest++from llm_broker import resolve_llm, allowed_provider_families, LLMProviderNotAllowed++pytestmark = pytest.mark.posture++CONF = {"llm": {"provider": "openai/gpt-4o-mini"}}+++class TestProviderAllowlist:+ def test_default_provider_allowed(self):+ out = resolve_llm(CONF, None)+ assert out["provider"] == "openai/gpt-4o-mini"++ def test_same_family_allowed(self):+ out = resolve_llm(CONF, "openai/gpt-4o")+ assert out["provider"] == "openai/gpt-4o"++ def test_other_family_rejected(self):+ with pytest.raises(LLMProviderNotAllowed):+ resolve_llm(CONF, "anthropic/claude-3-opus")++ def test_explicit_allowlist_widens(self):+ conf = {"llm": {"provider": "openai/gpt-4o-mini",+ "allowed_providers": ["anthropic/claude-3-opus"]}}+ assert resolve_llm(conf, "anthropic/claude-3-opus")["provider"].startswith("anthropic/")+++class TestBaseUrlIsServerOnly:+ def test_resolve_has_no_request_base_url_param(self):+ import inspect+ params = list(inspect.signature(resolve_llm).parameters)+ # only (config, requested_provider) - no way to inject base_url/api_token+ assert params == ["config", "requested_provider"]++ def test_base_url_is_canonical_from_env(self, monkeypatch):+ monkeypatch.setenv("OPENAI_BASE_URL", "https://api.openai.example")+ out = resolve_llm(CONF, "openai/gpt-4o-mini")+ assert out["base_url"] == "https://api.openai.example"++ def test_no_base_url_when_unset(self, monkeypatch):+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)+ monkeypatch.delenv("LLM_BASE_URL", raising=False)+ out = resolve_llm(CONF, "openai/gpt-4o-mini")+ assert out["base_url"] is None+++class TestRequestSurfaceRemoved:+ def test_markdown_request_has_no_base_url(self):+ from schemas import MarkdownRequest+ assert "base_url" not in MarkdownRequest.model_fields++ def test_llm_job_payload_has_no_base_url(self):+ from job import LlmJobPayload+ assert "base_url" not in LlmJobPayload.model_fields++ def test_llm_endpoint_has_no_base_url_query(self, server_module):+ import inspect+ assert "base_url" not in inspect.signature(server_module.llm_endpoint).parameters++ def test_md_endpoint_rejects_disallowed_provider(self, stock_client, server_module):+ from auth import create_access_token+ h = {"Authorization": f"Bearer {create_access_token({'sub': '[email protected]'})}"}+ # LLM filter + a provider outside the allowed family -> 400 (not a 500,+ # and no LLM call to an attacker endpoint).+ r = stock_client.post(+ "/md",+ json={"url": "https://example.com", "f": "llm", "provider": "attacker/model",+ "base_url": "http://169.254.169.254"},+ headers=h,+ )+ assert r.status_code == 400, r.status_codediff --git a/deploy/docker/tests/test_security_resource_caps.py b/deploy/docker/tests/test_security_resource_caps.pynew file mode 100644index 00000000..6cf4f038--- /dev/null+++ b/deploy/docker/tests/test_security_resource_caps.py@@ -0,0 +1,175 @@+"""+R5 resource-governance tests: request body-size limit (413) and the+defense-in-depth deep-crawl clamp. (The client-driven unbounded-crawl critical+is closed upstream by R2 forbidding deep_crawl_strategy on untrusted bodies.)+"""++import pytest++pytestmark = pytest.mark.posture+++class TestBodySizeLimit:+ def test_oversize_content_length_413(self, stock_client, server_module):+ from auth import create_access_token+ h = {+ "Authorization": f"Bearer {create_access_token({'sub': '[email protected]'})}",+ "Content-Length": str(50 * 1024 * 1024), # 50 MiB, over the 10 MiB cap+ "Content-Type": "application/json",+ }+ # TestClient won't actually send 50MiB; the declared Content-Length is+ # what the middleware checks.+ r = stock_client.post("/crawl", data=b"{}", headers=h)+ assert r.status_code == 413, r.status_code++ def test_normal_body_not_blocked_by_size(self, stock_client, server_module):+ from auth import create_access_token+ h = {"Authorization": f"Bearer {create_access_token({'sub': '[email protected]'})}"}+ # Small body: must pass the size gate (then rejected for missing urls, etc).+ r = stock_client.post("/crawl", json={}, headers=h)+ assert r.status_code != 413+++class TestDeepCrawlClamp:+ def test_infinite_max_pages_clamped(self):+ from governor import clamp_deep_crawl, DEFAULT_MAX_PAGES+ from crawl4ai.deep_crawling import BFSDeepCrawlStrategy+ from crawl4ai import CrawlerRunConfig++ strat = BFSDeepCrawlStrategy(max_depth=99) # max_pages defaults to infinity+ cfg = CrawlerRunConfig(deep_crawl_strategy=strat)+ clamp_deep_crawl(cfg)+ assert cfg.deep_crawl_strategy.max_pages <= DEFAULT_MAX_PAGES+ assert cfg.deep_crawl_strategy.max_depth <= 5++ def test_no_deep_crawl_is_noop(self):+ from governor import clamp_deep_crawl+ from crawl4ai import CrawlerRunConfig+ cfg = CrawlerRunConfig()+ clamp_deep_crawl(cfg) # must not raise+ assert cfg.deep_crawl_strategy is None+++class TestUntrustedDeepCrawlStillForbidden:+ def test_request_cannot_set_deep_crawl(self):+ # The clamp is defense in depth; the primary control is R2 rejecting it.+ from crawl4ai.async_configs import CrawlerRunConfig, Provenance, UntrustedConfigError+ with pytest.raises(UntrustedConfigError):+ CrawlerRunConfig.load(+ {"deep_crawl_strategy": {"type": "BFSDeepCrawlStrategy", "params": {"max_depth": 9}}},+ provenance=Provenance.UNTRUSTED,+ )+++class TestConfigCaps:+ def test_job_queue_caps_defaults(self):+ from governor import job_queue_caps+ caps = job_queue_caps({})+ assert caps == {"maxsize": 1000, "workers": 4, "per_principal": 0}++ def test_zero_means_unbounded(self):+ from governor import job_queue_caps, wall_clock_seconds+ caps = job_queue_caps({"limits": {"queue": {"maxsize": 0, "per_principal": 0}}})+ assert caps["maxsize"] == 0 and caps["per_principal"] == 0+ assert wall_clock_seconds({}) == 0 # no deadline by default++ def test_wall_clock_configurable(self):+ from governor import wall_clock_seconds+ assert wall_clock_seconds({"limits": {"wall_clock_s": 30}}) == 30+++class TestWorkQueue:+ async def test_queue_full_without_drain(self):+ import asyncio+ from work_queue import WorkQueue, QueueFull+ q = WorkQueue(maxsize=1, workers=1)+ q._q = asyncio.Queue(maxsize=1) # bypass workers so nothing drains++ async def noop():+ pass+ q.submit(noop)+ with pytest.raises(QueueFull):+ q.submit(noop)++ async def test_unbounded_never_full(self):+ import asyncio+ from work_queue import WorkQueue+ q = WorkQueue(maxsize=0, workers=1)+ q._q = asyncio.Queue(maxsize=0)++ async def noop():+ pass+ for _ in range(200):+ q.submit(noop) # maxsize 0 => unbounded, never raises++ async def test_per_principal_quota(self):+ import asyncio+ from work_queue import WorkQueue, QuotaExceeded+ q = WorkQueue(maxsize=0, workers=1, per_principal=1)+ q._q = asyncio.Queue(maxsize=0)++ async def noop():+ pass+ q.submit(noop, principal="alice")+ with pytest.raises(QuotaExceeded):+ q.submit(noop, principal="alice")+ q.submit(noop, principal="bob") # different caller is fine++ async def test_runs_job_and_releases_counter(self):+ import asyncio+ from work_queue import WorkQueue+ q = WorkQueue(maxsize=10, workers=1, per_principal=5)+ await q.start()+ try:+ done = asyncio.Event()++ async def job():+ done.set()+ q.submit(job, principal="p")+ await asyncio.wait_for(done.wait(), timeout=2)+ await asyncio.sleep(0.05) # allow the finally/release to run+ assert q._counts.get("p", 0) == 0+ finally:+ await q.stop()+++class TestEnqueueMapping:+ def test_enqueue_maps_queue_full_to_503(self):+ import asyncio+ import api+ import work_queue+ from fastapi import HTTPException+ q = work_queue.WorkQueue(maxsize=1, workers=1)+ q._q = asyncio.Queue(maxsize=1)+ work_queue.set_job_queue(q)++ async def noop():+ pass+ try:+ api._enqueue_job(None, noop) # fills the queue+ with pytest.raises(HTTPException) as exc:+ api._enqueue_job(None, noop)+ assert exc.value.status_code == 503+ assert exc.value.headers.get("Retry-After")+ finally:+ work_queue.set_job_queue(None)++ def test_enqueue_maps_quota_to_429(self):+ import asyncio+ import api+ import work_queue+ from fastapi import HTTPException+ q = work_queue.WorkQueue(maxsize=0, workers=1, per_principal=1)+ q._q = asyncio.Queue(maxsize=0)+ work_queue.set_job_queue(q)++ async def noop():+ pass+ try:+ api._enqueue_job(None, noop, principal="a")+ with pytest.raises(HTTPException) as exc:+ api._enqueue_job(None, noop, principal="a")+ assert exc.value.status_code == 429+ finally:+ work_queue.set_job_queue(None)diff --git a/deploy/docker/tests/test_security_ssrf_crawl.py b/deploy/docker/tests/test_security_ssrf_crawl.pyindex 6da09fc1..281da2b9 100644--- a/deploy/docker/tests/test_security_ssrf_crawl.py+++ b/deploy/docker/tests/test_security_ssrf_crawl.py@@ -213,6 +213,51 @@ class TestSSRFSourceCoverage(unittest.TestCase):self.assertGreaterEqual(count, 5, # 1 import + 4 call sitesf"api.py should call validate_url_destination at all URL entry points (found {count})")+ def test_every_crawl_handler_validates_destination(self):+ """Per-handler check: each crawl handler body must validate seed URL+ destinations (via the shared _normalize_and_validate_seeds helper). A+ bare occurrence count missed the streaming handler (it had zero calls+ while the count was still satisfied)."""+ with open(os.path.join(DEPLOY_DIR, "api.py")) as f:+ source = f.read()+ handlers = [+ "handle_crawl_request",+ "handle_stream_crawl_request",+ ]+ for handler in handlers:+ idx = source.index(f"async def {handler}")+ nxt = source.find("\nasync def ", idx + 1)+ body = source[idx: nxt if nxt != -1 else len(source)]+ self.assertIn("_normalize_and_validate_seeds(", body,+ f"{handler} must validate its seed URLs via _normalize_and_validate_seeds")++ def test_default_browser_config_pins_egress(self):+ """get_default_browser_config must apply enforce_egress so /html,+ /screenshot, /pdf, /execute_js fetch through the pinning proxy+ (DNS-rebinding / redirect-to-internal protection), not just validate+ the seed and then let the browser re-resolve."""+ with open(os.path.join(DEPLOY_DIR, "server.py")) as f:+ source = f.read()+ idx = source.index("def get_default_browser_config")+ nxt = source.find("\ndef ", idx + 1)+ body = source[idx: nxt if nxt != -1 else idx + 800]+ self.assertIn("enforce_egress", body,+ "get_default_browser_config must call enforce_egress on the returned config")++ def test_llm_and_markdown_handlers_pin_egress(self):+ """The /md and /llm handlers and the LLM background worker must pin+ egress on their fetch config (same seed-only SSRF root cause)."""+ with open(os.path.join(DEPLOY_DIR, "api.py")) as f:+ source = f.read()+ for handler in ("handle_llm_qa", "handle_markdown_request", "process_llm_extraction"):+ idx = source.index(f"def {handler}")+ nxt = source.find("\nasync def ", idx + 1)+ nxt2 = source.find("\ndef ", idx + 1)+ ends = [e for e in (nxt, nxt2) if e != -1]+ body = source[idx: min(ends) if ends else len(source)]+ self.assertIn("enforce_egress", body,+ f"{handler} must call enforce_egress on its fetch config")+def test_utils_has_allow_internal_flag(self):"""utils.py must have CRAWL4AI_ALLOW_INTERNAL_URLS env var."""with open(os.path.join(DEPLOY_DIR, "utils.py")) as f:@@ -230,6 +275,37 @@ class TestSSRFSourceCoverage(unittest.TestCase):"validate_url_destination must skip raw: URLs")+import pytest+++class TestStreamCrawlSSRFBehavioral:+ """End-to-end: an internal seed URL must be 400-blocked on the streaming+ path, not just asserted to exist in source. This is the behavioral guard+ for the KOH stream-SSRF fix (and proves the deliberate 400 is not masked+ to 500 by the handler's generic except)."""++ def _auth(self):+ from auth import create_access_token+ return {"Authorization": f"Bearer {create_access_token({'sub': '[email protected]'})}"}++ INTERNAL = "http://169.254.169.254/latest/meta-data/"++ def test_crawl_stream_blocks_internal(self, stock_client, server_module):+ r = stock_client.post("/crawl/stream", json={"urls": [self.INTERNAL]}, headers=self._auth())+ assert r.status_code == 400, f"expected 400 SSRF block, got {r.status_code}: {r.text[:200]}"+ assert "SSRF" in r.text or "blocked" in r.text.lower()++ def test_crawl_with_stream_true_blocks_internal(self, stock_client, server_module):+ body = {"urls": [self.INTERNAL],+ "crawler_config": {"type": "CrawlerRunConfig", "params": {"stream": True}}}+ r = stock_client.post("/crawl", json=body, headers=self._auth())+ assert r.status_code == 400, f"expected 400 SSRF block, got {r.status_code}: {r.text[:200]}"++ def test_non_stream_crawl_still_blocks_internal(self, stock_client, server_module):+ r = stock_client.post("/crawl", json={"urls": [self.INTERNAL]}, headers=self._auth())+ assert r.status_code == 400, f"expected 400 SSRF block, got {r.status_code}: {r.text[:200]}"++if __name__ == "__main__":print("=" * 70)print("Crawl4AI SSRF Tests - Crawl/MD/LLM Endpoints (secsys_codex)")diff --git a/deploy/docker/tests/test_security_ssrf_egress.py b/deploy/docker/tests/test_security_ssrf_egress.pynew file mode 100644index 00000000..ab5c43bd--- /dev/null+++ b/deploy/docker/tests/test_security_ssrf_egress.py@@ -0,0 +1,142 @@+"""+R3 egress-broker behavioral tests (fully offline via the conftest DNS fixtures).++One rule: reject any resolved IP where not ip.is_global, on every transition+form (v4-mapped / NAT64 / 6to4 / v4-compat). Resolve once and pin, so DNS+rebinding never reaches the second (internal) answer. Errors are opaque.+"""++import socket++import pytest++from egress_broker import (+ EgressBlocked,+ check_redirect,+ is_forbidden_ip,+ resolve_and_pin,+)++pytestmark = pytest.mark.posture+++class TestForbiddenIp:+ @pytest.mark.parametrize("ip", [+ "127.0.0.1", "169.254.169.254", "10.0.0.5", "192.168.1.1",+ "172.16.0.1", "100.64.0.1", "0.0.0.0",+ "::1", "::", "fc00::1", "fe80::1",+ "::ffff:127.0.0.1", # v4-mapped loopback+ "::ffff:169.254.169.254", # v4-mapped metadata+ "64:ff9b::a9fe:a9fe", # NAT64 -> 169.254.169.254+ "2002:a9fe:a9fe::1", # 6to4 embedding 169.254.169.254+ ])+ def test_internal_forms_forbidden(self, ip):+ assert is_forbidden_ip(ip) is True++ @pytest.mark.parametrize("ip", ["8.8.8.8", "1.1.1.1", "2606:4700:4700::1111"])+ def test_global_allowed(self, ip):+ assert is_forbidden_ip(ip) is False+++class TestResolveAndPin:+ def test_public_host_pins_ip(self, offline_dns):+ offline_dns.set("good.example", "93.184.216.34")+ t = resolve_and_pin("https://good.example/path")+ assert t.ip == "93.184.216.34" and t.host == "good.example" and t.port == 443++ def test_metadata_blocked(self, offline_dns):+ offline_dns.set("meta.example", "169.254.169.254")+ with pytest.raises(EgressBlocked):+ resolve_and_pin("http://meta.example/latest/meta-data/")++ def test_nat64_metadata_blocked(self, offline_dns):+ offline_dns.set("nat64.example", "64:ff9b::a9fe:a9fe")+ with pytest.raises(EgressBlocked):+ resolve_and_pin("http://nat64.example/")++ def test_localhost_name_blocked(self, offline_dns):+ with pytest.raises(EgressBlocked):+ resolve_and_pin("http://localhost/")++ def test_non_http_scheme_blocked(self):+ with pytest.raises(EgressBlocked):+ resolve_and_pin("file:///etc/passwd")+ with pytest.raises(EgressBlocked):+ resolve_and_pin("gopher://x/")++ def test_error_is_opaque(self, offline_dns):+ offline_dns.set("meta.example", "169.254.169.254")+ try:+ resolve_and_pin("http://meta.example/")+ assert False+ except EgressBlocked as e:+ # must not leak the resolved IP or hostname+ assert "169.254" not in e.reason+ assert "meta.example" not in e.reason+ assert e.reason == "URL blocked"++ def test_multi_record_one_internal_rejects_host(self, monkeypatch):+ def fake(host, port, *a, **k):+ return [+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", port or 0)),+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", port or 0)),+ ]+ monkeypatch.setattr(socket, "getaddrinfo", fake)+ with pytest.raises(EgressBlocked):+ resolve_and_pin("http://mixed.example/")+++class TestDnsRebinding:+ def test_pins_first_answer_never_reresolves_internal(self, rebinding_dns):+ r = rebinding_dns("rebind.example", "93.184.216.34", "169.254.169.254")+ t = resolve_and_pin("http://rebind.example/")+ # Pinned to the public answer; the caller dials t.ip, not the host, so+ # the internal second answer is never used.+ assert t.ip == "93.184.216.34"+ assert r.calls == 1 # resolved exactly once+++class TestEnforceEgress:+ def test_tls_verification_forced_on(self, monkeypatch):+ import egress_broker+ monkeypatch.setattr(egress_broker, "ALLOW_INSECURE_TLS", False)+ from crawl4ai import BrowserConfig+ b = BrowserConfig(ignore_https_errors=True)+ egress_broker.enforce_egress(b)+ assert b.ignore_https_errors is False++ def test_proxy_nulled(self):+ import egress_broker+ from crawl4ai import BrowserConfig+ b = BrowserConfig()+ b.proxy_config = object()+ egress_broker.enforce_egress(b)+ assert b.proxy_config is None++ def test_dangerous_args_stripped(self):+ import egress_broker+ from crawl4ai import BrowserConfig+ b = BrowserConfig(extra_args=["--proxy-server=http://evil", "--ignore-certificate-errors", "--headless"])+ egress_broker.enforce_egress(b)+ assert b.extra_args == ["--headless"]+++class TestRedirectRevalidation:+ def test_redirect_to_internal_blocked(self, offline_dns):+ offline_dns.set("evil-redirect.example", "169.254.169.254")+ with pytest.raises(EgressBlocked):+ check_redirect("http://evil-redirect.example/")+++class TestWebhookValidatorUsesBroker:+ def test_webhook_internal_blocked_opaque(self, offline_dns):+ from utils import validate_webhook_url+ offline_dns.set("hook.example", "10.0.0.9")+ with pytest.raises(ValueError) as exc:+ validate_webhook_url("http://hook.example/cb")+ assert "10.0.0" not in str(exc.value) # no IP leak++ def test_webhook_public_ok(self, offline_dns):+ from utils import validate_webhook_url+ offline_dns.set("hook.example", "93.184.216.34")+ validate_webhook_url("http://hook.example/cb") # no raisediff --git a/deploy/docker/tests/test_security_trust_boundary.py b/deploy/docker/tests/test_security_trust_boundary.pynew file mode 100644index 00000000..33b4be62--- /dev/null+++ b/deploy/docker/tests/test_security_trust_boundary.py@@ -0,0 +1,236 @@+"""+R2 trust-boundary behavioral tests (library-level provenance machinery).++Untrusted request bodies may only construct a strict subset of types and may+only set scalar, non-power fields, which are then clamped. Trusted (SDK /+in-process) construction is unchanged.++Docker-layer wiring tests (handlers passing UNTRUSTED, /config/dump+validate-only, declarative hooks) live alongside as the docker pieces land.+"""++import pytest++from crawl4ai.async_configs import (+ BrowserConfig,+ CrawlerRunConfig,+ Provenance,+ UntrustedConfigError,+)++T = Provenance.TRUSTED+U = Provenance.UNTRUSTED++pytestmark = pytest.mark.posture+++class TestTrustedUnchanged:+ """SDK/in-process callers (default TRUSTED) keep full power."""++ def test_trusted_keeps_power_fields(self):+ c = CrawlerRunConfig.load(+ {"js_code": "x=1", "page_timeout": 999999, "word_count_threshold": 5},+ provenance=T,+ )+ assert c.js_code == "x=1"+ assert c.page_timeout == 999999++ def test_trusted_is_the_default(self):+ # No provenance argument => behaves exactly as before.+ c = CrawlerRunConfig.load({"js_code": "y=2"})+ assert c.js_code == "y=2"++ def test_trusted_roundtrip(self):+ c = CrawlerRunConfig(js_code="z=3", screenshot=True, page_timeout=120000)+ c2 = CrawlerRunConfig.load(c.dump())+ assert c2.js_code == "z=3" and c2.page_timeout == 120000+++class TestUntrustedForbiddenFields:+ @pytest.mark.parametrize(+ "field,value",+ [+ ("js_code", "alert(1)"),+ ("js_code_before_wait", "x"),+ ("deep_crawl_strategy", {"type": "BFSDeepCrawlStrategy", "params": {}}),+ ("proxy_config", {"server": "http://evil"}),+ ("base_url", "http://evil"),+ ("simulate_user", True),+ ("magic", True),+ ("process_in_browser", True),+ ("session_id", "shared"),+ ],+ )+ def test_crawler_power_field_rejected(self, field, value):+ with pytest.raises(UntrustedConfigError):+ CrawlerRunConfig.load({field: value}, provenance=U)++ @pytest.mark.parametrize(+ "field,value",+ [+ ("extra_args", ["--proxy-server=http://evil"]),+ ("proxy", "http://evil"),+ ("user_data_dir", "/etc"),+ ("cdp_url", "ws://evil"),+ ("cookies", [{"name": "s", "value": "x"}]),+ ("headers", {"X": "y"}),+ ("init_scripts", ["evil()"]),+ ],+ )+ def test_browser_power_field_rejected(self, field, value):+ with pytest.raises(UntrustedConfigError):+ BrowserConfig.load({field: value}, provenance=U)++ @pytest.mark.parametrize(+ "payload",+ [+ ["--no-zygote", "--utility-cmd-prefix=sh -c id>/tmp/pwn"],+ ["--renderer-cmd-prefix=/bin/sh"],+ ["--gpu-launcher=touch /tmp/x"],+ ["--browser-subprocess-path=/bin/sh"],+ ],+ )+ def test_extra_args_chromium_cmd_injection_rejected(self, payload):+ """Y4tacker RCE: Chromium launch-arg command injection via extra_args.+ extra_args is a forbidden field for untrusted bodies, so ANY value+ (including the --*-cmd-prefix / --no-zygote exec primitives) is rejected+ outright rather than scrubbed by an always-incomplete denylist."""+ with pytest.raises(UntrustedConfigError):+ BrowserConfig.load({"extra_args": payload}, provenance=U)+++class TestUntrustedTypeGate:+ def test_llm_strategy_rejected(self):+ body = {+ "type": "CrawlerRunConfig",+ "params": {+ "extraction_strategy": {+ "type": "LLMExtractionStrategy",+ "params": {},+ }+ },+ }+ with pytest.raises(UntrustedConfigError):+ CrawlerRunConfig.load(body, provenance=U)++ def test_env_exfil_poc_rejected(self):+ """The verified os.getenv-via-'env:' credential-exfil PoC must 400."""+ poc = {+ "type": "CrawlerRunConfig",+ "params": {+ "extraction_strategy": {+ "type": "LLMExtractionStrategy",+ "params": {+ "llm_config": {+ "type": "LLMConfig",+ "params": {"api_token": "env:SECRET_KEY"},+ }+ },+ }+ },+ }+ with pytest.raises(UntrustedConfigError):+ CrawlerRunConfig.load(poc, provenance=U)++ def test_allowed_non_llm_strategy_accepted(self):+ body = {+ "type": "CrawlerRunConfig",+ "params": {+ "extraction_strategy": {+ "type": "JsonCssExtractionStrategy",+ "params": {"schema": {"name": "x", "baseSelector": "div", "fields": []}},+ }+ },+ }+ c = CrawlerRunConfig.load(body, provenance=U)+ assert c.extraction_strategy is not None+++class TestUntrustedClampAndDrop:+ def test_timeout_zero_becomes_cap(self):+ c = CrawlerRunConfig.load({"page_timeout": 0}, provenance=U)+ assert c.page_timeout == 60_000 # 0 ("no timeout") clamped, never unbounded++ def test_timeout_clamped(self):+ c = CrawlerRunConfig.load({"wait_for_timeout": 500000}, provenance=U)+ assert c.wait_for_timeout == 60_000++ def test_unknown_field_dropped_not_raised(self):+ c = CrawlerRunConfig.load(+ {"css_selector": ".x", "totally_unknown_field": 1}, provenance=U+ )+ assert c.css_selector == ".x"++ def test_viewport_clamped(self):+ b = BrowserConfig.load({"viewport_width": 99999, "headless": True}, provenance=U)+ assert b.viewport_width == 4000+ assert b.headless is True++ def test_safe_scalar_kept(self):+ c = CrawlerRunConfig.load(+ {"word_count_threshold": 7, "screenshot": True, "wait_until": "load"},+ provenance=U,+ )+ assert c.word_count_threshold == 7 and c.screenshot is True+++class TestLlmConfigGuard:+ def test_untrusted_env_token_rejected(self):+ from crawl4ai.async_configs import LLMConfig+ with pytest.raises(UntrustedConfigError):+ LLMConfig(api_token="env:SECRET_KEY", provenance=U)++ def test_untrusted_never_reads_env(self, monkeypatch):+ from crawl4ai.async_configs import LLMConfig+ monkeypatch.setenv("OPENAI_API_KEY", "leak-me")+ cfg = LLMConfig(provider="openai/gpt-4o-mini", provenance=U)+ assert cfg.api_token != "leak-me"+++class TestDockerHandlersEnforceUntrusted:+ """The Docker endpoints map UntrustedConfigError -> HTTP 400 (not 500)."""++ def _auth(self, server_module):+ from auth import create_access_token+ return {"Authorization": f"Bearer {create_access_token({'sub': '[email protected]'})}"}++ def test_crawl_rejects_js_code(self, stock_client, server_module):+ r = stock_client.post(+ "/crawl",+ json={"urls": ["https://example.com"], "crawler_config": {"js_code": "fetch('http://169.254.169.254')"}},+ headers=self._auth(server_module),+ )+ assert r.status_code == 400, r.status_code++ def test_crawl_rejects_proxy_config(self, stock_client, server_module):+ r = stock_client.post(+ "/crawl",+ json={"urls": ["https://example.com"],+ "browser_config": {"proxy_config": {"server": "http://evil"}}},+ headers=self._auth(server_module),+ )+ assert r.status_code == 400, r.status_code++ def test_config_dump_rejects_power_field(self, stock_client, server_module):+ r = stock_client.post(+ "/config/dump",+ json={"type": "BrowserConfig", "params": {"extra_args": ["--proxy-server=x"]}},+ headers=self._auth(server_module),+ )+ assert r.status_code == 400, r.status_code++ def test_config_dump_validates_safe_config(self, stock_client, server_module):+ r = stock_client.post(+ "/config/dump",+ json={"type": "CrawlerRunConfig", "params": {"word_count_threshold": 5, "screenshot": True}},+ headers=self._auth(server_module),+ )+ assert r.status_code == 200, r.status_code++ def test_config_dump_drops_unknown_keeps_safe(self, stock_client, server_module):+ r = stock_client.post(+ "/config/dump",+ json={"type": "CrawlerRunConfig", "params": {"css_selector": ".x", "bogus_field": 1}},+ headers=self._auth(server_module),+ )+ assert r.status_code == 200, r.status_codediff --git a/deploy/docker/tests/test_security_webhook_pinning.py b/deploy/docker/tests/test_security_webhook_pinning.pynew file mode 100644index 00000000..e7128f24--- /dev/null+++ b/deploy/docker/tests/test_security_webhook_pinning.py@@ -0,0 +1,82 @@+"""+R3 webhook connection-pinning tests (real loopback server, offline).++The webhook sender pins the connection to the validated IP (aiohttp resolver),+follows redirects manually, and re-validates every hop. We stub the egress+broker so a "good" host pins to the loopback test server and "internal" hosts /+redirects are refused.+"""++import asyncio++import pytest++import egress_broker+from egress_broker import EgressBlocked, PinnedTarget+from webhook import WebhookDeliveryService++pytestmark = pytest.mark.posture+++async def _raw_server(response: bytes):+ async def handle(reader, writer):+ await reader.read(65536)+ writer.write(response)+ await writer.drain()+ writer.close()+ server = await asyncio.start_server(handle, "127.0.0.1", 0)+ return server, server.sockets[0].getsockname()[1]+++def _svc():+ return WebhookDeliveryService({"webhooks": {"retry": {"max_attempts": 2,+ "initial_delay_ms": 1, "timeout_ms": 5000}}})+++class TestWebhookPinning:+ async def test_delivered_to_pinned_host(self, monkeypatch):+ server, port = await _raw_server(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok")+ monkeypatch.setattr(+ egress_broker, "resolve_and_pin",+ lambda url: PinnedTarget("http", "good.example", port, "127.0.0.1"),+ )+ try:+ ok = await _svc().send_webhook(f"http://good.example:{port}/cb", {"x": 1})+ assert ok is True+ finally:+ server.close()++ async def test_internal_target_blocked_no_retry(self, monkeypatch):+ def boom(url):+ raise EgressBlocked()+ monkeypatch.setattr(egress_broker, "resolve_and_pin", boom)+ ok = await _svc().send_webhook("http://169.254.169.254/cb", {"x": 1})+ assert ok is False++ async def test_redirect_to_internal_blocked(self, monkeypatch):+ server, port = await _raw_server(+ b"HTTP/1.1 302 Found\r\nLocation: http://evil.internal/\r\nContent-Length: 0\r\n\r\n"+ )+ monkeypatch.setattr(+ egress_broker, "resolve_and_pin",+ lambda url: PinnedTarget("http", "good.example", port, "127.0.0.1"),+ )++ def check(loc):+ raise EgressBlocked() # the redirect target is internal+ monkeypatch.setattr(egress_broker, "check_redirect", check)+ try:+ ok = await _svc().send_webhook(f"http://good.example:{port}/cb", {"x": 1})+ assert ok is False # redirect re-validation refused it+ finally:+ server.close()++ async def test_uses_pinned_resolver(self):+ # The resolver returns the pinned IP for any host (TLS still verifies the+ # hostname); confirm the wiring.+ from webhook import _PinnedResolver+ r = _PinnedResolver("good.example", "203.0.113.7")+ out = await r.resolve("good.example", 443)+ assert out[0]["host"] == "203.0.113.7"+ assert out[0]["hostname"] == "good.example"diff --git a/deploy/docker/utils.py b/deploy/docker/utils.pyindex 7292118b..8f8ecb18 100644--- a/deploy/docker/utils.py+++ b/deploy/docker/utils.py@@ -153,11 +153,12 @@ class CRLFSafeFilter(logging.Filter):"""Strip CR/LF/control chars from log records (log-injection / forging).A crawl URL or error reflected into a log line could otherwise inject- newlines and forge additional log entries."""+ newlines and forge additional log entries.+ """- _BAD = {ord(c): None for c in "\r\n"} | {i: None for i in range(0, 32) if i != 9}+ _BAD = {ord(c): None for c in "\r\n"} | {i: None for i in range(0, 32) if i not in (9,)}- def filter(self, record: "logging.LogRecord") -> bool:+ def filter(self, record: logging.LogRecord) -> bool:try:msg = record.getMessage()cleaned = msg.translate(self._BAD)@@ -316,45 +317,10 @@ def get_llm_base_url(config: Dict, provider: Optional[str] = None) -> Optional[s# ── Security utilities ──────────────────────────────────────--ALLOWED_OUTPUT_DIR = os.environ.get("CRAWL4AI_OUTPUT_DIR", "/tmp/crawl4ai-outputs")---def validate_output_path(user_path: str) -> str:- """Resolve and restrict output_path to ALLOWED_OUTPUT_DIR.-- Hardened against the symlink/TOCTOU bypass: in addition to the string- containment check, the REAL path (symlinks resolved) of the target and its- parent must also stay inside the allowed dir, so a symlink planted inside- the dir cannot redirect the write elsewhere. The final write must also use- O_NOFOLLOW (see write_output_file)."""- from fastapi import HTTPException- safe_path = os.path.normpath(user_path).lstrip(os.sep)- abs_path = os.path.abspath(os.path.join(ALLOWED_OUTPUT_DIR, safe_path))- abs_allowed = os.path.abspath(ALLOWED_OUTPUT_DIR) + os.sep- # Resolve symlinks on the parent dir (the file itself may not exist yet) and- # re-check containment; this defeats a symlinked path component. The trailing- # os.sep on both sides also rejects sibling-prefix names ("...-evil").- real_parent = os.path.realpath(os.path.dirname(abs_path))- real_path = os.path.join(real_parent, os.path.basename(abs_path))- string_ok = abs_path.startswith(abs_allowed)- real_ok = (real_path + os.sep).startswith(abs_allowed)- if not (string_ok and real_ok):- raise HTTPException(- status_code=400,- detail=f"output_path must resolve within {ALLOWED_OUTPUT_DIR}",- )- return real_path---def write_output_file(abs_path: str, data: bytes) -> None:- """Write bytes to a validated output path without following a symlink at the- final component (defends the symlink-TOCTOU write)."""- os.makedirs(os.path.dirname(abs_path), exist_ok=True)- flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0)- fd = os.open(abs_path, flags, 0o600)- with os.fdopen(fd, "wb") as f:- f.write(data)+# validate_output_path / ALLOWED_OUTPUT_DIR were removed: caller-supplied+# output paths are no longer accepted (string-only validation was bypassable via+# symlink/TOCTOU and sibling-prefix names -> arbitrary write -> RCE). The server+# owns all artifact paths now (see artifacts.py).import ipaddress@@ -400,95 +366,37 @@ def validate_url_destination(url: str) -> None:raise HTTPException(status_code=400, detail=f"URL blocked (SSRF protection): {e}")-_NAT64_NETWORK = ipaddress.ip_network("64:ff9b::/96")-_6TO4_NETWORK = ipaddress.ip_network("2002::/16")-_V4COMPAT_NETWORK = ipaddress.ip_network("::/96")--def _expand_ip_candidates(ip):- """Return [ip] plus any IPv4 form embedded inside the IPv6 address.- SSRF guards must check the unwrapped form because ::ffff:169.254.169.254,- NAT64 64:ff9b::a9fe:a9fe, and 6to4 2002:a9fe:a9fe:: all route to an internal- IPv4 that would not match an IPv6-only check."""+ """Return [ip] plus any IPv4 form wrapped inside the IPv6 address.+ SSRF guards must check the unwrapped form because ::ffff:127.0.0.1 and+ ::127.0.0.1 route to 127.0.0.1 but would not match IPv4 blocklists directly."""candidates = [ip]if isinstance(ip, ipaddress.IPv6Address):- mapped = ip.ipv4_mapped- if mapped is not None:- candidates.append(mapped)- elif ip in _NAT64_NETWORK or ip in _V4COMPAT_NETWORK:- candidates.append(ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF))- elif ip in _6TO4_NETWORK:- candidates.append(ipaddress.IPv4Address((int(ip) >> 80) & 0xFFFFFFFF))+ if ip.ipv4_mapped is not None:+ candidates.append(ip.ipv4_mapped)+ else:+ as_int = int(ip)+ if 0 < as_int < 2**32:+ candidates.append(ipaddress.IPv4Address(as_int))return candidatesdef validate_webhook_url(url: str) -> None:- """Reject webhook/crawl URLs targeting non-global (internal/private/reserved)- networks (SSRF protection).-- One rule: reject any resolved IP where not ip.is_global, evaluated on every- embedded IPv4 transition form (v4-mapped, NAT64, 6to4, v4-compat). This- closes the gaps in the old explicit blocklist (the IPv6 unspecified ::,- NAT64, 6to4). The error is opaque - it never echoes the resolved internal- IP (which would be a DNS/oracle leak)."""+ """Reject webhook/crawl URLs targeting non-global networks (SSRF protection).++ Delegates to the single egress rule (egress_broker: reject any resolved IP+ where not ip.is_global, including v4-mapped/NAT64/6to4/v4-compat embedded+ forms). The raised message is intentionally opaque - it never echoes the+ resolved IP or hostname, so this is not a DNS/oracle leak.+ """+ from egress_broker import resolve_and_pin, EgressBlockedparsed = urlparse(str(url))- hostname = parsed.hostname- if not hostname:+ if not parsed.hostname:raise ValueError("URL must have a valid hostname")- hostname_lower = hostname.lower()- if hostname_lower in _BLOCKED_HOSTNAMES or hostname_lower.startswith("host.docker.internal"):- raise ValueError("URL host is blocked")try:- resolved = socket.getaddrinfo(hostname, None)- except socket.gaierror:- raise ValueError("Cannot resolve URL host")- for _, _, _, _, sockaddr in resolved:- ip = ipaddress.ip_address(sockaddr[0])- for candidate in _expand_ip_candidates(ip):- if not candidate.is_global:- # opaque: do not leak the resolved internal IP- raise ValueError("URL resolves to a blocked address")---# Chromium launch flags that can redirect/route egress or remap DNS, enabling-# the same SSRF as a proxy field. Stripped from caller-supplied extra_args.-_DANGEROUS_BROWSER_ARGS = (- "--proxy-server", "--proxy-pac-url", "--proxy-bypass-list",- "--host-resolver-rules",-)---def validate_proxy_destination(server: str) -> None:- """Reject a proxy server whose host is non-global (SSRF via proxy_config).-- The crawl-target SSRF check is applied to the URL being fetched, but a proxy- address is also attacker-controllable and is handed to Chromium's- --proxy-server. Validate it with the same not-is_global rule. Honors- CRAWL4AI_ALLOW_INTERNAL_URLS. Raises ValueError (opaque) on a blocked host."""- if ALLOW_INTERNAL_URLS or not server:- return- s = str(server)- # proxy strings may be "scheme://host:port" or bare "host:port"- parsed = urlparse(s if "://" in s else "//" + s)- host = parsed.hostname- if not host:- raise ValueError("Invalid proxy server")- # Reuse the destination check (resolve + not-is_global on transition forms).- validate_webhook_url(f"http://{host}")---def scrub_browser_extra_args(extra_args):- """Drop egress/DNS-redirecting Chromium flags from caller-supplied args.-- The supported way to set a proxy is proxy_config (validated). Raw- --proxy-*/--host-resolver-rules flags bypass that validation and re-enable- the SSRF, so they are removed. Returns the filtered list."""- if not extra_args:- return extra_args- return [- a for a in extra_args- if not any(str(a).startswith(bad) for bad in _DANGEROUS_BROWSER_ARGS)- ]+ resolve_and_pin(url)+ except EgressBlocked:+ raise ValueError("URL blocked")def verify_email_domain(email: str) -> bool:diff --git a/deploy/docker/webhook.py b/deploy/docker/webhook.pyindex 0dffd327..a05e6e40 100644--- a/deploy/docker/webhook.py+++ b/deploy/docker/webhook.py@@ -4,14 +4,49 @@ Webhook delivery service for Crawl4AI.This module provides webhook notification functionality with exponential backoff retry logic."""import asyncio-import httpximport loggingimport re-from typing import Dict, Optional+import socket+from typing import Dict, List, Optionalfrom datetime import datetime, timezone+import aiohttp+from aiohttp.abc import AbstractResolver+logger = logging.getLogger(__name__)+_MAX_WEBHOOK_REDIRECTS = 5+++class _WebhookBlocked(Exception):+ """Webhook target (or a redirect hop) resolved to a non-global address."""+++class _PinnedResolver(AbstractResolver):+ """aiohttp resolver that returns a single pre-pinned IP for the target host.++ aiohttp connects to this IP but still performs TLS SNI / certificate+ verification against the original hostname, so this pins the connection+ (closing DNS rebinding) without weakening TLS or doing a MITM.+ """++ def __init__(self, host: str, ip: str):+ self._host = host+ self._ip = ip++ async def resolve(self, host, port=0, family=socket.AF_INET):+ return [{+ "hostname": host,+ "host": self._ip,+ "port": port,+ "family": family,+ "proto": 0,+ "flags": 0,+ }]++ async def close(self):+ pass+# Webhook request-header policy: user-controlled outbound headers could inject# hop-by-hop / smuggling headers or CRLF. Allow only well-formed names, reject# control chars in values, and deny sensitive/hop-by-hop names.@@ -77,60 +112,73 @@ class WebhookDeliveryService:Returns:bool: True if delivered successfully, False otherwise"""- # SECURITY: Validate webhook URL at send time (defense-in-depth against SSRF)- from utils import validate_webhook_url- validate_webhook_url(webhook_url)-default_headers = self.config.get("headers", {})try:safe_custom = sanitize_webhook_headers(headers)except ValueError as e:+ # Defense in depth (the schema validator rejects these at request+ # time); never send a forged/unsafe header.logger.warning(f"Dropping unsafe webhook headers: {e}")safe_custom = {}merged_headers = {**default_headers, **safe_custom}merged_headers["Content-Type"] = "application/json"- async with httpx.AsyncClient(timeout=self.timeout, follow_redirects=False) as client:- for attempt in range(self.max_attempts):- try:- logger.info(- f"Sending webhook (attempt {attempt + 1}/{self.max_attempts}) to {webhook_url}"- )-- response = await client.post(- webhook_url,- json=payload,- headers=merged_headers- )-- # Success or client error (don't retry client errors)- if response.status_code < 500:- if 200 <= response.status_code < 300:- logger.info(f"Webhook delivered successfully to {webhook_url}")- return True- else:- logger.warning(- f"Webhook rejected with status {response.status_code}: {response.text[:200]}"- )- return False # Client error - don't retry-- # Server error - retry with backoff- logger.warning(- f"Webhook failed with status {response.status_code}, will retry"- )-- except httpx.TimeoutException as exc:- logger.error(f"Webhook timeout (attempt {attempt + 1}): {exc}")- except httpx.RequestError as exc:- logger.error(f"Webhook request error (attempt {attempt + 1}): {exc}")- except Exception as exc:- logger.error(f"Webhook delivery error (attempt {attempt + 1}): {exc}")-- # Calculate exponential backoff delay- if attempt < self.max_attempts - 1:- delay = min(self.initial_delay * (2 ** attempt), self.max_delay)- logger.info(f"Retrying in {delay}s...")- await asyncio.sleep(delay)+ for attempt in range(self.max_attempts):+ try:+ status = await self._deliver(webhook_url, payload, merged_headers)+ if 200 <= status < 300:+ logger.info("Webhook delivered successfully")+ return True+ if status < 500:+ logger.warning(f"Webhook rejected with status {status}")+ return False # client error - don't retry+ logger.warning(f"Webhook failed with status {status}, will retry")+ except _WebhookBlocked as exc:+ # SSRF: target (or a redirect hop) resolved non-global. Do not+ # retry - it will not become safe.+ logger.warning(f"Webhook blocked (SSRF protection): {exc}")+ return False+ except Exception as exc:+ logger.error(f"Webhook delivery error (attempt {attempt + 1}): {exc}")++ if attempt < self.max_attempts - 1:+ delay = min(self.initial_delay * (2 ** attempt), self.max_delay)+ await asyncio.sleep(delay)+ return False++ async def _deliver(self, url: str, payload: Dict, headers: Dict[str, str]) -> int:+ """POST with the connection pinned to the validated IP, following (and+ re-validating) redirects manually. Returns the final status code."""+ from egress_broker import resolve_and_pin, check_redirect, EgressBlocked, ALLOW_INSECURE_TLS++ current = url+ for _hop in range(_MAX_WEBHOOK_REDIRECTS + 1):+ try:+ pin = resolve_and_pin(current)+ except EgressBlocked as e:+ raise _WebhookBlocked(str(e))++ connector = aiohttp.TCPConnector(resolver=_PinnedResolver(pin.host, pin.ip))+ ssl = None if not ALLOW_INSECURE_TLS else False+ timeout = aiohttp.ClientTimeout(total=self.timeout)+ async with aiohttp.ClientSession(connector=connector, timeout=timeout) as session:+ async with session.post(+ current, json=payload, headers=headers,+ allow_redirects=False, ssl=ssl,+ ) as resp:+ if resp.status in (301, 302, 303, 307, 308):+ loc = resp.headers.get("Location")+ if not loc:+ return resp.status+ # Re-validate every redirect hop before following it.+ try:+ check_redirect(loc)+ except EgressBlocked as e:+ raise _WebhookBlocked(f"redirect to blocked target: {e}")+ current = loc+ continue+ return resp.status+ raise _WebhookBlocked("too many webhook redirects")logger.error(f"Webhook delivery failed after {self.max_attempts} attempts to {webhook_url}"diff --git a/deploy/docker/work_queue.py b/deploy/docker/work_queue.pynew file mode 100644index 00000000..6176e4f2--- /dev/null+++ b/deploy/docker/work_queue.py@@ -0,0 +1,110 @@+"""+work_queue.py - bounded background-job execution with per-principal quotas.++/crawl/job and /llm/job used FastAPI BackgroundTasks with no bound: a client+could enqueue unlimited background jobs and exhaust memory / browser slots, and+one caller could starve others.++This replaces that with a fixed worker pool draining an asyncio.Queue, plus an+optional per-principal concurrency cap. Everything is configurable, and any+limit set to 0 (or null) means "unbounded" - i.e. the previous behavior is fully+recoverable:++ limits.queue.maxsize 0 => unbounded queue (never 503)+ limits.queue.workers worker pool size (>=1)+ limits.queue.per_principal 0 => no per-caller cap (never 429)+"""++from __future__ import annotations++import asyncio+import logging+from typing import Awaitable, Callable, Dict, Optional++logger = logging.getLogger("crawl4ai.workqueue")++JobFactory = Callable[[], Awaitable[None]]+++class QueueFull(Exception):+ """The bounded job queue is full -> 503 Retry-After."""+++class QuotaExceeded(Exception):+ """The principal has too many concurrent jobs -> 429."""+++class WorkQueue:+ def __init__(self, maxsize: int = 0, workers: int = 4, per_principal: int = 0):+ self.maxsize = max(0, int(maxsize)) # 0 = unbounded+ self.workers = max(1, int(workers))+ self.per_principal = max(0, int(per_principal)) # 0 = unlimited+ self._q: Optional[asyncio.Queue] = None+ self._tasks: list = []+ self._counts: Dict[str, int] = {}++ @property+ def started(self) -> bool:+ return self._q is not None++ async def start(self) -> None:+ self._q = asyncio.Queue(maxsize=self.maxsize)+ self._tasks = [asyncio.create_task(self._worker()) for _ in range(self.workers)]+ logger.info(+ "work queue started (maxsize=%s, workers=%s, per_principal=%s)",+ self.maxsize or "unbounded", self.workers, self.per_principal or "unlimited",+ )++ async def stop(self) -> None:+ for t in self._tasks:+ t.cancel()+ self._tasks = []+ self._q = None++ async def _worker(self) -> None:+ assert self._q is not None+ while True:+ principal, factory = await self._q.get()+ try:+ await factory()+ except Exception:+ logger.exception("background job failed")+ finally:+ self._release(principal)+ self._q.task_done()++ def _release(self, principal: Optional[str]) -> None:+ if not principal:+ return+ n = self._counts.get(principal, 0) - 1+ if n <= 0:+ self._counts.pop(principal, None)+ else:+ self._counts[principal] = n++ def submit(self, factory: JobFactory, principal: Optional[str] = None) -> None:+ """Enqueue a job. Raises QuotaExceeded / QueueFull (mapped to 429 / 503)."""+ if self._q is None:+ raise RuntimeError("work queue not started")+ if self.per_principal and principal:+ if self._counts.get(principal, 0) >= self.per_principal:+ raise QuotaExceeded()+ try:+ self._q.put_nowait((principal, factory))+ except asyncio.QueueFull:+ raise QueueFull()+ if principal:+ self._counts[principal] = self._counts.get(principal, 0) + 1+++# Process-wide singleton, set at server boot.+_JOB_QUEUE: Optional[WorkQueue] = None+++def set_job_queue(q: Optional[WorkQueue]) -> None:+ global _JOB_QUEUE+ _JOB_QUEUE = q+++def get_job_queue() -> Optional[WorkQueue]:+ return _JOB_QUEUEdiff --git a/docker-compose.yml b/docker-compose.ymlindex cb99c18f..1355439f 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -16,8 +16,22 @@ x-base-config: &base-config# - MISTRAL_API_KEY=${MISTRAL_API_KEY:-}# - GEMINI_API_KEY=${GEMINI_API_KEY:-}# - LLM_PROVIDER=${LLM_PROVIDER:-} # Optional: Override default provider (e.g., "anthropic/claude-3-opus")- volumes:- - /dev/shm:/dev/shm # Chromium performance+ # Chromium needs shared memory but the host /dev/shm bind was a shared,+ # writable mount; use a private sized tmpfs instead.+ shm_size: "1gb"+ # Least privilege: drop all capabilities, forbid privilege escalation, cap PIDs.+ cap_drop:+ - ALL+ security_opt:+ - no-new-privileges:true+ pids_limit: 512+ # Read-only root filesystem; only these paths are writable (tmpfs).+ read_only: true+ tmpfs:+ - /tmp+ - /var/lib/redis+ - /var/lib/crawl4ai/outputs:mode=0700+ - /home/appuser/.cachedeploy:resources:limits:diff --git a/docs/blog/release-v0.9.0.md b/docs/blog/release-v0.9.0.mdnew file mode 100644index 00000000..cbb874cb--- /dev/null+++ b/docs/blog/release-v0.9.0.md@@ -0,0 +1,78 @@+# Crawl4AI v0.9.0: Secure-by-Default Docker Server++*June 2026 - 6 min read*++---++I'm releasing Crawl4AI v0.9.0, a major, secure-by-default release of the Crawl4AI Docker API server. This is the biggest change to the self-hosted HTTP server since we shipped it. It moves the out-of-the-box deployment from an open, trust-the-caller posture to a closed, hardened one with defense in depth.++This is a breaking release for the Docker server only. The core pip library (the SDK and in-process use) is unchanged. If you only `pip install crawl4ai` and drive it from Python, nothing here affects you and you can upgrade freely.++If you self-host the Docker API server, please read the [migration guide](https://github.com/unclecode/crawl4ai/blob/main/deploy/docker/MIGRATION.md) before you upgrade, and roll out behind a staging environment first.++## Why this release++Over the last few releases we patched a series of issues in the Docker server one at a time. 0.9.0 finishes the job by changing the architecture instead of patching behavior. The principle is simple: the server should be safe the moment you start it, and the network request body should be treated as untrusted input rather than a trusted control channel.++That means the permissive defaults are gone. Authentication is on by default. The server binds loopback unless you give it a token. The request body carries declarative options only. Everything that used to let a caller reach into browser internals or supply code now lives server-side, where the operator controls it.++## What changed at a glance++- **Auth on by default, loopback bind**: no unauthenticated API on `0.0.0.0`.+- **Request trust boundary**: crawl request bodies are declarative and scalar; power fields are rejected at the network edge.+- **Declarative hooks**: a fixed action set replaces request-supplied hook code.+- **Artifact store**: `output_path` is gone; screenshots and PDFs return an artifact id you fetch with auth.+- **Provider by name**: LLM endpoints select a provider by name, configured server-side.+- **Hardened transport and infra**: TLS verification on, deny-by-default CORS, strict security headers, password-protected loopback-only Redis, a bounded job queue, and generic error responses with correlation ids.++## Hardening details++### Authentication and binding++The server no longer serves an unauthenticated API on `0.0.0.0`. With no token configured it binds `127.0.0.1` only and prints a one-off token at startup for local use. To expose it, set a token and put a TLS-terminating reverse proxy in front:++```bash+export CRAWL4AI_API_TOKEN="$(openssl rand -hex 32)"+```++Every request except `GET /health` then needs `Authorization: Bearer <token>`. WebSocket clients that cannot set headers may pass `?token=...`. The JWT implementation changed, so tokens from older versions are no longer valid; re-mint via `POST /token`.++### The request trust boundary++A crawl request body now carries declarative, scalar options only. Fields that previously let a caller drive browser internals or arbitrary code are rejected with HTTP 400 at the network boundary, including `js_code`, `c4a_script`, `proxy_config`, `extra_args`, `user_data_dir`, `cdp_url`, `cookies`, `headers`, `init_scripts`, `base_url`, `deep_crawl_strategy`, `simulate_user`, `magic`, and `process_in_browser`. Configure these server-side, or use the in-process SDK where you keep full control. Unknown fields are dropped, and timeouts, viewport, and scroll counts are clamped to safe maximums.++Request-supplied browser launch arguments (`browser_config.extra_args`) are part of this boundary and are now rejected, closing a Chromium launch-argument injection class.++### Declarative hooks++`hooks.code` (Python strings) is replaced by a fixed set of declarative actions: `block_resources`, `add_cookies`, `set_headers`, `scroll_to_bottom`, and `wait_for_timeout`. Call `GET /hooks/info` for the parameter schemas. Arbitrary hook code remains available in a self-hosted in-process build.++### Downloads, screenshots, and PDFs++Download sinks now confine writes with basename plus realpath plus `O_NOFOLLOW`, removing a path-traversal-to-file-write class. `output_path` is removed from `/screenshot` and `/pdf`; the server stores the result and returns an `artifact_id` plus a URL, which you fetch with authenticated `GET /artifacts/{artifact_id}` (artifacts have a TTL and a storage quota).++### SSRF on the streaming path++Destination validation now covers the streaming crawl handler. `/crawl/stream` and `/crawl` with `stream=true` validate the target and return HTTP 400 for disallowed destinations, matching the non-streaming handlers.++### Transport and infrastructure++TLS verification is on; self-signed or internal targets fail by default, with explicit escape hatches (`CRAWL4AI_ALLOW_INSECURE_TLS`, `CRAWL4AI_ALLOW_INTERNAL_URLS`) for trusted internal testing. CORS is deny-by-default; allowlist your frontend origin under `security.cors_allow_origins`. Redis runs in-container, loopback-only, password-protected, with its port no longer published. Background jobs run on a bounded queue, and request size, wall-clock, and per-principal concurrency are capped (all configurable, `0` = unbounded). 5xx responses return a generic body with a correlation id you can match in the logs.++## Migrating++How much you have to do scales with how much you drove through the API. A plain "crawl these URLs with a normal config" user only needs to set a token and re-issue tokens. Everything else applies only if you used that specific feature.++Read the [migration guide](https://github.com/unclecode/crawl4ai/blob/main/deploy/docker/MIGRATION.md) first, then follow `deploy/docker/SECURITY-VERIFY.md` for the deployment checklist.++## Upgrade++```bash+pip install -U crawl4ai+```++Docker users should pull the latest image once the Docker release workflow finishes.++## Security Credits++Thank you to the researchers who disclosed these issues responsibly: Y4tacker, KOH Jun Sheng, and UDU_RisePho ([hoanggxyuuki](https://github.com/hoanggxyuuki)). Full details are in `SECURITY-CREDITS.md`.