Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: validate external provider base URLs before proxying (#8549)

Daniel Han5eca9faf1d73
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index 5bd2007f1e5..d72aba48dc4 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -862,7 +862,13 @@ class ExternalProviderClient:
timeout: float = 120.0,
):
self.provider_type = provider_type
- self.base_url = base_url.rstrip("/")
+ # Single choke point for every outbound provider request (chat, models,
+ # responses, messages, containers): the URL is caller-controlled, so it
+ # is validated here even when a route already checked it. Routes turn the
+ # ValueError into a 400; reaching it here means a caller bypassed them.
+ from core.inference.providers import validate_provider_base_url
+
+ self.base_url = validate_provider_base_url(base_url)
# Strip a legacy `/openai` suffix from Google-hosted bases so configs
# saved before the native switch still route correctly. Custom proxy
# paths ending in `/openai` are left untouched.
diff --git a/studio/backend/core/inference/providers.py b/studio/backend/core/inference/providers.py
index 199de1c9552..bd0ae42c3b8 100644
--- a/studio/backend/core/inference/providers.py
+++ b/studio/backend/core/inference/providers.py
@@ -8,8 +8,11 @@ All providers expose OpenAI-compatible /v1/chat/completions endpoints
with Bearer token auth and SSE streaming.
"""
+import ipaddress
+import os
import re
from typing import Any
+from urllib.parse import urlsplit
PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
"openai_codex": {
@@ -388,6 +391,158 @@ def get_base_url(provider_type: str) -> str | None:
return info["base_url"] if info else None
+# Cloud-metadata hosts. The backend fetches the base URL on the caller's behalf,
+# so one of these would hand instance credentials to whoever asked, and no LLM
+# endpoint lives here. Refused on every deployment. Keep in sync with the
+# tool-approval gate's list in core/inference/tools.py (function-local there).
+_METADATA_HOST_NAMES = frozenset(
+ {
+ "metadata",
+ "metadata.google.internal",
+ "metadata.goog",
+ "metadata.tencentyun.com",
+ "instance-data.ec2.internal",
+ }
+)
+# Held parsed, so every spelling of the same address matches: fd00:ec2::254,
+# fd00:0ec2:0000:0000:0000:0000:0000:0254 and fd00:ec2::0.0.2.84 are one host.
+_METADATA_IPS = frozenset(
+ ipaddress.ip_address(address)
+ for address in (
+ "169.254.169.254",
+ "169.254.169.252",
+ "169.254.170.2",
+ "169.254.170.23",
+ "fd00:ec2::254",
+ "fd20:ce::254",
+ "100.100.100.200",
+ "100.100.100.110",
+ )
+)
+# Link-local, where the IPv4 metadata services live. Matched as a network so a
+# DNS name that merely starts with those digits (169.254.gateway.example.com) is
+# not mistaken for one.
+_METADATA_NETWORK = ipaddress.ip_network("169.254.0.0/16")
+
+# Opt-in for operators who expose Studio on a shared host: also refuse provider
+# URLs that resolve to a non-public address. Off by default, because loopback and
+# LAN endpoints are the normal case (Ollama, llama.cpp, vLLM, custom gateways).
+_BLOCK_PRIVATE_ENV = "UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS"
+
+
+# An all-numeric host is an IPv4 literal to the resolver, in decimal, octal or
+# hex. `ipaddress` parses only the dotted quad, so 2852039166, 0xA9FEA9FE and
+# 0251.0376.0251.0376 would read as names while getaddrinfo returns
+# 169.254.169.254.
+_NUMERIC_HOST_PART = re.compile(r"(?:0[xX][0-9a-fA-F]+|[0-9]+)")
+
+# IDNA label separators. httpx encodes a host through idna, which splits on all
+# of these, so http://169。254。169。254/ reaches 169.254.169.254.
+_IDNA_DOTS = str.maketrans({"。": ".", ".": ".", "。": "."})
+
+
+def _canonical_host(hostname: str) -> str:
+ """Return the dotted-quad form of a numeric host, else ``hostname``."""
+ parts = hostname.split(".")
+ if len(parts) > 4 or not all(_NUMERIC_HOST_PART.fullmatch(part) for part in parts):
+ return hostname
+ import socket
+
+ try:
+ # inet_aton parses every legacy spelling and never touches DNS.
+ return socket.inet_ntoa(socket.inet_aton(hostname))
+ except OSError:
+ return hostname
+
+
+def _metadata_host(hostname: str) -> bool:
+ """True when ``hostname`` names a cloud metadata service."""
+ # An IPv6 scope id (fd00:ec2::254%250 once the transport decodes it) keeps
+ # the address unequal to the unscoped entry while dialling the same host.
+ hostname = hostname.translate(_IDNA_DOTS).rstrip(".").split("%")[0]
+ hostname = _canonical_host(hostname)
+ if hostname in _METADATA_HOST_NAMES:
+ return True
+ try:
+ ip = ipaddress.ip_address(hostname)
+ except ValueError:
+ return False
+ # ::ffff:169.254.169.254 and 2002:a9fe:a9fe:: reach the same service.
+ for candidate in (getattr(ip, "ipv4_mapped", None), getattr(ip, "sixtofour", None)):
+ if candidate is not None and _metadata_host(candidate.compressed):
+ return True
+ return ip in _METADATA_IPS or (ip.version == 4 and ip in _METADATA_NETWORK)
+
+
+def _reject_non_public(hostname: str, port: int | None, scheme: str) -> None:
+ """Raise when ``hostname`` is, or resolves to, a non-public address."""
+ import socket
+
+ try:
+ addresses = [ipaddress.ip_address(hostname)]
+ except ValueError:
+ try:
+ infos = socket.getaddrinfo(
+ hostname,
+ port or (443 if scheme == "https" else 80),
+ type = socket.SOCK_STREAM,
+ )
+ except (OSError, UnicodeError) as exc:
+ raise ValueError("Provider base URL hostname could not be resolved.") from exc
+ addresses = [ipaddress.ip_address(str(info[4][0]).split("%", 1)[0]) for info in infos]
+ if not addresses or any(not ip.is_global for ip in addresses):
+ raise ValueError(
+ "Provider base URL points at a private address, which is disabled on this "
+ f"server ({_BLOCK_PRIVATE_ENV}=1)."
+ )
+
+
+def validate_provider_base_url(base_url: str) -> str:
+ """Return a normalized provider base URL, or raise ``ValueError``.
+
+ The backend issues outbound requests to this URL with the caller's decrypted
+ API key attached, so it is caller-controlled server-side egress. Only shapes
+ that can never be a real provider endpoint are refused: a non-http(s) scheme,
+ control characters, a missing host, and cloud metadata services. Plain http,
+ loopback, LAN hosts, odd ports, query strings and basic-auth userinfo all
+ stay valid -- Ollama, llama.cpp, vLLM and custom gateways rely on them. No
+ DNS lookup happens unless the private-address opt-in is set.
+
+ Normalization is strip + trailing-slash removal only (what the client did
+ before), so validating an already-validated URL returns it unchanged.
+ """
+ if not isinstance(base_url, str) or not base_url.strip():
+ raise ValueError("Provider base URL is required.")
+
+ raw = base_url.strip()
+ if any(char.isspace() or ord(char) < 32 or ord(char) == 127 for char in raw) or "\\" in raw:
+ raise ValueError("Provider base URL contains invalid characters.")
+
+ try:
+ parts = urlsplit(raw)
+ port = parts.port
+ hostname = parts.hostname
+ except ValueError as exc:
+ raise ValueError("Provider base URL is malformed.") from exc
+
+ scheme = parts.scheme.lower()
+ if scheme not in ("http", "https"):
+ raise ValueError("Provider base URL must use http or https.")
+ # Userinfo stays allowed for gateways behind basic auth; the checks below read
+ # the parsed hostname, so http://[email protected]/ is caught.
+ if not hostname:
+ raise ValueError("Provider base URL must contain a hostname.")
+
+ hostname = hostname.rstrip(".")
+ if _metadata_host(hostname):
+ raise ValueError("Cloud metadata endpoints cannot be used as a provider base URL.")
+
+ if os.environ.get(_BLOCK_PRIVATE_ENV) == "1":
+ _reject_non_public(hostname, port, scheme)
+
+ return raw.rstrip("/")
+
+
def list_available_providers() -> list[dict[str, Any]]:
"""Return all registered providers (for the /registry endpoint).
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index 27aa4a3ba35..66766c7afed 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -2313,7 +2313,11 @@ from core.inference.passthrough_healing import (
nudge_should_retry,
response_has_promotable_calls,
)
-from core.inference.providers import get_base_url
+from core.inference.providers import (
+ get_base_url,
+ get_provider_info,
+ validate_provider_base_url,
+)
from core.inference.external_provider import ExternalProviderClient
from core.inference.chat_templates import resolve_effective_chat_template_override
from routes.provider_credentials import resolve_provider_api_key_or_400
@@ -11050,14 +11054,27 @@ async def _proxy_to_external_provider(
param = "confirm_tool_calls",
),
)
- # Fall back to registry default base URL
+ # Fall back to registry default base URL. The registry lookup is checked on
+ # its own: a caller-supplied base_url used to make an unknown provider_type
+ # pass straight through to the proxy.
+ if get_provider_info(provider_type) is None:
+ raise HTTPException(
+ status_code = 400,
+ detail = f"Unknown provider type: {provider_type}",
+ )
if not base_url:
base_url = get_base_url(provider_type)
if not base_url:
raise HTTPException(
status_code = 400,
- detail = f"Unknown provider type: {provider_type}",
+ detail = f"Base URL is required for provider type: {provider_type}",
)
+ # Validate the proxy destination before the API key is decrypted, so a
+ # refused target never sees a credential.
+ try:
+ base_url = validate_provider_base_url(base_url)
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from None
if provider_type == "openai_codex":
from core.inference.openai_codex_auth import (
diff --git a/studio/backend/routes/providers.py b/studio/backend/routes/providers.py
index 0e91d1d5c83..4cd293d6c01 100644
--- a/studio/backend/routes/providers.py
+++ b/studio/backend/routes/providers.py
@@ -35,6 +35,7 @@ from core.inference.providers import (
get_base_url,
get_provider_info,
list_available_providers,
+ validate_provider_base_url,
)
from core.inference.pricing import pricing_snapshot
from core.inference.external_provider import ExternalProviderClient
@@ -178,9 +179,17 @@ async def create_provider_config(
updating = False,
)
+ base_url = payload.base_url or info["base_url"]
+ # An empty base URL stays allowed (custom/vLLM entries carry none until the
+ # user fills one in); anything present is checked before a key is decrypted.
+ if base_url:
+ try:
+ base_url = validate_provider_base_url(base_url)
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from None
+
api_key = resolve_provider_api_key_or_400(None, payload.encrypted_api_key)
provider_id = uuid.uuid4().hex[:16]
- base_url = payload.base_url or info["base_url"]
if api_key:
credential_secrets.get_or_create_credential_encryption_key()
@@ -237,6 +246,16 @@ async def update_provider_config(
metadata_fields = {"display_name", "base_url", "is_enabled", "models", "available_models"}
metadata_requested = bool(payload.model_fields_set & metadata_fields)
+ # Only a *changed* base URL is validated. The dialog re-sends the stored value
+ # on every edit, so validating an unchanged legacy row would lock the user out
+ # of editing its models or API key. Outbound use is still checked.
+ base_url = payload.base_url
+ if base_url and base_url != existing["base_url"]:
+ try:
+ base_url = validate_provider_base_url(base_url)
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from None
+
replacement_api_key = None
if payload.encrypted_api_key:
credential_secrets.get_or_create_credential_encryption_key()
@@ -251,7 +270,7 @@ async def update_provider_config(
providers_db.update_provider(
id = provider_id,
display_name = payload.display_name,
- base_url = payload.base_url,
+ base_url = base_url,
is_enabled = payload.is_enabled,
models = payload.models,
available_models = payload.available_models,
@@ -423,6 +442,14 @@ async def test_provider(
message = "Connection failed: Base URL is required for custom providers.",
models_count = None,
)
+ try:
+ base_url = validate_provider_base_url(base_url)
+ except ValueError as exc:
+ return ProviderTestResult(
+ success = False,
+ message = f"Connection failed: {exc}",
+ models_count = None,
+ )
client = ExternalProviderClient(
provider_type = payload.provider_type,
@@ -525,6 +552,11 @@ async def list_provider_models(
]
base_url = payload.base_url or info["base_url"]
+ try:
+ base_url = validate_provider_base_url(base_url)
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from None
+
client = ExternalProviderClient(
provider_type = payload.provider_type,
base_url = base_url,
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 90bb22a8211..47aa01c6f29 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -2747,7 +2747,9 @@ def _build_arg_parser():
parser.add_argument(
"--host",
default = "127.0.0.1",
- help = "Host to bind to (default: 127.0.0.1; use 0.0.0.0 for network/cloud access)",
+ help = "Host to bind to (default: 127.0.0.1; use 0.0.0.0 for network/cloud access). "
+ "On a shared host, set UNSLOTH_STUDIO_BLOCK_PRIVATE_PROVIDER_URLS=1 to stop external "
+ "provider connections from targeting private addresses.",
)
parser.add_argument(
"--password",
diff --git a/studio/backend/tests/test_provider_base_url_validation.py b/studio/backend/tests/test_provider_base_url_validation.py
new file mode 100644
index 00000000000..a4a28e453bf
--- /dev/null
+++ b/studio/backend/tests/test_provider_base_url_validation.py
@@ -0,0 +1,190 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""External-provider base URL validation (SSRF hardening).
+
+The backend fetches the provider base URL on the caller's behalf with their
+decrypted API key attached, so the URL is server-side egress under caller
+control. These tests pin both halves of the policy: every endpoint a user can
+configure today keeps working (plain http, loopback, LAN, odd ports, query
+strings), while shapes that can never be a provider -- non-http(s) schemes,
+embedded credentials, cloud metadata services -- are refused.
+"""
+
+import importlib.util
+import socket
+from pathlib import Path
+
+import pytest
+
+_PROVIDERS_PATH = Path(__file__).resolve().parents[1] / "core" / "inference" / "providers.py"
+_SPEC = importlib.util.spec_from_file_location("provider_registry_for_test", _PROVIDERS_PATH)
+_providers = importlib.util.module_from_spec(_SPEC)
+assert _SPEC.loader is not None
+_SPEC.loader.exec_module(_providers)
+
+validate_provider_base_url = _providers.validate_provider_base_url
+PROVIDER_REGISTRY = _providers.PROVIDER_REGISTRY
+BLOCK_PRIVATE_ENV = _providers._BLOCK_PRIVATE_ENV
+
+
+# Every base URL a user can reach today: shipped registry defaults, the local
+# server presets, LAN gateways, docker-compose hostnames, query strings.
+_SUPPORTED = [
+ "http://localhost:11434/v1",
+ "http://localhost:8080/v1",
+ "http://127.0.0.1:8080/v1",
+ "http://127.0.0.1:1",
+ "http://192.168.1.50:8000/v1",
+ "http://10.1.2.3:8000/v1",
+ "http://my_ollama:11434/v1",
+ "http://llama.test",
+ "https://my-vllm-server.com/v1",
+ "https://my-resource.openai.azure.com/openai/v1",
+ "https://gw.example/v1?tenant=a",
+ # A numeric host that canonicalizes to a public address is untouched.
+ "http://1681207502/v1",
+ # A DNS name is not link-local just because it starts with those digits.
+ "http://169.254.gateway.example.com/v1",
+ # An internationalized host is left alone.
+ "https://例え.テスト/v1",
+ # A neighbour of the metadata address is an ordinary host.
+ "http://[fd00:ec2::255]/v1",
+ "http://[fd20:ce::255]/v1",
+ "https://[2606:4700:4700::1111]/v1",
+ # Self-hosted gateways behind basic auth keep working.
+ "https://user:[email protected]/v1",
+] + [info["base_url"] for info in PROVIDER_REGISTRY.values() if info["base_url"]]
+
+
[email protected](autouse = True)
+def _default_policy(monkeypatch):
+ """Default deployment: the private-address opt-in is off."""
+ monkeypatch.delenv(BLOCK_PRIVATE_ENV, raising = False)
+
+
[email protected]("url", _SUPPORTED)
+def test_supported_base_urls_are_unchanged(url):
+ assert validate_provider_base_url(url) == url
+
+
[email protected]("url", _SUPPORTED)
+def test_validation_is_idempotent(url):
+ once = validate_provider_base_url(url)
+ assert validate_provider_base_url(once) == once
+
+
+def test_trailing_slash_and_whitespace_are_normalized():
+ assert validate_provider_base_url(" http://127.0.0.1:8080/v1/ ") == "http://127.0.0.1:8080/v1"
+
+
+def test_no_dns_lookup_on_the_default_path(monkeypatch):
+ def _fail(*args, **kwargs):
+ raise AssertionError("validation must not resolve DNS by default")
+
+ monkeypatch.setattr(socket, "getaddrinfo", _fail)
+ assert validate_provider_base_url("https://api.openai.com/v1") == "https://api.openai.com/v1"
+
+
+ "url, error",
+ [
+ ("file:///etc/passwd", "http or https"),
+ ("gopher://example.com/", "http or https"),
+ ("data:text/plain,hi", "http or https"),
+ ("http://exa mple.com/v1", "invalid characters"),
+ ("http://example.com\n/v1", "invalid characters"),
+ ("http://example.com\\@evil.com/v1", "invalid characters"),
+ ("https:///v1", "hostname"),
+ ("", "required"),
+ (" ", "required"),
+ ],
+)
+def test_rejected_url_shapes(url, error):
+ with pytest.raises(ValueError, match = error):
+ validate_provider_base_url(url)
+
+
+ "url",
+ [
+ "http://169.254.169.254/latest/meta-data/iam/security-credentials/",
+ "http://169.254.169.254./latest/meta-data/",
+ "http://[::ffff:169.254.169.254]/latest/meta-data/",
+ "http://169.254.170.2/v2/credentials",
+ "http://169.254.170.23/v1/credentials",
+ "http://[fd00:ec2::254]/latest/meta-data/",
+ "http://metadata.google.internal/computeMetadata/v1/",
+ "http://metadata/computeMetadata/v1/",
+ "http://100.100.100.200/latest/meta-data/",
+ # Userinfo does not disguise the real host.
+ "http://[email protected]/latest/meta-data/",
+ # Legacy numeric spellings the resolver maps to 169.254.169.254.
+ "http://2852039166/latest/meta-data/",
+ "http://0xA9FEA9FE/latest/meta-data/",
+ "http://0251.0376.0251.0376/latest/meta-data/",
+ "http://169.254.43518/latest/meta-data/",
+ # IDNA label separators: httpx encodes the host through idna, which
+ # splits on all of these, so they dial 169.254.169.254.
+ "http://169。254。169。254/latest/meta-data/",
+ "http://169.254.169.254/latest/meta-data/",
+ "http://169。254。169。254/latest/meta-data/",
+ "http://169.254.169.254。/latest/meta-data/",
+ "http://metadata。google。internal/computeMetadata/v1/",
+ # Equivalent spellings of the same IPv6 metadata address.
+ "http://[fd00:0ec2:0000:0000:0000:0000:0000:0254]/latest/meta-data/",
+ "http://[fd00:ec2::0.0.2.84]/latest/meta-data/",
+ "http://[FD00:EC2::254]/latest/meta-data/",
+ "http://[0:0:0:0:0:ffff:a9fe:a9fe]/latest/meta-data/",
+ # Google's IPv6 metadata address on IPv6-only VMs.
+ "http://[fd20:ce::254]/computeMetadata/v1/",
+ "http://[fd20:0ce:0:0:0:0:0:254]/computeMetadata/v1/",
+ # A scope id keeps the address unequal while dialling the same host.
+ "http://[fd00:ec2::254%250]/latest/meta-data/",
+ "http://[fd00:ec2::254%25eth0]/latest/meta-data/",
+ ],
+)
+def test_cloud_metadata_endpoints_are_always_refused(url, monkeypatch):
+ with pytest.raises(ValueError, match = "metadata"):
+ validate_provider_base_url(url)
+ # Also refused with the private-address opt-in on.
+ monkeypatch.setenv(BLOCK_PRIVATE_ENV, "1")
+ with pytest.raises(ValueError, match = "metadata"):
+ validate_provider_base_url(url)
+
+
+ "url",
+ [
+ "http://127.0.0.1:11434/v1",
+ "http://localhost:11434/v1",
+ "http://192.168.1.50:8000/v1",
+ "http://10.1.2.3:8000/v1",
+ ],
+)
+def test_private_targets_blocked_only_with_the_opt_in(url, monkeypatch):
+ # Default: allowed (this is the normal local-provider flow).
+ assert validate_provider_base_url(url) == url
+
+ monkeypatch.setenv(BLOCK_PRIVATE_ENV, "1")
+ # Names resolve to loopback; conftest blocks real resolution, and IP
+ # literals never reach the resolver.
+ monkeypatch.setattr(
+ socket,
+ "getaddrinfo",
+ lambda *a, **k: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 80))],
+ )
+ with pytest.raises(ValueError, match = "private address"):
+ validate_provider_base_url(url)
+
+
+def test_public_targets_still_allowed_with_the_opt_in(monkeypatch):
+ monkeypatch.setenv(BLOCK_PRIVATE_ENV, "1")
+ assert validate_provider_base_url("https://1.1.1.1/v1") == "https://1.1.1.1/v1"
+
+ monkeypatch.setattr(
+ socket,
+ "getaddrinfo",
+ lambda *a, **k: [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443))],
+ )
+ assert validate_provider_base_url("https://api.openai.com/v1") == "https://api.openai.com/v1"