Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
16 changes: 13 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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):

Expand Down Expand Up @@ -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

Expand Down
13 changes: 12 additions & 1 deletion app/domain/scrape_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
)
39 changes: 38 additions & 1 deletion app/engine/browser_tier.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down Expand Up @@ -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(
Expand Down
3 changes: 3 additions & 0 deletions app/engine/driver_protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down Expand Up @@ -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)
65 changes: 48 additions & 17 deletions app/engine/request_tier.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,27 @@
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()

if TYPE_CHECKING:
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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
25 changes: 18 additions & 7 deletions app/engine/warm_pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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,
Expand All @@ -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)
Expand Down
47 changes: 46 additions & 1 deletion app/infra/xhr_collector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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."""

Expand All @@ -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:
Expand All @@ -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."""
Expand All @@ -54,13 +72,40 @@ 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:
"""Latest main-frame document response (final hop after redirects)."""
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."""
Expand Down
Loading