The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(image_handling): answer every SSRF rejection with one message so error text cannot probe internal hostnames
mateo-berri827554954d30
diff --git a/litellm/litellm_core_utils/prompt_templates/image_handling.py b/litellm/litellm_core_utils/prompt_templates/image_handling.pyindex 99efbd13320..24f3b8bca7f 100644--- a/litellm/litellm_core_utils/prompt_templates/image_handling.py+++ b/litellm/litellm_core_utils/prompt_templates/image_handling.py@@ -15,7 +15,7 @@ import litellmfrom litellm import verbose_loggerfrom litellm.caching.caching import InMemoryCachefrom litellm.constants import MAX_IMAGE_URL_DOWNLOAD_SIZE_MB-from litellm.litellm_core_utils.url_utils import HostResolutionError, SSRFError, async_safe_get, safe_get+from litellm.litellm_core_utils.url_utils import SSRFError, async_safe_get, safe_getfrom litellm.types.llms.openai import AllMessageValuesMAX_IMGS_IN_MEMORY: Final = 10@@ -80,13 +80,9 @@ def _process_image_response(response: Response, url: str) -> str:def _rejected_image_fetch(url: str, verdict: SSRFError) -> "litellm.ImageFetchError":verbose_logger.warning("Image fetch of %s rejected before any request went out: %s", url, verdict)- if isinstance(verdict, HostResolutionError):- return litellm.ImageFetchError(- f"Error: Unable to fetch image from URL. The image host could not be resolved. url={url}"- )return litellm.ImageFetchError(- "Error: Unable to fetch image from URL. The proxy's URL policy rejected this host; "- f"an admin can allow it with `user_url_allowed_hosts` in general_settings. url={url}"+ "Error: Unable to fetch image from URL. The proxy could not resolve this host or its URL policy rejected it; "+ f"an admin can check the proxy log and `user_url_allowed_hosts` in general_settings. url={url}")diff --git a/litellm/litellm_core_utils/url_utils.py b/litellm/litellm_core_utils/url_utils.pyindex f4388d5fd12..fa070a648f5 100644--- a/litellm/litellm_core_utils/url_utils.py+++ b/litellm/litellm_core_utils/url_utils.py@@ -93,10 +93,6 @@ class SSRFError(ValueError):"""Raised when a URL targets a blocked network."""-class HostResolutionError(SSRFError):- pass--def encode_url_path_segment(value: object, *, field_name: str = "path parameter") -> str:"""Percent-encode one user-controlled URL path segment.@@ -328,10 +324,10 @@ def validate_url(url: str) -> tuple[str, str]:try:addrinfo: Final = socket.getaddrinfo(hostname, effective_port, proto=socket.IPPROTO_TCP)except socket.gaierror as e:- raise HostResolutionError(f"DNS resolution failed for '{hostname}': {e}")+ raise SSRFError(f"DNS resolution failed for '{hostname}': {e}")if not addrinfo:- raise HostResolutionError(f"No addresses found for '{hostname}'")+ raise SSRFError(f"No addresses found for '{hostname}'")if not is_allowlisted:for addrinfo_entry in addrinfo:diff --git a/tests/test_litellm/litellm_core_utils/test_image_handling.py b/tests/test_litellm/litellm_core_utils/test_image_handling.pyindex 3a909298aba..8fa4bd6c14d 100644--- a/tests/test_litellm/litellm_core_utils/test_image_handling.py+++ b/tests/test_litellm/litellm_core_utils/test_image_handling.py@@ -17,7 +17,7 @@ from litellm.litellm_core_utils.prompt_templates.image_handling import (async_inline_remote_media,convert_url_to_base64,)-from litellm.litellm_core_utils.url_utils import HostResolutionError, SSRFError+from litellm.litellm_core_utils.url_utils import SSRFError@pytest.fixture(autouse=True)@@ -425,32 +425,25 @@ async def test_async_inline_remote_media_cancels_the_other_fetches_when_one_fail_SSRF_VERDICTS = (- (- SSRFError(- "URL targets a blocked address (10.0.0.8). If this is a legitimate internal service, "- "add the host to `user_url_allowed_hosts` in general_settings."- ),- "The proxy's URL policy rejected this host; an admin can allow it with `user_url_allowed_hosts`",+ SSRFError(+ "URL targets a blocked address (10.0.0.8). If this is a legitimate internal service, "+ "add the host to `user_url_allowed_hosts` in general_settings."),- (- HostResolutionError(- "DNS resolution failed for 'internal.example': [Errno 8] nodename nor servname provided, or not known"- ),- "The image host could not be resolved",- ),- (HostResolutionError("No addresses found for 'internal.example'"), "The image host could not be resolved"),+ SSRFError("DNS resolution failed for 'internal.example': [Errno 8] nodename nor servname provided, or not known"),+ SSRFError("No addresses found for 'internal.example'"),)def _assert_verdict_free_messages(messages, url):- for message, (verdict, expected_guidance) in zip(messages, _SSRF_VERDICTS, strict=True):- assert expected_guidance in message- assert url in message- assert "10.0.0.8" not in message- assert "DNS" not in message- assert "No addresses" not in message- if isinstance(verdict, HostResolutionError):- assert "user_url_allowed_hosts" not in message+ assert len(messages) == len(_SSRF_VERDICTS)+ assert len(set(messages)) == 1, "a caller must not be able to tell a blocked host from one that does not resolve"+ message = messages[0]+ assert "The proxy could not resolve this host or its URL policy rejected it" in message+ assert "user_url_allowed_hosts" in message+ assert url in message+ assert "10.0.0.8" not in message+ assert "DNS" not in message+ assert "No addresses" not in messageasync def test_async_convert_url_to_base64_hides_the_ssrf_verdict_and_does_not_retry(monkeypatch):@@ -458,7 +451,7 @@ async def test_async_convert_url_to_base64_hides_the_ssrf_verdict_and_does_not_rmessages = []url = f"http://internal.example/{uuid.uuid4()}.png"- for verdict, _ in _SSRF_VERDICTS:+ for verdict in _SSRF_VERDICTS:async def block(client, fetched_url, verdict=verdict, **kwargs):attempts.append(fetched_url)@@ -478,7 +471,7 @@ def test_convert_url_to_base64_hides_the_ssrf_verdict_and_does_not_retry(monkeypmessages = []url = f"http://internal.example/{uuid.uuid4()}.png"- for verdict, _ in _SSRF_VERDICTS:+ for verdict in _SSRF_VERDICTS:def block(client, fetched_url, verdict=verdict, **kwargs):attempts.append(fetched_url)diff --git a/tests/test_litellm/litellm_core_utils/test_url_utils.py b/tests/test_litellm/litellm_core_utils/test_url_utils.pyindex 151c7ceb5bd..fccdc1a2a0a 100644--- a/tests/test_litellm/litellm_core_utils/test_url_utils.py+++ b/tests/test_litellm/litellm_core_utils/test_url_utils.py@@ -9,7 +9,6 @@ import pytestimport litellmfrom litellm.litellm_core_utils import url_utilsfrom litellm.litellm_core_utils.url_utils import (- HostResolutionError,SSRFError,_is_blocked_ip,assert_same_origin,@@ -162,24 +161,10 @@ class TestValidateUrl:assert "/path" in rewrittenassert "key=value" in rewritten- def test_dns_failure_raises_a_host_resolution_error(self, mock_dns_failure):- with pytest.raises(HostResolutionError, match="DNS resolution failed"):+ def test_dns_failure_raises(self, mock_dns_failure):+ with pytest.raises(SSRFError, match="DNS resolution failed"):validate_url("http://this-domain-does-not-exist-xyz123.invalid/test")- def test_empty_resolution_raises_a_host_resolution_error(self, monkeypatch):- monkeypatch.setattr(url_utils.socket, "getaddrinfo", lambda *args, **kwargs: [])- with pytest.raises(HostResolutionError, match="No addresses found"):- validate_url("http://this-domain-resolves-to-nothing.invalid/test")-- def test_blocked_address_is_not_a_host_resolution_error(self, monkeypatch):- def fake(host, port, *a, **kw):- return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("10.0.0.8", port or 80))]-- monkeypatch.setattr(url_utils.socket, "getaddrinfo", fake)- with pytest.raises(SSRFError, match="blocked address") as raised:- validate_url("http://internal.example/test")- assert not isinstance(raised.value, HostResolutionError)-def test_blocks_localhost_hostname(self, monkeypatch):def fake(host, port, *a, **kw):return [