import re import socket from ipaddress import ip_address, ip_network from time import monotonic import httpx2 DEFAULT_BASE_URL = "https://api.openai.com/v1" MAX_REPLY_BYTES = 1_048_576 PUBLIC_IPV6 = ip_network("2000::/3") SPECIAL_IPV6 = (ip_network("2001::/23"), ip_network("2002::/16")) SPECIAL_IPV4 = ip_network("192.0.0.0/24") class ProviderError(ValueError): pass def parse_base_url(value): value = value.strip() or DEFAULT_BASE_URL try: url = httpx2.URL(value) except httpx2.InvalidURL: raise ProviderError("Enter a valid HTTPS API base URL.") from None if (len(value) > 2048 or url.scheme != "https" or not url.host or url.port not in (None, 443) or url.userinfo or "?" in value or "#" in value or "\\" in value): raise ProviderError("Use an HTTPS API base URL on port 443 without credentials, a query, or a fragment.") return url.copy_with(raw_path=url.raw_path.rstrip(b"/")) def _is_public(address): if not address.is_global or address.is_multicast or address.is_reserved: return False if address.version == 4: return address not in SPECIAL_IPV4 return address in PUBLIC_IPV6 and not any(address in network for network in SPECIAL_IPV6) def _public_address(host): if not re.fullmatch(r"[a-zA-Z0-9.-]+", host) or "." not in host.rstrip("."): raise ProviderError("The API base URL must use a public hostname.") try: records = socket.getaddrinfo(host.rstrip(".") + ".", 443, type=socket.SOCK_STREAM) except OSError: raise ProviderError("Could not resolve the API base URL. Check the provider hostname.") from None addresses = [ip_address(record[4][0]) for record in records] if not addresses or not all(map(_is_public, addresses)): raise ProviderError("The API base URL must resolve to public addresses.") return str(min(addresses, key=lambda address: address.version)) class PublicProviderTransport(httpx2.HTTPTransport): def __init__(self, url): super().__init__(trust_env=False) self.host = url.raw_host.decode("ascii") self.address = _public_address(self.host) def handle_request(self, request): if (request.url.scheme != "https" or request.url.port is not None or request.url.raw_host.decode("ascii") != self.host): raise ProviderError("The API request must stay on the selected HTTPS host.") # Connect to the checked IP while keeping the original Host header and TLS hostname. pinned_request = httpx2.Request( request.method, request.url.copy_with(host=self.address), headers={**request.headers, "host": self.host, "accept-encoding": "identity"}, stream=request.stream, extensions={**request.extensions, "sni_hostname": self.host}, ) deadline = monotonic() + 25 response = super().handle_request(pinned_request) try: if 300 <= response.status_code < 400: raise ProviderError("The provider redirected the request. Enter its final API base URL.") if response.headers.get("content-encoding", "identity").lower() != "identity": raise ProviderError("The provider returned an unsupported response encoding.") body = bytearray() for chunk in response.iter_raw(): if monotonic() > deadline: raise httpx2.ReadTimeout("Provider response timed out.") if len(body) + len(chunk) > MAX_REPLY_BYTES: raise ProviderError("The provider returned a response that was too large.") body.extend(chunk) finally: response.close() return httpx2.Response(response.status_code, headers=response.headers, content=bytes(body), extensions=response.extensions)