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: retire the seeded password on Desktop and keep API callers on Sandbox High (#14422)
Daniel Hanfd8a88d5dfdc
diff --git a/studio/backend/main.py b/studio/backend/main.pyindex a536a789d17..7ed6fee86ff 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -745,7 +745,7 @@ def banner_autofill_available(app_state, environ) -> bool:api_only = getattr(app_state, "api_only", None)if api_only is None:api_only = environ.get("UNSLOTH_API_ONLY") == "1"- # Desktop-owned api-only still serves the UI (and the autofill) to a loopback browser.+ # Desktop-owned: the console gets the path, never the password (desktop logs land in bug reports).return not api_only or _desktop_owner() is not None@@ -967,6 +967,8 @@ async def lifespan(app: FastAPI):_suppress_bootstrap = getattr(app.state, "suppress_bootstrap_injection", False)_created = storage.ensure_default_admin()app.state.bootstrap_password = None if _suppress_bootstrap else storage.get_bootstrap_password()+ # Read by desktop-login, which cannot import this module.+ app.state.desktop_owned = _desktop_owner() is not None# A tunnel launch runs the pre-bind gate first and that gate seeds the account, so# _created is False there and the whole banner would be skipped on exactly the launch# that needs it. requires_password_change: the gate may also have taken a new password@@ -3130,6 +3132,10 @@ def _inject_bootstrap(html_bytes: bytes, app: FastAPI):if installation_has_managed_accounts():return html_bytes, None+ # The desktop shell never reads it, and any local process can fetch this page from loopback.+ if _desktop_owner() is not None:+ return html_bytes, None+bootstrap_pw = getattr(app.state, "bootstrap_password", None)if not bootstrap_pw:return html_bytes, Nonediff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.pyindex 67c40b7882a..be7e1955b71 100644--- a/studio/backend/routes/auth.py+++ b/studio/backend/routes/auth.py@@ -599,6 +599,9 @@ def desktop_login(payload: DesktopLoginRequest, request: Request) -> Token | Res# Safe to clear the aggregate as well now that the address is suffixed: it is this route's own entry,# not /login's, so a desktop success cannot hand anyone a fresh password-guessing budget._clear_login_bucket(key)+ # Shell-owned backends never use the seeded password; terminal-started ones keep the web autofill.+ if getattr(request.app.state, "desktop_owned", False):+ request.app.state.bootstrap_password = Nonefrom auth.policy import installation_is_multi_userdiff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 8d6c89794b4..6c2b61bfda6 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -5280,6 +5280,7 @@ def _admit_tool_access(payload) -> None:getattr(payload, "permission_mode", None),bypass_permissions = bool(getattr(payload, "bypass_permissions", False)),disable_sandbox = bool(getattr(payload, "disable_sandbox", False)),+ sandbox_level = getattr(payload, "sandbox_level", None),)diff --git a/studio/backend/state/tool_policy.py b/studio/backend/state/tool_policy.pyindex 545f74dc042..2cf6c86e60c 100644--- a/studio/backend/state/tool_policy.py+++ b/studio/backend/state/tool_policy.py@@ -45,8 +45,19 @@ def require_tool_access(*,bypass_permissions: bool = False,disable_sandbox: bool = False,+ sandbox_level: Optional[str] = None,) -> None:if permission_mode != "full" and not bypass_permissions and not disable_sandbox:+ if sandbox_level == "low":+ from auth.policy import api_full_access_refused+ if api_full_access_refused():+ from fastapi import HTTPException+ raise HTTPException(+ status_code = 400,+ detail = "Sandbox Low (sandbox_level 'low') is off for API keys: Python and Terminal "+ "run in the OS sandbox. Use sandbox_level 'high', or set "+ "UNSLOTH_STUDIO_ALLOW_API_FULL_ACCESS=1 on the server to allow it.",+ )returnfrom auth.policy import api_full_access_refused, full_access_permittedfrom fastapi import HTTPExceptiondiff --git a/studio/backend/tests/test_api_key_sandbox_level.py b/studio/backend/tests/test_api_key_sandbox_level.pynew file mode 100644index 00000000000..6c54f0e0d60--- /dev/null+++ b/studio/backend/tests/test_api_key_sandbox_level.py@@ -0,0 +1,114 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Sandbox Low (python/terminal without the OS sandbox) is the Unsloth UI's to pick, like full access."""++import pytest+from fastapi import FastAPI, HTTPException+from fastapi.testclient import TestClient++from auth.authentication import get_current_subject+from routes import inference+from state.tool_policy import require_tool_access+from utils.account_context import OWNER, as_api_caller, bind_account, reset_account++_OPT_IN = "UNSLOTH_STUDIO_ALLOW_API_FULL_ACCESS"++[email protected](autouse = True)+def no_opt_in(monkeypatch):+ monkeypatch.delenv(_OPT_IN, raising = False)+++def _under(account, *args, **kwargs):+ token = bind_account(account)+ try:+ require_tool_access(*args, **kwargs)+ finally:+ reset_account(token)++[email protected]("mode", [None, "auto", "ask", "off"])+def test_sandbox_level_low_is_refused_for_api_callers(mode):+ with pytest.raises(HTTPException) as refused:+ _under(as_api_caller(OWNER), mode, sandbox_level = "low")+ assert refused.value.status_code == 400+ assert _OPT_IN in refused.value.detail+ _under(as_api_caller(OWNER), mode, sandbox_level = "high")+ _under(as_api_caller(OWNER), mode)++[email protected]("level", ["low", "high", None])+def test_owner_ui_session_keeps_sandbox_low(level):+ _under(OWNER, "auto", sandbox_level = level)+++def test_operator_opt_in_restores_api_sandbox_low(monkeypatch):+ monkeypatch.setenv(_OPT_IN, "1")+ _under(as_api_caller(OWNER), "auto", sandbox_level = "low")+++def _client_for(account):+ app = FastAPI()++ async def subject():+ token = bind_account(account)+ try:+ yield account.username+ finally:+ reset_account(token)++ app.dependency_overrides[get_current_subject] = subject+ app.include_router(inference.router, prefix = "/v1")+ return TestClient(app)+++_REQUESTS = {+ "/v1/chat/completions": {"model": "m", "messages": [{"role": "user", "content": "hi"}]},+ "/v1/messages": {+ "model": "m",+ "max_tokens": 8,+ "messages": [{"role": "user", "content": "hi"}],+ },+}++[email protected]("path", sorted(_REQUESTS))[email protected]("api", [True, False], ids = ["api_key", "ui_session"])+def test_the_door_refuses_only_api_key_sandbox_low(monkeypatch, path, api):+ def backend(*_args, **_kwargs):+ raise HTTPException(status_code = 503, detail = "no backend in this test")++ monkeypatch.setattr(inference, "get_llama_cpp_backend", backend)+ monkeypatch.setattr(inference, "produce_openai_chat_completions", backend)+ body = {**_REQUESTS[path], "sandbox_level": "low"}+ with _client_for(as_api_caller(OWNER) if api else OWNER) as client:+ response = client.post(path, json = body)+ if api:+ assert response.status_code == 400, response.text+ assert _OPT_IN in response.json()["detail"]+ else:+ assert response.status_code == 503, response.text++[email protected]("api", [True, False], ids = ["api_key", "ui_session"])+def test_durable_chat_runs_refuse_api_key_sandbox_low_before_queueing(api):+ from routes import chat_generation_runs as runs++ payload = runs.CreateChatGenerationRun(+ runId = "r1",+ threadId = "t1",+ userMessageId = "u1",+ assistantMessageId = "a1",+ requestPayload = {"messages": [{"role": "user", "content": "hi"}], "sandbox_level": "low"},+ )+ token = bind_account(as_api_caller(OWNER) if api else OWNER)+ try:+ if api:+ with pytest.raises(HTTPException) as refused:+ runs._sanitize_request(payload)+ assert refused.value.status_code == 400 and _OPT_IN in refused.value.detail+ else:+ runs._sanitize_request(payload)+ finally:+ reset_account(token)diff --git a/studio/backend/tests/test_desktop_bootstrap_retired.py b/studio/backend/tests/test_desktop_bootstrap_retired.pynew file mode 100644index 00000000000..abf6d04e9a7--- /dev/null+++ b/studio/backend/tests/test_desktop_bootstrap_retired.py@@ -0,0 +1,112 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""A desktop-owned backend never hands the seeded password to a page, and a verified desktop sign-in retires it."""++import importlib.util+import secrets+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth import policy, storage++_HTML = b"<html><head></head><body>Studio</body></html>"+_DESKTOP = {"kind": "tauri", "token_sha256": "0" * 64}++[email protected](autouse = True)+def auth_db(tmp_path, monkeypatch):+ monkeypatch.setattr(storage, "DB_PATH", tmp_path / "auth.db")+ monkeypatch.setattr(storage, "_BOOTSTRAP_PW_PATH", tmp_path / ".bootstrap_password")+ monkeypatch.setattr(storage, "_bootstrap_password", None)+ monkeypatch.setattr(storage, "_api_key_pbkdf2_salt_cache", None)+ monkeypatch.setattr(storage, "_credential_encryption_key_cache", None)+ policy.invalidate_account_cache()+ storage.create_initial_user(+ username = storage.DEFAULT_ADMIN_USERNAME,+ password = "seeded-password-123",+ jwt_secret = secrets.token_urlsafe(64),+ must_change_password = True,+ )+ yield+ policy.invalidate_account_cache()+++def _app_state():+ return SimpleNamespace(state = SimpleNamespace(bootstrap_password = "seeded-password-123"))+++def test_desktop_owned_backend_never_injects_the_seeded_password(monkeypatch):+ import main++ monkeypatch.setattr(main, "_DESKTOP_OWNER", dict(_DESKTOP))+ html, nonce = main._inject_bootstrap(_HTML, _app_state())+ assert nonce is None+ assert b"__UNSLOTH_BOOTSTRAP__" not in html+ assert b"seeded-password-123" not in html+++def test_web_backend_still_injects_the_seeded_password(monkeypatch):+ import main++ monkeypatch.setattr(main, "_DESKTOP_OWNER", None)+ html, nonce = main._inject_bootstrap(_HTML, _app_state())+ assert nonce+ assert b"window.__UNSLOTH_BOOTSTRAP__=" in html and b"seeded-password-123" in html+++def test_desktop_banner_keeps_the_password_out_of_the_log(monkeypatch):+ import main++ monkeypatch.setattr(main, "_DESKTOP_OWNER", dict(_DESKTOP))+ state = SimpleNamespace(api_only = True)+ assert main.banner_autofill_available(state, {}) is True+++def _auth_app(*, desktop_owned = True):+ route_path = Path(__file__).resolve().parents[1] / "routes" / "auth.py"+ spec = importlib.util.spec_from_file_location("_desktop_bootstrap_route", route_path)+ auth_route = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(auth_route)+ app = FastAPI()+ app.include_router(auth_route.router, prefix = "/api/auth")+ app.state.bootstrap_password = "seeded-password-123"+ app.state.desktop_owned = desktop_owned+ return app+++def test_verified_desktop_login_retires_the_bootstrap_password():+ raw = storage.create_desktop_secret()+ app = _auth_app()+ with TestClient(app) as client:+ response = client.post("/api/auth/desktop-login", json = {"secret": raw})+ assert response.status_code == 200, response.text+ assert app.state.bootstrap_password is None+ # The web first-run flow is untouched: the account still has to change its password.+ assert storage.requires_password_change(storage.DEFAULT_ADMIN_USERNAME) is True+++def test_desktop_login_to_an_ownerless_backend_keeps_the_web_autofill():+ raw = storage.create_desktop_secret()+ app = _auth_app(desktop_owned = False)+ with TestClient(app) as client:+ response = client.post("/api/auth/desktop-login", json = {"secret": raw})+ assert response.status_code == 200, response.text+ assert app.state.bootstrap_password == "seeded-password-123"+++def test_failed_desktop_login_probe_keeps_the_bootstrap_password():+ storage.create_desktop_secret()+ app = _auth_app()+ with TestClient(app) as client:+ malformed = client.post("/api/auth/desktop-login", json = {"secret": "desktop-invalid"})+ wrong_secret = storage.DESKTOP_SECRET_PREFIX + secrets.token_urlsafe(48)+ assert storage.desktop_secret_is_well_formed(wrong_secret)+ wrong = client.post("/api/auth/desktop-login", json = {"secret": wrong_secret})+ assert malformed.status_code == 401+ assert wrong.status_code == 401+ assert app.state.bootstrap_password == "seeded-password-123"