Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: gate concrete non-loopback binds, and never block a launch that worked
danielhanchen605c7c2a1859
diff --git a/studio/backend/auth/terminal_prompt.py b/studio/backend/auth/terminal_prompt.pyindex 14e5b33564b..65cb3be44bd 100644--- a/studio/backend/auth/terminal_prompt.py+++ b/studio/backend/auth/terminal_prompt.py@@ -2,7 +2,8 @@# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0"""Interactive terminal prompt that forces a bootstrap password change before-Unsloth is exposed on a public Cloudflare URL (``--secure`` / ``--cloudflare``).+Unsloth is put where others can reach it: a public Cloudflare URL (``--secure``+/ ``--cloudflare``) or a raw non-loopback bind such as ``-H 0.0.0.0``.Masked input echoes one ``*`` per keystroke (unlike ``getpass``). Works onWindows (``msvcrt``) and Linux/macOS (``termios``). All output goes to stderr sodiff --git a/studio/backend/run.py b/studio/backend/run.pyindex 375f2aa3e94..460dc8ccb83 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -2183,6 +2183,17 @@ def _terminal_password_gate(if not tunnel_will_start and not bind_is_exposed:return True, False+ # A raw-bind-only launch decides promptability BEFORE opening auth storage.+ # Before this gate learned about non-tunnel exposure it returned above, so a+ # headless container never reached ensure_default_admin() from here. Doing so+ # now would move first seeding earlier, open the SQLite file sooner and give a+ # read-only or locked home a new place to fail, none of which a container+ # operator asked for. Tunnel launches are unaffected: they always came here.+ if not tunnel_will_start and not (+ _stream_isatty(sys.stdin) and _stream_isatty(sys.stderr)+ ):+ return True, False+from auth import hashing as _auth_hashingfrom auth import storage as _auth_storagefrom auth.bootstrap_timeout import (@@ -2277,7 +2288,29 @@ def _terminal_password_gate(out = sys.stderr,exposure = ("on the public internet" if tunnel_will_start else "on every network interface"),)- return (True, True) if changed else (False, False)+ if changed:+ return True, True+ if tunnel_will_start:+ # Refusing to secure a launch that is about to publish a public URL+ # aborts it, exactly as before.+ return False, False+ # A raw bind is different: this launch worked before the prompt existed, and+ # aborting it would turn Ctrl+C into "no Studio" for anyone who just wanted+ # the old behaviour. `docker run -it` on a fresh volume is precisely that+ # case (docker/studio_run.sh execs `unsloth studio -H 0.0.0.0` and only+ # supplies a password when the initial-password file is non-empty), so+ # aborting would stop a container that starts today. Warn and proceed at the+ # protection level this launch already had: the bootstrap deadline.+ print(+ " WARNING: continuing with the auto-generated admin password on a bind "+ "that is reachable from the network. Unsloth shuts down after the "+ "bootstrap deadline (UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT, default 1h) "+ "unless the password is changed. Change it by logging in, or with "+ "`unsloth studio reset-password`.",+ file = sys.stderr,+ flush = True,+ )+ return True, Falsedef _apply_supplied_password(password_value: "Optional[str]") -> None:diff --git a/studio/backend/tests/test_password_prompt_backstop.py b/studio/backend/tests/test_password_prompt_backstop.pyindex 8a79665dde5..459556b4bb7 100644--- a/studio/backend/tests/test_password_prompt_backstop.py+++ b/studio/backend/tests/test_password_prompt_backstop.py@@ -437,6 +437,73 @@ def test_a_headless_raw_bind_is_byte_for_byte_unchanged(monkeypatch):assert run._terminal_password_gate(tunnel_will_start = False, **_RAW_BIND_KWARGS) == (True, False)+def test_a_headless_raw_bind_does_not_open_auth_storage(monkeypatch):+ """"Unchanged" has to mean it does not touch the database either.++ Before this gate learned about non-tunnel exposure, a headless raw bind+ returned at `if not tunnel_will_start` without importing auth storage. If it+ now calls ensure_default_admin() first, first seeding moves earlier and the+ SQLite file is opened sooner, which gives a read-only or locked STUDIO_HOME a+ brand new place to fail on a launch that used to work. So the promptability+ decision has to happen before storage is consulted.+ """+ _patch_streams(monkeypatch, tty = False)++ def _boom(*_a, **_k):+ raise AssertionError(+ "auth storage was opened on a headless raw bind; the gate must "+ "decide it cannot prompt before touching the database"+ )++ from auth import storage as _storage+ monkeypatch.setattr(_storage, "ensure_default_admin", _boom)+ monkeypatch.setattr(_storage, "requires_password_change", _boom)++ assert run._terminal_password_gate(+ tunnel_will_start = False, **_RAW_BIND_KWARGS+ ) == (True, False)+++def test_refusing_the_prompt_on_a_raw_bind_still_launches(monkeypatch):+ """Ctrl+C must not turn a working launch into no Studio.++ `docker/studio_run.sh` execs `unsloth studio -H 0.0.0.0` and only supplies a+ password when the initial-password file is non-empty, so a fresh+ `docker run -it` meets this prompt. Aborting there would stop a container+ that starts today. The launch proceeds at the protection level it already+ had, which is the bootstrap deadline.+ """+ _patch_streams(monkeypatch, tty = True)+ _patch_seeded_admin(monkeypatch, requires_change = True)++ from auth import terminal_prompt+ monkeypatch.setattr(+ terminal_prompt, "prompt_for_password_change",+ lambda **_kw: False, # Ctrl+C / EOF+ )++ # proceed = True, and the bootstrap credential keeps being injected exactly+ # as it was before this prompt existed.+ assert run._terminal_password_gate(+ tunnel_will_start = False, **_RAW_BIND_KWARGS+ ) == (True, False)+++def test_refusing_the_prompt_on_a_tunnel_still_aborts(monkeypatch):+ """The tunnel case is unchanged: refusing to secure a public URL fails closed."""+ _patch_streams(monkeypatch, tty = True)+ _patch_seeded_admin(monkeypatch, requires_change = True)++ from auth import terminal_prompt+ monkeypatch.setattr(+ terminal_prompt, "prompt_for_password_change", lambda **_kw: False+ )++ assert run._terminal_password_gate(+ tunnel_will_start = True, **_GATE_KWARGS+ ) == (False, False)++def test_a_raw_bind_with_a_terminal_reaches_the_prompt(monkeypatch):"""The fix. Before this, `if not tunnel_will_start` returned first."""_patch_streams(monkeypatch, tty = True)diff --git a/studio/backend/tests/test_wildcard_prompt_compatibility.py b/studio/backend/tests/test_wildcard_prompt_compatibility.pynew file mode 100644index 00000000000..e878a516305--- /dev/null+++ b/studio/backend/tests/test_wildcard_prompt_compatibility.py@@ -0,0 +1,151 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Compatibility surface of the raw-bind password prompt.++The prompt itself is covered by test_password_prompt.py and the gate wiring by+test_password_prompt_backstop.py. This file covers the things that only break+somewhere else: other platforms, old installs, and the claim that none of this+touches hardware.+"""++from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path++import pytest++_BACKEND = Path(__file__).resolve().parents[1]+if str(_BACKEND) not in sys.path:+ sys.path.insert(0, str(_BACKEND))++from auth import terminal_prompt # noqa: E402+++# ── platform seams ───────────────────────────────────────────────────+++def test_the_windows_getch_path_decodes_a_password(monkeypatch):+ """`_getch` is selected by os.name at import; exercise the Windows half.++ This box is Linux, so the msvcrt branch is otherwise never executed. A stub+ stands in for the module so the two-wchar arrow-key sequence and ordinary+ characters both go through the real handler.+ """+ import types++ keys = list("pw1\r")+ fake = types.ModuleType("msvcrt")+ # An arrow key arrives as \xe0 then a second wchar that must be swallowed.+ queue = ["\xe0", "H"] + keys++ def _getwch():+ return queue.pop(0)++ fake.getwch = _getwch+ monkeypatch.setitem(sys.modules, "msvcrt", fake)++ out = []+ monkeypatch.setattr(terminal_prompt, "_getch", terminal_prompt._getch_windows)+ monkeypatch.setattr(terminal_prompt, "_prompt_raw_mode", lambda: _NullCtx())++ class _Out:+ encoding = "utf-8"+ def write(self, s): out.append(s)+ def flush(self): pass++ assert terminal_prompt._read_password("pw: ", out = _Out()) == "pw1"+ # The arrow key is swallowed, not masked, so exactly one star per character.+ assert "".join(out).count("*") == 3+++class _NullCtx:+ def __enter__(self): return self+ def __exit__(self, *exc): return False+++def test_a_stream_with_no_fileno_is_not_interactive():+ """pythonw / a Windows service has no console; isatty must not raise.++ _prompt_raw_mode swallows the resulting error, and the gate's own isatty+ helpers treat a broken stream as non-interactive, so such a launch takes the+ headless path rather than crashing.+ """+ class _Broken:+ def isatty(self): raise ValueError("I/O operation on closed file")+ def fileno(self): raise OSError("no console")++ import run as run_mod++ assert run_mod._stream_isatty(_Broken()) is False+ assert run_mod._stream_isatty(None) is False++[email protected]("stdin_tty,stderr_tty", [(True, False), (False, True), (False, False)])+def test_a_split_terminal_never_prompts(stdin_tty, stderr_tty):+ """Masked echo needs stderr; reading needs stdin. Half a terminal is none."""+ assert terminal_prompt.should_prompt_password_change(+ tunnel_will_start = False, bind_is_exposed = True, requires_change = True,+ stdin_isatty = stdin_tty, stderr_isatty = stderr_tty,+ ) is False+++# ── old installs ─────────────────────────────────────────────────────+++def test_an_old_caller_that_omits_bind_is_exposed_behaves_as_before():+ """Forwards compatibility: the new kwarg is optional and defaults off.++ A studio venv can hold an older backend than the CLI that launched it, so a+ caller predating this change must keep tunnel-only semantics.+ """+ assert terminal_prompt.should_prompt_password_change(+ tunnel_will_start = False, requires_change = True,+ stdin_isatty = True, stderr_isatty = True,+ ) is False+ assert terminal_prompt.should_prompt_password_change(+ tunnel_will_start = True, requires_change = True,+ stdin_isatty = True, stderr_isatty = True,+ ) is True+++def test_the_prompt_signature_stays_keyword_compatible():+ """`exposure` must be optional; an older caller passes neither it nor more."""+ import inspect++ params = inspect.signature(terminal_prompt.prompt_for_password_change).parameters+ assert params["exposure"].default == "on the public internet"+ for name, param in params.items():+ assert param.kind is not inspect.Parameter.POSITIONAL_ONLY, name+++# ── no hardware coupling ─────────────────────────────────────────────+++def test_the_password_gate_imports_no_gpu_or_torch_module():+ """The claim that this change is hardware-independent, checked not asserted.++ Run in a subprocess: importing torch in THIS interpreter would poison the+ rest of the session, and a sys.modules probe after the fact proves nothing+ about what the import graph actually pulls in.+ """+ probe = (+ "import sys;"+ f"sys.path.insert(0, {str(_BACKEND)!r});"+ "import auth.terminal_prompt, auth.bootstrap_timeout, utils.host_policy;"+ "bad = sorted(m for m in sys.modules"+ " if m.split('.')[0] in ('torch','triton','bitsandbytes','pynvml','amdsmi'));"+ "print(','.join(bad))"+ )+ out = subprocess.run(+ [sys.executable, "-c", probe],+ capture_output = True, text = True, timeout = 300,+ cwd = str(_BACKEND), env = {**os.environ, "PYTHONPATH": str(_BACKEND)},+ )+ assert out.returncode == 0, out.stderr+ assert out.stdout.strip() == "", (+ f"the password gate pulled in hardware modules: {out.stdout.strip()}"+ )diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.pyindex 59fe067bc7a..b91e465e8ed 100644--- a/unsloth_cli/commands/studio.py+++ b/unsloth_cli/commands/studio.py@@ -1203,12 +1203,23 @@ def _should_prompt_password_change(through this CLI path). --secure implies the tunnel; --cloudflare onlytunnels non-api-only wildcard binds.- A raw wildcard bind counts too, and only when a terminal is attached. It is- reachable by every host on the network, and by the internet on a machine+ A raw non-loopback bind counts too, and only when a terminal is attached. It+ is reachable by every host on the network, and by the internet on a machinewith a public address, while starting no tunnel, so it previously got noprompt, no warning and no strip: the seeded admin password stayed live andwas served in the page to anyone who loaded it.+ is_external_host, NOT is_wildcard_host. The backend gate classifies exposure+ with auth/bootstrap_timeout._is_exposed_bind, which counts anything that is+ not one of the three loopback aliases; wildcard is a strict subset of that.+ Using the narrower test here meant `unsloth studio -H 192.168.1.50`, an+ ordinary LAN bind, skipped the parent prompt and prompted in the re-exec'd+ child instead, and against an OLDER studio-venv child, which the mixed-version+ path explicitly supports and which has no backend gate, it prompted nowhere at+ all and served the seeded password. It is also cheaper: is_wildcard_host runs+ socket.getaddrinfo for any non-literal host, while is_external_host is a+ frozenset membership test.+The interactivity condition is deliberate and is what keeps this safe toship. Everything downstream of here is calibrated to publishing a publicURL: it refuses to launch when the deadline is disabled and it deletes@@ -1219,13 +1230,15 @@ def _should_prompt_password_change("""if secure:return True- from unsloth_cli._tool_policy import is_wildcard_host-- if not is_wildcard_host(host) or api_only:+ if not host or api_only:return False- if cloudflare is True:+ from unsloth_cli._tool_policy import is_external_host, is_wildcard_host++ if cloudflare is True and is_wildcard_host(host):+ # A tunnel launch prompts regardless of the terminal; the headless+ # fallback is handled downstream.return True- return _prompt_streams_interactive()+ return is_external_host(host) and _prompt_streams_interactive()def _prompt_streams_interactive() -> bool:diff --git a/unsloth_cli/tests/test_studio_password_prompt.py b/unsloth_cli/tests/test_studio_password_prompt.pyindex 6783a88f739..62d58182965 100644--- a/unsloth_cli/tests/test_studio_password_prompt.py+++ b/unsloth_cli/tests/test_studio_password_prompt.py@@ -82,25 +82,39 @@ def test_launch_publishes_tunnel_matrix(cloudflare, host, secure, api_only, expe# fallback is handled downstream, not here.*[(c, h, s, a, False, e) for c, h, s, a, e in _TUNNEL_MATRIX if e],*[(c, h, s, a, True, e) for c, h, s, a, e in _TUNNEL_MATRIX if e],- # The change: a RAW wildcard bind with a terminal attached. Reachable by- # every host on the network with the seeded password live, and it starts- # no tunnel, so before this it got no prompt at all.+ # The change: a RAW non-loopback bind with a terminal attached. Reachable+ # by every host on the network with the seeded password live, and it+ # starts no tunnel, so before this it got no prompt at all.(None, "0.0.0.0", False, False, True, True),(False, "0.0.0.0", False, False, True, True),(None, "::", False, False, True, True),(None, "0", False, False, True, True),(None, "::ffff:0.0.0.0", False, False, True, True),+ # Concrete LAN addresses and hostnames, NOT just wildcard spellings. The+ # backend counts these as exposed, so the parent must too; otherwise an+ # older re-exec'd child, which has no backend gate, prompts nowhere.+ (None, "192.168.1.50", False, False, True, True),+ (None, "10.0.0.5", False, False, True, True),+ (None, "172.16.4.9", False, False, True, True),+ (None, "example.com", False, False, True, True),+ (None, "myhost.local", False, False, True, True),+ (None, "[::]", False, False, True, True),# Headless raw binds stay exactly as they were: no prompt, no strip, no# refusal. Long-running containers are the common use of this flag and# the bootstrap deadline is what covers them.(None, "0.0.0.0", False, False, False, False),(False, "0.0.0.0", False, False, False, False),(None, "::", False, False, False, False),+ (None, "192.168.1.50", False, False, False, False),# --api-only authenticates by API key, not the admin password.(None, "0.0.0.0", False, True, True, False),+ (None, "192.168.1.50", False, True, True, False),# Loopback is not exposed, so nothing changes for plain `unsloth studio`.(None, "127.0.0.1", False, False, True, False),(None, "localhost", False, False, True, False),+ (None, "::1", False, False, True, False),+ # An empty host is rejected by the CLI long before this; never prompt on+ # it, even though is_external_host("") is True.(None, "", False, False, True, False),],)@@ -1753,3 +1767,56 @@ def test_studio_default_password_applies_on_headless_wildcard_no_tunnel(monkeypaassert after["must_change_password"] == 0assert after["password_hash"] != before["password_hash"]assert "--password" not in _exec_argv(events)+++# ── CLI / backend exposure agreement ─────────────────────────────────+++_EXPOSURE_HOSTS = [+ # wildcard spellings+ "0.0.0.0", "::", "::0", "0:0:0:0:0:0:0:0", "0", "::ffff:0.0.0.0",+ # loopback aliases+ "127.0.0.1", "localhost", "::1",+ # concrete external addresses and names+ "192.168.1.50", "10.0.0.5", "172.16.4.9", "example.com", "myhost.local",+ # odd spellings+ "[::]", "0.0.0.0.0",+]++[email protected]("host", _EXPOSURE_HOSTS)+def test_cli_and_backend_agree_on_which_hosts_are_exposed(monkeypatch, host):+ """The parent and the child must classify exposure identically.++ They are separate implementations in separate packages (the CLI cannot import+ the backend), and they are consulted at different moments: the parent decides+ before re-exec, the child decides after. When they disagree the prompt lands+ in the child instead of the parent, and against an OLDER studio-venv child,+ which the mixed-version path explicitly supports and which has no gate at all,+ it lands nowhere and the seeded password is served.++ Measured before the fix: wildcard was False but exposed was True for+ 192.168.1.50, 10.0.0.5, example.com, myhost.local, [::] and 0.0.0.0.0.+ """+ import importlib.util++ spec = importlib.util.spec_from_file_location(+ "_bootstrap_timeout_probe",+ _REPO_ROOT / "studio" / "backend" / "auth" / "bootstrap_timeout.py",+ )+ module = importlib.util.module_from_spec(spec)+ sys.path.insert(0, str(_REPO_ROOT / "studio" / "backend"))+ try:+ spec.loader.exec_module(module)+ backend_exposed = module._is_exposed_bind(host, False)+ finally:+ sys.path.remove(str(_REPO_ROOT / "studio" / "backend"))++ monkeypatch.setattr(_studio(), "_prompt_streams_interactive", lambda: True)+ cli_prompts = _studio()._should_prompt_password_change(+ cloudflare = None, host = host, secure = False, api_only = False+ )+ assert cli_prompts is backend_exposed, (+ f"{host!r}: CLI prompts={cli_prompts} but the backend considers it "+ f"exposed={backend_exposed}; the parent gate and the child gate disagree"+ )