Files
mcp-server/spark_executor/tools/fetch_url.py
T
ClaudeandClaude Fable 5 6d7387b022 feat: simplify fetch_url allowlist + add update_connection tool
Part 1 — fetch_url validation simplification
  Now that Connection.allowed_url_hosts exists, it's the ONLY check.
  The old 2-label suffix-overlap rule against yarn_rm_url is gone.

  - Connection.allowed_url_hosts: list[str] = Field(default_factory=list)
    (was list[str] | None = None). Default empty list means the
    connection has no fetch access; the user must explicitly opt in
    via save_connection or update_connection.
  - _validate_url_host drops the yarn_rm_url parameter and the
    _host_suffix_overlap helper. Now: scheme/host/IP checks, then
    empty-reject, then glob match. Reject everything else.
  - fetch_url's error message now points the user at
    Connection.allowed_url_hosts as the fix.
  - The label-by-label glob check from the previous commit is kept
    (SSRF guard: 'ccam*' matches 'ccam50' but NOT 'ccam50.evil.com').

Part 2 — update_connection tool
  PATCH-style update for an existing Connection record. Only the
  fields the caller provides are changed. Same pattern as
  update_pending_job: req.model_dump(exclude_none=True), with
  'name' popped before passing to the store.

  To CLEAR a field (e.g. drop auth_password), use delete_connection
  + save_connection. This is YAGNI; the alternative (model_fields_set
  to distinguish 'omitted' from 'null') adds surface for bugs.

  - ConnectionStore.update(name, **fields): get, model_copy(update=...),
    save. Lock + atomic write. Re-validates the patched record.
  - update_connection tool function: passes fields through to the
    store, logs which fields were changed.
  - UpdateConnectionRequest Pydantic model: 12 mutable fields + name.
  - /update_connection route with operation_id='update_connection'.
  - 9 new unit tests in test_connection_tools.py (PATCH, dict/list
    replace-not-merge, unknown name 404, validation of patched record,
    disk persistence).
  - test_fetch_url.py: existing 21 tests updated; 3 new tests for
    the empty/None/missing allowed_url_hosts cases.
  - test_mcp_routes.py: assert 22 tool routes.
  - README: update_connection row added; fetch_url row updated.

Tests: 386 passed (up from 377, +9 net).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 11:46:07 +08:00

122 lines
4.1 KiB
Python

# 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,
)