# coding=utf-8 """ @Time :2026/7/9 @Author :tao.chen Generic HTTP GET proxy for the agent. Lets the agent fetch URLs on the cluster's network when it cannot reach those hosts directly. Security: the host is checked against an explicit fnmatch glob allowlist configured on the connection (`allowed_url_hosts`). Empty or missing allowlist means no URL access; IP literals and non-HTTP schemes are rejected. Reuses the connection's saved auth/SSL config so the agent doesn't need cluster credentials. """ import ipaddress import fnmatch from urllib.parse import urlparse import httpx from common.logging import logger from spark_executor.core.yarn_client import YarnClientConfig from spark_executor.models import FetchUrlResult from spark_executor.tools.connections import store as conn_store _MAX_BODY_BYTES = 1_000_000 # 1 MB cap on response body _REQUEST_TIMEOUT_SECONDS = 30 def _host_matches_any_glob(host: str, patterns: list[str]) -> bool: """True if `host` matches any of the fnmatch glob patterns. fnmatch is case-sensitive on Linux (our deployment target). `*` in a pattern does NOT cross '.' boundaries, so 'ccam*' matches 'ccam50' but NOT 'ccam50.evil.com' (which is what we want — domain boundary matters for SSRF). """ host_labels = host.split(".") for p in patterns: pat_labels = p.split(".") if len(pat_labels) != len(host_labels): continue if all(fnmatch.fnmatchcase(h, pat) for h, pat in zip(host_labels, pat_labels)): return True return False def _validate_url_host( url: str, allowed_hosts: list[str] | None, ) -> None: """Raise ValueError if the URL is not allowed to be fetched. Allowed only if the URL host matches one of the fnmatch glob patterns in `allowed_hosts`. An empty or missing allowlist rejects everything. """ parsed = urlparse(url) if parsed.scheme not in ("http", "https"): raise ValueError( f"URL scheme must be http or https, got {parsed.scheme!r}" ) host = parsed.hostname if not host: raise ValueError(f"URL has no host: {url!r}") # IP literal check try: ipaddress.ip_address(host) raise ValueError( f"URL host {host!r} is an IP literal — IP targets are not allowed. " f"Use a hostname on the cluster network." ) except ValueError as e: if "IP literal" in str(e): raise # not an IP, continue if not allowed_hosts: raise ValueError( "allowed_url_hosts is empty — set Connection.allowed_url_hosts to " "allow specific hosts before calling fetch_url (e.g. ['ccam*'] " "for ccam1-ccam99 or ['*.prod.internal'] for a subdomain)." ) if _host_matches_any_glob(host, allowed_hosts): return raise ValueError( f"URL host {host!r} is not in Connection.allowed_url_hosts " f"{allowed_hosts!r}. Reject this fetch to prevent SSRF." ) def fetch_url(url: str, connection_name: str) -> FetchUrlResult: """Proxy an HTTP GET to url using the auth/SSL settings of connection_name.""" logger.debug(f"fetch_url enter url={url} connection_name={connection_name}") conn = conn_store.get(connection_name) if conn is None: raise KeyError(f"Connection not found: {connection_name}") _validate_url_host(url, conn.allowed_url_hosts) config = YarnClientConfig.from_connection(conn) resp = httpx.get( url, auth=config.auth_for_httpx(), verify=config.verify_for_httpx(), timeout=_REQUEST_TIMEOUT_SECONDS, follow_redirects=True, ) body = resp.text[:_MAX_BODY_BYTES] truncated = len(resp.text) > _MAX_BODY_BYTES logger.info( f"fetch_url ok url={url} connection_name={connection_name} " f"status_code={resp.status_code} " f"content_type={resp.headers.get('content-type', '')} " f"body_bytes={len(body)} truncated={truncated}" ) return FetchUrlResult( url=url, status_code=resp.status_code, content_type=resp.headers.get("content-type", ""), body=body, truncated=truncated, )