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
Studio: try every address a site resolves to when fetching a page (#10319)
Nilayc12a37f9b4c6
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.pyindex a41dcaef33a..1e377864c26 100644--- a/studio/backend/core/inference/external_provider.py+++ b/studio/backend/core/inference/external_provider.py@@ -815,7 +815,9 @@ def _safe_fetch_image_for_gemini_sync(# Reuse tools.py's pinned-IP hardening: validate-once-then-pin.from .tools import (+ _explicit_proxy_applies,_NoRedirect,+ _pinned_netloc,_SNIHTTPSHandler,_validate_and_resolve_host,)@@ -852,7 +854,7 @@ def _safe_fetch_image_for_gemini_sync(return Noneparsed, current_host, current_port = parsed_infocurrent_url = url- ok, reason, pinned_ip = _validate_and_resolve_host(current_host, current_port)+ ok, reason, pinned_ips = _validate_and_resolve_host(current_host, current_port)if not ok:logger.warning("Gemini image fetch: refusing host=%s reason=%s",@@ -867,14 +869,15 @@ def _safe_fetch_image_for_gemini_sync(if cp_info is None:return Nonecp, _cp_host, _cp_port = cp_info- ip_str = f"[{pinned_ip}]" if ":" in pinned_ip else pinned_ip- ip_netloc = f"{ip_str}:{cp.port}" if cp.port else ip_str- pinned_url = urlunparse(cp._replace(netloc = ip_netloc))-- opener = urllib.request.build_opener(- _NoRedirect,- _SNIHTTPSHandler(current_host),- )+ pinned_url = urlunparse(cp._replace(netloc = _pinned_netloc(pinned_ips[0], cp.port)))++ # Route on the hostname, as _fetch_url_raw does: no NO_PROXY entry matches the+ # pinned URL's IP. A proxied request reaches the origin through the proxy.+ proxied = _explicit_proxy_applies("https", _pinned_netloc(current_host, cp.port))+ handlers = [_NoRedirect, _SNIHTTPSHandler(current_host, () if proxied else pinned_ips)]+ if not proxied:+ handlers.append(urllib.request.ProxyHandler({}))+ opener = urllib.request.build_opener(*handlers)req = urllib.request.Request(pinned_url,headers = {"Host": current_host},@@ -906,7 +909,7 @@ def _safe_fetch_image_for_gemini_sync(if rp_info is None:return None_rp, current_host, current_port = rp_info- ok2, reason2, pinned_ip = _validate_and_resolve_host(current_host, current_port)+ ok2, reason2, pinned_ips = _validate_and_resolve_host(current_host, current_port)if not ok2:logger.warning("Gemini image fetch: refusing redirect host=%s reason=%s",diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex c92799c2342..10a00db2416 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -11542,21 +11542,93 @@ class _NoRedirect(urllib.request.HTTPRedirectHandler):return None+# Ceiling on one probe dial, and on the whole probe pass as a fraction of the timeout.+_PINNED_DIAL_TIMEOUT = 1.0+_PINNED_PROBE_BUDGET = 0.25+++def _pinned_create_connection(addresses):+ """``socket.create_connection`` that walks *addresses* instead of resolving.++ Pinning to one validated address dropped the walk every other client gets. Walking+ here rather than around ``opener.open`` keeps the caller's timeout covering one+ whole response.+ """+ import socket++ def create(+ address,+ timeout = socket._GLOBAL_DEFAULT_TIMEOUT,+ source_address = None,+ ):+ if timeout is socket._GLOBAL_DEFAULT_TIMEOUT:+ timeout = socket.getdefaulttimeout()+ # A proxy dial is not an origin dial, and callers withhold the addresses for it.+ if address[0] not in addresses:+ return socket.create_connection(address, timeout, source_address)++ port = address[1]+ expiry = None if timeout is None else time.monotonic() + timeout+ probe_timeout = (+ None+ if timeout is None+ else min(+ timeout * _PINNED_PROBE_BUDGET / len(addresses),+ _PINNED_DIAL_TIMEOUT,+ )+ )+ error = None+ # A brief look at every address, so one answering neither way cannot hold up the+ # reachable ones, then an equal share of the rest so none strands the next.+ passes = (True, False) if len(addresses) > 1 and timeout is not None else (False,)+ for probe in passes:+ for index, ip in enumerate(addresses):+ if timeout is None:+ dial_timeout = None+ elif probe:+ dial_timeout = probe_timeout+ else:+ # An overrun leaves nothing; zero still attempts, negative raises.+ dial_timeout = max(+ (expiry - time.monotonic()) / (len(addresses) - index),+ 0,+ )+ try:+ sock = socket.create_connection((ip, port), dial_timeout, source_address)+ except OSError as exc:+ error = exc+ continue+ # create_connection leaves the caller's timeout on the socket, not its own.+ sock.settimeout(timeout)+ return sock+ raise error++ return create++class _PinnedHTTPSConnection(http.client.HTTPSConnection):"""HTTPS connection to a pinned IP, using a different hostname for SNI andcert verification.SSRF IP-pinning rewrites URLs to raw IPs; a normal HTTPSConnection would thensend no SNI and verify the cert against the IP (both fail). This splits the- concerns: TCP connects to the pinned IP (``host``), TLS uses ``sni_hostname``.+ concerns: TCP connects to a validated IP, TLS uses ``sni_hostname``."""- def __init__(self, host: str, *, sni_hostname: str, **kwargs):+ def __init__(+ self,+ host: str,+ *,+ sni_hostname: str,+ addresses = (),+ **kwargs,+ ):super().__init__(host, **kwargs)self._sni_hostname = sni_hostname+ if addresses:+ self._create_connection = _pinned_create_connection(tuple(addresses))def connect(self):- # TCP connect to the pinned IP in self.host.http.client.HTTPConnection.connect(self)# TLS handshake with the real hostname for SNI + cert verification.self.sock = self._context.wrap_socket(@@ -11570,19 +11642,45 @@ class _SNIHTTPSHandler(urllib.request.HTTPSHandler):SSRF IP-pinning breaks SNI and cert verification; this returns a``_PinnedHTTPSConnection`` that connects to the pinned IP but verifies TLS- against the original hostname.+ against the original hostname. *addresses* are every validated address, pinned+ one first, for ``_pinned_create_connection`` to walk."""- def __init__(self, hostname: str):+ def __init__(+ self,+ hostname: str,+ addresses = (),+ ):super().__init__(context = _tls_ctx)self._sni_hostname = hostname+ self._addresses = tuple(addresses)def https_open(self, req):return self.do_open(self._sni_connection, req)def _sni_connection(self, host, **kwargs):kwargs["context"] = _tls_ctx- return _PinnedHTTPSConnection(host, sni_hostname = self._sni_hostname, **kwargs)+ return _PinnedHTTPSConnection(+ host,+ sni_hostname = self._sni_hostname,+ addresses = self._addresses,+ **kwargs,+ )+++class _PinnedHTTPHandler(urllib.request.HTTPHandler):+ def __init__(self, addresses = ()):+ super().__init__()+ self._addresses = tuple(addresses)++ def http_open(self, req):+ return self.do_open(self._pinned_connection, req)++ def _pinned_connection(self, host, **kwargs):+ conn = http.client.HTTPConnection(host, **kwargs)+ if self._addresses:+ conn._create_connection = _pinned_create_connection(self._addresses)+ return conndef _explicit_proxy_applies(scheme: str, host: str) -> bool:@@ -11609,12 +11707,12 @@ def _explicit_proxy_applies(scheme: str, host: str) -> bool: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.+def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, list[str]]:+ """Resolve *hostname*, reject non-public IPs, return the pinned IP strings.- Returns ``(ok, reason_or_empty, resolved_ip)``. The caller should connect- to *resolved_ip* (with a ``Host`` header) to prevent DNS rebinding between- validation and the actual fetch.+ Returns ``(ok, reason_or_empty, resolved_ips)`` in resolver order. The caller pins+ to these (with a ``Host`` header) rather than resolving again, which is the DNS+ rebinding window, and walks them as ``socket.create_connection`` would."""import ipaddressimport socket@@ -11623,11 +11721,12 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, strinfos = socket.getaddrinfo(hostname, port, type = socket.SOCK_STREAM)except (OSError, UnicodeError) as e:# IDNA encoding rejects a hostname with UnicodeError, not OSError.- return False, f"Failed to resolve host: {e}", ""+ return False, f"Failed to resolve host: {e}", []if not infos:- return False, f"Failed to resolve host: no addresses for {hostname!r}", ""+ return False, f"Failed to resolve host: no addresses for {hostname!r}", []+ resolved = []for *_, sockaddr in infos:ip = ipaddress.ip_address(sockaddr[0])# `not ip.is_global` is the source of truth (also rejects CGNAT and@@ -11641,11 +11740,11 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, stror ip.is_reservedor ip.is_unspecified):- return False, f"Blocked: refusing to fetch non-public address {ip}.", ""+ return False, f"Blocked: refusing to fetch non-public address {ip}.", []+ if sockaddr[0] not in resolved:+ resolved.append(sockaddr[0])- # Return the first resolved address for pinning.- first_ip = infos[0][4][0]- return True, "", first_ip+ return True, "", resolved# Binary application subtypes rejected by MIME; other application types are@@ -11786,7 +11885,7 @@ def _resolve_with_budget(hostname, port, deadline, cancel_event):"""budget_error = _fetch_budget_exceeded(deadline, cancel_event)if budget_error is not None:- return False, budget_error, ""+ return False, budget_error, []if deadline is None and cancel_event is None:return _validate_and_resolve_host(hostname, port)@@ -11796,13 +11895,13 @@ def _resolve_with_budget(hostname, port, deadline, cancel_event):try:result.put(_validate_and_resolve_host(hostname, port))except Exception as exc: # defensive: never let the worker die silently- result.put((False, f"Failed to resolve host: {exc}", ""))+ result.put((False, f"Failed to resolve host: {exc}", []))threading.Thread(target = _resolve, name = "web-fetch-dns", daemon = True).start()while True:budget_error = _fetch_budget_exceeded(deadline, cancel_event)if budget_error is not None:- return False, budget_error, ""+ return False, budget_error, []try:return result.get(timeout = 0.05)except queue.Empty:@@ -11902,6 +12001,11 @@ def _normalize_url_scheme(url: str) -> str:return "https://" + rest+def _pinned_netloc(ip: str, port: int | None) -> str:+ host = f"[{ip}]" if ":" in ip else ip+ return f"{host}:{port}" if port else host++def _fetch_url_raw(url: str,timeout: int = 30,@@ -11940,7 +12044,7 @@ def _fetch_url_raw(# check_url_access already parsed this and read .port, so this cannot raise.parsed = urlparse(url)port = parsed.port or (443 if parsed.scheme == "https" else 80)- ok, reason, pinned_ip = _resolve_with_budget(+ ok, reason, pinned_ips = _resolve_with_budget(canonical_host,port,deadline,@@ -11982,12 +12086,16 @@ def _fetch_url_raw(# 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.- ip_str = f"[{pinned_ip}]" if ":" in pinned_ip else pinned_ip- ip_netloc = f"{ip_str}:{cp.port}" if cp.port else ip_str- request_url = urlunparse(cp._replace(netloc = ip_netloc))-- handlers = [_NoRedirect, _SNIHTTPSHandler(current_host)]+ # Pin the first validated IP against DNS rebinding; the rest are below.+ request_url = urlunparse(cp._replace(netloc = _pinned_netloc(pinned_ips[0], cp.port)))++ # The proxy makes the origin connection, to the one address the URL pins.+ walk = () if proxied else pinned_ips+ handlers = [+ _NoRedirect,+ _SNIHTTPSHandler(current_host, walk),+ _PinnedHTTPHandler(walk),+ ]if not proxied:# An empty ProxyHandler is the documented way to opt a request out.handlers.append(urllib.request.ProxyHandler({}))@@ -12021,7 +12129,7 @@ def _fetch_url_raw(return policy_reason, "", ""rp = urlparse(current_url)rp_port = rp.port or (443 if rp.scheme == "https" else 80)- ok2, reason2, pinned_ip = _resolve_with_budget(+ ok2, reason2, pinned_ips = _resolve_with_budget(redirect_host,rp_port,deadline,diff --git a/studio/backend/tests/test_gemini_provider.py b/studio/backend/tests/test_gemini_provider.pyindex b113e165b7c..16561dd2da7 100644--- a/studio/backend/tests/test_gemini_provider.py+++ b/studio/backend/tests/test_gemini_provider.py@@ -2655,6 +2655,67 @@ def test_safe_fetch_image_pins_validated_ip_no_hostname_in_request(monkeypatch):assert captured["requests"][0]["host_header"] == "cdn.example.com"+ "configured,bypassed,proxied",+ [(False, False, False), (True, False, True), (True, True, False)],+)+def test_safe_fetch_image_carries_the_addresses_only_on_a_direct_request(+ monkeypatch, configured, bypassed, proxied+):+ """The URL pins the first validated address and all of them reach the connection,+ where the fallback happens; a proxied request carries none. Routing is decided on+ the hostname, since the pinned URL's IP matches no NO_PROXY entry."""+ import socket+ import urllib.error+ import urllib.request++ from core.inference import tools as tools_mod++ addresses = ("2606:4700::1", "104.16.0.1")+ original_getaddrinfo = socket.getaddrinfo++ def fake_getaddrinfo(host, *args, **kwargs):+ if host == "cdn.example.com":+ return [+ (socket.AF_INET6, socket.SOCK_STREAM, 0, "", (addresses[0], 0, 0, 0)),+ (socket.AF_INET, socket.SOCK_STREAM, 0, "", (addresses[1], 0)),+ ]+ return original_getaddrinfo(host, *args, **kwargs)++ captured: dict = {}++ class _StubOpener:+ def open(+ self,+ req,+ timeout = None,+ ):+ captured["url"] = req.full_url+ raise urllib.error.URLError(OSError(101, "Network is unreachable"))++ def fake_build_opener(*handlers, **_kw):+ captured["handlers"] = handlers+ return _StubOpener()++ monkeypatch.setattr(socket, "getaddrinfo", fake_getaddrinfo)+ proxies = {"https": "http://proxy.corp:3128"} if configured else {}+ monkeypatch.setattr(urllib.request, "getproxies", lambda: proxies)+ # A bracketed host is the pinned IP: NO_PROXY matching it but not the hostname+ # makes urllib's own decision disagree with the request's.+ monkeypatch.setattr(urllib.request, "proxy_bypass", lambda host: bypassed or host[0] == "[")+ monkeypatch.setattr("urllib.request.build_opener", fake_build_opener)++ _drive(ep_mod._safe_fetch_image_for_gemini("https://cdn.example.com/x.png", "image/png"))++ assert captured["url"] == f"https://[{addresses[0]}]/x.png"+ https = next(h for h in captured["handlers"] if isinstance(h, tools_mod._SNIHTTPSHandler))+ assert https._addresses == (() if proxied else addresses)+ opted_out = any(+ isinstance(h, urllib.request.ProxyHandler) and not h.proxies for h in captured["handlers"]+ )+ assert opted_out is not proxied++def test_safe_fetch_image_redirect_to_private_host_rejected(monkeypatch):"""Round 17: each redirect hop must re-validate the new host. A public hopthat redirects to an internal address must be dropped."""diff --git a/studio/backend/tests/test_search_images.py b/studio/backend/tests/test_search_images.pyindex 3c37fa87247..982dc3d32d2 100644--- a/studio/backend/tests/test_search_images.py+++ b/studio/backend/tests/test_search_images.py@@ -737,7 +737,7 @@ def _serve_bytes(content_type: str = "image/png",):monkeypatch.setattr(- tools, "_validate_and_resolve_host", lambda host, port: (True, "", "93.184.216.34")+ tools, "_validate_and_resolve_host", lambda host, port: (True, "", ["93.184.216.34"]))monkeypatch.setattr(tools.urllib.request,diff --git a/studio/backend/tests/test_web_access_policy.py b/studio/backend/tests/test_web_access_policy.pyindex be7c0787f8e..aaba9d05875 100644--- a/studio/backend/tests/test_web_access_policy.py+++ b/studio/backend/tests/test_web_access_policy.py@@ -254,7 +254,7 @@ def test_direct_fetch_rejects_blocked_host_before_dns(monkeypatch):monkeypatch.setattr(tools,"_validate_and_resolve_host",- lambda hostname, port: resolved.append((hostname, port)) or (True, "", "1.1.1.1"),+ lambda hostname, port: resolved.append((hostname, port)) or (True, "", ["1.1.1.1"]),)result = tools._fetch_page_text("https://example.com/article",@@ -269,7 +269,7 @@ def test_direct_fetch_rechecks_every_redirect_before_dns(monkeypatch):monkeypatch.setattr(tools,"_validate_and_resolve_host",- lambda hostname, port: resolved.append((hostname, port)) or (True, "", "1.1.1.1"),+ lambda hostname, port: resolved.append((hostname, port)) or (True, "", ["1.1.1.1"]),)headers = Message()headers["Location"] = "https://example.com/escaped"diff --git a/studio/backend/tests/test_web_fetch_binary_guard.py b/studio/backend/tests/test_web_fetch_binary_guard.pyindex 05a82529cec..4a5786dd6fe 100644--- a/studio/backend/tests/test_web_fetch_binary_guard.py+++ b/studio/backend/tests/test_web_fetch_binary_guard.py@@ -49,7 +49,7 @@ class _FakeOpener:def _fetch_with(monkeypatch, body: bytes, content_type: str | None) -> str:# Pass SSRF validation and skip real DNS/network.monkeypatch.setattr(- tools, "_validate_and_resolve_host", lambda host, port: (True, "", "93.184.216.34")+ tools, "_validate_and_resolve_host", lambda host, port: (True, "", ["93.184.216.34"]))monkeypatch.setattr(tools.urllib.request,diff --git a/studio/backend/tests/test_web_fetch_extraction.py b/studio/backend/tests/test_web_fetch_extraction.pyindex 8e31662cbff..2872c2466ac 100644--- a/studio/backend/tests/test_web_fetch_extraction.py+++ b/studio/backend/tests/test_web_fetch_extraction.py@@ -12,7 +12,9 @@ the skip-link / nav / footer furniture, and the README rendered insidefrom __future__ import annotations+import emailimport sys+import timefrom pathlib import Pathimport pytest@@ -705,7 +707,7 @@ def test_fetch_url_raw_missing_content_type_reported_empty(monkeypatch):monkeypatch.setattr("core.inference.tools._validate_and_resolve_host",- lambda host, port: (True, "", "203.0.113.7"),+ lambda host, port: (True, "", ["203.0.113.7"]),)monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _FakeOpener())err, body, content_type = _fetch_url_raw("https://example.com/")@@ -714,6 +716,295 @@ def test_fetch_url_raw_missing_content_type_reported_empty(monkeypatch):assert content_type == ""+def _four_address_getaddrinfo(hostname, port, *args, **kwargs):+ import socket as _socket+ return [+ (_socket.AF_INET6, _socket.SOCK_STREAM, 0, "", ("2606:4700::1", port, 0, 0)),+ (_socket.AF_INET6, _socket.SOCK_STREAM, 0, "", ("2606:4700::2", port, 0, 0)),+ (_socket.AF_INET, _socket.SOCK_STREAM, 0, "", ("104.16.0.1", port)),+ (_socket.AF_INET, _socket.SOCK_STREAM, 0, "", ("104.16.0.2", port)),+ ]+++def test_validate_and_resolve_host_returns_every_validated_address(monkeypatch):+ import socket as _socket++ from core.inference import tools as tools_mod++ monkeypatch.setattr(_socket, "getaddrinfo", _four_address_getaddrinfo)+ ok, reason, ips = tools_mod._validate_and_resolve_host("example.com", 443)++ assert (ok, reason) == (True, "")+ assert ips == ["2606:4700::1", "2606:4700::2", "104.16.0.1", "104.16.0.2"]+++class _FakeSocket:+ def __init__(self, address):+ self.address = address++ def settimeout(self, value):+ self.timeout = value+++def _recording_create_connection(+ monkeypatch,+ unreachable = (),+ stall = (),+ answers_above = None,+ overrun = 1.0,+):+ """``socket.create_connection`` on a virtual clock: a dial charges its timeout+ rather than sleeping it. *stall* burns the whole dial (*overrun* times it),+ *answers_above* is an ``(ip, seconds)`` that connects only when given more."""+ calls = []+ spent = [0.0]+ real_monotonic = time.monotonic+ monkeypatch.setattr(time, "monotonic", lambda: real_monotonic() + spent[0])++ def create(+ address,+ timeout = None,+ source_address = None,+ ):+ calls.append((address[0], timeout))+ if address[0] in stall:+ spent[0] += timeout * overrun+ raise TimeoutError("timed out")+ if address[0] in unreachable:+ raise OSError(101, f"unreachable {address[0]}")+ if answers_above is not None and address[0] == answers_above[0]:+ if timeout is None or timeout <= answers_above[1]:+ spent[0] += timeout+ raise TimeoutError("timed out")+ spent[0] += answers_above[1]+ return _FakeSocket(address)++ return calls, create++[email protected]("timeout", [30, None])+def test_pinned_dial_walks_to_the_next_address_when_first_is_unreachable(monkeypatch, timeout):+ import socket as _socket++ from core.inference import tools as tools_mod++ # Only the third answers, so trying just the ends cannot pass.+ addresses = ("2606:4700::1", "2606:4700::2", "104.16.0.1", "104.16.0.2")+ unreachable = set(addresses) - {addresses[2]}+ calls, create = _recording_create_connection(monkeypatch, unreachable = unreachable)+ monkeypatch.setattr(_socket, "create_connection", create)++ dial = tools_mod._pinned_create_connection(addresses)+ sock = dial((addresses[0], 443), timeout)++ assert sock.address == (addresses[2], 443)+ assert [ip for ip, _timeout in calls] == list(addresses[:3])+ capped = tools_mod._PINNED_DIAL_TIMEOUT if timeout else None+ assert [dialled for _ip, dialled in calls] == [capped] * 3++ calls.clear()+ assert dial(("proxy.corp", 3128), timeout).address == ("proxy.corp", 3128)+ assert [ip for ip, _timeout in calls] == ["proxy.corp"]++ calls.clear()+ with pytest.raises(OSError):+ tools_mod._pinned_create_connection(addresses[:2])((addresses[0], 443), timeout)+ assert len(calls) == (2 if timeout is None else 4)++[email protected]("overrun,budget", [(1.0, 0.3), (4.0, 0.001)])+def test_pinned_dial_asks_for_no_more_than_the_callers_timeout(monkeypatch, overrun, budget):+ # One budget for both passes; an overrunning dial still leaves the rest an attempt.+ import socket as _socket++ from core.inference import tools as tools_mod++ addresses = ("2606:4700::1", "2606:4700::2", "104.16.0.1")+ calls, create = _recording_create_connection(+ monkeypatch,+ stall = set(addresses),+ overrun = overrun,+ )+ monkeypatch.setattr(_socket, "create_connection", create)++ dial = tools_mod._pinned_create_connection(addresses)+ with pytest.raises(OSError):+ dial((addresses[0], 443), budget)++ assert sum(timeout for _ip, timeout in calls) <= budget+ assert all(timeout >= 0 for _ip, timeout in calls)+ assert [ip for ip, _timeout in calls] == list(addresses) * 2+++def test_pinned_dial_probe_stays_affordable_for_many_records(monkeypatch):+ # A share of what is left compounds: half the remainder each time spent three+ # quarters of a 31-record budget on probing alone.+ import socket as _socket++ from core.inference import tools as tools_mod++ addresses = tuple(f"198.51.100.{i}" for i in range(31))+ calls, create = _recording_create_connection(+ monkeypatch,+ stall = set(addresses[:-1]),+ unreachable = {addresses[-1]},+ )+ monkeypatch.setattr(_socket, "create_connection", create)++ dial = tools_mod._pinned_create_connection(addresses)+ with pytest.raises(OSError, match = addresses[-1]):+ dial((addresses[0], 443), 1.0)++ probes = [timeout for _ip, timeout in calls[: len(addresses)]]+ assert sum(probes) == pytest.approx(tools_mod._PINNED_PROBE_BUDGET)+ assert calls[len(addresses)][1] == pytest.approx(+ (1 - tools_mod._PINNED_PROBE_BUDGET) / len(addresses),+ rel = 0.05,+ )+++def test_pinned_dial_shares_what_is_left_so_no_address_strands_the_next(monkeypatch):+ # The probe is a first look, not a verdict.+ import socket as _socket++ from core.inference import tools as tools_mod++ monkeypatch.setattr(tools_mod, "_PINNED_DIAL_TIMEOUT", 0.02)+ addresses = ("192.0.2.1", "2606:4700::2", "104.16.0.1")+ calls, create = _recording_create_connection(+ monkeypatch,+ unreachable = {addresses[0]},+ stall = {addresses[1]},+ answers_above = (addresses[2], 0.05),+ )+ monkeypatch.setattr(_socket, "create_connection", create)++ dial = tools_mod._pinned_create_connection(addresses)+ sock = dial((addresses[0], 443), 0.6)++ assert sock.address == (addresses[2], 443)+ assert [ip for ip, _timeout in calls] == list(addresses) * 2+ assert [timeout for _ip, timeout in calls[:3]] == [0.02] * 3+ # The first fails for free, so the next share rises from a third to a half.+ assert calls[3][1] == pytest.approx((0.6 - 0.04) / 3, rel = 0.01)+ assert calls[4][1] == pytest.approx(calls[3][1] * 3 / 2, rel = 0.01)+ assert sock.timeout == 0.6+++def test_pinned_https_connection_walks_a_bracketed_ipv6_host(monkeypatch):+ # http.client strips the brackets; the walk must still see a pinned address.+ import socket as _socket++ from core.inference import tools as tools_mod++ addresses = ("2606:2800:220:1::1", "93.184.216.34")+ calls, create = _recording_create_connection(monkeypatch, unreachable = {addresses[0]})+ monkeypatch.setattr(_socket, "create_connection", create)++ handler = tools_mod._SNIHTTPSHandler("example.com", addresses)+ conn = handler._sni_connection(f"[{addresses[0]}]", timeout = 30)+ sock = conn._create_connection((conn.host, conn.port), conn.timeout, None)++ assert sock.address == (addresses[1], 443)+ assert [ip for ip, _timeout in calls] == list(addresses)+++def test_pinned_http_handler_walks_through_a_real_opener(monkeypatch):+ # urllib reaches the walk itself, through http_open; only the dial is faked.+ import socket as _socket+ import urllib.request++ from core.inference import tools as tools_mod++ addresses = ("2606:4700::1", "2606:4700::2", "203.0.113.9")+ dialled = []+ real_create_connection = _socket.create_connection+ server = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)+ server.bind(("127.0.0.1", 0))+ server.listen(1)++ def create(+ address,+ timeout = None,+ source_address = None,+ ):+ dialled.append(address[0])+ if address[0] != addresses[2]:+ raise OSError(101, "Network is unreachable")+ sock = real_create_connection(server.getsockname(), timeout)+ conn, _addr = server.accept()+ conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nthird one ok")+ return sock++ monkeypatch.setattr(_socket, "create_connection", create)+ opener = urllib.request.build_opener(+ tools_mod._PinnedHTTPHandler(addresses),+ urllib.request.ProxyHandler({}),+ )+ with opener.open(f"http://[{addresses[0]}]/page", timeout = 5) as resp:+ body = resp.read()+ server.close()++ assert body == b"third one ok"+ assert dialled == list(addresses)+++def test_fetch_url_raw_pins_one_address_and_hands_urllib_every_address(monkeypatch):+ # The URL pins one address, all of them reach the connection, response keeps all.+ import socket as _socket+ import urllib.error+ import urllib.request++ from core.inference import tools as tools_mod++ class _FakeResp:+ headers = email.message_from_string("Content-Type: text/plain\n")++ def __init__(self):+ self._body = b"slow origin answered"++ def read(self, n = -1):+ body, self._body = self._body, b""+ return body++ seen = {"timeouts": []}++ class _SlowOriginOpener:+ def open(+ self,+ req,+ timeout = None,+ ):+ seen["timeouts"].append(timeout)+ seen["url"] = req.full_url+ if timeout is not None and timeout < 9:+ raise urllib.error.URLError(TimeoutError("timed out"))+ return _FakeResp()++ def fake_build_opener(*handlers):+ seen["handlers"] = handlers+ return _SlowOriginOpener()++ monkeypatch.setattr(_socket, "getaddrinfo", _four_address_getaddrinfo)+ monkeypatch.setattr(urllib.request, "getproxies", dict)+ monkeypatch.setattr(urllib.request, "build_opener", fake_build_opener)++ err, body, _content_type = tools_mod._fetch_url_raw(+ "https://example.com/",+ timeout = 30,+ deadline = time.monotonic() + 30,+ )++ assert err is None+ assert "slow origin answered" in body+ assert seen["url"] == "https://[2606:4700::1]/"+ assert seen["timeouts"] == [pytest.approx(30, abs = 1)]+ addresses = ("2606:4700::1", "2606:4700::2", "104.16.0.1", "104.16.0.2")+ for handler_type in (tools_mod._SNIHTTPSHandler, tools_mod._PinnedHTTPHandler):+ handler = next(h for h in seen["handlers"] if isinstance(h, handler_type))+ assert handler._addresses == addresses++@pytest.mark.parametrize("disable_dns_pinning,proxied,expected_url",[@@ -758,11 +1049,17 @@ def test_fetch_url_raw_dns_pinning_proxy_opt_out(def resolve(host, port):resolved.append((host, port))- return True, "", "203.0.113.7"+ return True, "", ["203.0.113.7"]monkeypatch.setenv("UNSLOTH_STUDIO_DISABLE_DNS_PINNING", "1" if disable_dns_pinning else "0")+ built = []++ def fake_build_opener(*handlers):+ built.append(handlers)+ return _FakeOpener()+monkeypatch.setattr(tools_mod, "_validate_and_resolve_host", resolve)- monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _FakeOpener())+ monkeypatch.setattr(urllib.request, "build_opener", fake_build_opener)# Patch the lookups rather than the env: getproxies/proxy_bypass read system# settings on macOS and Windows.monkeypatch.setattr(@@ -781,6 +1078,9 @@ def test_fetch_url_raw_dns_pinning_proxy_opt_out(assert resolved == [("example.com", 8443)]assert [req.full_url for req in requested] == [expected_url]assert requested[0].get_header("Host") == "example.com:8443"+ for handler_type in (tools_mod._SNIHTTPSHandler, tools_mod._PinnedHTTPHandler):+ handler = next(h for h in built[0] if isinstance(h, handler_type))+ assert handler._addresses == (() if proxied else ("203.0.113.7",))def test_fetch_url_raw_proxy_scheme_key_case_insensitive(monkeypatch):@@ -818,7 +1118,7 @@ def test_fetch_url_raw_proxy_scheme_key_case_insensitive(monkeypatch):monkeypatch.setattr(tools_mod,"_validate_and_resolve_host",- lambda host, port: (True, "", "203.0.113.7"),+ 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)@@ -891,7 +1191,7 @@ def test_fetch_url_raw_no_proxy_routing(monkeypatch, no_proxy, disable_dns_pinnimonkeypatch.setattr(tools_mod,"_validate_and_resolve_host",- lambda host, port: (True, "", "203.0.113.7"),+ lambda host, port: (True, "", ["203.0.113.7"]),)monkeypatch.setattr(urllib.request, "build_opener", fake_build_opener)@@ -1166,7 +1466,7 @@ def test_fetch_url_raw_overall_deadline_aborts_across_redirects(monkeypatch):monkeypatch.setattr(tools_mod,"_validate_and_resolve_host",- lambda host, port: (True, "", "203.0.113.7"),+ lambda host, port: (True, "", ["203.0.113.7"]),)monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _RedirectingOpener())@@ -1204,7 +1504,7 @@ def test_fetch_url_raw_cancel_event_aborts_before_network(monkeypatch):monkeypatch.setattr(tools_mod,"_validate_and_resolve_host",- lambda host, port: (True, "", "203.0.113.7"),+ lambda host, port: (True, "", ["203.0.113.7"]),)monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _Opener())@@ -1279,7 +1579,7 @@ def test_fetch_url_raw_deadline_aborts_slow_body(monkeypatch):monkeypatch.setattr(tools_mod,"_validate_and_resolve_host",- lambda host, port: (True, "", "203.0.113.7"),+ lambda host, port: (True, "", ["203.0.113.7"]),)monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _Opener())@@ -1306,7 +1606,7 @@ def test_resolve_with_budget_aborts_on_slow_resolver(monkeypatch):def slow_resolve(host, port):release.wait(5.0) # block until released; the budget should abort first- return True, "", "203.0.113.7"+ return True, "", ["203.0.113.7"]monkeypatch.setattr(tools_mod, "_validate_and_resolve_host", slow_resolve)diff --git a/studio/backend/tests/test_web_fetch_scheme_normalization.py b/studio/backend/tests/test_web_fetch_scheme_normalization.pyindex 0f626675c22..15170cda807 100644--- a/studio/backend/tests/test_web_fetch_scheme_normalization.py+++ b/studio/backend/tests/test_web_fetch_scheme_normalization.py@@ -101,7 +101,7 @@ def test_redirect_to_out_of_range_port_is_blocked(monkeypatch):monkeypatch.setattr(tools,"_resolve_with_budget",- lambda host, port, deadline, cancel: (True, "", "93.184.216.34"),+ lambda host, port, deadline, cancel: (True, "", ["93.184.216.34"]),)class _Redirecting:@@ -184,7 +184,7 @@ def _request_url_for(monkeypatch, url):seen["url"] = req.full_urlraise RuntimeError("captured")- monkeypatch.setattr(tools, "_resolve_with_budget", lambda *a: (True, "", "93.184.216.34"))+ monkeypatch.setattr(tools, "_resolve_with_budget", lambda *a: (True, "", ["93.184.216.34"]))monkeypatch.setattr(tools.urllib.request, "build_opener", lambda *a: _Opener())tools._fetch_url_raw(url, timeout = 5)return seen.get("url", "")