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: fetch bare hostnames as https instead of refusing them (#7427)
Nilay1915ca98dbe6
diff --git a/studio/backend/core/inference/tool_loop_controller.py b/studio/backend/core/inference/tool_loop_controller.pyindex 61643b57950..361f4b20e3b 100644--- a/studio/backend/core/inference/tool_loop_controller.py+++ b/studio/backend/core/inference/tool_loop_controller.py@@ -212,7 +212,16 @@ def status_for_tool(tool_name: str, arguments: Mapping[str, Any]) -> str:if tool_name == "web_search":url = str(arguments.get("url") or "").strip()if url:- parsed = urlparse(url)+ # Bare hosts are fetched as https, so normalize first or the badge+ # stays generic for exactly the URLs the fetch layer accepts.+ from core.inference.tools import _normalize_url_scheme++ try:+ parsed = urlparse(_normalize_url_scheme(url))+ except ValueError:+ # Runs in prepare_call, outside the fetch's exception handler:+ # raising here kills the turn instead of returning "Blocked:".+ return "Reading page..."if parsed.scheme in ("http", "https") and parsed.hostname:host = parsed.hostnameif host.startswith("www."):diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.pyindex d45fede89af..bd5322819e7 100644--- a/studio/backend/core/inference/tools.py+++ b/studio/backend/core/inference/tools.py@@ -6332,7 +6332,8 @@ def _validate_and_resolve_host(hostname: str, port: int) -> tuple[bool, str, strtry:infos = socket.getaddrinfo(hostname, port, type = socket.SOCK_STREAM)- except OSError as e:+ except (OSError, UnicodeError) as e:+ # IDNA encoding rejects a hostname with UnicodeError, not OSError.return False, f"Failed to resolve host: {e}", ""if not infos:@@ -6562,6 +6563,56 @@ def _read_capped_body(resp, max_bytes, timeout, deadline, cancel_event):return None, b"".join(chunks)+_DOTTED_HOST_RE = re.compile(r"[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+")+# ASCII-only because str.isdigit() is True for digits int() refuses ("²"), and+# capped at 5 digits so the range check never converts an unbounded integer.+_PORT_RE = re.compile(r"[0-9]{1,5}")+++def _normalize_url_scheme(url: str) -> str:+ """Prepend ``https://`` to bare hosts (``google.com``, ``example.com:8443``).++ ``urlparse`` reads the host of a ``host:port`` input as the scheme, so those+ are recognised by a dotted host-like scheme with an empty netloc. Rewrites a+ dotted host with an optional in-range port, and the ``//host`` form. Real+ schemes (``file:``, ``javascript:``, including ``file:80``), root-relative+ paths (``/login``) and bad ports are returned untouched so the caller+ rejects them. A dotted scheme is indistinguishable from ``host:port``, so+ ``com.acme.app:443/cb`` is rewritten too; an empty port (``example.com:``)+ is kept as-is, matching ``https://example.com:``.++ The host is matched against the raw authority, never against what+ ``urlparse`` returned, because urlsplit strips tabs/newlines (3.10) and+ leading C0/space (3.12). Anything it would strip fails the match, so the+ decision and the rewritten string cannot disagree across versions."""+ from urllib.parse import urlparse++ url = url.strip()+ try:+ parsed = urlparse(url)+ except ValueError:+ # Unmatched IPv6 brackets, or an NFKC-decomposing netloc: not a bare host.+ return url+ if parsed.scheme:+ if parsed.netloc or not _DOTTED_HOST_RE.fullmatch(parsed.scheme):+ return url+ rest = url+ elif url.startswith("//"):+ rest = url[2:]+ elif url.startswith("/"):+ return url+ else:+ rest = url++ authority = re.split(r"[/?#]", rest, maxsplit = 1)[0]+ host, _, port = authority.partition(":")+ if not _DOTTED_HOST_RE.fullmatch(host):+ return url+ if port and not (_PORT_RE.fullmatch(port) and 1 <= int(port) <= 65535):+ return url+ return "https://" + rest++def _fetch_url_raw(url: str,timeout: int = 30,@@ -6575,6 +6626,8 @@ def _fetch_url_raw(``error`` is a user-facing message string when the fetch failed (theexisting "Blocked:" / "Failed to fetch URL:" wording), else ``None``.Blocks private/loopback/link-local targets and caps the download size.+ No input reaches the caller as an exception: the URL is model-supplied, so+ every malformed form resolves to one of these strings.``deadline`` is an optional ``time.monotonic`` cutoff for the whole fetch(redirect hops and body read included) and ``cancel_event`` aborts it when@@ -6583,11 +6636,15 @@ def _fetch_url_raw(from urllib.parse import urlparsefrom .web_access_policy import check_url_access- parsed = urlparse(url)+ # Before the policy gate: it requires an http(s) scheme, so a bare host+ # would be refused there and never reach the fetch.+ url = _normalize_url_scheme(url)allowed, reason, canonical_host = check_url_access(url, website_policy)if not allowed:return reason, "", ""+ # 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(canonical_host,@@ -6648,13 +6705,15 @@ def _fetch_url_raw(if not location:return "Failed to fetch URL: redirect missing Location header.", "", ""current_url = urljoin(current_url, location)- rp = urlparse(current_url)+ # Server-controlled, so never scheme-upgraded; the gate below+ # reads .port first, so the parse after it cannot raise.allowed, policy_reason, redirect_host = check_url_access(current_url,website_policy,)if not allowed: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(redirect_host,@@ -6872,6 +6931,8 @@ def _fetch_page_text(deadline = None if timeout is None else time.monotonic() + timeoutfrom .web_access_policy import check_url_access+ # Before the policy gate (needs a scheme) and the README routing (reads host/path).+ url = _normalize_url_scheme(url)allowed, reason, _hostname = check_url_access(url, website_policy)if not allowed:return reasondiff --git a/studio/backend/tests/test_tool_loop_controller.py b/studio/backend/tests/test_tool_loop_controller.pyindex 496c30ac136..e9ed58b0900 100644--- a/studio/backend/tests/test_tool_loop_controller.py+++ b/studio/backend/tests/test_tool_loop_controller.py@@ -7,6 +7,8 @@ import jsonimport sysfrom pathlib import Path+import pytest+_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)if _BACKEND_DIR not in sys.path:sys.path.insert(0, _BACKEND_DIR)@@ -93,6 +95,29 @@ def test_status_and_provenance_match_local_event_conventions():}+ "url, expected",+ [+ # bare hosts are fetched, so the badge must name them+ ("google.com", "Reading: google.com"),+ ("www.google.com/x", "Reading: google.com"),+ ("//google.com", "Reading: google.com"),+ ("example.com:8443/path", "Reading: example.com"),+ ("github.com/unslothai/unsloth", "Reading: github.com"),+ # still generic for what the fetch layer refuses+ ("/login", "Reading page..."),+ ("javascript:alert(1)", "Reading page..."),+ # urlparse raises on these, outside the fetch's handler: degrade, not raise+ ("https://[::1", "Reading page..."),+ ("https://::1]", "Reading page..."),+ ("//exam/ple.com", "Reading page..."),+ ("//example.com@", "Reading page..."),+ ],+)+def test_status_names_the_host_for_schemeless_urls(url, expected):+ assert status_for_tool("web_search", {"url": url}) == expected++def test_prepare_execute_builds_visible_events_and_model_tool_message():controller = ToolLoopController(tools = [_tool("web_search")])decision = controller.prepare_call(_call("web_search", {"query": "gpu prices"}))diff --git a/studio/backend/tests/test_web_fetch_scheme_normalization.py b/studio/backend/tests/test_web_fetch_scheme_normalization.pynew file mode 100644index 00000000000..b4dad837e6b--- /dev/null+++ b/studio/backend/tests/test_web_fetch_scheme_normalization.py@@ -0,0 +1,170 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Bare hosts ("google.com") must be fetched as https, not refused."""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parent.parent+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++from core.inference import tools # noqa: E402+++def resolved(monkeypatch):+ seen: dict = {}++ def fake_resolve(hostname, port, deadline, cancel_event):+ seen["hostname"] = hostname+ seen["port"] = port+ return False, "stopped", None++ monkeypatch.setattr(tools, "_resolve_with_budget", fake_resolve)+ return seen+++ "url, hostname, port",+ [+ ("google.com", "google.com", 443),+ ("www.google.com/x", "www.google.com", 443),+ ("//google.com", "google.com", 443),+ ("https://google.com", "google.com", 443),+ ("http://google.com", "google.com", 80),+ ("example.com:8443/path", "example.com", 8443),+ ("example.com:8443", "example.com", 8443),+ ("sub.example.co.uk:8080", "sub.example.co.uk", 8080),+ ],+)+def test_schemeless_urls_are_fetched_as_https(resolved, url, hostname, port):+ err, _, _ = tools._fetch_url_raw(url)+ assert resolved["hostname"] == hostname+ assert resolved["port"] == port+ assert "only http/https" not in (err or "")+++ "url",+ [+ "ftp://x.com",+ "file:///etc/passwd",+ "javascript:alert(1)",+ "mailto:[email protected]",+ # scheme:digits must not masquerade as host:port+ "file:80",+ "javascript:443/path",+ "mailto:25",+ # out-of-range ports are not host:port either+ "example.com:99999",+ "example.com:0",+ # ports must match ASCII [0-9]: str.isdigit() is True for digits int() refuses+ "example.com:²",+ "example.com:²/x",+ "example.com:①",+ "example.com:1²",+ "//example.com:²",+ # non-ASCII decimal digits int() accepts are ports urlparse then refuses+ "example.com:٤٤٣",+ # root-relative paths have no host to fetch+ "/login",+ "/github.com/owner/repo",+ ],+)+def test_non_http_schemes_still_blocked(url):+ err, _, _ = tools._fetch_url_raw(url)+ assert err and "only http/https" in err+++def test_absurdly_long_port_does_not_raise():+ err, _, _ = tools._fetch_url_raw("example.com:" + "9" * 4400)+ assert err and "only http/https" in err+++def test_out_of_range_port_returns_error_instead_of_raising():+ # check_url_access owns the wording; what matters is a string, not a raise.+ err, _, _ = tools._fetch_url_raw("https://example.com:99999")+ assert err and err.startswith("Blocked:")+++def test_redirect_to_out_of_range_port_is_blocked(monkeypatch):+ # A redirect target reads .port too, so it needs the same guard.+ import urllib.request+ from urllib.error import HTTPError++ monkeypatch.setattr(+ tools,+ "_resolve_with_budget",+ lambda host, port, deadline, cancel: (True, "", "93.184.216.34"),+ )++ class _Redirecting:+ def open(self, req, **kw):+ hdrs = {"Location": "https://example.org:99999/next"}+ raise HTTPError(req.full_url, 302, "Found", hdrs, None)++ monkeypatch.setattr(urllib.request, "build_opener", lambda *handlers: _Redirecting())+ err, _, _ = tools._fetch_url_raw("https://example.com")+ assert err and err.startswith("Blocked:")+++ "url",+ [+ # urlparse raises on these; a model-supplied URL must still return a string+ "//exam/ple.com", # NFKC-decomposes into "/"+ "//example.com@", # NFKC-decomposes into "@"+ "//example.com:", # NFKC-decomposes into ":"+ "https://[::1", # unmatched IPv6 bracket+ "https://::1]",+ ],+)+def test_malformed_url_is_blocked_instead_of_raising(url):+ err, _, _ = tools._fetch_url_raw(url)+ assert err and err.startswith("Blocked:")+++def test_idna_failure_is_reported_instead_of_raising(monkeypatch):+ # getaddrinfo raises UnicodeError, not OSError, when IDNA encoding fails.+ import socket++ def boom(*a, **k):+ raise UnicodeError("encoding with 'idna' codec failed")++ monkeypatch.setattr(socket, "getaddrinfo", boom)+ err, _, _ = tools._fetch_url_raw("https://münich.example")+ assert err and err.startswith("Failed to resolve host:")+++ "url, hostname",+ [+ (" google.com", "google.com"),+ ("google.com\n", "google.com"),+ ("\t example.com:8443 ", "example.com"),+ ],+)+def test_surrounding_whitespace_is_stripped(resolved, url, hostname):+ # _web_search strips, but direct callers of the fetch layer do not.+ tools._fetch_url_raw(url)+ assert resolved["hostname"] == hostname++[email protected]("url", ["127.0.0.1", "169.254.169.254", "10.0.0.1", "192.168.1.1"])+def test_normalization_does_not_bypass_ssrf_guard(url):+ err, _, _ = tools._fetch_url_raw(url, timeout = 3)+ assert err and "non-public address" in err+++def test_schemeless_github_repo_still_routes_to_readme_api():+ # Must run before _github_repo_readme_api_url, else a bare repo URL scrapes HTML.+ normalized = tools._normalize_url_scheme("github.com/unslothai/unsloth")+ assert tools._github_repo_readme_api_url(normalized) == (+ "https://api.github.com/repos/unslothai/unsloth/readme"+ )diff --git a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsxindex 062d0b13700..e11ef6cc2a2 100644--- a/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx+++ b/studio/frontend/src/components/assistant-ui/tool-ui-web-search.tsx@@ -23,6 +23,18 @@ const RE_BLOCK_SEP = /\n---\n/;const RE_TITLE = /Title:\s*(.+)/;const RE_URL = /URL:\s*(.+)/;const RE_SNIPPET = /Snippet:\s*(.+)/s;+// Mirrors _normalize_url_scheme: a dotted host, optionally followed by a port+// that may be empty ("example.com:" fetches on the default port) but otherwise+// has to be in range, so the card names a host only when the backend fetches it.+const RE_BARE_HOST = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+(?::(\d{0,5}))?(?:[/?#]|$)/;++function isBareHostFetchedAsHttps(value: string): boolean {+ const match = RE_BARE_HOST.exec(value);+ if (!match) return false;+ const port = match[1];+ if (!port) return true;+ return Number(port) >= 1 && Number(port) <= 65535;+}/*** Reject non-http(s) URLs. Web-search/fetch output is provider-controlled,@@ -72,8 +84,12 @@ const WebSearchToolUIImpl: ToolCallMessagePartComponent = ({const isUrlFetch = !!url;const displayDomain = (() => {if (!url) return "";+ // new URL() throws on the bare hosts the backend fetches, so mirror that+ // grammar or the card names no host for exactly the URLs it does fetch.+ const bare = url.startsWith("//") ? url.slice(2) : url;+ const candidate = isBareHostFetchedAsHttps(bare) ? `https://${bare}` : url;try {- const parsed = new URL(url);+ const parsed = new URL(candidate);if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return "";return parsed.hostname.replace(/^www\./, "");} catch {