diff --git a/AGENTS.md b/AGENTS.md index 62aeb59..290378d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -69,6 +69,7 @@ Challenge corpus: `tests/fixtures/challenge/` is the single interstitial fixture ## Safety - SSRF: localhost/domain checks + blocked IP classes (loopback/private/link-local/multicast/reserved/unspecified) in `app/security/`. Do not weaken without explicit request + docs/tests. +- In-browser egress: `UrlGuard.resolve_host` is the single policy owner. `app/security/egress_proxy.py` applies it to every Chromium and request-tier connection, connecting to the IP it checked (pinned DNS). Drivers come only from `create_driver_from_fingerprint`, which binds the listener; `close_driver` releases it. Never pass `proxy=` to Botasaurus, and never drop `--proxy-bypass-list=<-loopback>`. ## Performance diff --git a/README.md b/README.md index 9e87224..e95cfed 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ Request options (contract): - `window_size`: viewport object `{ "width": 1920, "height": 1080 }` passed to driver. - `lang`: browser language passed to driver (for example `en-US`). - `headless`: pass headless browser mode to driver. Default `false`. -- `proxy`: proxy URL passed to driver. Invalid or blocked proxy URLs are rejected by SSRF guardrails. +- `proxy`: upstream `http://` proxy URL (credentials allowed) for the browser and request tiers, chained behind the service's egress guard. Invalid or blocked proxy URLs are rejected by SSRF guardrails. Success response (`ScrapeSuccess`, HTTP 200): @@ -318,13 +318,23 @@ Blocked targets include: - `localhost` and `*.localhost` - loopback addresses -- private network ranges +- private network ranges, including CGNAT shared space `100.64.0.0/10` - link-local addresses - multicast, reserved, and unspecified addresses Exception: -- IPv6 NAT64 well-known prefix `64:ff9b::/96` is allowed. +- IPv6 NAT64 well-known prefix `64:ff9b::/96` is allowed when the embedded IPv4 address is public. IPv4-mapped IPv6 (`::ffff:a.b.c.d`) is judged by its IPv4 address. + +The same policy also runs inside the browser and the request tier, not only on the input URL. Each Chromium driver (warm spares included) and each request-tier call sends all traffic through its own loopback egress proxy. That covers navigations, redirects, sub-resources, XHR/fetch, iframes and websockets. The proxy resolves each destination once, refuses blocked addresses, and connects to the exact IP it checked, so DNS rebinding cannot switch a host to a private address after the check. Chromium runs with `--proxy-bypass-list=<-loopback>` and `--disable-quic`. Each profile is seeded with the WebRTC preference `disable_non_proxied_udp`, because the matching command-line flag is ignored by the bundled Chromium. WebRTC then gathers no candidates, so it can neither send UDP to a page-chosen STUN address nor reveal the host IP. No traffic skips the proxy. + +- A refused sub-request is dropped and logged as `egress_blocked` (`dest_host`, `dest_port`, `reason`, plus the scrape's `request_id` and `host`). Each host is logged once per navigation attempt, and repeats are only counted. The page still succeeds. +- When anything was refused or failed, each egress proxy logs one `egress_summary` as it closes. The fields are `lookups`, `blocked_connections`, `blocked_unrecorded` (hosts beyond the 1024-host ledger), `dns_timeouts`, `dns_failures`, `connect_failures`, `upstream_refused`, `upstream_status` (for example `407` or `402` from a residential gateway), `upstream_configured`, `request_id` and `host`. The level is `WARNING` when the upstream refused a tunnel or DNS timed out, and `INFO` otherwise. +- A refused main-frame navigation or redirect returns `403` with `error_category: validation`, the same as the pre-check. Only hosts in the page's own navigation chain count. In the browser that is the target plus its redirect hops, taken from CDP. The request tier only follows the redirect chain, so any refusal there counts. Blocks count per navigation attempt, so a sub-request refused on an earlier retry cannot turn a later failure into a 403. +- A request `proxy` becomes the egress proxy's upstream. The proxy host is resolved and pinned the same way, and its credentials are sent as `Proxy-Authorization`. Each destination is still resolved and checked locally first, so a blocked host is refused and a host the service cannot resolve fails even if the upstream could resolve it. After the check, the upstream receives the hostname (`CONNECT host:port`, or an absolute-form URL with the original authority) and resolves it on its own network. Our private network is not reachable from there. TLS-inspecting upstreams need the name (they also need their CA trusted, which this service does not do), and geo-routed CDNs then pick the edge nearest the exit node. Only `http://` upstream proxies are supported. +- Each egress proxy resolves a host once per scrape and reuses that checked answer for the page's later connections. It holds at most 4 lookups on the shared DNS pool at once, counted until the lookup thread returns. A page that floods slow DNS names therefore stalls only its own scrape. + +Host-level egress filtering of the container network is out of scope. ## Isolation Guarantee diff --git a/app/domain/scrape_service.py b/app/domain/scrape_service.py index 382393d..73c4158 100644 --- a/app/domain/scrape_service.py +++ b/app/domain/scrape_service.py @@ -101,6 +101,17 @@ def _emit_scrape_finished( ) +def _engine_status(result: ScrapeSuccess | ScrapeError) -> int: + """HTTP status for an engine result. + + The engine's only ``validation`` error is the egress guard refusing the + page's own navigation, which is the same SSRF contract as the pre-check. + """ + if isinstance(result, ScrapeSuccess): + return 200 + return 403 if result.error_category == ErrorCategory.VALIDATION else 502 + + def _finish_outcome( *, payload: ScrapeRequest, @@ -287,7 +298,7 @@ async def _run( payload=payload, host=host, body=result, - status_code=200 if isinstance(result, ScrapeSuccess) else 502, + status_code=_engine_status(result), lease=lease, started_monotonic=started_monotonic, ) diff --git a/app/engine/browser_tier.py b/app/engine/browser_tier.py index bb64e0b..bcf9202 100644 --- a/app/engine/browser_tier.py +++ b/app/engine/browser_tier.py @@ -37,7 +37,13 @@ from app.logging_config import get_logger, log_event from app.schemas.enums import ErrorCategory, ExecutionTier, NavigationMode, TimeoutPhase from app.schemas.request import ScrapeRequest -from app.schemas.response import ScrapeError, ScrapeSuccess, XhrResponse +from app.schemas.response import ( + ScrapeError, + ScrapeSuccess, + XhrResponse, + validation_error, +) +from app.security.egress_proxy import EgressListener, driver_listener logger = get_logger() @@ -93,6 +99,21 @@ def settle_page_state( return html, meta, assessment, xhr_responses +def _egress_block( + listener: EgressListener | None, + collector: XhrCollector, + target_url: str, + request_id: str, +) -> ScrapeError | None: + """Map a refused hop of the main-frame navigation chain to the SSRF error.""" + if listener is None: + return None + reason = listener.main_frame_block(collector.main_frame_hosts) + if reason is None: + return None + return validation_error(target_url, reason, request_id=request_id) + + def _inspect_assessment( driver: DriverProtocol, collector: XhrCollector ) -> ChallengeAssessment | None: @@ -355,8 +376,16 @@ def run_browser_tier( execution_tier=ExecutionTier.BROWSER_DRIVER, ) + listener = driver_listener(driver) + if listener is not None: + # A warm spare's listener was built outside this request's context. + listener.attach_request() for attempt_index, strategy in enumerate(strategies, start=1): attempts = attempt_index + if listener is not None: + # Blocks are attributed per attempt: an earlier attempt's refused + # sub-request must not turn a later failure into an SSRF error. + listener.clear_blocked() has_more = attempt_index < len(strategies) lease.mark( TimeoutPhase.WORK, @@ -377,6 +406,10 @@ def run_browser_tier( ) try: navigate(driver, target_url, strategy, step_budget) + if ( + blocked := _egress_block(listener, collector, target_url, request_id) + ) is not None: + return blocked mid_wait = wait_for_readiness( driver, selector=payload.wait_for_selector, @@ -437,6 +470,10 @@ def run_browser_tier( attempt=attempt_index, error=str(exc), ) + if ( + blocked := _egress_block(listener, collector, target_url, request_id) + ) is not None: + return blocked assessment = _inspect_assessment(driver, collector) if assessment is None or not assessment.is_clean: return _surface_unclean( diff --git a/app/engine/driver_protocol.py b/app/engine/driver_protocol.py index 0a57dbe..9d0f06d 100644 --- a/app/engine/driver_protocol.py +++ b/app/engine/driver_protocol.py @@ -8,6 +8,7 @@ from typing import Any, Protocol from app.logging_config import get_logger, log_event +from app.security.egress_proxy import release_driver logger = get_logger() @@ -94,3 +95,5 @@ def close_driver(driver: DriverProtocol) -> None: driver.close() except Exception as exc: log_event(logger, logging.WARNING, "driver_close_failed", error=str(exc)) + finally: + release_driver(driver) diff --git a/app/engine/request_tier.py b/app/engine/request_tier.py index f7982d0..52b6400 100644 --- a/app/engine/request_tier.py +++ b/app/engine/request_tier.py @@ -17,7 +17,8 @@ from app.logging_config import get_logger, log_event from app.schemas.enums import ErrorCategory, ExecutionMode, ExecutionTier, TimeoutPhase from app.schemas.request import ScrapeRequest -from app.schemas.response import ScrapeError, ScrapeSuccess +from app.schemas.response import ScrapeError, ScrapeSuccess, validation_error +from app.security.egress_proxy import EgressListener logger = get_logger() @@ -25,6 +26,18 @@ from botasaurus.request import HttpResponse +def _redirect_chain_block( + listener: EgressListener, target_url: str, request_id: str +) -> ScrapeError | None: + """The request tier fetches only the redirect chain, so any block is SSRF.""" + blocked = listener.blocked + if not blocked: + return None + return validation_error( + target_url, next(reversed(blocked.values())), request_id=request_id + ) + + def run_request_tier( payload: ScrapeRequest, request_id: str, @@ -61,21 +74,37 @@ def run_request_tier( ) req_headers = dict(payload.headers) if payload.headers else {} - proxies = {"http": payload.proxy, "https": payload.proxy} if payload.proxy else None + # Every hop (redirects included) goes through a per-call egress listener + # that pins DNS and refuses blocked addresses; payload.proxy is its upstream. + listener = EgressListener(payload.proxy) + proxies = {"http": listener.url, "https": listener.url} - req = Request() + req: Request | None = None resp: HttpResponse | None = None try: - resp = req.get( - target_url, - headers=req_headers if req_headers else None, - cookies=payload.cookies, - user_agent=payload.effective_user_agent, - proxies=proxies, - timeout=remaining_budget, - browser="chrome", - allow_redirects=True, - ) + req = Request() + try: + resp = req.get( + target_url, + headers=req_headers if req_headers else None, + cookies=payload.cookies, + user_agent=payload.effective_user_agent, + proxies=proxies, + timeout=remaining_budget, + browser="chrome", + allow_redirects=True, + ) + except Exception: + if ( + blocked := _redirect_chain_block(listener, target_url, request_id) + ) is not None: + return blocked + raise + # A refused plain-http hop comes back as the proxy's own 403 response. + if ( + blocked := _redirect_chain_block(listener, target_url, request_id) + ) is not None: + return blocked html = resp.text or "" status_code = int(resp.status_code) if resp.status_code is not None else 200 @@ -172,7 +201,9 @@ def run_request_tier( cookies=jar_cookies(resp.cookies, target_url, final_url), ) finally: - try: - req.close() - except Exception: - pass + listener.close() + if req is not None: + try: + req.close() + except Exception: + pass diff --git a/app/engine/warm_pool.py b/app/engine/warm_pool.py index 4017011..09930a6 100644 --- a/app/engine/warm_pool.py +++ b/app/engine/warm_pool.py @@ -28,6 +28,7 @@ ) from app.infra.cgroup import cgroup_memory_under_pressure, read_cgroup_memory from app.logging_config import get_logger, log_event +from app.security.egress_proxy import EgressListener, bind_driver, seed_profile if TYPE_CHECKING: from app.schemas.request import ScrapeRequest @@ -49,7 +50,12 @@ def create_driver_from_fingerprint( fingerprint: DriverFingerprint, spare_dir: Path ) -> DriverProtocol: - """Build a Botasaurus Driver for a warm spare (lazy vendor import).""" + """Build a Botasaurus Driver behind its own egress listener (lazy vendor import). + + The user's proxy becomes the listener's upstream; Botasaurus never sees it, + so every Chromium connection passes the SSRF policy with pinned DNS. + The profile is seeded first so WebRTC cannot send UDP around the listener. + """ from typing import cast from botasaurus.browser import Driver @@ -59,12 +65,13 @@ def create_driver_from_fingerprint( if fingerprint.window_size is not None else None ) - return cast( - DriverProtocol, - Driver( + seed_profile(spare_dir) + listener = EgressListener(fingerprint.proxy) + try: + driver = Driver( headless=fingerprint.headless, enable_xvfb_virtual_display=not fingerprint.headless, - proxy=fingerprint.proxy, + arguments=listener.chrome_arguments, profile=str(spare_dir), tiny_profile=False, block_images=fingerprint.block_images, @@ -74,8 +81,12 @@ def create_driver_from_fingerprint( window_size=window_size, lang=fingerprint.lang, remove_default_browser_check_argument=True, - ), - ) + ) + except BaseException: + listener.close() + raise + bind_driver(driver, listener) + return cast(DriverProtocol, driver) @dataclass(frozen=True, slots=True) diff --git a/app/infra/xhr_collector.py b/app/infra/xhr_collector.py index cad7ad7..d2da42e 100644 --- a/app/infra/xhr_collector.py +++ b/app/infra/xhr_collector.py @@ -8,7 +8,9 @@ import base64 import threading -from typing import cast +from collections.abc import Generator +from typing import Any, cast +from urllib.parse import urlsplit from app.engine.driver_protocol import CdpTabProtocol from app.infra.cdp_types import PendingXhrMeta @@ -19,6 +21,12 @@ logger = get_logger() +def _main_frame_id() -> Generator[dict[str, object], dict[str, Any], str]: + """CDP ``Page.getFrameTree`` reduced to the top-level frame id.""" + result = yield {"method": "Page.getFrameTree"} + return str(result["frameTree"]["frame"]["id"]) + + class XhrCollector: """Collects JSON XHR/fetch response bodies via CDP handlers.""" @@ -35,6 +43,8 @@ def __init__(self, target_url: str) -> None: self._collected: list[XhrResponse] = [] self._aggregate_bytes: int = 0 self._document: DocumentResponse | None = None + self._main_frame_hosts: list[str] = [] + self._main_frame_id: str | None = None self._lock = threading.Lock() def install(self, tab: CdpTabProtocol) -> None: @@ -45,6 +55,14 @@ def install(self, tab: CdpTabProtocol) -> None: tab.send(enable_network()) tab.after_response_received(self._on_response) tab.add_handler(cdp.network.LoadingFinished, self._on_finished) + tab.add_handler(cdp.network.RequestWillBeSent, self._on_request) + try: + main_frame_id = tab.send(_main_frame_id()) + except Exception as exc: + logger.debug("main_frame_id_unavailable error=%s", exc) + main_frame_id = None + with self._lock: + self._main_frame_id = main_frame_id def reset(self) -> None: """Clear pending/ready/collected state between strategy attempts.""" @@ -54,6 +72,7 @@ def reset(self) -> None: self._collected.clear() self._aggregate_bytes = 0 self._document = None + self._main_frame_hosts.clear() @property def document(self) -> DocumentResponse | None: @@ -61,6 +80,32 @@ def document(self) -> DocumentResponse | None: with self._lock: return self._document + @property + def main_frame_hosts(self) -> tuple[str, ...]: + """Hosts the main frame navigated to: target plus every redirect hop.""" + with self._lock: + return tuple(self._main_frame_hosts) + + def _on_request(self, event: object) -> None: + # Iframe navigations are Documents with request id == loader id too; + # only the top-level frame counts. Redirect hops re-fire per hop. + resource_type = getattr(getattr(event, "type_", None), "value", None) + frame_id = getattr(event, "frame_id", None) + if ( + resource_type != "Document" + or self._main_frame_id is None + or frame_id is None + or str(frame_id) != self._main_frame_id + ): + return + url = str(getattr(getattr(event, "request", None), "url", "") or "") + host = urlsplit(url).hostname + if host is None: + return + with self._lock: + if host not in self._main_frame_hosts: + self._main_frame_hosts.append(host) + @classmethod def _allowlisted_headers(cls, headers: object) -> dict[str, str]: """Keep only content-type; drop Set-Cookie and other headers.""" diff --git a/app/logging_config.py b/app/logging_config.py index 74f4f78..4375ecf 100644 --- a/app/logging_config.py +++ b/app/logging_config.py @@ -26,6 +26,11 @@ def get_logger() -> logging.Logger: return logging.getLogger(LOGGER_NAME) +def request_log_fields() -> dict[str, str]: + """Current request context, for events logged later from another thread.""" + return dict(_request_context.get()) + + @contextmanager def request_log_context(**fields: str) -> Generator[None]: """Attach ``fields`` (request_id, host) to every JSON record in this scope. diff --git a/app/schemas/request.py b/app/schemas/request.py index d9e26be..2d2deb7 100644 --- a/app/schemas/request.py +++ b/app/schemas/request.py @@ -140,7 +140,12 @@ class ScrapeRequest(BaseModel): ) proxy: str | None = Field( default=None, - description="Proxy URL passed to the driver. Invalid or blocked proxy URLs are rejected by SSRF guardrails.", + description=( + "Upstream proxy URL (http:// only, credentials allowed). It is the egress " + "guard's next hop for both tiers; every destination is still resolved and " + "checked locally against the SSRF policy first. Non-http, invalid, or " + "blocked proxy URLs are rejected by SSRF guardrails." + ), examples=["http://user:pass@proxy.example:8080"], ) diff --git a/app/security/egress_proxy.py b/app/security/egress_proxy.py new file mode 100644 index 0000000..2677390 --- /dev/null +++ b/app/security/egress_proxy.py @@ -0,0 +1,476 @@ +"""Pinned-DNS egress proxy: the SSRF policy applied to every outbound connection. + +Chromium (``--proxy-server``) and the request tier send all traffic through a +per-driver/per-call loopback listener. The listener resolves each destination +once via ``UrlGuard.resolve_host``, refuses blocked addresses, and connects to +the exact IP it checked, so DNS rebinding cannot swap the address afterwards. +WebRTC, which would send UDP around any HTTP proxy, is limited to proxied +transports through the profile (``seed_profile``). +With an upstream proxy, the destination is still checked first, but the +upstream receives the hostname and resolves it on its own network. +""" + +import asyncio +import base64 +import json +import logging +import threading +import time +import weakref +from collections import Counter +from collections.abc import Awaitable, Callable, Iterable +from concurrent.futures import ThreadPoolExecutor +from functools import partial +from pathlib import Path +from types import TracebackType +from typing import Any, Self +from urllib.parse import unquote, urlsplit + +from app.logging_config import get_logger, log_event, request_log_fields +from app.security.url_guard import PinnedHost, UrlGuard, ValidationResult + +logger = get_logger() + +type Streams = tuple[asyncio.StreamReader, asyncio.StreamWriter] +type Connector = Callable[[str, int], Awaitable[Streams]] +type HostResolver = Callable[[str, int], PinnedHost | ValidationResult] + +# Module-level so tests can shorten them. +RESOLVE_TIMEOUT_SECONDS = 5.0 +# Lookups one listener may hold on the DNS pool, counted until the thread +# returns (a timed-out getaddrinfo keeps its thread). +DNS_SLOTS_PER_LISTENER = 4 +HEAD_TIMEOUT_SECONDS = 10.0 +BLOCKED_LEDGER_LIMIT = 1024 +_HEAD_LIMIT = 64 * 1024 +_PUMP_CHUNK = 64 * 1024 +_HOP_HEADERS = frozenset( + {"connection", "keep-alive", "proxy-connection", "proxy-authorization"} +) +_FORBIDDEN = b"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" +_BAD_GATEWAY = ( + b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" +) +_ESTABLISHED = b"HTTP/1.1 200 Connection Established\r\n\r\n" + +# getaddrinfo is blocking and cannot be cancelled; a dedicated pool keeps slow +# DNS off the loop's default executor. 32 workers hold the slots of 8 +# listeners (default 4 scrape workers plus a warm spare fit), so one hostile +# page cannot starve another scrape's lookups. +_dns_executor = ThreadPoolExecutor(max_workers=32, thread_name_prefix="egress-dns") +_loop_lock = threading.Lock() +_loop: asyncio.AbstractEventLoop | None = None +_driver_listeners: weakref.WeakKeyDictionary[object, EgressListener] = ( + weakref.WeakKeyDictionary() +) + + +class EgressBlockedError(Exception): + """Destination refused by the SSRF policy.""" + + +_monotonic = time.monotonic + + +class _EgressLoop(asyncio.SelectorEventLoop): + # Bound at import so patched ``time.monotonic`` (tests) cannot stall it. + def time(self) -> float: + return _monotonic() + + +def _shared_loop() -> asyncio.AbstractEventLoop: + global _loop + with _loop_lock: + if _loop is None: + loop = _EgressLoop() + threading.Thread( + target=loop.run_forever, name="egress-proxy", daemon=True + ).start() + _loop = loop + return _loop + + +async def _open_tcp(host: str, port: int) -> Streams: + return await asyncio.open_connection(host, port, limit=_HEAD_LIMIT) + + +async def _pump(src: asyncio.StreamReader, dst: asyncio.StreamWriter) -> None: + try: + while chunk := await src.read(_PUMP_CHUNK): + dst.write(chunk) + await dst.drain() + # Half-close: the peer may still be answering the other direction. + if dst.can_write_eof(): + dst.write_eof() + except OSError: + dst.close() + + +def _authority(address: str, port: int) -> str: + return f"[{address}]:{port}" if ":" in address else f"{address}:{port}" + + +def _split_authority(authority: str, default_port: int) -> tuple[str, int]: + parsed = urlsplit(f"//{authority}") + if not parsed.hostname: + raise ValueError(f"invalid authority: {authority!r}") + return parsed.hostname, parsed.port or default_port + + +class EgressListener: + """One loopback proxy listener; ``upstream`` is the user's optional next hop.""" + + def __init__( + self, + upstream: str | None = None, + *, + resolve: HostResolver = UrlGuard.resolve_host, + connect: Connector = _open_tcp, + ) -> None: + self._resolve = resolve + self._connect = connect + self._upstream_host: str | None = None + self._upstream_port = 0 + self._upstream_auth: str | None = None + if upstream: + parsed = urlsplit(upstream) + if parsed.scheme != "http" or not parsed.hostname: + raise ValueError("Only http:// upstream proxies are supported") + self._upstream_host = parsed.hostname + self._upstream_port = parsed.port or 80 + if parsed.username is not None: + raw = f"{unquote(parsed.username)}:{unquote(parsed.password or '')}" + self._upstream_auth = base64.b64encode(raw.encode()).decode("ascii") + self._blocked: dict[str, str] = {} + self._blocked_lock = threading.Lock() + # Loop-thread only: per-scrape pins (failures are not kept) and slots. + self._pins: dict[tuple[str, int], asyncio.Future[PinnedHost]] = {} + self._dns_slots = asyncio.Semaphore(DNS_SLOTS_PER_LISTENER) + # The listener logs from its loop and DNS threads, which never see the + # caller's request context; ``attach_request`` re-captures it. + self._log_fields = request_log_fields() + self._stats: Counter[str] = Counter() + self._upstream_status: str | None = None + self._closed = False + self._loop = _shared_loop() + self._server = asyncio.run_coroutine_threadsafe( + asyncio.start_server(self._handle, "127.0.0.1", 0, limit=_HEAD_LIMIT), + self._loop, + ).result(timeout=5) + self.port: int = self._server.sockets[0].getsockname()[1] + + @property + def url(self) -> str: + return f"http://127.0.0.1:{self.port}" + + @property + def chrome_arguments(self) -> list[str]: + # Chromium bypasses proxies for loopback unless told otherwise; QUIC + # would also skip the guard. WebRTC UDP is closed by ``seed_profile``. + return [ + f"--proxy-server={self.url}", + "--proxy-bypass-list=<-loopback>", + "--disable-quic", + ] + + @property + def blocked(self) -> dict[str, str]: + """Blocked destination host → policy reason, in block order.""" + with self._blocked_lock: + return dict(self._blocked) + + def clear_blocked(self) -> None: + """Start a new navigation attempt with an empty ledger.""" + with self._blocked_lock: + self._blocked.clear() + + def main_frame_block(self, navigation_hosts: Iterable[str]) -> str | None: + """Reason when a host of the page's own navigation chain was refused. + + Only hosts the main frame navigated to (target plus redirect hops) + count; refused sub-requests never turn into an SSRF error. + """ + blocked = self.blocked + for host in navigation_hosts: + if (reason := blocked.get(host.lower().rstrip("."))) is not None: + return reason + return None + + def attach_request(self) -> None: + """Tag later egress events with the current request (warm spares).""" + self._log_fields = request_log_fields() + + def close(self) -> None: + def _shutdown() -> None: + self._server.close() + self._server.close_clients() + + if not self._loop.is_closed(): + self._loop.call_soon_threadsafe(_shutdown) + with self._blocked_lock: + if self._closed: + return + self._closed = True + stats = dict(self._stats) + self._log_summary(stats) + + def _log_summary(self, stats: dict[str, int]) -> None: + """One event per listener (scrape) when anything was refused or failed.""" + if not any(v for k, v in stats.items() if k != "lookups"): + return + degraded = stats.get("upstream_refused", 0) or stats.get("dns_timeouts", 0) + log_event( + logger, + logging.WARNING if degraded else logging.INFO, + "egress_summary", + upstream_configured=self._upstream_host is not None, + upstream_status=self._upstream_status, + lookups=stats.get("lookups", 0), + blocked_connections=stats.get("blocked_connections", 0), + blocked_unrecorded=stats.get("blocked_unrecorded", 0), + dns_timeouts=stats.get("dns_timeouts", 0), + dns_failures=stats.get("dns_failures", 0), + connect_failures=stats.get("connect_failures", 0), + upstream_refused=stats.get("upstream_refused", 0), + request_id=self._log_fields.get("request_id"), + host=self._log_fields.get("host"), + ) + + def __enter__(self) -> Self: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + self.close() + + def _decide(self, host: str, port: int) -> PinnedHost: + decision = self._resolve(host, port) + if isinstance(decision, PinnedHost): + return decision + if decision.status_code != 403: + raise OSError(decision.error_message or "Hostname could not be resolved") + reason = decision.error_message or "Target is blocked" + key = host.lower().rstrip(".") + # One entry per host, first reason kept; once full, new hosts are still + # refused but not recorded, so a flood can never evict an earlier + # (typically main-frame) hit. + with self._blocked_lock: + self._stats["blocked_connections"] += 1 + first = key not in self._blocked + if first and len(self._blocked) >= BLOCKED_LEDGER_LIMIT: + self._stats["blocked_unrecorded"] += 1 + first = False + elif first: + self._blocked[key] = reason + # Logged once per host and attempt; repeats only count in the summary. + if first: + log_event( + logger, + logging.WARNING, + "egress_blocked", + dest_host=host, + dest_port=port, + reason=reason, + request_id=self._log_fields.get("request_id"), + host=self._log_fields.get("host"), + ) + raise EgressBlockedError(reason) + + async def _pin(self, host: str, port: int) -> PinnedHost: + """Resolve once per scrape; concurrent connections share one lookup. + + A pinned answer is reused for the listener's lifetime (one scrape), so + a page's many connections cost one lookup per host. Refusals and + failures are dropped, so each attempt re-records its blocks. + """ + key = (host.lower().rstrip("."), port) + pinned = self._pins.get(key) + if pinned is None: + pinned = asyncio.ensure_future( + asyncio.wait_for(self._lookup(host, port), RESOLVE_TIMEOUT_SECONDS) + ) + self._pins[key] = pinned + self._count("lookups") + pinned.add_done_callback(partial(self._forget_failed, key)) + return await asyncio.shield(pinned) + + def _forget_failed( + self, key: tuple[str, int], pinned: asyncio.Future[PinnedHost] + ) -> None: + if pinned.cancelled(): + self._pins.pop(key, None) + return + error = pinned.exception() + if error is None: + return + self._pins.pop(key, None) + if isinstance(error, TimeoutError): + self._count("dns_timeouts") + elif not isinstance(error, EgressBlockedError): + self._count("dns_failures") + + def _count(self, stat: str) -> None: + with self._blocked_lock: + self._stats[stat] += 1 + + async def _lookup(self, host: str, port: int) -> PinnedHost: + loop = asyncio.get_running_loop() + await self._dns_slots.acquire() + job = _dns_executor.submit(self._decide, host, port) + # Free the slot when the thread returns, not when the caller gives up. + job.add_done_callback( + lambda _: loop.call_soon_threadsafe(self._dns_slots.release) + ) + return await asyncio.wrap_future(job) + + async def _pinned_connect(self, host: str, port: int) -> Streams: + pinned = await self._pin(host, port) + last_error: OSError | None = None + for address in pinned.addresses: + try: + return await self._connect(str(address), port) + except OSError as exc: + last_error = exc + self._count("connect_failures") + raise last_error or OSError(f"no address for {host}") + + async def _open_destination(self, host: str, port: int) -> tuple[Streams, str]: + """Open the next hop; returns streams and the authority for the upstream.""" + if self._upstream_host is None: + streams = await self._pinned_connect(host, port) + return streams, "" + # The destination must still pass the local check, but the upstream gets + # the hostname: it resolves on its own network, which cannot reach ours, + # and TLS-inspecting or geo-routing upstreams need the name. The upstream + # hop itself is pinned like any destination. + await self._pin(host, port) + streams = await self._pinned_connect(self._upstream_host, self._upstream_port) + return streams, _authority(host, port) + + def _proxy_auth_line(self) -> str: + if self._upstream_auth is None: + return "" + return f"Proxy-Authorization: Basic {self._upstream_auth}\r\n" + + async def _handle( + self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter + ) -> None: + try: + head = await asyncio.wait_for( + reader.readuntil(b"\r\n\r\n"), HEAD_TIMEOUT_SECONDS + ) + request_line, *header_lines = head.decode("latin-1").split("\r\n") + method, target, version = request_line.split(" ", 2) + if method.upper() == "CONNECT": + host, port = _split_authority(target, 443) + (up_reader, up_writer), authority = await self._open_destination( + host, port + ) + if self._upstream_host is not None: + up_writer.write( + ( + f"CONNECT {authority} HTTP/1.1\r\nHost: {authority}\r\n" + f"{self._proxy_auth_line()}\r\n" + ).encode("latin-1") + ) + reply = await asyncio.wait_for( + up_reader.readuntil(b"\r\n\r\n"), HEAD_TIMEOUT_SECONDS + ) + if (status := reply.split(b" ", 2)[1:2]) != [b"200"]: + # e.g. 407 bad credentials or 402 quota: the operator's + # proxy, not the target, refused the tunnel. + self._count("upstream_refused") + self._upstream_status = ( + status[0].decode("latin-1") if status else "invalid" + ) + up_writer.close() + writer.write(_BAD_GATEWAY) + return + writer.write(_ESTABLISHED) + else: + parsed = urlsplit(target) + if parsed.scheme != "http" or not parsed.hostname: + raise ValueError(f"unsupported proxy target: {target!r}") + (up_reader, up_writer), authority = await self._open_destination( + parsed.hostname, parsed.port or 80 + ) + origin = parsed.path or "/" + if parsed.query: + origin = f"{origin}?{parsed.query}" + if self._upstream_host is None: + line = f"{method} {origin} {version}\r\n" + else: + line = ( + f"{method} http://{authority}{origin} {version}\r\n" + f"{self._proxy_auth_line()}" + ) + kept = [ + h + for h in header_lines + if h and h.split(":", 1)[0].strip().lower() not in _HOP_HEADERS + ] + up_writer.write( + ( + line + + "".join(f"{h}\r\n" for h in kept) + + "Connection: close\r\n\r\n" + ).encode("latin-1") + ) + await writer.drain() + try: + await asyncio.gather(_pump(reader, up_writer), _pump(up_reader, writer)) + finally: + up_writer.close() + except EgressBlockedError: + writer.write(_FORBIDDEN) + except ( + OSError, + ValueError, + asyncio.IncompleteReadError, + asyncio.LimitOverrunError, + ): + writer.write(_BAD_GATEWAY) + finally: + writer.close() + + +def seed_profile(profile_dir: Path) -> None: + """Restrict WebRTC to proxied transports before Chromium starts. + + WebRTC sends STUN/TURN over raw UDP to page-chosen addresses, which no + HTTP proxy sees. ``--force-webrtc-ip-handling-policy`` is ignored by the + bundled Chromium, so the policy is set in the profile's preferences; with + no UDP proxy, WebRTC then gathers no candidates at all. + """ + prefs_path = profile_dir / "Default" / "Preferences" + prefs_path.parent.mkdir(parents=True, exist_ok=True) + prefs: dict[str, Any] = ( + json.loads(prefs_path.read_text()) if prefs_path.exists() else {} + ) + prefs["webrtc"] = { + **prefs.get("webrtc", {}), + "ip_handling_policy": "disable_non_proxied_udp", + "multiple_routes_enabled": False, + "nonproxied_udp_enabled": False, + } + prefs_path.write_text(json.dumps(prefs)) + + +def bind_driver(driver: object, listener: EgressListener) -> None: + """Tie ``listener`` to ``driver``; it closes with the driver (or its GC).""" + _driver_listeners[driver] = listener + weakref.finalize(driver, listener.close) + + +def driver_listener(driver: object) -> EgressListener | None: + return _driver_listeners.get(driver) + + +def release_driver(driver: object) -> None: + listener = _driver_listeners.pop(driver, None) + if listener is not None: + listener.close() diff --git a/app/security/url_guard.py b/app/security/url_guard.py index ce65f48..6f2fb50 100644 --- a/app/security/url_guard.py +++ b/app/security/url_guard.py @@ -2,10 +2,33 @@ import ipaddress import socket +from collections.abc import Callable, Sequence from dataclasses import dataclass from urllib.parse import urlparse _NAT64_WELL_KNOWN_PREFIX = ipaddress.ip_network("64:ff9b::/96") +# Not globally routable, yet missed by the stdlib ``is_*`` flags. +_EXTRA_BLOCKED_NETWORKS = ( + # RFC 6598 shared space (CGNAT); cloud-internal (e.g. 100.100.100.200). + ipaddress.ip_network("100.64.0.0/10"), + # Deprecated 6to4 relay anycast (RFC 7526). + ipaddress.ip_network("192.88.99.0/24"), + # ORCHIDv2 (RFC 7343), non-routable identifiers. + ipaddress.ip_network("2001:20::/28"), + # Deprecated IPv6 site-local (RFC 3879). + ipaddress.ip_network("fec0::/10"), +) +# Local and cloud-metadata names, refused before resolution. +_BLOCKED_HOSTNAMES = frozenset({"localhost", "metadata.google.internal"}) + +type IPAddress = ipaddress.IPv4Address | ipaddress.IPv6Address +type Resolver = Callable[[str, int | None], Sequence[str]] + + +def system_resolve(host: str, port: int | None) -> list[str]: + """Resolve every address for ``host``; raises ``socket.gaierror``.""" + infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) + return [str(info[4][0]) for info in infos if info[4]] @dataclass(frozen=True, slots=True) @@ -15,11 +38,21 @@ class ValidationResult: error_message: str | None = None +@dataclass(frozen=True, slots=True) +class PinnedHost: + """Addresses checked for ``host``; callers connect to these, never re-resolve.""" + + host: str + addresses: tuple[IPAddress, ...] + + class UrlGuard: """Deep module enforcing network security and SSRF prevention guardrails.""" @classmethod - def is_blocked_ip(cls, ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool: + def is_blocked_ip(cls, ip: IPAddress) -> bool: + if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None: + return cls.is_blocked_ip(ip.ipv4_mapped) if isinstance(ip, ipaddress.IPv6Address) and ip in _NAT64_WELL_KNOWN_PREFIX: try: embedded_ipv4 = ipaddress.IPv4Address(ip.packed[-4:]) @@ -29,6 +62,7 @@ def is_blocked_ip(cls, ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> boo return ( ip.is_loopback + or any(ip in network for network in _EXTRA_BLOCKED_NETWORKS) or ip.is_private or ip.is_link_local or ip.is_multicast @@ -54,8 +88,20 @@ def validate(cls, raw_url: str) -> ValidationResult: error_message="URL must include a hostname", ) - normalized_host = host.strip().lower().rstrip(".") - if normalized_host == "localhost" or normalized_host.endswith(".localhost"): + decision = cls.resolve_host(host, parsed.port) + if isinstance(decision, ValidationResult): + return decision + return ValidationResult(is_allowed=True, status_code=200, error_message=None) + + @classmethod + def resolve_host( + cls, host: str, port: int | None, resolver: Resolver = system_resolve + ) -> PinnedHost | ValidationResult: + """Resolve ``host`` once and allow it only if every address is public.""" + normalized_host = host.strip().strip("[]").lower().rstrip(".") + if normalized_host in _BLOCKED_HOSTNAMES or normalized_host.endswith( + ".localhost" + ): return ValidationResult( is_allowed=False, status_code=403, @@ -63,23 +109,18 @@ def validate(cls, raw_url: str) -> ValidationResult: ) try: - addr_infos = socket.getaddrinfo(host, parsed.port, type=socket.SOCK_STREAM) - except socket.gaierror: + ip_texts = resolver(normalized_host, port) + except OSError, UnicodeError: return ValidationResult( is_allowed=False, status_code=400, error_message="Hostname could not be resolved", ) - resolved_ips: set[str] = set() - for info in addr_infos: - sockaddr = info[4] - if sockaddr: - resolved_ips.add(str(sockaddr[0])) - - for ip_text in resolved_ips: + addresses: list[IPAddress] = [] + for ip_text in dict.fromkeys(ip_texts): try: - ip = ipaddress.ip_address(ip_text) + ip = ipaddress.ip_address(ip_text.split("%", 1)[0]) except ValueError: continue if cls.is_blocked_ip(ip): @@ -88,11 +129,24 @@ def validate(cls, raw_url: str) -> ValidationResult: status_code=403, error_message=f"Target resolved to blocked IP address: {ip_text}", ) - - return ValidationResult(is_allowed=True, status_code=200, error_message=None) + addresses.append(ip) + if not addresses: + return ValidationResult( + is_allowed=False, + status_code=400, + error_message="Hostname could not be resolved", + ) + return PinnedHost(host=normalized_host, addresses=tuple(addresses)) @classmethod def validate_proxy(cls, proxy_url: str) -> ValidationResult: + # The egress proxy chains to plain-HTTP upstreams only. + if urlparse(proxy_url).scheme != "http": + return ValidationResult( + is_allowed=False, + status_code=400, + error_message="Proxy URL is invalid or blocked: Only http:// proxy URLs are supported", + ) result = cls.validate(proxy_url) if not result.is_allowed: return ValidationResult( diff --git a/openapi.yaml b/openapi.yaml index 16b9c78..cb40024 100644 --- a/openapi.yaml +++ b/openapi.yaml @@ -525,8 +525,10 @@ components: - type: string - type: 'null' title: Proxy - description: Proxy URL passed to the driver. Invalid or blocked proxy URLs - are rejected by SSRF guardrails. + description: Upstream proxy URL (http:// only, credentials allowed). It + is the egress guard's next hop for both tiers; every destination is still + resolved and checked locally against the SSRF policy first. Non-http, + invalid, or blocked proxy URLs are rejected by SSRF guardrails. examples: - http://user:pass@proxy.example:8080 type: object diff --git a/scripts/smoke.sh b/scripts/smoke.sh index d748b58..e956bf7 100755 --- a/scripts/smoke.sh +++ b/scripts/smoke.sh @@ -334,6 +334,100 @@ assert_no_tmp_bota() { echo "[smoke] /tmp usage after browser scrape: ${tmp_usage}" } +assert_chrome_egress_guard() { + # The /scrape pre-check rejects private targets before Chromium boots, so + # drive the service's own driver factory inside the container: sub-requests + # and a main-frame navigation to internal targets must be refused by the + # egress listener (the API on :4010 must never be served to Chromium). + echo "[smoke] Checking in-Chromium egress guard (sub-requests + main frame)" + local probe_out + probe_out="$(docker exec -i "${CONTAINER_NAME}" python - <<'PY' 2>&1 +import tempfile +import time +from pathlib import Path + +from app.engine.driver_protocol import close_driver, resolve_cdp_tab +from app.infra.xhr_collector import XhrCollector +from app.engine.warm_pool import DriverFingerprint, create_driver_from_fingerprint +from app.security.egress_proxy import driver_listener + +fingerprint = DriverFingerprint( + headless=True, proxy=None, block_images=False, block_images_and_css=False, + wait_for_complete_page_load=False, user_agent=None, window_size=None, lang=None, +) +driver = create_driver_from_fingerprint(fingerprint, Path(tempfile.mkdtemp(dir="/tmp"))) +try: + listener = driver_listener(driver) + assert listener is not None, "driver has no egress listener" + collector = XhrCollector("http://127.0.0.1:4010/health") + tab = resolve_cdp_tab(driver) + assert tab is not None, "no CDP tab" + collector.install(tab) + driver.get( + "data:text/html,

probe

" + "" + "", + timeout=20, + ) + deadline = time.monotonic() + 10 + while time.monotonic() < deadline and not {"169.254.169.254", "10.0.0.1"} <= set(listener.blocked): + time.sleep(0.2) + assert {"169.254.169.254", "10.0.0.1"} <= set(listener.blocked), listener.blocked + assert "probe" in (driver.page_html or ""), "page with blocked sub-requests did not render" + # WebRTC sends raw UDP no HTTP proxy sees; the seeded profile must stop + # it from gathering any candidate (host, srflx, or via a private STUN). + candidates = driver.run_js( + "return new Promise(res => { const out = [];" + " const pc = new RTCPeerConnection({iceServers: [{urls: 'stun:10.0.0.1:3478'}," + " {urls: 'stun:stun.l.google.com:19302'}]});" + " pc.createDataChannel('x');" + " pc.onicecandidate = e => e.candidate ? out.push(e.candidate.candidate) : res(out);" + " pc.createOffer().then(o => pc.setLocalDescription(o));" + " setTimeout(() => res(out), 5000); })" + ) + assert candidates == [], candidates + # A page can also hand Chromium a remote candidate; ICE checks to it would + # be UDP to a page-chosen address. None may arrive. + import socket + udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + udp.bind(("127.0.0.1", 0)) + udp.settimeout(6) + udp_port = udp.getsockname()[1] + driver.run_js( + "return new Promise(async res => {" + " const a = new RTCPeerConnection(), b = new RTCPeerConnection();" + " a.createDataChannel('x');" + " await a.setLocalDescription(await a.createOffer());" + " await b.setRemoteDescription(a.localDescription);" + " await b.setLocalDescription(await b.createAnswer());" + " await a.setRemoteDescription(b.localDescription);" + " await a.addIceCandidate({candidate: 'candidate:1 1 udp 2122260223 127.0.0.1 " + + str(udp_port) + + " typ host', sdpMid: '0'});" + " setTimeout(() => res(a.iceConnectionState), 3000); })" + ) + try: + udp.recvfrom(2048) + raise AssertionError("WebRTC sent UDP to a page-supplied remote candidate") + except TimeoutError: + pass + finally: + udp.close() + # Iframe navigations are Documents too; they must not count as main frame. + assert not {"10.0.0.1", "169.254.169.254"} & set(collector.main_frame_hosts), collector.main_frame_hosts + driver.get("http://127.0.0.1:4010/health", timeout=20) + assert "botasaurus_version" not in (driver.page_html or ""), "Chromium reached the API on loopback" + assert "127.0.0.1" in collector.main_frame_hosts, collector.main_frame_hosts + assert listener.main_frame_block(collector.main_frame_hosts), listener.blocked + print("EGRESS_PROBE_OK") +finally: + close_driver(driver) +PY +)" || fail "Egress probe failed: ${probe_out}" + echo "$probe_out" | grep -q "EGRESS_PROBE_OK" || fail "Egress probe did not pass: ${probe_out}" + echo "$probe_out" | grep -q "egress_blocked" || fail "Egress probe missing egress_blocked log: ${probe_out}" +} + start_sentry_sidecar() { SENTRY_CONTAINER="${CONTAINER_NAME}-sentry" echo "[smoke] Starting Sentry sidecar: ${SENTRY_CONTAINER}" @@ -426,6 +520,7 @@ run_contract_prewarm_off() { blocked_code="$(echo "$blocked_response" | tail -n1)" [[ "$blocked_code" == "403" ]] || fail "Expected localhost scrape 403, got ${blocked_code}" assert_json_key_nonempty "$blocked_body" "error" || fail "Blocked response missing error message" + assert_chrome_egress_guard echo "[smoke] Checking execution_mode=request (fast anti-detect HTTP)" local request_tier_response request_tier_body request_tier_code diff --git a/tests/api/test_http_contract.py b/tests/api/test_http_contract.py index bf1d766..4545b1d 100644 --- a/tests/api/test_http_contract.py +++ b/tests/api/test_http_contract.py @@ -10,7 +10,12 @@ ExecutionTier, ) from app.schemas.request import ScrapeRequest -from app.schemas.response import ScrapeDiagnostics, ScrapeSuccess +from app.schemas.response import ( + ScrapeDiagnostics, + ScrapeError, + ScrapeSuccess, + validation_error, +) from tests.support.http import ExecuteSideEffect, test_client @@ -137,6 +142,31 @@ def test_blocked_proxy_returns_403_before_execution(self): self.assertEqual(body["error_category"], "validation") self.assertEqual(body["diagnostics"]["request_id"], self.REQUEST_ID) + def test_in_browser_egress_block_returns_403(self): + # The engine reports a refused main-frame navigation as the SSRF body. + def blocked_execute( + payload: ScrapeRequest, + deadline_monotonic: float | None = None, + *, + request_id: str | None = None, + lease: WorkLease | None = None, + ) -> ScrapeError: + del deadline_monotonic, lease + return validation_error( + str(payload.url), + "Target resolved to blocked IP address: 169.254.169.254", + request_id=request_id, + ) + + side_effect: ExecuteSideEffect = blocked_execute + with test_client(execute_side_effect=side_effect) as client: + response = self._post(client, {"url": "https://example.com"}) + self.assertEqual(response.status_code, 403) + body = response.json() + self.assertEqual(body["error_category"], "validation") + self.assertIn("169.254.169.254", body["error"]) + self.assertNotIn("html", body) + class SchemaValidationHttpTests(unittest.TestCase): def test_empty_body_returns_validation_error_envelope(self): diff --git a/tests/engine/test_driver_profile.py b/tests/engine/test_driver_profile.py index 538849a..57bf174 100644 --- a/tests/engine/test_driver_profile.py +++ b/tests/engine/test_driver_profile.py @@ -1,5 +1,6 @@ """Driver construction keeps Chromium's profile inside the request runtime dir.""" +import json import tempfile import unittest from pathlib import Path @@ -7,8 +8,10 @@ from app.config import get_settings from app.engine import ScraperEngine +from app.engine.driver_protocol import close_driver from app.engine.warm_pool import DriverFingerprint, create_driver_from_fingerprint from app.schemas.response import ScrapeSuccess +from app.security.egress_proxy import driver_listener from tests.support.factories import scrape_request from tests.support.fakes import CaptureDriver @@ -26,7 +29,7 @@ def test_create_driver_from_fingerprint_disables_tiny_profile(self) -> None: window_size={"width": 1280, "height": 720}, ) fingerprint = DriverFingerprint.from_request(payload) - profile_dir = Path("/tmp/scrape/req-profile/profile") + profile_dir = Path(self.enterContext(tempfile.TemporaryDirectory())) with patch("botasaurus.browser.Driver", CaptureDriver): driver = create_driver_from_fingerprint(fingerprint, profile_dir) @@ -42,6 +45,32 @@ def test_create_driver_from_fingerprint_disables_tiny_profile(self) -> None: self.assertEqual(kwargs["window_size"], [1280, 720]) self.assertIs(kwargs["remove_default_browser_check_argument"], True) + def test_driver_routes_all_egress_through_its_listener(self) -> None: + payload = scrape_request( + execution_mode="browser", proxy="http://proxy.example:8080" + ) + fingerprint = DriverFingerprint.from_request(payload) + profile_dir = Path(self.enterContext(tempfile.TemporaryDirectory())) + + with patch("botasaurus.browser.Driver", CaptureDriver): + driver = create_driver_from_fingerprint(fingerprint, profile_dir) + listener = driver_listener(driver) + self.assertIsNotNone(listener) + assert listener is not None + kwargs = CaptureDriver.last_init_kwargs + assert kwargs is not None + # The user proxy is the listener's upstream, never Chromium's. + self.assertNotIn("proxy", kwargs) + self.assertEqual(kwargs["arguments"], listener.chrome_arguments) + self.assertIn("--proxy-bypass-list=<-loopback>", listener.chrome_arguments) + prefs = json.loads((profile_dir / "Default" / "Preferences").read_text()) + self.assertEqual( + prefs["webrtc"]["ip_handling_policy"], "disable_non_proxied_udp" + ) + + close_driver(driver) + self.assertIsNone(driver_listener(driver)) + def test_browser_cold_boot_uses_fingerprint_builder(self) -> None: payload = scrape_request( execution_mode="browser", diff --git a/tests/engine/test_egress_tiers.py b/tests/engine/test_egress_tiers.py new file mode 100644 index 0000000..17b17fb --- /dev/null +++ b/tests/engine/test_egress_tiers.py @@ -0,0 +1,221 @@ +"""Both tiers map an egress-guard refusal of the page's own navigation to SSRF.""" + +import socket +import tempfile +import unittest +from collections.abc import Callable +from pathlib import Path +from typing import Any +from unittest.mock import patch + +from app.config import get_settings +from app.engine import ScraperEngine +from app.schemas.enums import ErrorCategory +from app.schemas.response import ScrapeError, ScrapeSuccess +from tests.support.factories import scrape_request +from tests.support.fakes import FakeDriver, FakeDriverTab, FakeHttpResponse + +CHROME_ERROR_PREFIX = "chrome-error://" +_HTML = "

Example Domain

" + + +def _connect_via(proxy_url: str, authority: str) -> bytes: + host, port = proxy_url.removeprefix("http://").split(":") + with socket.create_connection((host, int(port)), timeout=5) as sock: + sock.sendall(f"CONNECT {authority} HTTP/1.1\r\n\r\n".encode()) + return sock.recv(65536) + + +class _RedirectToMetadataRequest: + """Follows a redirect to the metadata IP through the tier's proxy.""" + + def get(self, *_args: object, proxies: dict[str, str], **_kwargs: object) -> None: + reply = _connect_via(proxies["https"], "169.254.169.254:80") + raise RuntimeError(f"Proxy responded with non 200 code: {reply[:12]!r}") + + def close(self) -> None: + return None + + +class _PlainHttpRedirectRequest: + """tls-client returning the proxy's 403 for a plain-http redirect hop.""" + + def get( + self, *_args: object, proxies: dict[str, str], **_kwargs: object + ) -> FakeHttpResponse: + host, port = proxies["http"].removeprefix("http://").split(":") + with socket.create_connection((host, int(port)), timeout=5) as sock: + sock.sendall(b"GET http://169.254.169.254/ HTTP/1.1\r\n\r\n") + status = int(sock.recv(65536).split(b" ", 2)[1]) + return FakeHttpResponse( + text="", status_code=status, headers={}, url="http://169.254.169.254/" + ) + + def close(self) -> None: + return None + + +class _RecordingTab(FakeDriverTab): + def __init__(self) -> None: + self.handlers: dict[str, Callable[..., None]] = {} + + def add_handler(self, event_type: type[Any], handler: Any, /) -> None: + self.handlers[event_type.__name__] = handler + + def send(self, cdp_obj: Any) -> Any: + if next(cdp_obj).get("method") != "Page.getFrameTree": + return None + try: + cdp_obj.send({"frameTree": {"frame": {"id": "MAIN"}}}) + except StopIteration as exc: + return exc.value + return None + + +def _main_frame_event(url: str) -> object: + kind = type("T", (), {"value": "Document"})() + request = type("Q", (), {"url": url})() + return type( + "E", + (), + { + "request_id": "L1", + "loader_id": "L1", + "frame_id": "MAIN", + "request": request, + "type_": kind, + }, + )() + + +class _ProxyAwareDriver(FakeDriver): + """Navigates through the --proxy-server the factory configured.""" + + redirect_to: str | None = None + subrequest_to: str | None = None + fail_main_frame: bool = False + + def __init__(self, *args: object, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self._proxy = next( + a.split("=", 1)[1] + for a in kwargs["arguments"] + if a.startswith("--proxy-server=") + ) + self.page_html = _HTML + self.current_url = "https://example.com/" + self.tab = _RecordingTab() + self._tab = self.tab + + def _navigated(self, url: str) -> None: + handler = self.tab.handlers.get("RequestWillBeSent") + if handler is not None: + handler(_main_frame_event(url)) + + def get(self, *_args: object, **_kwargs: Any) -> None: + self._navigated("https://example.com/") + if (sub := type(self).subrequest_to) is not None: + _connect_via(self._proxy, sub) # e.g. ; refusal must not fail page + if type(self).fail_main_frame: + self.current_url = f"{CHROME_ERROR_PREFIX}chromewebdata/" + self.page_html = "error page" + target = type(self).redirect_to + if target is None: + return + self._navigated(f"https://{target}/") + reply = _connect_via(self._proxy, target) + if not reply.startswith(b"HTTP/1.1 200"): + self.current_url = f"{CHROME_ERROR_PREFIX}chromewebdata/" + self.page_html = "error page" + + +def _run(payload_kwargs: dict[str, Any], **patches: Any) -> ScrapeSuccess | ScrapeError: + with tempfile.TemporaryDirectory() as tmp: + engine = ScraperEngine(settings=get_settings(), runtime_root=Path(tmp)) + with ( + patch( + "botasaurus.browser.Driver", patches.get("Driver", _ProxyAwareDriver) + ), + patch("botasaurus.request.Request", patches.get("Request", object)), + ): + return engine.execute(scrape_request(**payload_kwargs)) + + +class _BlockThenUnrelatedFailureDriver(_ProxyAwareDriver): + """Attempt 1: blocked sub-request then a crash; attempt 2: plain error page.""" + + def get(self, *_args: object, **_kwargs: Any) -> None: + self.calls = getattr(self, "calls", 0) + 1 + if self.calls == 1: + _connect_via(self._proxy, "169.254.169.254:80") + raise RuntimeError("navigation crashed") + self.current_url = f"{CHROME_ERROR_PREFIX}chromewebdata/" + self.page_html = "error page" + + +class EgressTierTests(unittest.TestCase): + def test_request_tier_proxy_403_response_on_redirect_is_ssrf(self) -> None: + for mode in ("request", "auto"): + with self.subTest(mode=mode): + result = _run( + {"execution_mode": mode}, Request=_PlainHttpRedirectRequest + ) + assert isinstance(result, ScrapeError) + self.assertEqual(result.error_category, ErrorCategory.VALIDATION) + self.assertIn("169.254.169.254", result.error) + + def test_blocked_subrequest_with_unrelated_main_frame_failure_is_not_ssrf( + self, + ) -> None: + _ProxyAwareDriver.subrequest_to = "169.254.169.254:80" + _ProxyAwareDriver.fail_main_frame = True + self.addCleanup(setattr, _ProxyAwareDriver, "subrequest_to", None) + self.addCleanup(setattr, _ProxyAwareDriver, "fail_main_frame", False) + result = _run( + {"execution_mode": "browser", "navigation_mode": "get", "max_retries": 0} + ) + self.assertNotEqual( + getattr(result, "error_category", None), ErrorCategory.VALIDATION + ) + + def test_previous_attempt_block_does_not_classify_later_failure(self) -> None: + result = _run( + {"execution_mode": "browser", "navigation_mode": "get", "max_retries": 1}, + Driver=_BlockThenUnrelatedFailureDriver, + ) + self.assertEqual(result.diagnostics.attempts, 2) + self.assertNotEqual( + getattr(result, "error_category", None), ErrorCategory.VALIDATION + ) + + def test_request_tier_redirect_to_private_ip_is_ssrf_not_escalated(self) -> None: + for mode in ("request", "auto"): + with self.subTest(mode=mode): + result = _run( + {"execution_mode": mode}, Request=_RedirectToMetadataRequest + ) + assert isinstance(result, ScrapeError) + self.assertEqual(result.error_category, ErrorCategory.VALIDATION) + self.assertIn("169.254.169.254", result.error) + + def test_browser_main_frame_redirect_to_private_ip_is_ssrf(self) -> None: + _ProxyAwareDriver.redirect_to = "127.0.0.1:4010" + self.addCleanup(setattr, _ProxyAwareDriver, "redirect_to", None) + result = _run( + {"execution_mode": "browser", "navigation_mode": "get", "max_retries": 0} + ) + assert isinstance(result, ScrapeError) + self.assertEqual(result.error_category, ErrorCategory.VALIDATION) + self.assertIn("127.0.0.1", result.error) + + def test_blocked_subrequest_does_not_fail_the_page(self) -> None: + _ProxyAwareDriver.subrequest_to = "169.254.169.254:80" + self.addCleanup(setattr, _ProxyAwareDriver, "subrequest_to", None) + result = _run( + {"execution_mode": "browser", "navigation_mode": "get", "max_retries": 0} + ) + self.assertIsInstance(result, ScrapeSuccess) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/engine/test_scraper_engine.py b/tests/engine/test_scraper_engine.py index 6c7b491..9ed61de 100644 --- a/tests/engine/test_scraper_engine.py +++ b/tests/engine/test_scraper_engine.py @@ -415,9 +415,8 @@ def test_run_scrape_forwards_driver_kwargs(self): self.assertEqual(CaptureDriver.last_init_kwargs["window_size"], [1920, 1080]) self.assertEqual(CaptureDriver.last_init_kwargs["lang"], "en-US") self.assertTrue(CaptureDriver.last_init_kwargs["headless"]) - self.assertEqual( - CaptureDriver.last_init_kwargs["proxy"], "http://proxy.example:8080" - ) + # The user proxy is the egress listener's upstream, never Chromium's. + self.assertNotIn("proxy", CaptureDriver.last_init_kwargs) def test_request_tier_blocked_status_escalates_to_browser(self): from tests.support.fakes import ArticleDriver, FakeHttpResponse, FakeRequest diff --git a/tests/infra/test_xhr_collector.py b/tests/infra/test_xhr_collector.py index 34bdd70..12a9263 100644 --- a/tests/infra/test_xhr_collector.py +++ b/tests/infra/test_xhr_collector.py @@ -76,6 +76,37 @@ def test_records_main_frame_document_response(self) -> None: self.collector.reset() self.assertIsNone(self.collector.document) + def test_records_main_frame_navigation_hosts_including_redirects(self) -> None: + tab = FakeTab() + self.collector.install(tab) + handler = tab.request_handler + assert handler is not None + document_type = type("T", (), {"value": "Document"})() + image_type = type("T", (), {"value": "Image"})() + + def event(rid: str, frame: str, url: str, kind: object) -> object: + request = type("Q", (), {"url": url})() + fields = { + "request_id": rid, + "loader_id": rid, + "frame_id": frame, + "request": request, + "type_": kind, + } + return type("E", (), fields)() + + main = FakeTab.MAIN_FRAME_ID + handler(event("L1", main, "https://public.example/", document_type)) + handler(event("L1", main, "http://169.254.169.254/x", document_type)) + handler(event("R7", main, "https://10.0.0.1/pixel.gif", image_type)) + # An iframe navigation is also a Document whose request id == loader id. + handler(event("F2", "CHILD", "http://127.0.0.1/", document_type)) + self.assertEqual( + self.collector.main_frame_hosts, ("public.example", "169.254.169.254") + ) + self.collector.reset() + self.assertEqual(self.collector.main_frame_hosts, ()) + def test_install_enables_network_and_registers_handlers(self) -> None: tab = FakeTab() self.collector.install(tab) diff --git a/tests/security/test_egress_proxy.py b/tests/security/test_egress_proxy.py new file mode 100644 index 0000000..b4f2810 --- /dev/null +++ b/tests/security/test_egress_proxy.py @@ -0,0 +1,371 @@ +"""Egress listener: SSRF policy on every hop with pinned DNS.""" + +import asyncio +import base64 +import json +import socket +import tempfile +import threading +import time +import unittest +from collections.abc import Iterator, Sequence +from functools import partial +from pathlib import Path +from unittest.mock import patch + +from app.logging_config import get_logger, request_log_context +from app.security import egress_proxy +from app.security.egress_proxy import EgressListener, Streams +from app.security.url_guard import PinnedHost, UrlGuard + +PUBLIC_IP = "93.184.215.14" + + +def _resolver(*answers: Sequence[str]): + """Return a resolver yielding each answer in turn (TTL-0 rebinding).""" + queue: Iterator[Sequence[str]] = iter(answers) + + def resolve(host: str, port: int | None) -> Sequence[str]: + del host, port + return next(queue) + + return resolve + + +def _exchange(listener: EgressListener, raw: bytes) -> bytes: + with socket.create_connection(("127.0.0.1", listener.port), timeout=5) as sock: + sock.sendall(raw) + sock.shutdown(socket.SHUT_WR) + chunks: list[bytes] = [] + while chunk := sock.recv(65536): + chunks.append(chunk) + return b"".join(chunks) + + +class _Origin: + """One-shot TCP peer that records the request head and sends ``reply``.""" + + def __init__(self, reply: bytes) -> None: + self.received = b"" + self._reply = reply + self._sock = socket.create_server(("127.0.0.1", 0)) + self.port: int = self._sock.getsockname()[1] + threading.Thread(target=self._serve, daemon=True).start() + + def _serve(self) -> None: + conn, _ = self._sock.accept() + with conn: + while b"\r\n\r\n" not in self.received: + chunk = conn.recv(65536) + if not chunk: + break + self.received += chunk + conn.sendall(self._reply) + self._sock.close() + + +class _RefusingConnect: + async def __call__(self, host: str, port: int) -> Streams: + raise ConnectionRefusedError(f"{host}:{port}") + + +class _RecordingConnect: + def __init__(self, origin_port: int) -> None: + self.calls: list[tuple[str, int]] = [] + self._origin_port = origin_port + + async def __call__(self, host: str, port: int) -> Streams: + self.calls.append((host, port)) + return await asyncio.open_connection("127.0.0.1", self._origin_port) + + +class EgressListenerTests(unittest.TestCase): + def test_rebinding_to_private_ip_is_refused_after_public_precheck(self) -> None: + resolve = _resolver([PUBLIC_IP], ["169.254.169.254"]) + precheck = UrlGuard.resolve_host("rebind.example", 443, resolver=resolve) + self.assertIsInstance(precheck, PinnedHost) + + connect = _RecordingConnect(origin_port=9) + with EgressListener( + resolve=partial(UrlGuard.resolve_host, resolver=resolve), connect=connect + ) as listener: + reply = _exchange(listener, b"CONNECT rebind.example:443 HTTP/1.1\r\n\r\n") + + self.assertTrue(reply.startswith(b"HTTP/1.1 403")) + self.assertEqual(connect.calls, []) + self.assertIn("169.254.169.254", listener.blocked["rebind.example"]) + + def test_connects_to_the_checked_address_not_the_hostname(self) -> None: + origin = _Origin(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") + connect = _RecordingConnect(origin.port) + resolve = partial(UrlGuard.resolve_host, resolver=_resolver([PUBLIC_IP])) + with EgressListener(resolve=resolve, connect=connect) as listener: + reply = _exchange( + listener, + b"GET http://pinned.example/feed?x=1 HTTP/1.1\r\n" + b"Host: pinned.example\r\nProxy-Connection: keep-alive\r\n\r\n", + ) + + self.assertEqual(connect.calls, [(PUBLIC_IP, 80)]) + self.assertTrue(reply.endswith(b"ok")) + self.assertTrue(origin.received.startswith(b"GET /feed?x=1 HTTP/1.1\r\n")) + self.assertIn(b"Connection: close\r\n", origin.received) + self.assertNotIn(b"Proxy-Connection", origin.received) + self.assertEqual(listener.blocked, {}) + + def test_blocks_private_literals_on_every_hop_kind(self) -> None: + cases = [ + b"CONNECT 127.0.0.1:4010 HTTP/1.1\r\n\r\n", + b"CONNECT [::ffff:169.254.169.254]:443 HTTP/1.1\r\n\r\n", + b"GET http://169.254.169.254/latest/meta-data/ HTTP/1.1\r\n\r\n", + b"GET http://10.0.0.1/ HTTP/1.1\r\n\r\n", + b"CONNECT localhost:443 HTTP/1.1\r\n\r\n", + ] + with EgressListener() as listener: + for raw in cases: + with self.subTest(raw=raw): + self.assertTrue( + _exchange(listener, raw).startswith(b"HTTP/1.1 403") + ) + self.assertEqual( + set(listener.blocked), + { + "127.0.0.1", + "::ffff:169.254.169.254", + "169.254.169.254", + "10.0.0.1", + "localhost", + }, + ) + + def test_upstream_gets_checked_hostname_and_auth(self) -> None: + upstream = _Origin(b"HTTP/1.1 200 Connection established\r\n\r\n") + connect = _RecordingConnect(upstream.port) + resolve = partial( + UrlGuard.resolve_host, resolver=_resolver([PUBLIC_IP], ["8.8.4.4"]) + ) + with EgressListener( + "http://user:p%40ss@proxy.example:8080", resolve=resolve, connect=connect + ) as listener: + reply = _exchange(listener, b"CONNECT example.com:443 HTTP/1.1\r\n\r\n") + + self.assertTrue(reply.startswith(b"HTTP/1.1 200")) + self.assertEqual(connect.calls, [("8.8.4.4", 8080)]) + token = base64.b64encode(b"user:p@ss").decode() + self.assertIn( + f"Proxy-Authorization: Basic {token}\r\n".encode(), upstream.received + ) + # The destination was checked locally; the upstream still gets the name. + self.assertTrue(upstream.received.startswith(b"CONNECT example.com:443 ")) + + def test_upstream_plain_http_keeps_hostname_authority(self) -> None: + upstream = _Origin(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") + connect = _RecordingConnect(upstream.port) + resolve = partial( + UrlGuard.resolve_host, resolver=_resolver([PUBLIC_IP], ["8.8.4.4"]) + ) + with EgressListener( + "http://proxy.example:8080", resolve=resolve, connect=connect + ) as listener: + reply = _exchange( + listener, + b"GET http://pinned.example/feed HTTP/1.1\r\nHost: pinned.example\r\n\r\n", + ) + self.assertTrue(reply.endswith(b"ok")) + self.assertTrue( + upstream.received.startswith(b"GET http://pinned.example:80/feed ") + ) + self.assertIn(b"Host: pinned.example\r\n", upstream.received) + + def test_upstream_mode_still_refuses_private_destination(self) -> None: + connect = _RecordingConnect(origin_port=9) + with EgressListener("http://proxy.example:8080", connect=connect) as listener: + reply = _exchange(listener, b"CONNECT 169.254.169.254:80 HTTP/1.1\r\n\r\n") + self.assertTrue(reply.startswith(b"HTTP/1.1 403")) + self.assertEqual(connect.calls, []) + + def test_main_frame_block_only_matches_navigation_hosts(self) -> None: + with EgressListener() as listener: + _exchange(listener, b"CONNECT 10.0.0.1:443 HTTP/1.1\r\n\r\n") + self.assertIsNone(listener.main_frame_block(["example.com"])) + _exchange(listener, b"CONNECT 127.0.0.1:443 HTTP/1.1\r\n\r\n") + reason = listener.main_frame_block(["example.com", "127.0.0.1"]) + self.assertIsNotNone(reason) + assert reason is not None + self.assertIn("127.0.0.1", reason) + + def test_blocked_ledger_dedupes_hosts_and_never_evicts(self) -> None: + with ( + patch.object(egress_proxy, "BLOCKED_LEDGER_LIMIT", 4), + EgressListener() as listener, + ): + _exchange(listener, b"CONNECT 127.0.0.1:443 HTTP/1.1\r\n\r\n") + for _ in range(10): + _exchange(listener, b"CONNECT 10.0.0.1:443 HTTP/1.1\r\n\r\n") + for octet in range(2, 9): + raw = f"CONNECT 10.0.0.{octet}:443 HTTP/1.1\r\n\r\n".encode() + self.assertTrue(_exchange(listener, raw).startswith(b"HTTP/1.1 403")) + blocked = listener.blocked + self.assertEqual( + list(blocked), ["127.0.0.1", "10.0.0.1", "10.0.0.2", "10.0.0.3"] + ) + + def test_resolution_runs_on_bounded_dns_executor(self) -> None: + seen: list[str] = [] + + def resolver(_h: str, _p: int | None) -> list[str]: + seen.append(threading.current_thread().name) + return ["10.0.0.9"] + + with EgressListener( + resolve=partial(UrlGuard.resolve_host, resolver=resolver) + ) as listener: + _exchange(listener, b"CONNECT slow.example:443 HTTP/1.1\r\n\r\n") + self.assertTrue(seen and seen[0].startswith("egress-dns")) + + def test_slow_resolution_times_out_as_bad_gateway(self) -> None: + def resolver(_h: str, _p: int | None) -> list[str]: + time.sleep(0.5) + return [PUBLIC_IP] + + with ( + patch.object(egress_proxy, "RESOLVE_TIMEOUT_SECONDS", 0.1), + EgressListener( + resolve=partial(UrlGuard.resolve_host, resolver=resolver) + ) as listener, + ): + reply = _exchange(listener, b"CONNECT slow.example:443 HTTP/1.1\r\n\r\n") + self.assertTrue(reply.startswith(b"HTTP/1.1 502")) + + def test_pinned_answer_is_reused_across_connections(self) -> None: + lookups: list[str] = [] + + def resolver(host: str, _p: int | None) -> list[str]: + lookups.append(host) + return [PUBLIC_IP] + + with EgressListener( + resolve=partial(UrlGuard.resolve_host, resolver=resolver), + connect=_RefusingConnect(), + ) as listener: + for _ in range(3): + _exchange(listener, b"CONNECT pub.example:443 HTTP/1.1\r\n\r\n") + self.assertEqual(lookups, ["pub.example"]) + + def test_hung_lookups_hold_only_their_own_listener_slots(self) -> None: + release = threading.Event() + + def resolver(host: str, _p: int | None) -> list[str]: + if host == "hang.example": + release.wait(5) + return ["10.0.0.9"] + + resolve = partial(UrlGuard.resolve_host, resolver=resolver) + connect_hang = b"CONNECT hang.example:443 HTTP/1.1\r\n\r\n" + connect_other = b"CONNECT other.example:443 HTTP/1.1\r\n\r\n" + with ( + patch.object(egress_proxy, "RESOLVE_TIMEOUT_SECONDS", 0.2), + patch.object(egress_proxy, "DNS_SLOTS_PER_LISTENER", 1), + EgressListener(resolve=resolve) as hostile, + EgressListener(resolve=resolve) as other, + ): + try: + self.assertTrue( + _exchange(hostile, connect_hang).startswith(b"HTTP/1.1 502") + ) + # The timed-out thread still holds the slot ... + self.assertTrue( + _exchange(hostile, connect_other).startswith(b"HTTP/1.1 502") + ) + # ... but another listener's lookups are unaffected. + self.assertTrue( + _exchange(other, connect_other).startswith(b"HTTP/1.1 403") + ) + finally: + release.set() + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if _exchange(hostile, connect_other).startswith(b"HTTP/1.1 403"): + break + time.sleep(0.05) + else: + self.fail("slot was not released after the lookup returned") + + def test_silent_client_is_dropped_after_head_timeout(self) -> None: + with ( + patch.object(egress_proxy, "HEAD_TIMEOUT_SECONDS", 0.1), + EgressListener() as listener, + socket.create_connection(("127.0.0.1", listener.port), timeout=5) as sock, + ): + started = time.monotonic() + reply = sock.recv(65536) + self.assertTrue(reply.startswith(b"HTTP/1.1 502")) + self.assertLess(time.monotonic() - started, 3) + + def test_chrome_arguments_force_loopback_through_proxy(self) -> None: + with EgressListener() as listener: + args = listener.chrome_arguments + self.assertIn(f"--proxy-server={listener.url}", args) + self.assertIn("--proxy-bypass-list=<-loopback>", args) + self.assertIn("--disable-quic", args) + + def test_blocked_host_is_logged_once_with_request_context(self) -> None: + with ( + self.assertLogs(get_logger(), "INFO") as logs, + request_log_context(request_id="req-1", host="page.example"), + EgressListener() as listener, + ): + for _ in range(3): + _exchange(listener, b"CONNECT 10.0.0.1:443 HTTP/1.1\r\n\r\n") + events = [ + (getattr(r, "event_name", None), getattr(r, "event_fields", {})) + for r in logs.records + ] + blocked = [f for name, f in events if name == "egress_blocked"] + self.assertEqual(len(blocked), 1) + self.assertEqual(blocked[0]["request_id"], "req-1") + (summary,) = [f for name, f in events if name == "egress_summary"] + self.assertEqual(summary["blocked_connections"], 3) + self.assertEqual(summary["request_id"], "req-1") + + def test_upstream_refusal_is_summarised_as_warning(self) -> None: + upstream = _Origin(b"HTTP/1.1 407 Proxy Authentication Required\r\n\r\n") + resolve = partial( + UrlGuard.resolve_host, resolver=_resolver([PUBLIC_IP], ["8.8.4.4"]) + ) + with ( + self.assertLogs(get_logger(), "WARNING") as logs, + EgressListener( + "http://proxy.example:8080", + resolve=resolve, + connect=_RecordingConnect(upstream.port), + ) as listener, + ): + reply = _exchange(listener, b"CONNECT example.com:443 HTTP/1.1\r\n\r\n") + self.assertTrue(reply.startswith(b"HTTP/1.1 502")) + (record,) = [ + r + for r in logs.records + if getattr(r, "event_name", None) == "egress_summary" + ] + fields = getattr(record, "event_fields", {}) + self.assertEqual(fields["upstream_refused"], 1) + self.assertEqual(fields["upstream_status"], "407") + + def test_quiet_listener_logs_no_summary(self) -> None: + with self.assertNoLogs(get_logger(), "INFO"): + EgressListener().close() + + def test_seed_profile_keeps_existing_prefs(self) -> None: + with tempfile.TemporaryDirectory() as tmp: + prefs_path = Path(tmp) / "Default" / "Preferences" + prefs_path.parent.mkdir() + prefs_path.write_text('{"intl": {"accept_languages": "de"}}') + egress_proxy.seed_profile(Path(tmp)) + prefs = json.loads(prefs_path.read_text()) + self.assertEqual(prefs["intl"], {"accept_languages": "de"}) + self.assertFalse(prefs["webrtc"]["nonproxied_udp_enabled"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/security/test_url_guard.py b/tests/security/test_url_guard.py index db4ef98..5666b05 100644 --- a/tests/security/test_url_guard.py +++ b/tests/security/test_url_guard.py @@ -38,3 +38,47 @@ def test_is_blocked_ip_allows_well_known_nat64_prefix(self): def test_is_blocked_ip_still_blocks_loopback(self): loopback = ipaddress.ip_address("127.0.0.1") self.assertTrue(UrlGuard.is_blocked_ip(loopback)) + + +class UrlGuardResolveHostTests(unittest.TestCase): + def test_cgnat_shared_address_space_is_blocked(self): + self.assertTrue(UrlGuard.is_blocked_ip(ipaddress.ip_address("100.100.100.200"))) + self.assertTrue(UrlGuard.is_blocked_ip(ipaddress.ip_address("100.64.0.1"))) + self.assertFalse(UrlGuard.is_blocked_ip(ipaddress.ip_address("100.128.0.1"))) + + def test_non_routable_ranges_missed_by_stdlib_are_blocked(self): + for text in ("192.88.99.1", "2001:20::1", "fec0::1"): + with self.subTest(ip=text): + self.assertTrue(UrlGuard.is_blocked_ip(ipaddress.ip_address(text))) + + def test_cloud_metadata_hostname_is_blocked_before_resolution(self): + decision = UrlGuard.resolve_host( + "Metadata.Google.Internal.", 80, resolver=lambda _h, _p: ["93.184.215.14"] + ) + self.assertEqual(getattr(decision, "status_code", None), 403) + + def test_ipv4_mapped_ipv6_is_blocked(self): + self.assertTrue( + UrlGuard.is_blocked_ip(ipaddress.ip_address("::ffff:169.254.169.254")) + ) + + def test_any_blocked_address_blocks_the_host(self): + decision = UrlGuard.resolve_host( + "mixed.example", 443, resolver=lambda _h, _p: ["93.184.215.14", "10.0.0.5"] + ) + self.assertFalse(getattr(decision, "is_allowed", True)) + self.assertEqual(getattr(decision, "status_code", None), 403) + + def test_public_host_is_pinned_to_resolved_addresses(self): + decision = UrlGuard.resolve_host( + "pub.example", 80, resolver=lambda _h, _p: ["93.184.215.14"] + ) + self.assertEqual( + getattr(decision, "addresses", None), + (ipaddress.ip_address("93.184.215.14"),), + ) + + def test_validate_proxy_rejects_non_http_scheme(self): + res = UrlGuard.validate_proxy("https://proxy.example:8443") + self.assertFalse(res.is_allowed) + self.assertEqual(res.status_code, 400) diff --git a/tests/support/fakes.py b/tests/support/fakes.py index 37f982f..608a606 100644 --- a/tests/support/fakes.py +++ b/tests/support/fakes.py @@ -252,11 +252,14 @@ def __init__( class FakeTab: """Minimal CDP tab stub for XhrCollector unit tests.""" + MAIN_FRAME_ID = "MAIN" + def __init__(self, bodies: dict[str, tuple[str, bool]] | None = None) -> None: self.bodies = bodies or {} self.network_enabled = False self.response_handler: Callable[..., None] | None = None self.finished_handler: Callable[..., None] | None = None + self.request_handler: Callable[..., None] | None = None def send(self, cdp_obj: Any) -> Any: cmd = next(cdp_obj) @@ -276,12 +279,21 @@ def send(self, cdp_obj: Any) -> Any: except StopIteration as exc: return exc.value return None + if method == "Page.getFrameTree": + try: + cdp_obj.send({"frameTree": {"frame": {"id": self.MAIN_FRAME_ID}}}) + except StopIteration as exc: + return exc.value + return None raise AssertionError(f"unexpected CDP method: {method}") def after_response_received(self, handler: Callable[..., None]) -> None: self.response_handler = handler def add_handler( - self, _event_type: type[object], handler: Callable[..., None] + self, event_type: type[object], handler: Callable[..., None] ) -> None: - self.finished_handler = handler + if event_type.__name__ == "RequestWillBeSent": + self.request_handler = handler + else: + self.finished_handler = handler diff --git a/typings/botasaurus_driver/cdp/network.pyi b/typings/botasaurus_driver/cdp/network.pyi index 3400824..85485e2 100644 --- a/typings/botasaurus_driver/cdp/network.pyi +++ b/typings/botasaurus_driver/cdp/network.pyi @@ -3,6 +3,10 @@ from typing import Any RequestId = str | int +class RequestWillBeSent: + request_id: RequestId + loader_id: str + class LoadingFinished: request_id: RequestId