"""SSRF-safe URL validation for every server-driven navigation. Baseline (Mimosa constraint): only http/https; the host is validated before any request and localhost, loopback, private and reserved addresses are rejected — including hostnames that merely *resolve* to them, which closes the classic `http://[username]@127.0.0.1` and DNS-rebinding openings. Layered on top (enterprise-agent-ops): per-environment allow/block lists (settings.allowed_domains / settings.blocked_domains) act as a live kill switch without a redeploy. """ from __future__ import annotations import ipaddress import socket from collections.abc import Callable from dataclasses import dataclass from typing import Any from urllib.parse import urlsplit _ALLOWED_SCHEMES = ("http", "https") # Host names that mean "this machine" regardless of what DNS says. _LOCAL_HOST_SUFFIXES = (".localhost", ".local", ".home.arpa") _LOCAL_HOST_NAMES = {"localhost", "localhost.localdomain"} class BlockedUrlError(ValueError): """Raised when a URL fails the navigation guard.""" @dataclass(frozen=True) class GuardPolicy: """Domain kill switches; empty allow-list means "all public domains".""" allowed_domains: tuple[str, ...] = () blocked_domains: tuple[str, ...] = () def _ip_is_forbidden(ip: str) -> bool: """True for loopback / private / link-local / reserved / multicast / ::1.""" try: addr = ipaddress.ip_address(ip) except ValueError: return True return ( addr.is_loopback or addr.is_private or addr.is_link_local or addr.is_multicast or addr.is_reserved or addr.is_unspecified ) def host_matches(host: str, pattern: str) -> bool: """Case-insensitive match with a leading-`*.` wildcard. Shared by the HTTP navigation guard and the chat tool URL policy so both layers agree on what a domain pattern means. """ host = host.lower().rstrip(".") pattern = pattern.lower().strip().rstrip(".") if pattern.startswith("*."): suffix = pattern[2:] return host.endswith("." + suffix) return host == pattern # Backwards-compatible private alias. _host_matches = host_matches def validate_public_http_url( raw_url: str, *, policy: GuardPolicy | None = None, resolver: Callable[..., Any] | None = None, ) -> str: """Return the validated URL string, or raise BlockedUrlError. `resolver` is injectable for tests; defaults to socket.getaddrinfo so a public-looking name that resolves into loopback/private space is caught before the browser ever dials it. """ if not raw_url or not isinstance(raw_url, str): raise BlockedUrlError("URL is required") candidate = raw_url.strip() parts = urlsplit(candidate) if parts.scheme not in _ALLOWED_SCHEMES: raise BlockedUrlError(f"Only http/https URLs may be navigated to (got scheme {parts.scheme!r})") if not parts.hostname: raise BlockedUrlError("URL has no host") if parts.username or parts.password: raise BlockedUrlError("URLs with embedded credentials are not allowed") host = parts.hostname.lower().rstrip(".") port = parts.port # also validates out-of-range ports (ValueError) if host in _LOCAL_HOST_NAMES or any(host.endswith(suffix) for suffix in _LOCAL_HOST_SUFFIXES): raise BlockedUrlError(f"Host {host!r} is a loopback/local name") # Literal IPs are checked directly; names are resolved so a hostname that # lands on a forbidden address is rejected too (SSRF/DNS-rebinding guard). try: ipaddress.ip_address(host) resolved: list[str] = [host] except ValueError: resolve = resolver or socket.getaddrinfo try: infos = resolve(host, port or None) except socket.gaierror as exc: raise BlockedUrlError(f"Host {host!r} could not be resolved") from exc resolved = [str(info[4][0]) for info in infos] if not resolved: raise BlockedUrlError(f"Host {host!r} resolved to no addresses") for ip in resolved: if _ip_is_forbidden(ip): raise BlockedUrlError( f"Host {host!r} resolves to a forbidden address ({ip}); " "loopback/private/reserved targets are blocked" ) if policy is not None: if policy.allowed_domains and not any( _host_matches(host, pattern) for pattern in policy.allowed_domains ): raise BlockedUrlError(f"Host {host!r} is not on the allowed-domains list") if any(_host_matches(host, pattern) for pattern in policy.blocked_domains): raise BlockedUrlError(f"Host {host!r} is on the blocked-domains list") return candidate def policy_from_settings() -> GuardPolicy: """Build the runtime policy from the app settings singleton.""" from .config import settings return GuardPolicy( allowed_domains=tuple(settings.allowed_domains), blocked_domains=tuple(settings.blocked_domains), )