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: fix lan address actions and launch bind reporting (#9170)

Long Yixingce99e954cbb6
diff --git a/studio/backend/cloudflare_tunnel.py b/studio/backend/cloudflare_tunnel.py
index 3131eb0ba25..a9577559fc8 100644
--- a/studio/backend/cloudflare_tunnel.py
+++ b/studio/backend/cloudflare_tunnel.py
@@ -398,11 +398,18 @@ def _process_exited(proc: subprocess.Popen) -> bool:
return False
+def _origin_url(host: str, port: int) -> str:
+ url_host = host.replace("%", "%25")
+ if ":" in url_host and not url_host.startswith("["):
+ url_host = f"[{url_host}]"
+ return f"http://{url_host}:{port}"
+
+
class CloudflareTunnel:
- """A cloudflared quick tunnel to http://localhost:<port>. Best-effort throughout.
+ """A cloudflared quick tunnel to a local Studio endpoint. Best-effort throughout.
- Use localhost (not the wildcard bind) as the tunnel origin so cloudflared's
- upstream stays local-only.
+ Use a loopback address for wildcard binds so cloudflared's upstream stays
+ local-only while matching Studio's active address family.
"""
def __init__(
@@ -410,9 +417,11 @@ class CloudflareTunnel:
port: int,
binary: str,
protocol: Optional[str] = None,
+ origin_host: str = "localhost",
):
self.port = port
self.binary = binary
+ self.origin_host = origin_host
# None lets cloudflared pick its default (quic, with its own http2
# fallback); set to "http2" to force it when quic is blocked.
self.protocol = protocol
@@ -433,7 +442,7 @@ class CloudflareTunnel:
self.binary,
"tunnel",
"--url",
- f"http://localhost:{self.port}",
+ _origin_url(self.origin_host, self.port),
"--no-autoupdate",
]
if self.protocol:
@@ -762,6 +771,7 @@ def start_studio_tunnel(
*,
managed_by: str = "launch",
admission: Optional[Tuple[int, int]] = None,
+ origin_host: str = "localhost",
) -> Optional[str]:
"""Start a quick tunnel and return its public URL once it is actually
serving, or None (best-effort).
@@ -790,6 +800,7 @@ def start_studio_tunnel(
and _tunnel_owner == managed_by
and _tunnel_port == port
and _active_tunnel is not None
+ and getattr(_active_tunnel, "origin_host", "localhost") == origin_host
):
return _tunnel_url
if (
@@ -827,7 +838,12 @@ def start_studio_tunnel(
if _shutdown_requested or generation != _tunnel_generation:
_active_tunnel = None
return None
- tunnel = CloudflareTunnel(port, binary, protocol = protocol)
+ tunnel = CloudflareTunnel(
+ port,
+ binary,
+ protocol = protocol,
+ origin_host = origin_host,
+ )
prior, _active_tunnel = _active_tunnel, tunnel
if prior is not None and prior.stop() is False:
with _active_lock:
diff --git a/studio/backend/lan_access.py b/studio/backend/lan_access.py
index 0afe5e1d43b..233ad4d8bd2 100644
--- a/studio/backend/lan_access.py
+++ b/studio/backend/lan_access.py
@@ -15,9 +15,9 @@ runs on the primary server's event loop with ``lifespan="off"``, so the app's
startup and shutdown handlers stay owned by the primary server and never fire
twice.
-IPv4 only. Every consumer of this (URLs in the UI, the QR code, the frontend
-gate) works off the addresses reported here, and a link-local IPv6 URL is not
-something a phone can be handed.
+The settings-managed listener remains IPv4 only. Address discovery also serves
+an existing IPv6 wildcard launch, while link-local IPv6 addresses are omitted
+because another device cannot use them without the listener's interface scope.
"""
from __future__ import annotations
@@ -48,10 +48,15 @@ _STOP_TIMEOUT = 3.0
# for all of them; on expiry the trust flag is left active rather than downgraded
_DRAIN_TIMEOUT = 300.0
+# networking mode rarely changes, but a failed wslinfo probe must eventually recover
+_WSL_MODE_CACHE_TTL = 60.0
+
# uvicorn's own default, so a burst queues on the LAN socket as it does on loopback
_LISTEN_BACKLOG = 2048
_lock = threading.RLock()
+_wsl_mode_lock = threading.Lock()
+_wsl_mode_cache: Optional[tuple[float, str]] = None
_server: Any = None
_serve_loop: Any = None
_sockets: tuple[socket.socket, ...] = ()
@@ -64,8 +69,8 @@ _pending_drains = 0
_bound_addresses: tuple[str, ...] = ()
-def detect_lan_addresses() -> list[str]:
- """The machine's own reachable IPv4 addresses, default route first.
+def detect_lan_addresses(ip_version: int = 4) -> list[str]:
+ """The machine's own reachable addresses for one IP version, default route first.
Loopback, link-local (169.254/16) and multicast are dropped: none of them is
an address another device on the network can open. A public address is kept
@@ -79,27 +84,38 @@ def detect_lan_addresses() -> list[str]:
if _wsl_networking_mode() not in (None, "mirrored"):
return []
+ if ip_version == 4:
+ socket_family = socket.AF_INET
+ route_probe = ("8.8.8.8", 80)
+ elif ip_version == 6:
+ socket_family = socket.AF_INET6
+ route_probe = ("2001:4860:4860::8888", 80, 0, 0)
+ else:
+ raise ValueError("ip_version must be 4 or 6")
+
addresses: list[str] = []
def _add(candidate: str) -> None:
+ candidate = candidate.split("%", 1)[0]
try:
parsed = ipaddress.ip_address(candidate)
except ValueError:
return
- if parsed.version != 4:
+ if parsed.version != ip_version:
return
if parsed.is_loopback or parsed.is_link_local or parsed.is_multicast:
return
if parsed.is_unspecified or parsed.is_reserved:
return
- if candidate not in addresses:
- addresses.append(candidate)
+ normalized = str(parsed)
+ if normalized not in addresses:
+ addresses.append(normalized)
- # a UDP connect only fixes the local end of the socket; nothing is sent to 8.8.8.8
+ # a UDP connect only fixes the local end of the socket; nothing is sent to the target
probe = None
try:
- probe = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
- probe.connect(("8.8.8.8", 80))
+ probe = socket.socket(socket_family, socket.SOCK_DGRAM)
+ probe.connect(route_probe)
_add(probe.getsockname()[0])
except OSError:
pass
@@ -107,9 +123,9 @@ def detect_lan_addresses() -> list[str]:
if probe is not None:
probe.close()
- # every other adapter that is up: the route to 8.8.8.8 picks one source address, and
+ # every other adapter that is up: a route probe picks one source address, and
# an isolated LAN has no route at all, so neither it nor the hostname enumerates them
- for address in _interface_addresses():
+ for address in _interface_addresses(ip_version):
_add(address)
return addresses
@@ -121,21 +137,30 @@ def _wsl_networking_mode() -> Optional[str]:
advertised. Older releases use NAT, so failing closed avoids handing a phone
an address that only the Windows host can route to.
"""
+ global _wsl_mode_cache
+
if sys.platform != "linux" or "microsoft" not in platform.release().casefold():
return None
- try:
- result = subprocess.run(
- ["wslinfo", "--networking-mode"],
- capture_output = True,
- check = False,
- text = True,
- encoding = "utf-8",
- timeout = 1,
- )
- except (OSError, subprocess.SubprocessError):
- return "unknown"
- mode = result.stdout.strip().casefold()
- return mode or "unknown"
+ with _wsl_mode_lock:
+ now = time.monotonic()
+ cached = _wsl_mode_cache
+ if cached is not None and now - cached[0] < _WSL_MODE_CACHE_TTL:
+ return cached[1]
+ try:
+ result = subprocess.run(
+ ["wslinfo", "--networking-mode"],
+ capture_output = True,
+ check = False,
+ text = True,
+ encoding = "utf-8",
+ timeout = 1,
+ )
+ except (OSError, subprocess.SubprocessError):
+ mode = "unknown"
+ else:
+ mode = result.stdout.strip().casefold() or "unknown"
+ _wsl_mode_cache = (time.monotonic(), mode)
+ return mode
def _is_host_only_interface(name: str) -> bool:
@@ -149,8 +174,8 @@ def _is_host_only_interface(name: str) -> bool:
)
-def _interface_addresses() -> list[str]:
- """IPv4 addresses on every interface that is up.
+def _interface_addresses(ip_version: int = 4) -> list[str]:
+ """Addresses for one IP version on every interface that is up.
Falls back to resolving the hostname where psutil is unavailable. That
fallback is not an enumeration: a Linux host mapping its name to 127.0.1.1
@@ -162,12 +187,17 @@ def _interface_addresses() -> list[str]:
try:
return [
info[4][0]
- for info in socket.getaddrinfo(socket.gethostname(), None, socket.AF_INET)
+ for info in socket.getaddrinfo(
+ socket.gethostname(),
+ None,
+ socket.AF_INET if ip_version == 4 else socket.AF_INET6,
+ )
]
except OSError:
return []
try:
stats = psutil.net_if_stats()
+ family = socket.AF_INET if ip_version == 4 else socket.AF_INET6
addresses = []
for name, entries in psutil.net_if_addrs().items():
if _is_host_only_interface(name):
@@ -175,7 +205,7 @@ def _interface_addresses() -> list[str]:
interface = stats.get(name)
if interface is not None and not interface.isup:
continue
- addresses.extend(e.address for e in entries if e.family == socket.AF_INET)
+ addresses.extend(e.address for e in entries if e.family == family)
return addresses
except Exception:
return []
diff --git a/studio/backend/routes/settings.py b/studio/backend/routes/settings.py
index 932270705f0..230424f2121 100644
--- a/studio/backend/routes/settings.py
+++ b/studio/backend/routes/settings.py
@@ -3006,6 +3006,8 @@ class LanAccessResponse(BaseModel):
can_start: bool
can_stop: bool
block_reason: Optional[str] = None
+ bind_host: Optional[str] = None
+ wildcard_bind: bool = False
serves_web_ui: bool = True
keyless_lan_eligible: bool = False
keyless_scope: Literal["off", "inference", "full"] = "off"
diff --git a/studio/backend/run.py b/studio/backend/run.py
index d370aac2e9f..62c617a7b2d 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -152,6 +152,13 @@ import _platform_compat # noqa: F401
from loggers import get_logger, install_uvicorn_duplicate_exception_filter
from startup_banner import print_studio_access_banner, print_studio_stop_hint
+from utils.host_policy import (
+ is_wildcard_host,
+ normalize_wildcard_bind_host,
+ resolved_bind_address_count,
+ wildcard_ip_versions,
+ wildcard_loopback_host,
+)
logger = get_logger(__name__)
@@ -221,9 +228,7 @@ def _install_uvicorn_startup_log_rewrite(bind_host: str, display_host: str) -> N
import logging
import re
- rewrite_host = (
- bind_host in ("0.0.0.0", "::") and bool(display_host) and display_host != bind_host
- )
+ rewrite_host = is_wildcard_host(bind_host) and bool(display_host) and display_host != bind_host
new_suffix = "(To stop: press Ctrl+C -- on macOS, Control+C not Command+C)"
old_suffix_re = re.compile(r"\(Press CTRL\+C to quit\)")
old_prefix = "Uvicorn running on "
@@ -374,7 +379,7 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
import urllib.parse
import urllib.request
- if not display_host or display_host in ("0.0.0.0", "::"):
+ if not display_host or is_wildcard_host(display_host):
return
use_color = _stdout_color_ok()
@@ -409,7 +414,7 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
return
try:
- qs = urllib.parse.urlencode({"host": f"{display_host}:{port}", "max_nodes": 3})
+ qs = urllib.parse.urlencode({"host": f"{_url_host(display_host)}:{port}", "max_nodes": 3})
req = urllib.request.Request(
f"https://check-host.net/check-tcp?{qs}",
headers = {
@@ -519,16 +524,32 @@ def _verify_global_reachability(display_host: str, port: int) -> None:
def _display_host_for_bind(host: str) -> str:
- return _resolve_external_ip() if host in ("0.0.0.0", "::") else host
+ wildcard_versions = wildcard_ip_versions(host)
+ if not wildcard_versions:
+ return host
+ ipv4_display_host = None
+ if 4 in wildcard_versions:
+ ipv4_display_host = _resolve_external_ip()
+ if not is_wildcard_host(ipv4_display_host):
+ return ipv4_display_host
+ if 6 in wildcard_versions:
+ from lan_access import detect_lan_addresses
+ addresses = detect_lan_addresses(6)
+ if addresses:
+ return addresses[0]
+ return ipv4_display_host or "::"
def _loopback_bind_host_for(host: str) -> str:
- return "::1" if host == "::" else "127.0.0.1"
+ return wildcard_loopback_host(host) or "127.0.0.1"
def _url_host(host: str) -> str:
+ url_host = host.replace("%", "%25")
return (
- f"[{host}]" if ":" in host and not (host.startswith("[") and host.endswith("]")) else host
+ f"[{url_host}]"
+ if ":" in url_host and not (url_host.startswith("[") and url_host.endswith("]"))
+ else url_host
)
@@ -554,7 +575,7 @@ def _tool_policy_notice(host: str, secure: bool, enable_tools: "Optional[bool]")
)
from utils.host_policy import is_external_host
- if host in ("0.0.0.0", "::") or is_external_host(host):
+ if is_external_host(host):
return (
f"Server-side tools are {state} and this port is network-reachable. "
"Anyone who can reach it with the API key can run code on this "
@@ -596,7 +617,7 @@ def _emit_startup_output(
if secure:
_emit_secure_startup_output(port, enable_tools)
return
- wildcard_bind = host in ("0.0.0.0", "::")
+ wildcard_bind = is_wildcard_host(host)
localhost_mismatch_url = _localhost_ipv6_mismatch_url(host, port)
print_studio_access_banner(
port = port,
@@ -761,11 +782,10 @@ def _addresses_collide(recorded: "str | None", host: str, port: int) -> bool:
*recorded* may list several addresses. Unknown or wildcard on either side
collides: refusing with a clear message beats silently starting a duplicate.
"""
- wildcards = ("0.0.0.0", "::", "")
- if not recorded or host in wildcards:
+ if not recorded or is_wildcard_host(host):
return True
listed = {a.strip() for a in recorded.split(",") if a.strip()}
- if not listed or listed & set(wildcards):
+ if not listed or any(is_wildcard_host(address) for address in listed):
return True
return bool(listed & _bind_addresses(host, port))
@@ -781,18 +801,32 @@ def _is_port_free(host: str, port: int) -> bool:
# 1. Can we bind to the requested address? getaddrinfo resolves both
# IPv4 and IPv6 to the right address family.
+ sockets = []
try:
addr_info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
- family, socktype, proto, _, sockaddr = addr_info[0]
- with socket.socket(family, socktype, proto) as s:
- s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
- s.bind(sockaddr)
+ seen = set()
+ for family, socktype, proto, _, sockaddr in addr_info:
+ key = (family, socktype, proto, sockaddr)
+ if key in seen:
+ continue
+ seen.add(key)
+ probe = socket.socket(family, socktype, proto)
+ sockets.append(probe)
+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ if family == socket.AF_INET6 and hasattr(socket, "IPV6_V6ONLY"):
+ probe.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
+ probe.bind(sockaddr)
+ if not sockets:
+ return False
except OSError:
return False
+ finally:
+ for probe in sockets:
+ probe.close()
# 2. On a wildcard bind, verify localhost isn't already claimed by another
# process (e.g. an SSH -L tunnel); a successful connect means it is.
- if host in ("0.0.0.0", "::"):
+ if is_wildcard_host(host):
for loopback, family in [
("127.0.0.1", socket.AF_INET),
("::1", socket.AF_INET6),
@@ -1968,7 +2002,7 @@ def _cloudflare_tunnel_should_start(
return False
if secure:
return True
- return host in ("0.0.0.0", "::") and not api_only
+ return is_wildcard_host(host) and not api_only
def _final_bound_port(server, requested_port: int) -> int:
@@ -1983,6 +2017,23 @@ def _final_bound_port(server, requested_port: int) -> int:
raise RuntimeError("Uvicorn did not expose its final bound port")
+def _bound_request_host(server) -> str:
+ """Return a literal address from Uvicorn's active listener sockets."""
+ for listener in getattr(server, "servers", ()):
+ for sock in getattr(listener, "sockets", ()) or ():
+ address = sock.getsockname()
+ if not isinstance(address, tuple) or not address or not isinstance(address[0], str):
+ continue
+ host = address[0]
+ loopback_host = wildcard_loopback_host(host)
+ if loopback_host is not None:
+ return loopback_host
+ if len(address) >= 4 and address[3] and ":" in host and "%" not in host:
+ return f"{host}%{address[3]}"
+ return host
+ raise RuntimeError("Uvicorn did not expose its bound address")
+
+
_CLOUDFLARE_INTENT_ENV = "_UNSLOTH_CLOUDFLARE_INTENT"
@@ -2307,6 +2358,9 @@ def run_server(
"""
global _server, _server_thread, _shutdown_event
+ if not isinstance(host, str) or not host.strip():
+ raise SystemExit("--host cannot be empty; use 0.0.0.0 to bind every IPv4 interface.")
+
boot_started = time.perf_counter()
# --secure exposes ONLY the Cloudflare link, so --secure --no-cloudflare contradicts
@@ -2317,6 +2371,16 @@ def run_server(
raise SystemExit(
"--secure requires the Cloudflare tunnel; do not combine it with --no-cloudflare."
)
+ if not secure:
+ try:
+ host = normalize_wildcard_bind_host(host)
+ except ValueError as exc:
+ raise SystemExit(str(exc)) from None
+ if port == 0 and resolved_bind_address_count(host) > 1:
+ raise SystemExit(
+ "--port 0 cannot be used when --host resolves to multiple bind addresses; "
+ "choose an explicit port."
+ )
# Windows cp1252 can't encode emoji; reconfigure stdout to UTF-8. Before the tee, so
# it reaches the console stream rather than the wrapper.
@@ -2614,6 +2678,7 @@ def run_server(
# backend, not whatever a proxy/tunnel exposed. For ephemeral binds (port==0)
# leave it unset so handlers fall back to the request scope / base_url.
app.state.server_port = port if port and port > 0 else None
+ app.state.server_request_host = None
# Direct (non-tunnel) base for the API panel; resolve wildcard binds to the LAN IP.
if port and port > 0:
_direct_host = _display_host_for_bind(host)
@@ -2760,6 +2825,7 @@ def run_server(
port = _final_bound_port(_server, port)
app.state.server_port = port
+ app.state.server_request_host = _bound_request_host(_server)
app.state.server_url = f"http://{_url_host(_display_host_for_bind(host))}:{port}"
app.state.remote_access_port = port
app.state.lan_access_port = port
@@ -2809,7 +2875,11 @@ def run_server(
if _cloudflare_enabled:
try: # best-effort: any failure must not block startup
from cloudflare_tunnel import start_studio_tunnel
- start_studio_tunnel(port, managed_by = "launch")
+ start_studio_tunnel(
+ port,
+ managed_by = "launch",
+ origin_host = app.state.server_request_host,
+ )
except Exception as e:
logger.debug("Cloudflare tunnel skipped: %s", e)
diff --git a/studio/backend/startup_banner.py b/studio/backend/startup_banner.py
index 6584048af21..145c7f6dcf5 100644
--- a/studio/backend/startup_banner.py
+++ b/studio/backend/startup_banner.py
@@ -11,6 +11,8 @@ from __future__ import annotations
import os
import sys
+from utils.host_policy import is_wildcard_host, wildcard_loopback_host
+
def _safe_print(text: str) -> None:
"""Print text without crashing on terminals that cannot encode Unicode."""
@@ -99,7 +101,8 @@ def print_studio_access_banner(
def style(text: str, code: str) -> str:
return f"{code}{text}{reset}" if use_color else text
- ipv6_bind = bind_host in ("::", "::1")
+ listen_all = is_wildcard_host(bind_host)
+ ipv6_bind = bind_host == "::1" or wildcard_loopback_host(bind_host) == "::1"
if ipv6_bind:
loopback_url = f"http://[::1]:{port}"
alt_local = f"http://localhost:{port}"
@@ -111,7 +114,6 @@ def print_studio_access_banner(
else:
external_url = f"http://{display_host}:{port}"
- listen_all = bind_host in ("0.0.0.0", "::")
# The exact aliases the canned loopback_url below is valid for; any other bind
# (e.g. a specific LAN IP) must show its real address, not http://127.0.0.1.
loopback_bind = bind_host in ("127.0.0.1", "localhost", "::1")
diff --git a/studio/backend/tests/test_bind_host_policy.py b/studio/backend/tests/test_bind_host_policy.py
new file mode 100644
index 00000000000..47be9886147
--- /dev/null
+++ b/studio/backend/tests/test_bind_host_policy.py
@@ -0,0 +1,230 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import asyncio
+import socket
+
+import pytest
+
+from utils import host_policy
+from utils.host_policy import (
+ is_wildcard_host,
+ normalize_wildcard_bind_host,
+ resolved_bind_address_count,
+ wildcard_ip_versions,
+ wildcard_loopback_host,
+)
+
+
+ "host",
+ [
+ "0.0.0.0",
+ "::",
+ "::0",
+ "0:0:0:0:0:0:0:0",
+ "0",
+ "00",
+ "0.0",
+ "0.0.0",
+ "::ffff:0.0.0.0",
+ "::ffff:0:0",
+ ],
+)
+def test_unspecified_bind_aliases_are_wildcards(host):
+ assert is_wildcard_host(host) is True
+
+
[email protected]("host", ["", "127.0.0.1", "localhost", "::1", "192.168.1.24", "fd00::5"])
+def test_specific_bind_hosts_are_not_wildcards(host):
+ assert is_wildcard_host(host) is False
+
+
+ "host,expected",
+ [
+ ("0.0.0.0", "127.0.0.1"),
+ ("::0", "::1"),
+ ("::ffff:0.0.0.0", "127.0.0.1"),
+ ],
+)
+def test_wildcard_loopback_matches_the_effective_address_family(host, expected):
+ assert wildcard_loopback_host(host) == expected
+
+
+ "host,expected",
+ [
+ ("0", "0.0.0.0"),
+ ("::0", "::"),
+ ("::ffff:0.0.0.0", "0.0.0.0"),
+ ("::ffff:127.0.0.1", "127.0.0.1"),
+ ("192.168.1.24", "192.168.1.24"),
+ ],
+)
+def test_effective_wildcards_are_normalized_before_binding(host, expected):
+ assert normalize_wildcard_bind_host(host) == expected
+
+
+def test_a_mapped_wildcard_is_bindable_through_asyncio_after_normalization():
+ async def bind():
+ server = await asyncio.start_server(
+ lambda _reader, _writer: None,
+ host = normalize_wildcard_bind_host("::ffff:0.0.0.0"),
+ port = 0,
+ )
+ try:
+ return server.sockets[0].family
+ finally:
+ server.close()
+ await server.wait_closed()
+
+ assert asyncio.run(bind()) == socket.AF_INET
+
+
+def test_a_mapped_specific_bind_is_bindable_through_asyncio_after_normalization():
+ async def bind():
+ server = await asyncio.start_server(
+ lambda _reader, _writer: None,
+ host = normalize_wildcard_bind_host("::ffff:127.0.0.1"),
+ port = 0,
+ )
+ try:
+ return server.sockets[0].family
+ finally:
+ server.close()
+ await server.wait_closed()
+
+ assert asyncio.run(bind()) == socket.AF_INET
+
+
+def test_a_resolved_mapped_bind_is_bindable_through_asyncio_after_normalization(monkeypatch):
+ with monkeypatch.context() as patch:
+ patch.setattr(
+ host_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::ffff:127.0.0.1", 0, 0, 0))
+ ],
+ )
+ normalized_host = normalize_wildcard_bind_host("mapped.test")
+
+ async def bind():
+ server = await asyncio.start_server(
+ lambda _reader, _writer: None,
+ host = normalized_host,
+ port = 0,
+ )
+ try:
+ return server.sockets[0].family
+ finally:
+ server.close()
+ await server.wait_closed()
+
+ assert normalized_host == "127.0.0.1"
+ assert asyncio.run(bind()) == socket.AF_INET
+
+
+def test_ambiguous_resolved_mapped_binds_are_rejected(monkeypatch):
+ monkeypatch.setattr(
+ host_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::ffff:127.0.0.1", 0, 0, 0)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::ffff:192.168.1.24", 0, 0, 0)),
+ ],
+ )
+
+ with pytest.raises(ValueError, match = "resolves to ambiguous IPv4-mapped addresses"):
+ normalize_wildcard_bind_host("ambiguous-mapped.test")
+
+
+def test_a_resolved_ipv6_wildcard_uses_ipv6_loopback(monkeypatch):
+ monkeypatch.setattr(
+ host_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [(socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::", 0, 0, 0))],
+ )
+
+ assert is_wildcard_host("wildcard.test") is True
+ assert normalize_wildcard_bind_host("wildcard.test") == "::"
+ assert wildcard_ip_versions("wildcard.test") == (6,)
+ assert wildcard_loopback_host("wildcard.test") == "::1"
+
+
+def test_a_dual_stack_wildcard_hostname_keeps_both_address_families(monkeypatch):
+ monkeypatch.setattr(
+ host_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("0.0.0.0", 0)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::", 0, 0, 0)),
+ ],
+ )
+
+ assert is_wildcard_host("dual-wildcard.test") is True
+ assert normalize_wildcard_bind_host("dual-wildcard.test") == "dual-wildcard.test"
+ assert resolved_bind_address_count("dual-wildcard.test") == 2
+ assert wildcard_ip_versions("dual-wildcard.test") == (4, 6)
+ assert wildcard_loopback_host("dual-wildcard.test") == "127.0.0.1"
+
+
+def test_a_mixed_family_wildcard_hostname_is_rejected(monkeypatch):
+ monkeypatch.setattr(
+ host_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("0.0.0.0", 0)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fd00::24", 0, 0, 0)),
+ ],
+ )
+
+ with pytest.raises(ValueError, match = "mixes wildcard and specific address families"):
+ normalize_wildcard_bind_host("mixed-wildcard.test")
+
+
+def test_scoped_ipv6_endpoints_count_as_distinct_binds(monkeypatch):
+ monkeypatch.setattr(
+ host_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", 0, 0, 2)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", 0, 0, 3)),
+ ],
+ )
+
+ assert resolved_bind_address_count("scoped.test") == 2
+
+
+def test_run_server_rejects_an_empty_bind_before_startup():
+ from run import run_server
+ with pytest.raises(SystemExit, match = "--host cannot be empty"):
+ run_server(host = "")
+
+
+def test_run_server_rejects_a_mixed_family_wildcard_before_startup(monkeypatch):
+ monkeypatch.setattr(
+ host_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("0.0.0.0", 0)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fd00::24", 0, 0, 0)),
+ ],
+ )
+ from run import run_server
+ with pytest.raises(SystemExit, match = "mixes wildcard and specific address families"):
+ run_server(host = "mixed-wildcard.test")
+
+
+def test_run_server_rejects_an_ephemeral_multi_address_bind(monkeypatch):
+ monkeypatch.setattr(
+ host_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("0.0.0.0", 0)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::", 0, 0, 0)),
+ ],
+ )
+ from run import run_server
+ with pytest.raises(SystemExit, match = "--port 0 cannot be used"):
+ run_server(host = "dual-wildcard.test", port = 0)
diff --git a/studio/backend/tests/test_cloudflare_tunnel.py b/studio/backend/tests/test_cloudflare_tunnel.py
index 5d8390265d8..b69eb943236 100644
--- a/studio/backend/tests/test_cloudflare_tunnel.py
+++ b/studio/backend/tests/test_cloudflare_tunnel.py
@@ -75,6 +75,20 @@ def test_url_regex_skips_api_host_but_matches_real_url():
assert m.group(0) == "https://brave-mountain-river-clouds.trycloudflare.com"
+ "host,expected",
+ [
+ ("localhost", "http://localhost:8080"),
+ ("127.0.0.1", "http://127.0.0.1:8080"),
+ ("::1", "http://[::1]:8080"),
+ ("fe80::1234%eth0", "http://[fe80::1234%25eth0]:8080"),
+ ("fe80::1234%12", "http://[fe80::1234%2512]:8080"),
+ ],
+)
+def test_origin_url_brackets_ipv6_hosts(host, expected):
+ assert ct._origin_url(host, 8080) == expected
+
+
# ── asset mapping ────────────────────────────────────────────────────
@@ -874,6 +888,7 @@ def test_start_studio_tunnel_drops_url_that_is_not_publicly_reachable(monkeypatc
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.url = None
attempts.append(protocol)
@@ -904,9 +919,11 @@ def test_start_studio_tunnel_returns_url_once_probe_passes(monkeypatch):
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.url = None
self.protocol = protocol
+ self.origin_host = origin_host
def start(self):
self.url = "https://words.trycloudflare.com"
@@ -925,8 +942,9 @@ def test_start_studio_tunnel_returns_url_once_probe_passes(monkeypatch):
monkeypatch.setattr(ct, "CloudflareTunnel", _Stub)
monkeypatch.setattr(ct, "verify_public_url", _probe)
try:
- assert ct.start_studio_tunnel(8080) == "https://words.trycloudflare.com"
+ assert ct.start_studio_tunnel(8080, origin_host = "::1") == "https://words.trycloudflare.com"
assert probed == ["https://words.trycloudflare.com"]
+ assert ct._active_tunnel.origin_host == "::1"
finally:
ct.stop_studio_tunnel()
@@ -994,6 +1012,7 @@ def test_start_studio_tunnel_registers_before_wait(monkeypatch):
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.url = None
@@ -1026,6 +1045,7 @@ def test_start_studio_tunnel_clears_and_stops_on_no_url(monkeypatch):
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.url = None
@@ -1052,6 +1072,7 @@ def test_start_studio_tunnel_returns_url(monkeypatch):
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.url = None
@@ -1083,6 +1104,7 @@ def test_start_studio_tunnel_falls_back_to_http2(monkeypatch):
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.protocol = protocol
self.url = None
@@ -1119,6 +1141,7 @@ def test_start_studio_tunnel_no_retry_when_shutdown_between_attempts(monkeypatch
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.url = None
attempts.append(protocol)
@@ -1150,6 +1173,7 @@ def test_start_studio_tunnel_no_http2_retry_when_no_url(monkeypatch):
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.url = None
attempts.append(protocol)
@@ -1180,6 +1204,7 @@ def test_start_studio_tunnel_both_protocols_fail_registration(monkeypatch):
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.url = None
attempts.append(protocol)
@@ -1212,6 +1237,7 @@ def test_start_studio_tunnel_aborts_retry_on_concurrent_shutdown(monkeypatch):
port,
binary,
protocol = None,
+ origin_host = "localhost",
):
self.url = None
attempts.append(protocol)
@@ -1288,6 +1314,7 @@ def test_verify_global_reachability_marks_private_address_unreachable():
ns = {
"_public_reachable": None,
"_stdout_color_ok": lambda: False,
+ "is_wildcard_host": lambda _host: False,
"_url_host": lambda host: host,
"print": lambda *a, **k: captured.append(" ".join(str(x) for x in a)),
}
diff --git a/studio/backend/tests/test_lan_access_settings.py b/studio/backend/tests/test_lan_access_settings.py
index abef23b2403..47d1ecfcbae 100644
--- a/studio/backend/tests/test_lan_access_settings.py
+++ b/studio/backend/tests/test_lan_access_settings.py
@@ -38,6 +38,7 @@ def _app(**over):
lan_access_is_colab = False,
lan_access_launch_managed = False,
lan_access_wildcard_bind = False,
+ lan_access_wildcard_ip_versions = (),
lan_access_secure_launch = False,
lan_access_frontend_served = True,
lan_access_loop = None,
@@ -89,17 +90,23 @@ def test_auto_start_persistence_is_strict_and_fail_closed(monkeypatch, stored_se
@pytest.mark.parametrize(
- "bind_host,launch_managed",
+ "bind_host,launch_managed,wildcard,ip_versions",
[
- ("127.0.0.1", False),
- ("localhost", False),
- ("::1", False),
- ("0.0.0.0", True),
- ("::", True),
- ("192.168.1.24", True),
+ ("127.0.0.1", False, False, ()),
+ ("localhost", False, False, ()),
+ ("::1", False, False, ()),
+ ("0.0.0.0", True, True, (4,)),
+ ("::", True, True, (6,)),
+ ("::0", True, True, (6,)),
+ ("0:0:0:0:0:0:0:0", True, True, (6,)),
+ ("0", True, True, (4,)),
+ ("::ffff:0.0.0.0", True, True, (4,)),
+ ("192.168.1.24", True, False, ()),
],
)
-def test_configure_reads_launch_ownership_from_the_bind_host(bind_host, launch_managed):
+def test_configure_reads_launch_ownership_from_the_bind_host(
+ bind_host, launch_managed, wildcard, ip_versions
+):
state = SimpleNamespace()
lan_settings.configure_lan_access(
state,
@@ -110,9 +117,35 @@ def test_configure_reads_launch_ownership_from_the_bind_host(bind_host, launch_m
frontend_served = True,
)
assert state.lan_access_launch_managed is launch_managed
+ assert state.lan_access_wildcard_bind is wildcard
+ assert state.lan_access_wildcard_ip_versions == ip_versions
+ assert state.lan_access_bind_host == bind_host
assert state.lan_access_ready is False
+def test_an_ephemeral_hostname_launch_keeps_its_loopback_policy(monkeypatch):
+ monkeypatch.setattr(
+ lan_settings.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("127.0.0.1", 0)),
+ ],
+ )
+ state = SimpleNamespace()
+
+ lan_settings.configure_lan_access(
+ state,
+ port = 0,
+ bind_host = "loopback.test",
+ secure = False,
+ is_colab = False,
+ frontend_served = True,
+ )
+
+ assert state.lan_access_launch_addresses == ("127.0.0.1",)
+ assert state.lan_access_launch_managed is False
+
+
def _transport_request(
*,
server = ("192.168.1.24", 8888),
@@ -188,6 +221,9 @@ def test_private_lan_ignores_forwarding_headers(monkeypatch):
("192.168.1.24", None, "192.168.1.24", False, False, True),
("0.0.0.0", None, "192.168.1.24", False, False, True),
("::", None, "fd00::24", False, False, True),
+ ("::0", None, "fd00::24", False, False, True),
+ ("0", None, "192.168.1.24", False, False, True),
+ ("::ffff:0.0.0.0", None, "192.168.1.24", False, False, True),
("studio.lan", "192.168.1.24", "192.168.1.24", False, False, True),
("studio.lan", "127.0.0.1", "127.0.0.1", False, False, False),
("studio.lan", "64.227.100.5", "64.227.100.5", False, False, False),
@@ -199,7 +235,7 @@ def test_private_lan_ignores_forwarding_headers(monkeypatch):
def test_private_lan_launch_managed_matrix(
monkeypatch, bind_host, resolved, server, secure, is_colab, expected
):
- def resolve(_host, port, **_kwargs):
+ def resolve(_host, port, *_args, **_kwargs):
if resolved == "error":
raise OSError("dns unavailable")
return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (resolved, port))]
@@ -281,6 +317,97 @@ def test_a_pending_admin_password_blocks_exposing_the_server(monkeypatch):
assert status["can_start"] is False
+ "bind_host,wildcard,expected_urls",
+ [
+ ("0.0.0.0", True, ["http://10.1.1.144:8888"]),
+ ("::", True, ["http://[fd00::144]:8888"]),
+ ("::0", True, ["http://[fd00::144]:8888"]),
+ ("0:0:0:0:0:0:0:0", True, ["http://[fd00::144]:8888"]),
+ ("0", True, ["http://10.1.1.144:8888"]),
+ ("::ffff:0.0.0.0", True, ["http://10.1.1.144:8888"]),
+ ("10.1.1.144", False, ["http://203.0.113.9:8888"]),
+ ],
+)
+def test_status_carries_the_bind_host_so_a_block_can_name_it(
+ monkeypatch, bind_host, wildcard, expected_urls
+):
+ """The launch-managed block covers a wildcard and a single-address bind
+ alike, so the address itself has to reach the settings UI."""
+ monkeypatch.setattr(
+ lan_access,
+ "detect_lan_addresses",
+ lambda ip_version = 4: ["fd00::144"] if ip_version == 6 else ["10.1.1.144"],
+ )
+ state = SimpleNamespace(server_url = "http://203.0.113.9:8888")
+ lan_settings.configure_lan_access(
+ state,
+ port = 8888,
+ bind_host = bind_host,
+ secure = False,
+ is_colab = False,
+ frontend_served = True,
+ )
+ state.lan_access_ready = True
+ status = lan_settings.lan_access_status(SimpleNamespace(state = state))
+ assert status["bind_host"] == bind_host
+ assert status["wildcard_bind"] is wildcard
+ assert status["urls"] == expected_urls
+ assert status["block_reason"] == "launch_managed"
+
+
+def test_a_dual_stack_wildcard_launch_reports_both_address_families(monkeypatch):
+ monkeypatch.setattr(
+ host_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("0.0.0.0", 8888)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::", 8888, 0, 0)),
+ ],
+ )
+ detected_versions = []
+
+ def _detect(ip_version = 4):
+ detected_versions.append(ip_version)
+ return ["10.1.1.144"] if ip_version == 4 else ["fd00::144"]
+
+ monkeypatch.setattr(lan_access, "detect_lan_addresses", _detect)
+ state = SimpleNamespace(server_url = "http://203.0.113.9:8888")
+ lan_settings.configure_lan_access(
+ state,
+ port = 8888,
+ bind_host = "dual-wildcard.test",
+ secure = False,
+ is_colab = False,
+ frontend_served = True,
+ )
+ state.lan_access_ready = True
+
+ status = lan_settings.lan_access_status(SimpleNamespace(state = state))
+ assert state.lan_access_wildcard_ip_versions == (4, 6)
+ assert status["urls"] == ["http://10.1.1.144:8888", "http://[fd00::144]:8888"]
+ assert detected_versions == [4, 6]
+
+
+def test_the_response_model_carries_the_bind_host_to_the_client():
+ """The status dict reaches the client through LanAccessResponse, which drops
+ any field it does not declare."""
+ state = SimpleNamespace(server_url = "http://10.1.1.144:8888")
+ lan_settings.configure_lan_access(
+ state,
+ port = 8888,
+ bind_host = "10.1.1.144",
+ secure = False,
+ is_colab = False,
+ frontend_served = True,
+ )
+ state.lan_access_ready = True
+ request = SimpleNamespace(app = SimpleNamespace(state = state))
+ served = routes._lan_access_response(request).model_dump()
+ assert served["bind_host"] == "10.1.1.144"
+ assert served["wildcard_bind"] is False
+
+
def test_a_specific_host_launch_reports_the_address_it_was_given():
status = lan_settings.lan_access_status(_app(lan_access_launch_managed = True))
assert status["state"] == "online" and status["managed_by"] == "launch"
@@ -289,10 +416,12 @@ def test_a_specific_host_launch_reports_the_address_it_was_given():
assert status["can_stop"] is False
-def test_a_wildcard_launch_shows_lan_addresses_not_the_public_sharing_address(monkeypatch):
+def test_a_wildcard_launch_refreshes_lan_addresses_instead_of_showing_the_public_address(
+ monkeypatch,
+):
"""server_url resolves the public IP for sharing, which behind NAT reaches
nothing on the LAN and would trip the public-address warning as well."""
- monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda: ["192.168.1.24"])
+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda _ip_version = 4: ["192.168.1.24"])
state = _app(
lan_access_launch_managed = True,
lan_access_wildcard_bind = True,
@@ -302,11 +431,15 @@ def test_a_wildcard_launch_shows_lan_addresses_not_the_public_sharing_address(mo
assert status["urls"] == ["http://192.168.1.24:8888"]
assert status["public_urls"] == []
- # detection is not repeated on every poll
- monkeypatch.setattr(
- lan_access, "detect_lan_addresses", lambda: pytest.fail("re-detected on a poll")
- )
- assert lan_settings.lan_access_status(state)["urls"] == ["http://192.168.1.24:8888"]
+ monkeypatch.setattr(lan_access, "detect_lan_addresses", lambda _ip_version = 4: ["10.0.0.7"])
+ assert lan_settings.lan_access_status(state)["urls"] == ["http://10.0.0.7:8888"]
+
+
+def test_listener_urls_bracket_ipv6_literals():
+ assert lan_settings._listener_urls(["192.168.1.24", "fd00::24"], 8888) == [
+ "http://192.168.1.24:8888",
+ "http://[fd00::24]:8888",
+ ]
def test_a_publicly_routable_bind_is_flagged_so_the_ui_can_warn(monkeypatch):
@@ -338,6 +471,8 @@ def test_a_publicly_routable_bind_is_flagged_so_the_ui_can_warn(monkeypatch):
("100.64.1.1", False),
("64.227.100.5", True),
("8.8.8.8", True),
+ ("fd00::24", False),
+ ("2001:4860:4860::8844", True),
("not-an-ip", False),
],
)
@@ -393,7 +528,7 @@ def test_detection_drops_addresses_no_other_device_can_open(monkeypatch):
monkeypatch.setattr(
lan_access,
"_interface_addresses",
- lambda: [
+ lambda _ip_version = 4: [
"127.0.0.1",
"169.254.10.1",
"224.0.0.1",
@@ -413,7 +548,7 @@ def test_detection_drops_addresses_no_other_device_can_open(monkeypatch):
@pytest.mark.allow_network
def test_the_default_route_address_leads_so_it_becomes_the_shown_url(monkeypatch):
routed = _require_lan_address()
- monkeypatch.setattr(lan_access, "_interface_addresses", lambda: ["203.0.113.9"])
+ monkeypatch.setattr(lan_access, "_interface_addresses", lambda _ip_version = 4: ["203.0.113.9"])
assert lan_access.detect_lan_addresses() == [routed, "203.0.113.9"]
@@ -462,6 +597,33 @@ def test_interface_enumeration_skips_adapters_that_are_down(monkeypatch):
)
monkeypatch.setitem(sys.modules, "psutil", fake)
assert lan_access._interface_addresses() == ["10.0.0.7"]
+ assert lan_access._interface_addresses(6) == ["fe80::1"]
+
+
+def test_ipv6_detection_keeps_only_reachable_unscoped_addresses(monkeypatch):
+ class _NoRouteSocket:
+ def connect(self, _address):
+ raise OSError("network is unreachable")
+
+ def close(self):
+ pass
+
+ monkeypatch.setattr(lan_access.socket, "socket", lambda *_args, **_kwargs: _NoRouteSocket())
+ monkeypatch.setattr(
+ lan_access,
+ "_interface_addresses",
+ lambda _ip_version = 4: [
+ "::1",
+ "fe80::1%en0",
+ "ff02::1",
+ "::",
+ "fd00::24",
+ "2001:4860:4860::8844",
+ "fd00::24",
+ ],
+ )
+
+ assert lan_access.detect_lan_addresses(6) == ["fd00::24", "2001:4860:4860::8844"]
def test_interface_enumeration_skips_windows_host_only_switches(monkeypatch):
@@ -498,20 +660,107 @@ def test_interface_enumeration_skips_windows_host_only_switches(monkeypatch):
def test_wsl_nat_address_is_not_advertised(monkeypatch):
monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: "nat")
- monkeypatch.setattr(lan_access, "_interface_addresses", lambda: ["172.25.35.232"])
+ monkeypatch.setattr(lan_access, "_interface_addresses", lambda _ip_version = 4: ["172.25.35.232"])
assert lan_access.detect_lan_addresses() == []
def test_wsl_unknown_networking_mode_fails_closed(monkeypatch):
monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: "unknown")
- monkeypatch.setattr(lan_access, "_interface_addresses", lambda: ["172.25.35.232"])
+ monkeypatch.setattr(lan_access, "_interface_addresses", lambda _ip_version = 4: ["172.25.35.232"])
assert lan_access.detect_lan_addresses() == []
def test_wsl_mirrored_networking_keeps_reachable_addresses(monkeypatch):
monkeypatch.setattr(lan_access, "_wsl_networking_mode", lambda: "mirrored")
- monkeypatch.setattr(lan_access, "_interface_addresses", lambda: ["192.168.1.20"])
+ monkeypatch.setattr(lan_access, "_interface_addresses", lambda _ip_version = 4: ["192.168.1.20"])
+ assert lan_access.detect_lan_addresses() == ["192.168.1.20"]
+
+
+def test_wsl_mode_is_cached_while_interface_addresses_still_refresh(monkeypatch):
+ class _NoRouteSocket:
+ def connect(self, _address):
+ raise OSError("network is unreachable")
+
+ def close(self):
+ pass
+
+ mode_calls = []
+ interface_addresses = iter([["192.168.1.20"], ["192.168.1.21"]])
+ monkeypatch.setattr(lan_access.sys, "platform", "linux")
+ monkeypatch.setattr(lan_access.platform, "release", lambda: "6.6.87.2-microsoft-standard-WSL2")
+ monkeypatch.setattr(lan_access, "_wsl_mode_cache", None)
+ monkeypatch.setattr(lan_access.socket, "socket", lambda *_args, **_kwargs: _NoRouteSocket())
+ monkeypatch.setattr(
+ lan_access,
+ "_interface_addresses",
+ lambda _ip_version = 4: next(interface_addresses),
+ )
+ monkeypatch.setattr(
+ lan_access.subprocess,
+ "run",
+ lambda *_args, **_kwargs: mode_calls.append(True) or SimpleNamespace(stdout = "mirrored\n"),
+ )
+
assert lan_access.detect_lan_addresses() == ["192.168.1.20"]
+ assert lan_access.detect_lan_addresses() == ["192.168.1.21"]
+ assert len(mode_calls) == 1
+
+
+def test_wsl_mode_cache_retries_a_timeout_after_expiry(monkeypatch):
+ now = [100.0]
+ mode_calls = []
+
+ def _run(*_args, **_kwargs):
+ mode_calls.append(True)
+ if len(mode_calls) == 1:
+ raise lan_access.subprocess.TimeoutExpired(["wslinfo"], 1)
+ return SimpleNamespace(stdout = "mirrored\n")
+
+ monkeypatch.setattr(lan_access.sys, "platform", "linux")
+ monkeypatch.setattr(lan_access.platform, "release", lambda: "microsoft-standard-WSL2")
+ monkeypatch.setattr(lan_access, "_wsl_mode_cache", None)
+ monkeypatch.setattr(lan_access.time, "monotonic", lambda: now[0])
+ monkeypatch.setattr(lan_access.subprocess, "run", _run)
+
+ assert lan_access._wsl_networking_mode() == "unknown"
+ now[0] += lan_access._WSL_MODE_CACHE_TTL - 1
+ assert lan_access._wsl_networking_mode() == "unknown"
+ assert len(mode_calls) == 1
+ now[0] += 2
+ assert lan_access._wsl_networking_mode() == "mirrored"
+ assert len(mode_calls) == 2
+
+
+def test_concurrent_wsl_mode_checks_share_one_probe(monkeypatch):
+ probe_started = threading.Event()
+ release_probe = threading.Event()
+ mode_calls = []
+ results = []
+
+ def _run(*_args, **_kwargs):
+ mode_calls.append(True)
+ probe_started.set()
+ assert release_probe.wait(2)
+ return SimpleNamespace(stdout = "mirrored\n")
+
+ monkeypatch.setattr(lan_access.sys, "platform", "linux")
+ monkeypatch.setattr(lan_access.platform, "release", lambda: "microsoft-standard-WSL2")
+ monkeypatch.setattr(lan_access, "_wsl_mode_cache", None)
+ monkeypatch.setattr(lan_access.subprocess, "run", _run)
+ threads = [
+ threading.Thread(target = lambda: results.append(lan_access._wsl_networking_mode()))
+ for _ in range(2)
+ ]
+
+ threads[0].start()
+ assert probe_started.wait(2)
+ threads[1].start()
+ release_probe.set()
+ for thread in threads:
+ thread.join(2)
+
+ assert results == ["mirrored", "mirrored"]
+ assert len(mode_calls) == 1
# ── live listener ──
diff --git a/studio/backend/tests/test_password_prompt_backstop.py b/studio/backend/tests/test_password_prompt_backstop.py
index 918da101ef1..ef4179e5743 100644
--- a/studio/backend/tests/test_password_prompt_backstop.py
+++ b/studio/backend/tests/test_password_prompt_backstop.py
@@ -219,8 +219,8 @@ def test_gate_runs_before_server_bind_in_source():
src = (_BACKEND / "run.py").read_text(encoding = "utf-8")
gate_call = src.index("_pw_proceed, _pw_drop_bootstrap = _terminal_password_gate(")
thread_start = src.index("thread.start()")
- tunnel_start = src.index('start_studio_tunnel(port, managed_by = "launch")')
callback_bind = src.index("set_studio_tunnel_url_callback(")
+ tunnel_start = src.index("start_studio_tunnel(", callback_bind)
assert gate_call < thread_start < callback_bind < tunnel_start
assert "_cloudflare_url = start_studio_tunnel" not in src
# The fail-closed branch exits before any server exists.
diff --git a/studio/backend/tests/test_public_check_optout.py b/studio/backend/tests/test_public_check_optout.py
index 8c13cb16c93..f95ffef1241 100644
--- a/studio/backend/tests/test_public_check_optout.py
+++ b/studio/backend/tests/test_public_check_optout.py
@@ -88,11 +88,50 @@ def test_public_ip_lookup_skipped_when_disabled(monkeypatch, calls):
assert IFCONFIG not in calls
+def test_display_host_resolves_every_wildcard_alias(monkeypatch):
+ monkeypatch.setattr(run, "_resolve_external_ip", lambda: "192.168.1.50")
+ monkeypatch.setattr("lan_access.detect_lan_addresses", lambda _ip_version = 4: ["fd00::50"])
+ for host in ("0.0.0.0", "0", "::ffff:0.0.0.0"):
+ assert run._display_host_for_bind(host) == "192.168.1.50"
+ for host in ("::", "::0", "0:0:0:0:0:0:0:0"):
+ assert run._display_host_for_bind(host) == "fd00::50"
+
+ monkeypatch.setattr("lan_access.detect_lan_addresses", lambda _ip_version = 4: [])
+ assert run._display_host_for_bind("::") == "::"
+
+
+def test_display_host_falls_back_to_ipv6_for_dual_stack_wildcard(monkeypatch):
+ original_getaddrinfo = socket.getaddrinfo
+
+ def dual_stack_wildcard(host, *args, **kwargs):
+ if host == "dual-wildcard.test":
+ return [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("0.0.0.0", 0)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::", 0, 0, 0)),
+ ]
+ return original_getaddrinfo(host, *args, **kwargs)
+
+ monkeypatch.setattr(socket, "getaddrinfo", dual_stack_wildcard)
+ monkeypatch.setattr(run, "_resolve_external_ip", lambda: "0.0.0.0")
+ monkeypatch.setattr("lan_access.detect_lan_addresses", lambda _ip_version = 4: ["fd00::50"])
+
+ assert run._display_host_for_bind("dual-wildcard.test") == "fd00::50"
+
+
def test_reachability_probe_runs_by_default(calls):
_verify_global_reachability("95.216.11.2", 8888)
assert any(CHECK_HOST in url for url in calls)
+def test_ipv6_reachability_probe_brackets_the_host(calls):
+ import urllib.parse
+
+ _verify_global_reachability("2001:4860:4860::8844", 8888)
+ request_url = next(url for url in calls if CHECK_HOST in url)
+ query = urllib.parse.parse_qs(urllib.parse.urlparse(request_url).query)
+ assert query["host"] == ["[2001:4860:4860::8844]:8888"]
+
+
def test_reachability_probe_skipped_when_disabled(monkeypatch, calls, capsys):
monkeypatch.setenv(DISABLE_PUBLIC_CHECK_ENV, "1")
diff --git a/studio/backend/tests/test_remote_access_settings.py b/studio/backend/tests/test_remote_access_settings.py
index fd0e85e0fed..7b6a8bfbabb 100644
--- a/studio/backend/tests/test_remote_access_settings.py
+++ b/studio/backend/tests/test_remote_access_settings.py
@@ -27,12 +27,14 @@ def _state(
intent = "unset",
is_colab = False,
launch_managed = False,
+ request_host = "127.0.0.1",
):
return SimpleNamespace(
remote_access_intent = intent,
remote_access_is_colab = is_colab,
remote_access_launch_managed = launch_managed,
remote_access_port = 8888,
+ server_request_host = request_host,
remote_access_ready = True,
)
@@ -211,7 +213,8 @@ def test_settings_start_logs_public_url_when_tunnel_is_ready(monkeypatch, trigge
"block_reason": None,
}
- def _start(*_args, **_kwargs):
+ def _start(*_args, **kwargs):
+ assert kwargs["origin_host"] == "::1"
ready.set()
return "https://example.trycloudflare.com"
@@ -227,14 +230,26 @@ def test_settings_start_logs_public_url_when_tunnel_is_ready(monkeypatch, trigge
)
if trigger == "auto":
- assert remote_access.maybe_auto_start_remote_access(_state())
+ assert remote_access.maybe_auto_start_remote_access(_state(request_host = "::1"))
else:
- remote_access.start_remote_access(_state())
+ remote_access.start_remote_access(_state(request_host = "::1"))
assert ready.wait(1)
remote_access._start_worker.join(1)
assert messages == ["Secure link access via Cloudflare: https://example.trycloudflare.com"]
+def test_settings_start_fails_closed_without_a_bound_address(monkeypatch):
+ monkeypatch.setattr(remote_access, "_start_worker", None)
+ monkeypatch.setattr(remote_access, "_start_worker_admission", None)
+ status = {"state": "off", "managed_by": None, "can_start": True, "block_reason": None}
+ monkeypatch.setattr(remote_access, "remote_access_status", lambda _: status)
+ monkeypatch.setattr(cloudflare_tunnel, "capture_studio_tunnel_start_admission", lambda: (1, 1))
+ monkeypatch.setattr(cloudflare_tunnel, "get_studio_tunnel_control_token", lambda: (1, 1))
+
+ with pytest.raises(RuntimeError, match = "server_address_unavailable"):
+ remote_access.start_remote_access(_state(request_host = None))
+
+
@pytest.mark.parametrize("operation", ["start", "stop"])
def test_request_cannot_adopt_reopened_lifecycle(monkeypatch, operation):
status = (
diff --git a/studio/backend/tests/test_secure_tunnel_gate.py b/studio/backend/tests/test_secure_tunnel_gate.py
index 451913e531e..0b6ef8ee0da 100644
--- a/studio/backend/tests/test_secure_tunnel_gate.py
+++ b/studio/backend/tests/test_secure_tunnel_gate.py
@@ -24,6 +24,10 @@ from run import _cloudflare_tunnel_should_start as should_start # noqa: E402
# Non-secure wildcard binds tunnel only when --cloudflare is passed (True).
(True, "0.0.0.0", False, False, False, True),
(True, "::", False, False, False, True),
+ (True, "::0", False, False, False, True),
+ (True, "0:0:0:0:0:0:0:0", False, False, False, True),
+ (True, "0", False, False, False, True),
+ (True, "::ffff:0.0.0.0", False, False, False, True),
(True, "127.0.0.1", False, False, False, False),
(True, "localhost", False, False, False, False),
# --secure tunnels a loopback bind too.
@@ -108,11 +112,40 @@ def test_final_bound_port_uses_uvicorn_listener_for_ephemeral_bind():
assert all(
resolved < source.index(consumer, resolved)
for consumer in (
+ "app.state.server_request_host",
"app.state.remote_access_port",
"TAURI_PORT={port}",
- "start_studio_tunnel(port",
+ "start_studio_tunnel(",
)
)
+ assert "origin_host = app.state.server_request_host" in source[resolved:]
+
+
+ "address,expected",
+ [
+ (("0.0.0.0", 43123), "127.0.0.1"),
+ (("::", 43123, 0, 0), "::1"),
+ (("192.0.2.24", 43123), "192.0.2.24"),
+ (("fe80::1234", 43123, 0, 7), "fe80::1234%7"),
+ ],
+)
+def test_bound_request_host_uses_the_active_listener_address(address, expected):
+ from types import SimpleNamespace
+
+ import run
+
+ sock = SimpleNamespace(getsockname = lambda: address)
+ server = SimpleNamespace(servers = [SimpleNamespace(sockets = [sock])])
+ assert run._bound_request_host(server) == expected
+
+
+def test_bound_request_host_fails_closed_without_a_listener():
+ from types import SimpleNamespace
+
+ import run
+ with pytest.raises(RuntimeError, match = "did not expose its bound address"):
+ run._bound_request_host(SimpleNamespace(servers = []))
def test_arg_parser_secure_polarity_and_not_secure_alias():
diff --git a/studio/backend/tests/test_startup_banner_loopback.py b/studio/backend/tests/test_startup_banner_loopback.py
index c8875bf5dba..9a541562d7f 100644
--- a/studio/backend/tests/test_startup_banner_loopback.py
+++ b/studio/backend/tests/test_startup_banner_loopback.py
@@ -27,6 +27,22 @@ def test_alias_loopback_shows_canned_url(capsys, host):
assert "http://127.0.0.1:8891" in capsys.readouterr().out
+ "host,loopback_url",
+ [
+ ("::0", "http://[::1]:8891"),
+ ("0:0:0:0:0:0:0:0", "http://[::1]:8891"),
+ ("0", "http://127.0.0.1:8891"),
+ ("::ffff:0.0.0.0", "http://127.0.0.1:8891"),
+ ],
+)
+def test_wildcard_aliases_show_reachable_urls(capsys, host, loopback_url):
+ print_studio_access_banner(port = 8891, bind_host = host, display_host = "192.168.1.24")
+ out = capsys.readouterr().out
+ assert loopback_url in out
+ assert "http://192.168.1.24:8891" in out
+
+
def test_banner_prints_on_strict_cp1252_stdout(monkeypatch):
buf = io.BytesIO()
stdout = io.TextIOWrapper(buf, encoding = "cp1252", errors = "strict")
diff --git a/studio/backend/tests/test_studio_pid_files.py b/studio/backend/tests/test_studio_pid_files.py
index 827d270fd08..0e9593f7253 100644
--- a/studio/backend/tests/test_studio_pid_files.py
+++ b/studio/backend/tests/test_studio_pid_files.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import contextlib
import errno
import os
+import socket
import threading
import time
import sys
@@ -414,6 +415,15 @@ def test_address_matching(tmp_path):
assert run._addresses_collide(None, "127.0.0.1", 8889) is True
+ "wildcard",
+ ["0", "00", "0.0", "0.0.0", "::0", "0:0:0:0:0:0:0:0", "::ffff:0.0.0.0"],
+)
+def test_every_wildcard_alias_collides_with_a_specific_bind(wildcard):
+ assert run._addresses_collide("127.0.0.1", wildcard, 8889) is True
+ assert run._addresses_collide(wildcard, "127.0.0.1", 8889) is True
+
+
def test_a_hostname_resolves_the_same_way_the_bind_does(tmp_path):
# `localhost` and the address _is_port_free actually binds must agree, or a
# recorded server is missed and a duplicate starts.
@@ -432,6 +442,49 @@ def test_a_hostname_records_every_address_it_resolves_to(tmp_path):
assert run._addresses_collide(recorded, literal, 8889) is True
+def test_port_probe_checks_every_resolved_bind_address(monkeypatch):
+ bind_attempts = []
+ sockets = []
+
+ class _ProbeSocket:
+ def __init__(self, family):
+ self.family = family
+ self.closed = False
+ sockets.append(self)
+
+ def setsockopt(self, *_args):
+ pass
+
+ def bind(self, sockaddr):
+ bind_attempts.append((self.family, sockaddr))
+ if self.family == socket.AF_INET6:
+ raise OSError("address already in use")
+
+ def close(self):
+ self.closed = True
+
+ monkeypatch.setattr(
+ socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("0.0.0.0", 8888)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::", 8888, 0, 0)),
+ ],
+ )
+ monkeypatch.setattr(
+ socket,
+ "socket",
+ lambda family, _socktype, _proto: _ProbeSocket(family),
+ )
+
+ assert run._is_port_free("dual-wildcard.test", 8888) is False
+ assert bind_attempts == [
+ (socket.AF_INET, ("0.0.0.0", 8888)),
+ (socket.AF_INET6, ("::", 8888, 0, 0)),
+ ]
+ assert all(probe.closed for probe in sockets)
+
+
def test_a_multi_address_record_matches_either_literal(tmp_path):
recorded = "127.0.0.1,::1"
diff --git a/studio/backend/utils/host_policy.py b/studio/backend/utils/host_policy.py
index 138d7fc51fc..fe4752ed4cd 100644
--- a/studio/backend/utils/host_policy.py
+++ b/studio/backend/utils/host_policy.py
@@ -14,7 +14,9 @@ have `unsloth_cli` on sys.path. Keep the two in sync.
from __future__ import annotations
+import ipaddress
import os
+import socket
# Loopback aliases; any other bind address is treated as network-reachable. Only
# the exact aliases the rest of the stack assumes for loopback (health checks,
@@ -36,6 +38,147 @@ def is_external_host(host: str) -> bool:
return host.lower() not in _LOOPBACK_HOSTS
+def _normalized_ip(address: str):
+ try:
+ parsed = ipaddress.ip_address(address)
+ except ValueError:
+ return None
+ if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
+ parsed = parsed.ipv4_mapped
+ return parsed
+
+
+def _literal_ip_address(host: str):
+ if not isinstance(host, str) or not host:
+ return None
+ literal = _normalized_ip(host)
+ if literal is not None:
+ return literal
+ try:
+ return ipaddress.IPv4Address(socket.inet_aton(host))
+ except OSError:
+ return None
+
+
+def _resolved_host_ip_addresses(host: str):
+ if not isinstance(host, str) or not host:
+ return ()
+ try:
+ addresses = socket.getaddrinfo(host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)
+ except OSError:
+ return ()
+ resolved = []
+ for _family, _kind, _protocol, _name, sockaddr in addresses:
+ try:
+ parsed = ipaddress.ip_address(sockaddr[0])
+ except (IndexError, ValueError):
+ continue
+ if parsed not in resolved:
+ resolved.append(parsed)
+ return tuple(resolved)
+
+
+def _resolved_ip_addresses(host: str):
+ literal = _literal_ip_address(host)
+ if literal is not None:
+ return (literal,)
+ resolved = []
+ for parsed in _resolved_host_ip_addresses(host):
+ if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
+ parsed = parsed.ipv4_mapped
+ if parsed not in resolved:
+ resolved.append(parsed)
+ return tuple(resolved)
+
+
+def wildcard_ip_versions(host: str) -> tuple[int, ...]:
+ """IP versions for every unspecified address this host resolves to."""
+ versions = {
+ address.version for address in _resolved_ip_addresses(host) if address.is_unspecified
+ }
+ return tuple(version for version in (4, 6) if version in versions)
+
+
+def resolved_bind_address_count(host: str) -> int:
+ """Number of distinct socket addresses this host resolves to."""
+ if _literal_ip_address(host) is not None:
+ return 1
+ if not isinstance(host, str) or not host:
+ return 0
+ try:
+ addresses = socket.getaddrinfo(host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)
+ except OSError:
+ return 0
+ endpoints = {
+ (family, tuple(sockaddr))
+ for family, _kind, _protocol, _name, sockaddr in addresses
+ if sockaddr
+ }
+ return len(endpoints)
+
+
+def is_wildcard_host(host: str) -> bool:
+ """True when the host resolves to an unspecified bind address."""
+ return bool(wildcard_ip_versions(host))
+
+
+def normalize_wildcard_bind_host(host: str) -> str:
+ """Return a safe canonical bind for an effective wildcard host."""
+ if isinstance(host, str):
+ try:
+ parsed_literal = ipaddress.ip_address(host)
+ except ValueError:
+ pass
+ else:
+ if (
+ isinstance(parsed_literal, ipaddress.IPv6Address)
+ and parsed_literal.ipv4_mapped is not None
+ ):
+ return str(parsed_literal.ipv4_mapped)
+ literal = _literal_ip_address(host)
+ if literal is not None:
+ if not literal.is_unspecified:
+ return host
+ return "::" if literal.version == 6 else "0.0.0.0"
+
+ raw_addresses = _resolved_host_ip_addresses(host)
+ addresses = []
+ has_mapped_address = False
+ for address in raw_addresses:
+ if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
+ address = address.ipv4_mapped
+ has_mapped_address = True
+ if address not in addresses:
+ addresses.append(address)
+ if has_mapped_address:
+ if len(addresses) == 1:
+ return str(addresses[0])
+ raise ValueError(
+ f"--host {host!r} resolves to ambiguous IPv4-mapped addresses; "
+ "use an explicit bind address."
+ )
+ wildcard_versions = {address.version for address in addresses if address.is_unspecified}
+ if not wildcard_versions:
+ return host
+ specific_versions = {address.version for address in addresses if not address.is_unspecified}
+ if len(wildcard_versions) == 2 and not specific_versions:
+ return host
+ if specific_versions - wildcard_versions or (len(wildcard_versions) == 2 and specific_versions):
+ raise ValueError(
+ f"--host {host!r} mixes wildcard and specific address families; "
+ "use an explicit bind address."
+ )
+ return "::" if 6 in wildcard_versions else "0.0.0.0"
+
+
+def wildcard_loopback_host(host: str) -> "str | None":
+ """The loopback address reachable through a wildcard bind."""
+ versions = wildcard_ip_versions(host)
+ if 4 in versions:
+ return "127.0.0.1"
+ return "::1" if 6 in versions else None
+
+
# Tauri desktop webview origins. api-only serving (the desktop app calling a
# local backend) locks CORS to these.
_TAURI_CORS_ORIGINS = (
diff --git a/studio/backend/utils/lan_access_settings.py b/studio/backend/utils/lan_access_settings.py
index bb9772d02bb..d0b78afbf1d 100644
--- a/studio/backend/utils/lan_access_settings.py
+++ b/studio/backend/utils/lan_access_settings.py
@@ -52,7 +52,7 @@ def _resolve_host_addresses(host: str, port: int) -> tuple:
literal = _normalized_ip(host)
if literal is not None:
return (literal,)
- if not isinstance(host, str) or not isinstance(port, int) or port <= 0:
+ if not isinstance(host, str) or not isinstance(port, int) or port < 0:
return ()
try:
infos = socket.getaddrinfo(host, port, type = socket.SOCK_STREAM)
@@ -205,8 +205,11 @@ def configure_lan_access(
app_state, *, port: int, bind_host: str, secure: bool, is_colab: bool, frontend_served: bool
) -> None:
"""Publish immutable launch policy used by every settings request."""
+ from utils.host_policy import wildcard_ip_versions
+
app_state.lan_access_port = port
- app_state.lan_access_wildcard_bind = bind_host in ("0.0.0.0", "::")
+ app_state.lan_access_wildcard_ip_versions = wildcard_ip_versions(bind_host)
+ app_state.lan_access_wildcard_bind = bool(app_state.lan_access_wildcard_ip_versions)
app_state.lan_access_bind_host = bind_host
app_state.lan_access_launch_addresses = tuple(
str(address) for address in _resolve_host_addresses(bind_host, port)
@@ -234,14 +237,17 @@ def _launch_urls(app_state) -> list[str]:
sharing, and behind NAT that address reaches nothing on the LAN.
"""
if getattr(app_state, "lan_access_wildcard_bind", False):
- cached = getattr(app_state, "lan_access_wildcard_urls", None)
- if cached is None:
- from lan_access import detect_lan_addresses
- cached = _listener_urls(
- detect_lan_addresses(), getattr(app_state, "lan_access_port", None)
- )
- app_state.lan_access_wildcard_urls = cached
- return list(cached)
+ from lan_access import detect_lan_addresses
+
+ addresses = []
+ for ip_version in getattr(app_state, "lan_access_wildcard_ip_versions", ()) or (4,):
+ for address in detect_lan_addresses(ip_version):
+ if address not in addresses:
+ addresses.append(address)
+ return _listener_urls(
+ addresses,
+ getattr(app_state, "lan_access_port", None),
+ )
url = getattr(app_state, "server_url", None)
return [url] if url else []
@@ -249,7 +255,11 @@ def _launch_urls(app_state) -> list[str]:
def _listener_urls(addresses, port: Optional[int]) -> list[str]:
if not port:
return []
- return [f"http://{address}:{port}" for address in addresses]
+ urls = []
+ for address in addresses:
+ url_host = f"[{address}]" if ":" in address else address
+ urls.append(f"http://{url_host}:{port}")
+ return urls
def _public_urls(urls: list[str], resolved_addresses: tuple[str, ...] = ()) -> list[str]:
@@ -366,6 +376,8 @@ def lan_access_status(app) -> dict:
"can_start": controllable and not running,
"can_stop": controllable and running,
"block_reason": block_reason,
+ "bind_host": getattr(app_state, "lan_access_bind_host", None),
+ "wildcard_bind": bool(getattr(app_state, "lan_access_wildcard_bind", False)),
"serves_web_ui": frontend_served,
"keyless_lan_eligible": _has_keyless_lan_url(urls),
"keyless_scope": keyless_scope,
diff --git a/studio/backend/utils/remote_access_settings.py b/studio/backend/utils/remote_access_settings.py
index 81d787c6f3e..786ba8e5f6d 100644
--- a/studio/backend/utils/remote_access_settings.py
+++ b/studio/backend/utils/remote_access_settings.py
@@ -269,12 +269,20 @@ def start_remote_access(app_state) -> dict:
port = getattr(app_state, "remote_access_port", None)
if not isinstance(port, int) or port <= 0:
raise RuntimeError("server_port_unavailable")
+ origin_host = getattr(app_state, "server_request_host", None)
+ if not isinstance(origin_host, str) or not origin_host:
+ raise RuntimeError("server_address_unavailable")
if get_studio_tunnel_control_token() != admission:
raise RuntimeError("server_lifecycle_changed")
def _start() -> None:
from cloudflare_tunnel import start_studio_tunnel
- url = start_studio_tunnel(port, managed_by = "settings", admission = admission)
+ url = start_studio_tunnel(
+ port,
+ managed_by = "settings",
+ admission = admission,
+ origin_host = origin_host,
+ )
if url:
logger.info("Secure link access via Cloudflare: %s", url)
diff --git a/studio/frontend/src/features/settings/api/lan-access-state.ts b/studio/frontend/src/features/settings/api/lan-access-state.ts
index 3b5bf57f4d3..a332913d1ee 100644
--- a/studio/frontend/src/features/settings/api/lan-access-state.ts
+++ b/studio/frontend/src/features/settings/api/lan-access-state.ts
@@ -15,6 +15,8 @@ export type LanAccessStatus = {
canStart: boolean;
canStop: boolean;
blockReason: string | null;
+ bindHost: string | null;
+ wildcardBind: boolean;
servesWebUi: boolean;
keylessLanEligible: boolean;
keylessScope: LanKeylessScope;
@@ -38,6 +40,10 @@ export type ApiLanAccessStatus = {
// biome-ignore lint/style/useNamingConvention: API schema
block_reason?: string | null;
// biome-ignore lint/style/useNamingConvention: API schema
+ bind_host?: string | null;
+ // biome-ignore lint/style/useNamingConvention: API schema
+ wildcard_bind?: boolean;
+ // biome-ignore lint/style/useNamingConvention: API schema
serves_web_ui?: boolean;
// biome-ignore lint/style/useNamingConvention: API schema
keyless_lan_eligible?: boolean | null;
@@ -65,6 +71,8 @@ export function normalizeLanAccessStatus(
canStart: status.can_start,
canStop: status.can_stop,
blockReason: status.block_reason ?? null,
+ bindHost: status.bind_host ?? null,
+ wildcardBind: status.wildcard_bind === true,
// absent on a backend that predates the field, where the web UI is served
servesWebUi: status.serves_web_ui !== false,
keylessLanEligible: status.keyless_lan_eligible === true,
@@ -125,11 +133,23 @@ export function lanAccessStopDisconnectsOrigin(
});
}
+// the backend owns wildcard classification so the message follows its flag
+function launchManagedMessage(status: LanAccessStatus): string {
+ if (status.wildcardBind) {
+ const option = status.bindHost ? ` (--host ${status.bindHost})` : "";
+ return `This launch binds every network interface${option}, so Unsloth is on the network already.`;
+ }
+ if (!status.bindHost) {
+ return "This launch already puts Unsloth on the network.";
+ }
+ return `This launch binds ${status.bindHost} (--host ${status.bindHost}), so Unsloth is on the network already.`;
+}
+
export function lanAccessBlockMessage(
- reason: string | null,
+ status: LanAccessStatus | null,
isDesktop: boolean,
): string | null {
- switch (reason) {
+ switch (status?.blockReason) {
case "server_starting":
return "Unsloth is still starting.";
case "admin_password_change_required":
@@ -137,7 +157,7 @@ export function lanAccessBlockMessage(
? "Set a remote password before putting this server on the network."
: "Change the administrator password before putting this server on the network. In the desktop app, run unsloth studio reset-password.";
case "launch_managed":
- return "This launch already binds every network interface (-H 0.0.0.0), so Unsloth is on the network already.";
+ return launchManagedMessage(status);
case "secure_launch":
return "This launch used --secure, which serves only through the Cloudflare link and keeps the raw port closed. Relaunch without --secure to use LAN access.";
case "colab":
diff --git a/studio/frontend/src/features/settings/components/lan-access-section.tsx b/studio/frontend/src/features/settings/components/lan-access-section.tsx
index 6937617fb2a..d3ec946a5e2 100644
--- a/studio/frontend/src/features/settings/components/lan-access-section.tsx
+++ b/studio/frontend/src/features/settings/components/lan-access-section.tsx
@@ -75,8 +75,9 @@ function AccessStatus({ status }: { status: LanAccessStatus | null }) {
);
}
-function CopyLanUrlButton({ url }: { url: string }) {
+function CopyLanUrlButton({ url, label }: { url: string; label: string }) {
const [copied, setCopied] = useState(false);
+ const text = copied ? "Copied" : label;
const copyTimer = useRef<number | null>(null);
useEffect(() => {
return () => {
@@ -91,7 +92,7 @@ function CopyLanUrlButton({ url }: { url: string }) {
size="sm"
variant="outline"
className="gap-1.5"
- aria-label={`Copy ${url}`}
+ aria-label={`${text} ${url}`}
onClick={async () => {
if (!(await copyToClipboard(url))) {
return;
@@ -107,7 +108,7 @@ function CopyLanUrlButton({ url }: { url: string }) {
icon={copied ? Tick02Icon : Copy01Icon}
className="size-3.5"
/>
- {copied ? "Copied" : "Copy"}
+ {text}
</Button>
);
}
@@ -116,7 +117,13 @@ function LanUrlQrButton({ url }: { url: string }) {
return (
<Dialog>
<DialogTrigger asChild={true}>
- <Button type="button" size="sm" variant="outline" className="gap-1.5">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="gap-1.5"
+ aria-label={`Show QR code for ${url}`}
+ >
<HugeiconsIcon icon={QrCodeIcon} className="size-3.5" />
QR
</Button>
@@ -161,25 +168,36 @@ function StatusMessage({
);
}
+function LanUrlActions({ url, copyLabel }: { url: string; copyLabel: string }) {
+ return (
+ <div className="flex shrink-0 items-center gap-2">
+ <LanUrlQrButton url={url} />
+ <CopyLanUrlButton url={url} label={copyLabel} />
+ </div>
+ );
+}
+
function LanUrlPanel({ status }: { status: LanAccessStatus | null }) {
if (!status || status.urls.length === 0) {
return null;
}
- const [primary] = status.urls;
+ const single = status.urls.length === 1;
return (
<div className="flex flex-col gap-1.5 border-t border-border/60 p-4">
<div className="flex items-center justify-between gap-3">
<span className="text-sm font-medium text-foreground">
- {status.urls.length > 1 ? "Network addresses" : "Network address"}
+ {single ? "Network address" : "Network addresses"}
</span>
- <LanUrlQrButton url={primary} />
+ {single ? (
+ <LanUrlActions url={status.urls[0]} copyLabel="Copy URL" />
+ ) : null}
</div>
{status.urls.map((url) => (
<div key={url} className="flex items-center gap-2">
<code className="block w-full min-w-0 break-all rounded-md border border-border bg-muted/40 px-3 py-2 font-mono text-xs text-foreground">
{url}
</code>
- <CopyLanUrlButton url={url} />
+ {single ? null : <LanUrlActions url={url} copyLabel="Copy" />}
</div>
))}
{status.publicUrls.length > 0 ? (
@@ -298,10 +316,7 @@ export function LanAccessSection() {
const setAutoStart = (enabled: boolean) =>
perform("auto", () => updateLanAccessAutoStart(enabled));
- const blockMessage = lanAccessBlockMessage(
- status?.blockReason ?? null,
- isTauri,
- );
+ const blockMessage = lanAccessBlockMessage(status, isTauri);
const errorMessage = lanAccessErrorMessage(status?.error ?? null);
const stopAction = status?.state === "online";
const actionDisabled =
diff --git a/studio/frontend/tests/lan-access-state.test.ts b/studio/frontend/tests/lan-access-state.test.ts
index edc406f6794..60bffe6416d 100644
--- a/studio/frontend/tests/lan-access-state.test.ts
+++ b/studio/frontend/tests/lan-access-state.test.ts
@@ -7,6 +7,7 @@ import test from "node:test";
// lan-access-section.tsx pulls in hugeicons, so only its pure helpers are tested here
import {
type ApiLanAccessStatus,
+ type LanAccessStatus,
keylessLanAccessDescription,
lanAccessAutoStartReadOnly,
lanAccessBlockMessage,
@@ -51,6 +52,10 @@ test("normalize maps every snake_case field onto its camelCase name", () => {
// biome-ignore lint/style/useNamingConvention: API schema
block_reason: null,
// biome-ignore lint/style/useNamingConvention: API schema
+ bind_host: "0.0.0.0",
+ // biome-ignore lint/style/useNamingConvention: API schema
+ wildcard_bind: true,
+ // biome-ignore lint/style/useNamingConvention: API schema
serves_web_ui: true,
// biome-ignore lint/style/useNamingConvention: API schema
keyless_lan_eligible: true,
@@ -66,6 +71,8 @@ test("normalize maps every snake_case field onto its camelCase name", () => {
canStart: false,
canStop: true,
blockReason: null,
+ bindHost: "0.0.0.0",
+ wildcardBind: true,
servesWebUi: true,
keylessLanEligible: true,
keylessScope: "off",
@@ -80,6 +87,8 @@ test("normalize defaults the optional fields an older backend may omit", () => {
assert.equal(s.error, null);
assert.equal(s.managedBy, null);
assert.equal(s.blockReason, null);
+ assert.equal(s.bindHost, null);
+ assert.equal(s.wildcardBind, false);
assert.equal(s.servesWebUi, true);
assert.equal(s.keylessLanEligible, false);
assert.equal(s.keylessScope, "off");
@@ -242,8 +251,24 @@ test("stop-disconnects does not treat a different port as the same origin", () =
);
});
+test("stop-disconnects accepts a bracketed IPv6 LAN origin", () => {
+ const url = "http://[fd00::24]:8888";
+ assert.equal(lanAccessStopDisconnectsOrigin([url], url), true);
+});
+
// ── lanAccessBlockMessage ──
+function blocked(
+ reason: string,
+ over: Partial<LanAccessStatus> = {},
+): LanAccessStatus {
+ return {
+ ...normalizeLanAccessStatus(apiStatus()),
+ blockReason: reason,
+ ...over,
+ };
+}
+
test("every block reason the backend can emit has a message", () => {
// mirrors the block_reason chain in utils/lan_access_settings.py
const reasons = [
@@ -255,7 +280,10 @@ test("every block reason the backend can emit has a message", () => {
];
for (const reason of reasons) {
for (const isDesktop of [true, false]) {
- const msg = lanAccessBlockMessage(reason, isDesktop);
+ const msg = lanAccessBlockMessage(
+ blocked(reason, { bindHost: "0.0.0.0", wildcardBind: true }),
+ isDesktop,
+ );
assert.ok(
msg && msg.length > 0,
`no message for ${reason} (desktop=${isDesktop})`,
@@ -264,9 +292,55 @@ test("every block reason the backend can emit has a message", () => {
}
});
+test("a launch bound to one host names that host, not the wildcard", () => {
+ // any host but the three loopback aliases is launch-managed, hostnames included
+ for (const host of ["10.1.1.144", "fd00::5", "studio.local"]) {
+ const msg = lanAccessBlockMessage(
+ blocked("launch_managed", { bindHost: host }),
+ false,
+ );
+ assert.ok(msg?.includes(`binds ${host}`), host);
+ assert.ok(msg?.includes(`--host ${host}`), host);
+ assert.ok(!msg?.includes("every network interface"), host);
+ }
+});
+
+test("the backend decides what counts as a wildcard, whatever it is spelled", () => {
+ for (const host of ["0.0.0.0", "::", "::0"]) {
+ const msg = lanAccessBlockMessage(
+ blocked("launch_managed", { bindHost: host, wildcardBind: true }),
+ false,
+ );
+ assert.ok(msg?.includes("every network interface"), host);
+ assert.ok(msg?.includes(`--host ${host}`), host);
+ assert.ok(!msg?.includes(`binds ${host} `), host);
+ }
+});
+
+test("an empty wildcard bind is distinct from a missing bind field", () => {
+ const msg = lanAccessBlockMessage(
+ blocked("launch_managed", { bindHost: "", wildcardBind: true }),
+ false,
+ );
+ assert.equal(
+ msg,
+ "This launch binds every network interface, so Unsloth is on the network already.",
+ );
+ assert.ok(!msg.includes("--host"));
+});
+
+test("a backend that omits the bind host still explains the block", () => {
+ // fixed text with nothing to interpolate, so the sentence itself is the contract
+ assert.equal(
+ lanAccessBlockMessage(blocked("launch_managed"), false),
+ "This launch already puts Unsloth on the network.",
+ );
+});
+
test("the pending-password message is desktop-aware", () => {
- const desktop = lanAccessBlockMessage("admin_password_change_required", true);
- const web = lanAccessBlockMessage("admin_password_change_required", false);
+ const reason = blocked("admin_password_change_required");
+ const desktop = lanAccessBlockMessage(reason, true);
+ const web = lanAccessBlockMessage(reason, false);
assert.notEqual(desktop, web);
assert.ok(!desktop?.includes("reset-password"));
assert.ok(web?.includes("reset-password"));
@@ -274,8 +348,8 @@ test("the pending-password message is desktop-aware", () => {
test("an unknown or absent reason yields no message", () => {
assert.equal(lanAccessBlockMessage(null, false), null);
- assert.equal(lanAccessBlockMessage("something_new", false), null);
- assert.equal(lanAccessBlockMessage("", true), null);
+ assert.equal(lanAccessBlockMessage(blocked("something_new"), false), null);
+ assert.equal(lanAccessBlockMessage(blocked(""), true), null);
});
// ── lanAccessErrorMessage ──
diff --git a/tests/studio/playwright_settings_tabs.py b/tests/studio/playwright_settings_tabs.py
index 39d9034530a..3e9b13ffee9 100644
--- a/tests/studio/playwright_settings_tabs.py
+++ b/tests/studio/playwright_settings_tabs.py
@@ -54,6 +54,24 @@ CHUNK_DELAY_MS = int(os.environ.get("PW_CHUNK_DELAY_MS", "0"))
CHUNK_FAIL = os.environ.get("PW_CHUNK_FAIL", "")
SETTLE_MS = 600
SETTLE_TIMEOUT_S = 25.0
+LAN_URLS = ("http://192.168.1.24:8888", "http://10.0.0.7:8888")
+LAN_STATUS = {
+ "state": "online",
+ "urls": list(LAN_URLS),
+ "public_urls": [],
+ "error": None,
+ "auto_start": False,
+ "managed_by": "settings",
+ "can_start": False,
+ "can_stop": True,
+ "block_reason": None,
+ "bind_host": "0.0.0.0",
+ "wildcard_bind": True,
+ "serves_web_ui": True,
+ "keyless_lan_eligible": True,
+ "keyless_scope": "off",
+ "keyless_tools": False,
+}
# The panel scroller inside the dialog, the element `mainScrollRef` points at.
PANEL = 'div[role="dialog"] main div.hover-scrollbar'
# How long the Data module is held, and how far into that hold the deep-open is abandoned.
@@ -335,6 +353,52 @@ def run_chunk_fail(page) -> None:
log("another tab still renders after the failure")
+def run_lan_address_actions(page) -> None:
+ """Every listed address must own the actions that operate on it."""
+ click_forced(page.locator('[data-testid="settings-tab-remote-lan"]'), timeout = 15000)
+ settle_panel(page)
+
+ rows = {}
+ for url in LAN_URLS:
+ address = page.get_by_text(url, exact = True)
+ if address.count() != 1:
+ fail(f"LAN address {url}: expected one visible row, found {address.count()}")
+ continue
+ labels = address.evaluate(
+ """(node) => [...node.parentElement.querySelectorAll('button')]
+ .map((button) => button.getAttribute('aria-label'))"""
+ )
+ rows[url] = labels
+ expected = [f"Show QR code for {url}", f"Copy {url}"]
+ if labels != expected:
+ fail(f"LAN address {url}: row actions {labels}, expected {expected}")
+
+ if len(rows) != len(LAN_URLS):
+ return
+
+ target = LAN_URLS[1]
+ click_forced(page.get_by_role("button", name = f"Show QR code for {target}", exact = True))
+ qr_dialog = page.locator('div[role="dialog"]').last
+ qr_dialog.wait_for(state = "visible", timeout = 15000)
+ qr_value = qr_dialog.locator("code").inner_text().strip()
+ if qr_value != target:
+ fail(f"LAN QR action opened {qr_value}, expected {target}")
+ page.keyboard.press("Escape")
+ page.get_by_role("heading", name = "Open on your phone").wait_for(state = "hidden", timeout = 15000)
+
+ page.evaluate(
+ """() => Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: async (text) => { window.__copiedLanUrl = text; } },
+ })"""
+ )
+ click_forced(page.get_by_role("button", name = f"Copy {target}", exact = True))
+ page.wait_for_function("(url) => window.__copiedLanUrl === url", arg = target, timeout = 15000)
+ report["lan_address_actions"] = {"rows": rows, "qr": qr_value, "copied": target}
+ report["steps"].append("lan-address-actions")
+ log("each LAN address keeps its own QR and copy target")
+
+
def run(page) -> None:
if CHUNK_FAIL:
run_chunk_fail(page)
@@ -366,7 +430,10 @@ def run(page) -> None:
)
report["steps"].append("all-tabs-render")
- # --- 3. close/reopen, and deep-open straight to a tab ----------------------------
+ # --- 3. every lan address has actions bound to that address ----------------------
+ run_lan_address_actions(page)
+
+ # --- 4. close/reopen, and deep-open straight to a tab ----------------------------
page.evaluate("() => window.__settingsSmoke.close()")
page.wait_for_timeout(300)
for tab in ("voice", "api-keys", "data", "about", "connections"):
@@ -389,7 +456,7 @@ def run(page) -> None:
page.wait_for_timeout(200)
report["steps"].append("deep-open")
- # --- 4. search, then jump to a result and confirm the scroll target flashed ------
+ # --- 5. search, then jump to a result and confirm the scroll target flashed ------
# A real setting well down a long panel, so a jump that never happens shows in scrollTop.
target_tab = "general"
target_label = report["tabs"][target_tab]["settled"]["labels"][-1]
@@ -463,12 +530,20 @@ def main() -> int:
reduced_motion = "reduce",
)
page = ctx.new_page()
+ page.route(
+ "**/api/settings/lan-access*",
+ lambda route: route.fulfill(
+ status = 200,
+ content_type = "application/json",
+ body = json.dumps(LAN_STATUS),
+ ),
+ )
if CHUNK_DELAY_MS or CHUNK_FAIL:
def handle(route):
path = route.request.url
if "/tabs/" not in path:
- return route.continue_()
+ return route.fallback()
if CHUNK_FAIL and f"/{CHUNK_FAIL}-tab" in path:
return route.abort("failed")
if CHUNK_DELAY_MS:
diff --git a/unsloth_cli/_tool_policy.py b/unsloth_cli/_tool_policy.py
index 664e1a3c83b..d3ffcd5d450 100644
--- a/unsloth_cli/_tool_policy.py
+++ b/unsloth_cli/_tool_policy.py
@@ -6,13 +6,13 @@ Kept as a standalone module so the truth table can be unit-tested
without spinning up Typer or the studio venv.
"""
+import ipaddress
+import socket
from typing import Callable, Optional
import typer
-# Loopback aliases; any other bind address is treated as network-reachable.
-# Mirrored in studio/backend/utils/host_policy.py (kept separate because the
-# backend is self-contained); keep the two in sync.
+# loopback aliases mirror the self-contained backend bind policy
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"})
@@ -21,6 +21,147 @@ def is_external_host(host: str) -> bool:
return host.lower() not in _LOOPBACK_HOSTS
+def _normalized_ip(address: str):
+ try:
+ parsed = ipaddress.ip_address(address)
+ except ValueError:
+ return None
+ if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
+ parsed = parsed.ipv4_mapped
+ return parsed
+
+
+def _literal_ip_address(host: str):
+ if not isinstance(host, str) or not host:
+ return None
+ literal = _normalized_ip(host)
+ if literal is not None:
+ return literal
+ try:
+ return ipaddress.IPv4Address(socket.inet_aton(host))
+ except OSError:
+ return None
+
+
+def _resolved_host_ip_addresses(host: str):
+ if not isinstance(host, str) or not host:
+ return ()
+ try:
+ addresses = socket.getaddrinfo(host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)
+ except OSError:
+ return ()
+ resolved = []
+ for _family, _kind, _protocol, _name, sockaddr in addresses:
+ try:
+ parsed = ipaddress.ip_address(sockaddr[0])
+ except (IndexError, ValueError):
+ continue
+ if parsed not in resolved:
+ resolved.append(parsed)
+ return tuple(resolved)
+
+
+def _resolved_ip_addresses(host: str):
+ literal = _literal_ip_address(host)
+ if literal is not None:
+ return (literal,)
+ resolved = []
+ for parsed in _resolved_host_ip_addresses(host):
+ if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
+ parsed = parsed.ipv4_mapped
+ if parsed not in resolved:
+ resolved.append(parsed)
+ return tuple(resolved)
+
+
+def wildcard_ip_versions(host: str) -> tuple[int, ...]:
+ """IP versions for every unspecified address this host resolves to."""
+ versions = {
+ address.version for address in _resolved_ip_addresses(host) if address.is_unspecified
+ }
+ return tuple(version for version in (4, 6) if version in versions)
+
+
+def resolved_bind_address_count(host: str) -> int:
+ """Number of distinct socket addresses this host resolves to."""
+ if _literal_ip_address(host) is not None:
+ return 1
+ if not isinstance(host, str) or not host:
+ return 0
+ try:
+ addresses = socket.getaddrinfo(host, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)
+ except OSError:
+ return 0
+ endpoints = {
+ (family, tuple(sockaddr))
+ for family, _kind, _protocol, _name, sockaddr in addresses
+ if sockaddr
+ }
+ return len(endpoints)
+
+
+def is_wildcard_host(host: str) -> bool:
+ """True when the host resolves to an unspecified bind address."""
+ return bool(wildcard_ip_versions(host))
+
+
+def normalize_wildcard_bind_host(host: str) -> str:
+ """Return a safe canonical bind for an effective wildcard host."""
+ if isinstance(host, str):
+ try:
+ parsed_literal = ipaddress.ip_address(host)
+ except ValueError:
+ pass
+ else:
+ if (
+ isinstance(parsed_literal, ipaddress.IPv6Address)
+ and parsed_literal.ipv4_mapped is not None
+ ):
+ return str(parsed_literal.ipv4_mapped)
+ literal = _literal_ip_address(host)
+ if literal is not None:
+ if not literal.is_unspecified:
+ return host
+ return "::" if literal.version == 6 else "0.0.0.0"
+
+ raw_addresses = _resolved_host_ip_addresses(host)
+ addresses = []
+ has_mapped_address = False
+ for address in raw_addresses:
+ if isinstance(address, ipaddress.IPv6Address) and address.ipv4_mapped is not None:
+ address = address.ipv4_mapped
+ has_mapped_address = True
+ if address not in addresses:
+ addresses.append(address)
+ if has_mapped_address:
+ if len(addresses) == 1:
+ return str(addresses[0])
+ raise ValueError(
+ f"--host {host!r} resolves to ambiguous IPv4-mapped addresses; "
+ "use an explicit bind address."
+ )
+ wildcard_versions = {address.version for address in addresses if address.is_unspecified}
+ if not wildcard_versions:
+ return host
+ specific_versions = {address.version for address in addresses if not address.is_unspecified}
+ if len(wildcard_versions) == 2 and not specific_versions:
+ return host
+ if specific_versions - wildcard_versions or (len(wildcard_versions) == 2 and specific_versions):
+ raise ValueError(
+ f"--host {host!r} mixes wildcard and specific address families; "
+ "use an explicit bind address."
+ )
+ return "::" if 6 in wildcard_versions else "0.0.0.0"
+
+
+def wildcard_loopback_host(host: str) -> Optional[str]:
+ """The loopback address reachable through a wildcard bind."""
+ versions = wildcard_ip_versions(host)
+ if 4 in versions:
+ return "127.0.0.1"
+ return "::1" if 6 in versions else None
+
+
def resolve_tool_policy(
host: str,
flag: Optional[bool],
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 2cca7f766b3..9399ae211a3 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -334,16 +334,54 @@ def _stream_for_subprocess(stream):
def _display_host_for_bind(run_mod, host: str) -> str:
- return run_mod._resolve_external_ip() if host in ("0.0.0.0", "::") else host
+ return run_mod._display_host_for_bind(host)
def _loopback_bind_host_for(host: str) -> str:
- return "::1" if host == "::" else "127.0.0.1"
+ from unsloth_cli._tool_policy import wildcard_loopback_host
+ return wildcard_loopback_host(host) or "127.0.0.1"
+
+
+def _require_bind_host(host: str) -> None:
+ if isinstance(host, str) and host.strip():
+ return
+ typer.echo(
+ "Error: --host cannot be empty; use 0.0.0.0 to bind every IPv4 interface.",
+ err = True,
+ )
+ raise typer.Exit(2)
+
+
+def _normalize_wildcard_bind_host(host: str) -> str:
+ from unsloth_cli._tool_policy import normalize_wildcard_bind_host
+ try:
+ return normalize_wildcard_bind_host(host)
+ except ValueError as exc:
+ typer.echo(f"Error: {exc}", err = True)
+ raise typer.Exit(2) from None
+
+
+def _require_unambiguous_ephemeral_bind(host: str, port: int) -> None:
+ if port != 0:
+ return
+ from unsloth_cli._tool_policy import resolved_bind_address_count
+
+ if resolved_bind_address_count(host) <= 1:
+ return
+ typer.echo(
+ "Error: --port 0 cannot be used when --host resolves to multiple bind "
+ "addresses; choose an explicit port.",
+ err = True,
+ )
+ raise typer.Exit(2)
def _url_host(host: str) -> str:
+ url_host = host.replace("%", "%25")
return (
- f"[{host}]" if ":" in host and not (host.startswith("[") and host.endswith("]")) else host
+ f"[{url_host}]"
+ if ":" in url_host and not (url_host.startswith("[") and url_host.endswith("]"))
+ else url_host
)
@@ -820,17 +858,42 @@ def _find_frontend_dist() -> Optional[Path]:
# ── helpers for `unsloth studio run` ────────────────────────────────
+_direct_http_opener = None
+
+
+def _direct_urlopen(request, timeout):
+ """Open a process-local URL without proxies or redirects."""
+ global _direct_http_opener
+
+ if _direct_http_opener is None:
+
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
+ raise urllib.error.HTTPError(
+ req.full_url, code, f"refusing redirect to {newurl}", headers, fp
+ )
+
+ _direct_http_opener = urllib.request.build_opener(
+ urllib.request.ProxyHandler({}),
+ _NoRedirect(),
+ )
+ return _direct_http_opener.open(request, timeout = timeout)
+
-def _wait_for_server(port: int, timeout: int = 30) -> bool:
+def _wait_for_server(
+ port: int,
+ timeout: int = 30,
+ request_host: str = "127.0.0.1",
+) -> bool:
"""Poll ``GET /api/health`` until the server responds 200 or *timeout* expires."""
import urllib.request
import urllib.error
- url = f"http://127.0.0.1:{port}/api/health"
+ url = f"http://{_url_host(request_host)}:{port}/api/health"
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
- with urllib.request.urlopen(url, timeout = 2) as resp:
+ with _direct_urlopen(url, timeout = 2) as resp:
if resp.status == 200:
return True
except (urllib.error.URLError, OSError, ConnectionError):
@@ -1093,7 +1156,9 @@ def _should_prompt_password_change(
return True
if cloudflare is not True:
return False
- return host in ("0.0.0.0", "::") and not api_only
+ from unsloth_cli._tool_policy import is_wildcard_host
+
+ return is_wildcard_host(host) and not api_only
def _prompt_streams_interactive() -> bool:
@@ -1633,6 +1698,7 @@ def _load_model_via_http(
spec_draft_n_max: Optional[int] = None,
llama_extra_args: Optional[List[str]] = None,
timeout: int = 600,
+ request_host: str = "127.0.0.1",
) -> dict:
"""POST to ``/api/inference/load`` using the API key for auth."""
import json
@@ -1661,7 +1727,7 @@ def _load_model_via_http(
payload["llama_extra_args"] = list(llama_extra_args)
data = json.dumps(payload).encode()
- url = f"http://127.0.0.1:{port}/api/inference/load"
+ url = f"http://{_url_host(request_host)}:{port}/api/inference/load"
req = urllib.request.Request(
url,
data = data,
@@ -1672,7 +1738,7 @@ def _load_model_via_http(
method = "POST",
)
try:
- with urllib.request.urlopen(req, timeout = timeout) as resp:
+ with _direct_urlopen(req, timeout = timeout) as resp:
try:
body = json.loads(resp.read())
except ValueError:
@@ -1871,6 +1937,7 @@ def studio_default(
raise typer.Exit(2)
return
+ _require_bind_host(host)
runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
_preserve_cloudflare_intent(cloudflare, secure)
@@ -1892,6 +1959,9 @@ def studio_default(
)
host = "127.0.0.1"
+ host = _normalize_wildcard_bind_host(host)
+ _require_unambiguous_ephemeral_bind(host, port)
+
# --verbose restores the per-request access logs that are suppressed by
# default (plain-server path; the `run` subcommand has its own --verbose).
if verbose:
@@ -2552,6 +2622,8 @@ def run(
model = parsed_repo
gguf_variant = gguf_variant or embedded_variant
+ _require_bind_host(host)
+
# --secure requires the tunnel; force a loopback bind so the raw port is never public.
if secure:
if cloudflare is False:
@@ -2570,6 +2642,9 @@ def run(
)
host = "127.0.0.1"
+ host = _normalize_wildcard_bind_host(host)
+ _require_unambiguous_ephemeral_bind(host, port)
+
# Tool policy does not depend on the bind: tools default on everywhere
# (--secure is a loopback tunnel; the operator owns a raw bind). With no flag
# this stays None, so the default applies without becoming an override and a
@@ -2794,10 +2869,14 @@ def run(
from studio.backend.run import _graceful_shutdown, _server
try:
+ request_host = getattr(app.state, "server_request_host", None)
+ if not isinstance(request_host, str) or not request_host:
+ typer.echo("Error: server did not expose its bound address.", err = True)
+ raise typer.Exit(1)
# 3. Wait for server health.
if not silent:
typer.echo("Starting Unsloth Studio...")
- if not _wait_for_server(actual_port):
+ if not _wait_for_server(actual_port, request_host = request_host):
typer.echo("Error: server did not become healthy within 30 seconds.", err = True)
raise typer.Exit(1)
@@ -2824,6 +2903,7 @@ def run(
speculative_type = speculative_type,
spec_draft_n_max = spec_draft_n_max,
llama_extra_args = extra_llama_args,
+ request_host = request_host,
)
except RuntimeError as exc:
typer.echo(f"Error: {exc}", err = True)
diff --git a/unsloth_cli/tests/test_studio_cloudflare_flag.py b/unsloth_cli/tests/test_studio_cloudflare_flag.py
index 4d51b3d44b0..112c92d350c 100644
--- a/unsloth_cli/tests/test_studio_cloudflare_flag.py
+++ b/unsloth_cli/tests/test_studio_cloudflare_flag.py
@@ -269,14 +269,17 @@ def test_run_in_venv_passes_cloudflare_to_run_server(monkeypatch, user_flag, exp
assert captured.get("cloudflare") is expected, captured
-def test_run_display_host_and_url_helpers_cover_ipv6_wildcard():
+def test_run_display_host_delegates_wildcard_aliases_to_the_backend():
import types
studio_mod = _studio()
- run_mod = types.SimpleNamespace(_resolve_external_ip = lambda: "198.51.100.7")
+ aliases = {"0.0.0.0", "::", "::0", "0:0:0:0:0:0:0:0", "0"}
+ run_mod = types.SimpleNamespace(
+ _display_host_for_bind = lambda host: "198.51.100.7" if host in aliases else host
+ )
- assert studio_mod._display_host_for_bind(run_mod, "0.0.0.0") == "198.51.100.7"
- assert studio_mod._display_host_for_bind(run_mod, "::") == "198.51.100.7"
+ for host in aliases:
+ assert studio_mod._display_host_for_bind(run_mod, host) == "198.51.100.7"
assert studio_mod._url_host("2001:db8::7") == "[2001:db8::7]"
assert studio_mod._url_host("127.0.0.1") == "127.0.0.1"
@@ -304,12 +307,19 @@ def test_run_cloudflare_notice_uses_external_host_policy():
("print", {"secure": False, "loopback_host": "::1"}),
]
+ calls.clear()
+ studio_mod._emit_run_cloudflare_notice(run_mod, "::ffff:0.0.0.0", "198.51.100.7", 8888, False)
+ assert calls == [
+ ("verify", "198.51.100.7", 8888),
+ ("print", {"secure": False, "loopback_host": "127.0.0.1"}),
+ ]
+
calls.clear()
studio_mod._emit_run_cloudflare_notice(run_mod, "127.0.0.1", "127.0.0.1", 8888, False)
assert calls == []
-def test_run_silent_emits_cloudflare_notice_for_external_bind(monkeypatch):
+def test_run_silent_pins_internal_requests_to_the_bound_address(monkeypatch):
import types
studio_mod = _studio()
@@ -338,12 +348,16 @@ def test_run_silent_emits_cloudflare_notice_for_external_bind(monkeypatch):
class _App:
class state:
server_port = 8888
+ server_request_host = "127.0.0.1"
cloudflare_url = "https://x.trycloudflare.com"
calls = []
backend = types.ModuleType("studio.backend.run")
backend.run_server = lambda **_kwargs: _App()
backend._resolve_external_ip = lambda: "198.51.100.7"
+ backend._display_host_for_bind = lambda host: (
+ backend._resolve_external_ip() if host == "0.0.0.0" else host
+ )
backend._verify_global_reachability = lambda host, port: calls.append(("verify", host, port))
backend._print_cloudflare_line = lambda **kw: calls.append(("print", kw))
backend._server = object()
@@ -360,12 +374,19 @@ def test_run_silent_emits_cloudflare_notice_for_external_bind(monkeypatch):
monkeypatch.setitem(sys.modules, "state", state_mod)
monkeypatch.setitem(sys.modules, "state.tool_policy", tp_mod)
- monkeypatch.setattr(studio_mod, "_wait_for_server", lambda *a, **k: True)
+ monkeypatch.setattr(
+ studio_mod,
+ "_wait_for_server",
+ lambda port, **kwargs: calls.append(("health", port, kwargs)) or True,
+ )
monkeypatch.setattr(studio_mod, "_create_api_key_inprocess", lambda name: "sk-test")
monkeypatch.setattr(
studio_mod,
"_load_model_via_http",
- lambda **_kwargs: {"model": "unsloth/Qwen3-1.7B-GGUF", "context_length": 4096},
+ lambda **kwargs: (
+ calls.append(("load", kwargs))
+ or {"model": "unsloth/Qwen3-1.7B-GGUF", "context_length": 4096}
+ ),
)
import typer as _typer
@@ -376,13 +397,14 @@ def test_run_silent_emits_cloudflare_notice_for_external_bind(monkeypatch):
)(studio_mod.run)
result = CliRunner().invoke(
app,
- _BASE + ["--silent", "-H", "0.0.0.0"],
+ _BASE + ["--silent", "-H", "localhost"],
catch_exceptions = True,
)
assert result.exit_code == 0, result.output
- assert ("verify", "198.51.100.7", 8888) in calls
- assert ("print", {"secure": False, "loopback_host": "127.0.0.1"}) in calls
+ assert ("health", 8888, {"request_host": "127.0.0.1"}) in calls
+ assert next(entry[1] for entry in calls if entry[0] == "load")["request_host"] == "127.0.0.1"
+ assert all(entry[0] not in {"verify", "print"} for entry in calls)
# ── parent-level --cloudflare/--no-cloudflare with a subcommand is rejected ─
diff --git a/unsloth_cli/tests/test_studio_password_prompt.py b/unsloth_cli/tests/test_studio_password_prompt.py
index 753c22edc24..1761afc04e9 100644
--- a/unsloth_cli/tests/test_studio_password_prompt.py
+++ b/unsloth_cli/tests/test_studio_password_prompt.py
@@ -47,6 +47,11 @@ _NEW_PW = "brand-new-password"
# --cloudflare tunnels only non-api-only wildcard binds.
(True, "0.0.0.0", False, False, True),
(True, "::", False, False, True),
+ (True, "::0", False, False, True),
+ (True, "0:0:0:0:0:0:0:0", False, False, True),
+ (True, "0", False, False, True),
+ (True, "::ffff:0.0.0.0", False, False, True),
+ (True, "", False, False, False),
(True, "127.0.0.1", False, False, False),
(True, "0.0.0.0", False, True, False),
# Off/unset never prompts without --secure.
@@ -224,6 +229,259 @@ def _invoke_run(monkeypatch, events, args):
return CliRunner().invoke(app, args, catch_exceptions = True)
[email protected]("command", ["default", "run"])
+def test_an_empty_bind_is_rejected_before_password_or_launch(monkeypatch, command):
+ studio_mod = _studio()
+ events = []
+ monkeypatch.setattr(
+ studio_mod,
+ "_enforce_password_change_before_exposure",
+ lambda **_kwargs: events.append(("password", None)),
+ )
+ if command == "default":
+ result = _invoke_studio_default(monkeypatch, events, ["--host", "", "--cloudflare"])
+ else:
+ result = _invoke_run(
+ monkeypatch,
+ events,
+ _BASE + ["--host", "", "--cloudflare"],
+ )
+
+ assert result.exit_code == 2, result.output
+ assert "--host cannot be empty" in result.output
+ assert events == []
+
+
[email protected]("command", ["default", "run"])
+def test_a_mixed_family_wildcard_is_rejected_before_password_or_launch(monkeypatch, command):
+ import socket
+
+ from unsloth_cli import _tool_policy
+
+ studio_mod = _studio()
+ events = []
+ monkeypatch.setattr(
+ studio_mod,
+ "_enforce_password_change_before_exposure",
+ lambda **_kwargs: events.append(("password", None)),
+ )
+ monkeypatch.setattr(
+ _tool_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("0.0.0.0", 0)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fd00::24", 0, 0, 0)),
+ ],
+ )
+ if command == "default":
+ result = _invoke_studio_default(
+ monkeypatch,
+ events,
+ ["--host", "mixed-wildcard.test", "--cloudflare"],
+ )
+ else:
+ result = _invoke_run(
+ monkeypatch,
+ events,
+ _BASE + ["--host", "mixed-wildcard.test", "--cloudflare"],
+ )
+
+ assert result.exit_code == 2, result.output
+ assert "mixes wildcard and specific address families" in result.output
+ assert events == []
+
+
[email protected]("command", ["default", "run"])
+def test_a_mapped_wildcard_is_canonicalized_before_reexec(monkeypatch, command):
+ studio_mod = _studio()
+ events = []
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
+ if command == "default":
+ result = _invoke_studio_default(
+ monkeypatch,
+ events,
+ ["--host", "::ffff:0.0.0.0", "--api-only"],
+ )
+ else:
+ result = _invoke_run(
+ monkeypatch,
+ events,
+ _BASE + ["--host", "::ffff:0.0.0.0", "--api-only"],
+ )
+
+ assert result.exit_code == 0, result.output
+ argv = next(payload for kind, payload in events if kind == "exec")
+ assert argv[argv.index("--host") + 1] == "0.0.0.0"
+
+
[email protected]("command", ["default", "run"])
+def test_a_mapped_specific_bind_is_canonicalized_before_reexec(monkeypatch, command):
+ studio_mod = _studio()
+ events = []
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
+ if command == "default":
+ result = _invoke_studio_default(
+ monkeypatch,
+ events,
+ ["--host", "::ffff:127.0.0.1", "--api-only"],
+ )
+ else:
+ result = _invoke_run(
+ monkeypatch,
+ events,
+ _BASE + ["--host", "::ffff:127.0.0.1", "--api-only"],
+ )
+
+ assert result.exit_code == 0, result.output
+ argv = next(payload for kind, payload in events if kind == "exec")
+ assert argv[argv.index("--host") + 1] == "127.0.0.1"
+
+
[email protected]("command", ["default", "run"])
+def test_a_resolved_mapped_bind_is_canonicalized_before_reexec(monkeypatch, command):
+ import socket
+
+ from unsloth_cli import _tool_policy
+
+ studio_mod = _studio()
+ events = []
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
+ monkeypatch.setattr(
+ _tool_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::ffff:127.0.0.1", 0, 0, 0))
+ ],
+ )
+ if command == "default":
+ result = _invoke_studio_default(
+ monkeypatch,
+ events,
+ ["--host", "mapped.test", "--api-only"],
+ )
+ else:
+ result = _invoke_run(
+ monkeypatch,
+ events,
+ _BASE + ["--host", "mapped.test", "--api-only"],
+ )
+
+ assert result.exit_code == 0, result.output
+ argv = next(payload for kind, payload in events if kind == "exec")
+ assert argv[argv.index("--host") + 1] == "127.0.0.1"
+
+
[email protected]("command", ["default", "run"])
+def test_ambiguous_resolved_mapped_binds_are_rejected_before_launch(monkeypatch, command):
+ import socket
+
+ from unsloth_cli import _tool_policy
+
+ studio_mod = _studio()
+ events = []
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
+ monkeypatch.setattr(
+ _tool_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::ffff:127.0.0.1", 0, 0, 0)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::ffff:192.168.1.24", 0, 0, 0)),
+ ],
+ )
+ if command == "default":
+ result = _invoke_studio_default(
+ monkeypatch,
+ events,
+ ["--host", "ambiguous-mapped.test", "--api-only"],
+ )
+ else:
+ result = _invoke_run(
+ monkeypatch,
+ events,
+ _BASE + ["--host", "ambiguous-mapped.test", "--api-only"],
+ )
+
+ assert result.exit_code == 2, result.output
+ assert "resolves to ambiguous IPv4-mapped addresses" in result.output
+ assert events == []
+
+
[email protected]("command", ["default", "run"])
+def test_a_dual_stack_wildcard_hostname_is_preserved_for_reexec(monkeypatch, command):
+ import socket
+
+ from unsloth_cli import _tool_policy
+
+ studio_mod = _studio()
+ events = []
+ monkeypatch.setattr(studio_mod, "_enforce_password_change_before_exposure", lambda **_kw: None)
+ monkeypatch.setattr(
+ _tool_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET, socket.SOCK_STREAM, 6, "", ("0.0.0.0", 0)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("::", 0, 0, 0)),
+ ],
+ )
+ if command == "default":
+ result = _invoke_studio_default(
+ monkeypatch,
+ events,
+ ["--host", "dual-wildcard.test", "--api-only"],
+ )
+ else:
+ result = _invoke_run(
+ monkeypatch,
+ events,
+ _BASE + ["--host", "dual-wildcard.test", "--api-only"],
+ )
+
+ assert result.exit_code == 0, result.output
+ argv = next(payload for kind, payload in events if kind == "exec")
+ assert argv[argv.index("--host") + 1] == "dual-wildcard.test"
+
+
[email protected]("command", ["default", "run"])
+def test_an_ephemeral_multi_address_bind_is_rejected_before_password_or_launch(
+ monkeypatch, command
+):
+ import socket
+
+ from unsloth_cli import _tool_policy
+
+ studio_mod = _studio()
+ events = []
+ monkeypatch.setattr(
+ studio_mod,
+ "_enforce_password_change_before_exposure",
+ lambda **_kwargs: events.append(("password", None)),
+ )
+ monkeypatch.setattr(
+ _tool_policy.socket,
+ "getaddrinfo",
+ lambda *_args, **_kwargs: [
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", 0, 0, 2)),
+ (socket.AF_INET6, socket.SOCK_STREAM, 6, "", ("fe80::1", 0, 0, 3)),
+ ],
+ )
+ if command == "default":
+ result = _invoke_studio_default(
+ monkeypatch,
+ events,
+ ["--host", "scoped.test", "--port", "0", "--cloudflare"],
+ )
+ else:
+ result = _invoke_run(
+ monkeypatch,
+ events,
+ _BASE + ["--host", "scoped.test", "--port", "0", "--cloudflare"],
+ )
+
+ assert result.exit_code == 2, result.output
+ assert "--port 0 cannot be used" in result.output
+ assert events == []
+
+
# ── plain `unsloth studio` ───────────────────────────────────────────
diff --git a/unsloth_cli/tests/test_studio_run_parallel_flag.py b/unsloth_cli/tests/test_studio_run_parallel_flag.py
index 91bbb05496c..3aeb6644e2d 100644
--- a/unsloth_cli/tests/test_studio_run_parallel_flag.py
+++ b/unsloth_cli/tests/test_studio_run_parallel_flag.py
@@ -512,7 +512,7 @@ def test_load_model_http_payload_for_gpu_memory_mode(monkeypatch, mode, expected
captured["timeout"] = timeout
return BytesIO(b'{"model": "owner/model-GGUF"}')
- monkeypatch.setattr(studio_mod.urllib.request, "urlopen", urlopen)
+ monkeypatch.setattr(studio_mod, "_direct_urlopen", urlopen)
result = studio_mod._load_model_via_http(
port = 8888,
api_key = "sk-test",
@@ -521,11 +521,92 @@ def test_load_model_http_payload_for_gpu_memory_mode(monkeypatch, mode, expected
max_seq_length = 0,
load_in_4bit = True,
gpu_memory_mode = mode,
+ request_host = "::1",
)
assert result == {"model": "owner/model-GGUF"}
assert json.loads(captured["request"].data) == expected
assert captured["request"].get_header("Authorization") == "Bearer sk-test"
+ assert captured["request"].full_url == "http://[::1]:8888/api/inference/load"
+
+
+def test_health_poll_brackets_an_ipv6_request_host(monkeypatch):
+ studio_mod = _load_run_command()
+ urls = []
+
+ class _Healthy(BytesIO):
+ status = 200
+
+ def _urlopen(url, timeout):
+ urls.append((url, timeout))
+ return _Healthy()
+
+ monkeypatch.setattr(studio_mod, "_direct_urlopen", _urlopen)
+
+ assert studio_mod._wait_for_server(8888, timeout = 1, request_host = "::1") is True
+ assert urls == [("http://[::1]:8888/api/health", 2)]
+
+
+def test_internal_request_urls_encode_an_ipv6_scope(monkeypatch):
+ studio_mod = _load_run_command()
+ urls = []
+
+ class _Healthy(BytesIO):
+ status = 200
+
+ def _urlopen(url, timeout):
+ urls.append(url)
+ return _Healthy()
+
+ monkeypatch.setattr(studio_mod, "_direct_urlopen", _urlopen)
+
+ assert studio_mod._wait_for_server(8888, timeout = 1, request_host = "fe80::1234%7") is True
+ assert urls == ["http://[fe80::1234%257]:8888/api/health"]
+
+
+def test_process_local_http_opener_disables_proxies_and_redirects(monkeypatch):
+ studio_mod = _load_run_command()
+ handlers = []
+ opened = []
+
+ class _Opener:
+ def open(self, request, timeout):
+ opened.append((request, timeout))
+ return BytesIO(b"ok")
+
+ def _build_opener(*configured):
+ handlers.extend(configured)
+ return _Opener()
+
+ monkeypatch.setenv("HTTP_PROXY", "http://proxy.example:3128")
+ monkeypatch.setattr(studio_mod, "_direct_http_opener", None)
+ monkeypatch.setattr(studio_mod.urllib.request, "build_opener", _build_opener)
+
+ with studio_mod._direct_urlopen("http://192.0.2.24:8888/api/health", timeout = 2):
+ pass
+
+ proxy_handler = next(
+ handler
+ for handler in handlers
+ if isinstance(handler, studio_mod.urllib.request.ProxyHandler)
+ )
+ redirect_handler = next(
+ handler
+ for handler in handlers
+ if isinstance(handler, studio_mod.urllib.request.HTTPRedirectHandler)
+ )
+ assert proxy_handler.proxies == {}
+ assert opened == [("http://192.0.2.24:8888/api/health", 2)]
+ request = studio_mod.urllib.request.Request("http://192.0.2.24:8888/api/inference/load")
+ with pytest.raises(studio_mod.urllib.error.HTTPError, match = "refusing redirect"):
+ redirect_handler.redirect_request(
+ request,
+ None,
+ 302,
+ "Found",
+ {},
+ "http://attacker.example/steal",
+ )
def test_load_model_http_payload_for_dspark(monkeypatch):
@@ -536,7 +617,7 @@ def test_load_model_http_payload_for_dspark(monkeypatch):
captured["request"] = request
return BytesIO(b'{"model": "owner/model-GGUF"}')
- monkeypatch.setattr(studio_mod.urllib.request, "urlopen", urlopen)
+ monkeypatch.setattr(studio_mod, "_direct_urlopen", urlopen)
studio_mod._load_model_via_http(
port = 8888,
api_key = "sk-test",
@@ -568,7 +649,7 @@ def test_load_model_http_fails_on_a_deferred_error(monkeypatch):
).encode()
)
- monkeypatch.setattr(studio_mod.urllib.request, "urlopen", urlopen)
+ monkeypatch.setattr(studio_mod, "_direct_urlopen", urlopen)
with pytest.raises(RuntimeError) as excinfo:
studio_mod._load_model_via_http(
port = 8888,
@@ -587,9 +668,7 @@ def test_load_model_http_rejects_a_truncated_padded_body(monkeypatch, body):
"""A 200 the load never finished under must fail like any other load failure."""
studio_mod = _load_run_command()
- monkeypatch.setattr(
- studio_mod.urllib.request, "urlopen", lambda request, timeout: BytesIO(body)
- )
+ monkeypatch.setattr(studio_mod, "_direct_urlopen", lambda request, timeout: BytesIO(body))
with pytest.raises(RuntimeError) as excinfo:
studio_mod._load_model_via_http(
port = 8888,