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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Scope the Studio DNS-pinning opt-out to proxied fetches (#8420)
Daniel Han428a14f145fc
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex 9632737e062..a98cf7c4f9d 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -9829,6 +9829,30 @@ class _SNIHTTPSHandler(urllib.request.HTTPSHandler):return _PinnedHTTPSConnection(host, sni_hostname = self._sni_hostname, **kwargs)+def _explicit_proxy_applies(scheme: str, host: str) -> bool:+ """Whether urllib routes a *scheme* request for *host* through a proxy.++ Only a proxied fetch may keep the hostname in the request URL: the proxy+ resolves it, so this host never looks it up again. A direct one would, which+ is the DNS-rebinding window, so it stays pinned to the validated IP.++ *host* must be the ``host[:port]`` form ``Request.host`` carries, since that+ is what ``ProxyHandler`` passes to ``proxy_bypass``; probing the bare hostname+ instead would disagree with it on a port-qualified NO_PROXY entry.+ """+ from urllib.request import getproxies, proxy_bypass++ # ProxyHandler lowercases every mapping key, and the Windows registry can hand+ # back "HTTPS=...", so normalize before testing or a proxy-only host goes direct.+ if scheme not in {key.lower() for key in getproxies()}:+ return False+ try:+ return not proxy_bypass(host)+ except (OSError, ValueError):+ # proxy_bypass reads system config on macOS/Windows; failure falls back to pinning.+ return False++def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, str]:"""Resolve *hostname*, reject non-public IPs, return a pinned IP string.@@ -10182,8 +10206,13 @@ def _fetch_url_raw(validated_netloc = f"[{current_host}]" if ":" in current_host else current_hostif cp.port:validated_netloc = f"{validated_netloc}:{cp.port}"- if os.environ.get(_DISABLE_DNS_PINNING_ENV) == "1":- # Enterprise proxies need the hostname in CONNECT for policy and TLS interception.+ # Decide routing once, on the netloc urllib tests: a pinned request+ # carries an IP, which no NO_PROXY entry matches, so the opener below+ # has to carry the decision rather than re-derive it.+ proxied = _explicit_proxy_applies(cp.scheme, validated_netloc)+ if os.environ.get(_DISABLE_DNS_PINNING_ENV) == "1" and proxied:+ # Enterprise proxies need the hostname in CONNECT for policy and TLS+ # interception, and they resolve it, so nothing rebinds behind us.request_url = urlunparse(cp._replace(netloc = validated_netloc))else:# Pin to the validated IP to prevent DNS rebinding.@@ -10191,10 +10220,11 @@ def _fetch_url_raw(ip_netloc = f"{ip_str}:{cp.port}" if cp.port else ip_strrequest_url = urlunparse(cp._replace(netloc = ip_netloc))- opener = urllib.request.build_opener(- _NoRedirect,- _SNIHTTPSHandler(current_host),- )+ handlers = [_NoRedirect, _SNIHTTPSHandler(current_host)]+ if not proxied:+ # An empty ProxyHandler is the documented way to opt a request out.+ handlers.append(urllib.request.ProxyHandler({}))+ opener = urllib.request.build_opener(*handlers)headers = {"User-Agent": ua,diff --git a/studio/backend/run.py b/studio/backend/run.pyindex b68d3af38ac..5cf0db371c4 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -2479,8 +2479,9 @@ def _build_arg_parser():parser.add_argument("--disable-dns-pinning",action = "store_true",- help = "Allow hostname-based web fetches for enterprise proxies. WARNING: weakens "- "DNS-rebinding protection; hostname and redirect validation remain enabled.",+ help = "Send the hostname (not the validated IP) in web fetches that go through an "+ "explicitly configured HTTP(S)_PROXY, so the proxy can apply hostname policy and "+ "TLS interception. Direct fetches stay pinned to the validated IP.",)parser.add_argument("--parallel",diff --git a/studio/backend/tests/test_web_fetch_extraction.py b/studio/backend/tests/test_web_fetch_extraction.pyindex 0d3d2af1aee..8e31662cbff 100644--- a/studio/backend/tests/test_web_fetch_extraction.py+++ b/studio/backend/tests/test_web_fetch_extraction.py@@ -715,13 +715,19 @@ def test_fetch_url_raw_missing_content_type_reported_empty(monkeypatch):@pytest.mark.parametrize(- "disable_dns_pinning,expected_url",+ "disable_dns_pinning,proxied,expected_url",[- (False, "https://203.0.113.7:8443/page?q=1"),- (True, "https://example.com:8443/page?q=1"),+ (False, False, "https://203.0.113.7:8443/page?q=1"),+ (False, True, "https://203.0.113.7:8443/page?q=1"),+ # The opt-out only applies to a proxied fetch: a direct one would resolve+ # the hostname again, which is the DNS-rebinding hole it must not reopen.+ (True, False, "https://203.0.113.7:8443/page?q=1"),+ (True, True, "https://example.com:8443/page?q=1"),],)-def test_fetch_url_raw_dns_pinning_proxy_opt_out(monkeypatch, disable_dns_pinning, expected_url):+def test_fetch_url_raw_dns_pinning_proxy_opt_out(+ monkeypatch, disable_dns_pinning, proxied, expected_url+):import emailimport urllib.request@@ -757,6 +763,14 @@ def test_fetch_url_raw_dns_pinning_proxy_opt_out(monkeypatch, disable_dns_pinninmonkeypatch.setenv("UNSLOTH_STUDIO_DISABLE_DNS_PINNING", "1" if disable_dns_pinning else "0")monkeypatch.setattr(tools_mod, "_validate_and_resolve_host", resolve)monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _FakeOpener())+ # Patch the lookups rather than the env: getproxies/proxy_bypass read system+ # settings on macOS and Windows.+ monkeypatch.setattr(+ urllib.request,+ "getproxies",+ lambda: {"https": "http://proxy.corp:3128"} if proxied else {},+ )+ monkeypatch.setattr(urllib.request, "proxy_bypass", lambda host: False)# No embedded credentials: the web access policy rejects those outright# (see test_fetch_url_raw_rejects_embedded_credentials).@@ -769,6 +783,132 @@ def test_fetch_url_raw_dns_pinning_proxy_opt_out(monkeypatch, disable_dns_pinninassert requested[0].get_header("Host") == "example.com:8443"+def test_fetch_url_raw_proxy_scheme_key_case_insensitive(monkeypatch):+ # A Windows registry ProxyServer value keeps the case it was written in, so+ # getproxies can return "HTTPS". ProxyHandler lowercases its keys, so an+ # exact-case test here would disable a proxy that urllib would have used.+ import email+ import urllib.request++ import core.inference.tools as tools_mod++ class _FakeResp:+ headers = email.message_from_string("Content-Type: text/plain\n")++ def __init__(self):+ self._body = b"ok"++ def read(self, n = -1):+ body, self._body = self._body, b""+ return body++ requested = []+ built = []++ class _FakeOpener:+ def open(+ self,+ req,+ timeout = None,+ ):+ requested.append(req)+ return _FakeResp()++ monkeypatch.setenv("UNSLOTH_STUDIO_DISABLE_DNS_PINNING", "1")+ monkeypatch.setattr(+ tools_mod,+ "_validate_and_resolve_host",+ lambda host, port: (True, "", "203.0.113.7"),+ )+ monkeypatch.setattr(urllib.request, "getproxies", lambda: {"HTTPS": "http://proxy.corp:3128"})+ monkeypatch.setattr(urllib.request, "proxy_bypass", lambda host: False)+ monkeypatch.setattr(+ urllib.request,+ "build_opener",+ lambda *handlers: built.append(handlers) or _FakeOpener(),+ )++ err, body, _content_type = tools_mod._fetch_url_raw("https://example.com:8443/page?q=1")++ assert err is None+ assert body == "ok"+ assert [req.full_url for req in requested] == ["https://example.com:8443/page?q=1"]+ assert not [h for h in built[0] if isinstance(h, urllib.request.ProxyHandler) and not h.proxies]+++ "no_proxy,disable_dns_pinning,expected_url",+ [+ # urllib tests NO_PROXY against Request.host, so a port-qualified entry only+ # matches with the port: probing the bare hostname would call this proxied,+ # keep the hostname, and let the direct connect re-resolve it.+ ("example.com:8443", True, "https://203.0.113.7:8443/page?q=1"),+ ("example.com", True, "https://203.0.113.7:8443/page?q=1"),+ ("other.example", True, "https://example.com:8443/page?q=1"),+ ("example.com", False, "https://203.0.113.7:8443/page?q=1"),+ ],+)+def test_fetch_url_raw_no_proxy_routing(monkeypatch, no_proxy, disable_dns_pinning, expected_url):+ # Real getproxies/proxy_bypass here, not stubs: both read the environment first+ # on every platform, and the point is to agree with what urllib actually does.+ import email+ import urllib.request++ import core.inference.tools as tools_mod++ class _FakeResp:+ headers = email.message_from_string("Content-Type: text/plain\n")++ def __init__(self):+ self._body = b"ok"++ def read(self, n = -1):+ body, self._body = self._body, b""+ return body++ requested = []+ built = []++ class _FakeOpener:+ def open(+ self,+ req,+ timeout = None,+ ):+ requested.append(req)+ return _FakeResp()++ def fake_build_opener(*handlers):+ built.append(handlers)+ return _FakeOpener()++ for var in ("http_proxy", "https_proxy", "no_proxy", "all_proxy", "REQUEST_METHOD"):+ monkeypatch.delenv(var, raising = False)+ monkeypatch.delenv(var.upper(), raising = False)+ monkeypatch.setenv("https_proxy", "http://proxy.corp:3128")+ monkeypatch.setenv("no_proxy", no_proxy)+ monkeypatch.setenv("UNSLOTH_STUDIO_DISABLE_DNS_PINNING", "1" if disable_dns_pinning else "0")+ monkeypatch.setattr(+ tools_mod,+ "_validate_and_resolve_host",+ lambda host, port: (True, "", "203.0.113.7"),+ )+ monkeypatch.setattr(urllib.request, "build_opener", fake_build_opener)++ err, body, _content_type = tools_mod._fetch_url_raw("https://example.com:8443/page?q=1")++ assert err is None+ assert body == "ok"+ assert [req.full_url for req in requested] == [expected_url]+ # A bypassed host keeps its direct route: the pinned IP would never match the+ # NO_PROXY entry, so the opener has to carry the decision instead.+ bypassed = expected_url.startswith("https://203.0.113.7")+ empty_proxy_handlers = [+ h for h in built[0] if isinstance(h, urllib.request.ProxyHandler) and not h.proxies+ ]+ assert bool(empty_proxy_handlers) is bypassed++def test_fetch_url_raw_rejects_embedded_credentials(monkeypatch):# Credentials in the URL are blocked rather than stripped, so they can never# leak to a redirect target or into logs.diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 279f10ac1c2..098dd2b2c25 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -1407,8 +1407,9 @@ def studio_default(disable_dns_pinning: bool = typer.Option(False,"--disable-dns-pinning",- help = "Allow hostname-based web fetches for enterprise proxies. WARNING: weakens "- "DNS-rebinding protection; hostname and redirect validation remain enabled.",+ help = "Send the hostname (not the validated IP) in web fetches that go through an "+ "explicitly configured HTTP(S)_PROXY, so the proxy can apply hostname policy and "+ "TLS interception. Direct fetches stay pinned to the validated IP.",),password: str = typer.Option("",@@ -1926,8 +1927,9 @@ def run(False,"--disable-dns-pinning",rich_help_panel = _RUN_PANEL_TOOLS,- help = "Allow hostname-based web fetches for enterprise proxies. WARNING: weakens "- "DNS-rebinding protection; hostname and redirect validation remain enabled.",+ help = "Send the hostname (not the validated IP) in web fetches that go through an "+ "explicitly configured HTTP(S)_PROXY, so the proxy can apply hostname policy and "+ "TLS interception. Direct fetches stay pinned to the validated IP.",),tool_call_healing: Optional[bool] = typer.Option(None,