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: harden the server against stalled bodies, long login names, readable logs and managed-account fetches (#14426)
Daniel Han49d38a46591f
diff --git a/studio/backend/core/inference/llama_server_args.py b/studio/backend/core/inference/llama_server_args.pyindex 3644f47df82..918e08bb18d 100644--- a/studio/backend/core/inference/llama_server_args.py+++ b/studio/backend/core/inference/llama_server_args.py@@ -180,9 +180,28 @@ OWNER_ONLY_PATH_FLAGS: frozenset[str] = frozenset("--video-ffmpeg-dir",# Not a path: llama-server sends the model's tensors to these hosts."--rpc",+ # Not a path either: llama-server downloads these Hub drafters with the installation's HF token.+ "-hfd",+ "-hfrd",+ "--hf-repo-draft",+ "--spec-draft-hf",+ "-hffd",+ "--hf-file-draft",})+# Built-in presets (--*-default, older --fim-qwen-7b-spec) fetch a Hub repo with the HF token; --spec-default stays open.+_PRESET_FLAG_RE = re.compile(r"^--[a-z0-9.-]+-default$|^--fim-[a-z0-9.-]+-spec$")+_NON_PRESET_DEFAULT_FLAGS: frozenset[str] = frozenset({"--spec-default"})+++def _is_preset_flag(flag: Optional[str]) -> bool:+ return (+ flag is not None+ and flag not in _NON_PRESET_DEFAULT_FLAGS+ and _PRESET_FLAG_RE.match(flag.lower()) is not None+ )+def owner_only_path_args(args: Optional[Iterable[str]]) -> list[tuple[str, str]]:"""``(flag, value)`` for each OWNER_ONLY_PATH_FLAGS occurrence in ``args``, in order."""@@ -193,6 +212,8 @@ def owner_only_path_args(args: Optional[Iterable[str]]) -> list[tuple[str, str]]if flag in OWNER_ONLY_PATH_FLAGS:_, eq, inline = raw.partition("=")found.append((flag, inline if eq else (tokens[i + 1] if i + 1 < len(tokens) else "")))+ elif _is_preset_flag(flag):+ found.append((flag, ""))return founddiff --git a/studio/backend/main.py b/studio/backend/main.pyindex 7ed6fee86ff..20b3d71c451 100644--- a/studio/backend/main.py+++ b/studio/backend/main.py@@ -1761,6 +1761,11 @@ from utils.model_aliases import ModelAliasMiddleware # noqa: E402app.add_middleware(ModelAliasMiddleware)+# Idle auto-unload request tracker; added before MaxBodyMiddleware so only fully received requests count.+from core.inference.llama_keepwarm import LlamaKeepWarmMiddleware # noqa: E402++app.add_middleware(LlamaKeepWarmMiddleware)+app.add_middleware(MaxBodyMiddleware,max_bytes_getter = default_request_body_limit_bytes,@@ -1773,11 +1778,6 @@ app.add_middleware(upload_passthrough_pattern = _UPLOAD_PASSTHROUGH_RE,)-# Tracks in-flight inference requests for idle auto-unload; off -> passthrough.-from core.inference.llama_keepwarm import LlamaKeepWarmMiddleware # noqa: E402--app.add_middleware(LlamaKeepWarmMiddleware)-from starlette.responses import RedirectResponse as _RedirectResponse # noqa: E402diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.pyindex be7e1955b71..1f989f80f8e 100644--- a/studio/backend/routes/auth.py+++ b/studio/backend/routes/auth.py@@ -7,6 +7,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request, Response, statusfrom fastapi.security import HTTPAuthorizationCredentialsimport base64+import hashlibimport importlib.utilimport ipaddressimport os@@ -294,8 +295,15 @@ def _client_ip(request: Request | None) -> str:return (request.client.host if request.client else None) or "_unknown"+_MAX_BUCKET_USERNAME_CHARS = 256++def _bucket_key(request: Request | None, username: str) -> tuple[str, str]:- return (_client_ip(request), (username or "").casefold())+ name = (username or "").casefold()+ # Bound the memory each bucket key holds; real usernames are far shorter and keep their own key.+ if len(name) > _MAX_BUCKET_USERNAME_CHARS:+ name = "\x00long:" + hashlib.sha256(name.encode("utf-8", "surrogatepass")).hexdigest()+ return (_client_ip(request), name)def _unknown_user_key(request: Request | None) -> tuple[str, str]:diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 6c2b61bfda6..6be23286e8b 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -28730,8 +28730,28 @@ def _video_scheme_rejection(clip: str) -> Optional[tuple[int, str]]:finds the same way, honouring ``file://`` under ``--media-path``. Forwarding such a clip asopaque payload is therefore still a local file read, so refuse it by name instead."""- if not clip or clip[:5].lower() == "data:" or _is_remote_video(clip):+ if not clip or _is_remote_video(clip):return None+ if clip[:5].lower() == "data:":+ # Skip every data: header (bounded) and judge what follows like any other clip.+ pos = 0+ while clip[pos : pos + 5].lower() == "data:":+ comma = clip.find(",", pos, pos + 256)+ if comma < 0:+ # No payload separator within a real header's length: never forward it as data.+ return (400, "Unsupported video payload in data URI. Send the clip as base64 data.")+ pos = comma + 1+ rest = clip[pos : pos + _MAX_VIDEO_SCHEME_CHARS + 1]+ if ":" not in rest:+ return None+ return (+ _REMOTE_VIDEO_REFUSAL+ if _is_remote_video(rest)+ else (+ 400,+ "Unsupported video payload in data URI. Send the clip as base64 data.",+ )+ )# ':' is not in the base64 alphabet, so an early colon marks a URL, not payload.head = clip[: _MAX_VIDEO_SCHEME_CHARS + 1]if ":" not in head:@@ -40553,6 +40573,9 @@ async def openai_embeddings(request: Request, current_subject: str = Depends(get# llama-server ignores `dimensions`; checked against the returned width below.body = dict(body)+ if account_access.managed_account():+ # llama-server fetches media URLs inside multimodal items; a managed account sends text or tokens only.+ _embeddings_items(body, tokens_ok = True)dimensions = body.pop("dimensions", None)target_url = f"{llama_backend.base_url}/v1/embeddings"prompt_text = _flatten_monitor_prompt(body.get("input", ""))diff --git a/studio/backend/run.py b/studio/backend/run.pyindex 2502b14ce72..5aabc633e9c 100644--- a/studio/backend/run.py+++ b/studio/backend/run.py@@ -1958,6 +1958,25 @@ def _harden_console_close(stream):pass+def _restrict_server_log_perms(log_dir: Path) -> None:+ """Best-effort owner-only modes on the server log dir and its existing session logs (POSIX only)."""+ if os.name == "nt":+ return+ try:+ os.chmod(log_dir, 0o700)+ except OSError:+ pass+ try:+ for old_log in log_dir.glob("server-*.log"):+ try:+ if not old_log.is_symlink() and old_log.stat().st_mode & 0o077:+ os.chmod(old_log, 0o600)+ except OSError:+ pass+ except OSError:+ pass++def _setup_server_disk_logging():"""Tee stdout/stderr to ~/.unsloth/studio/logs/server/ and aim faulthandler at the same file so hardcrashes (access violations / SIGSEGV in the GPU runtime) leave a stack trace on disk. Also exports@@ -1976,12 +1995,20 @@ def _setup_server_disk_logging():)log_dir = Path(home) / "logs" / "server"try:- log_dir.mkdir(parents = True, exist_ok = True)+ log_dir.mkdir(parents = True, exist_ok = True, mode = 0o700)+ _restrict_server_log_perms(log_dir)stamp = time.strftime("%Y%m%d-%H%M%S")log_path = log_dir / f"server-{stamp}-pid{os.getpid()}.log"+ # Owner-only from creation: the session log carries the startup banner's API key.+ fd = os.open(str(log_path), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ if os.name != "nt":+ try:+ os.fchmod(fd, 0o600)+ except OSError:+ pass# Line-buffered so the tail survives a hard kill; errors="replace" so a console encoding quirk can# never take the server down.- log_fh = open(log_path, "w", encoding = "utf-8", errors = "replace", buffering = 1)+ log_fh = os.fdopen(fd, "w", encoding = "utf-8", errors = "replace", buffering = 1)except Exception:return Nonediff --git a/studio/backend/tests/test_middleware.py b/studio/backend/tests/test_middleware.pyindex 92994fa50bd..bbba2c42626 100644--- a/studio/backend/tests/test_middleware.py+++ b/studio/backend/tests/test_middleware.py@@ -1767,3 +1767,80 @@ def test_delete_bodies_and_root_path_are_capped(main_module):# The root_path prefix in scope["path"] does not hide the protected prefix.assert c.post("/studio/api/models/delete-cached", content = b"x" * 512).status_code == 413assert c.post("/studio/api/models/delete-cached", content = b"x" * 64).json() == {"total": 64}+++def test_a_withheld_body_is_not_counted_as_running_inference(main_module, health_app):+ """Keep-warm runs inside the body limiter: a request is counted once its body is here.++ A model switch drains the in-flight count with no time limit, holding the gate every chat request needs, and+ nothing bounds how long a client may withhold a body. Counted from the headers on, an anonymous POST that never+ sent one stayed in flight until its socket closed: the 401 that uncounts it comes from the route, after the body.+ """+ from auth import storage+ from auth.authentication import create_access_token+ from core.inference import llama_keepwarm, media_keepwarm++ async def counted_while_withheld(path: str, headers: dict) -> int:+ waiting, hang_up = asyncio.Event(), asyncio.Event()++ async def receive():+ waiting.set()+ await hang_up.wait()+ return {"type": "http.disconnect"}++ async def send(message):+ pass++ scope = {+ "type": "http",+ "asgi": {"version": "3.0"},+ "http_version": "1.1",+ "method": "POST",+ "scheme": "http",+ "path": path,+ "raw_path": path.encode(),+ "query_string": b"",+ "root_path": "",+ "headers": [(k.lower().encode(), v.encode()) for k, v in headers.items()],+ "client": ("203.0.113.7", 5555),+ "server": ("127.0.0.1", 8888),+ }+ request = asyncio.ensure_future(main_module.app(scope, receive, send))+ asked = asyncio.ensure_future(waiting.wait())+ # Either the body is being waited for, or the route refused the request before asking for one.+ await asyncio.wait({request, asked}, return_when = asyncio.FIRST_COMPLETED)+ counted = llama_keepwarm.other_inference_request_count(current_request_counted = False)+ counted += sum(+ media_keepwarm.other_request_count(owner)+ for owner in set(media_keepwarm._TRACKED_PATHS.values())+ )+ hang_up.set()+ asked.cancel()+ await request+ return counted++ tracked = {+ *(+ prefix.rstrip("/") + suffix+ for prefix in llama_keepwarm._INFERENCE_PREFIXES+ for suffix in llama_keepwarm._INFERENCE_SUFFIXES+ ),+ *llama_keepwarm._INFERENCE_EXACT_PATHS,+ *media_keepwarm._TRACKED_PATHS,+ "/p/run/v1/chat/completions",+ "/p/run/checkpoint-1/v1/chat/completions",+ }+ session = create_access_token(subject = storage.DEFAULT_ADMIN_USERNAME)+ for path in sorted(tracked):+ for framing in ({"Content-Length": "2"}, {"Transfer-Encoding": "chunked"}):+ for credential in ({}, {"Authorization": f"Bearer {session}"}):+ if (+ credential+ and "Content-Length" in framing+ and path in main_module._VIDEO_MULTIPART_UPLOAD_PATHS+ ):+ # The videos upload passes through on its Content-Length; its route reads the multipart body+ # itself, after the auth dependencies, so only a credentialed client can hold it counted.+ continue+ headers = {"Content-Type": "application/json", **framing, **credential}+ assert asyncio.run(counted_while_withheld(path, headers)) == 0, (path, headers)diff --git a/studio/backend/tests/test_server_hardening.py b/studio/backend/tests/test_server_hardening.pynew file mode 100644index 00000000000..b4b6c29991c--- /dev/null+++ b/studio/backend/tests/test_server_hardening.py@@ -0,0 +1,244 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Server hardening: login limiter key size, session log modes, vision probe argv, owner-only+llama-server Hub flags, video data URI payloads and managed embeddings input."""++import asyncio+import os+import stat+import subprocess+import sys+from types import SimpleNamespace++import pytest+from fastapi import HTTPException++_backend = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+if _backend not in sys.path:+ sys.path.insert(0, _backend)+++# Login limiter key+++def test_login_bucket_key_is_bounded_for_long_usernames():+ from routes import auth as auth_route++ huge = "A" * (1 << 20)+ ip, name = auth_route._bucket_key(None, huge)+ assert len(name) < 128+ # Same name, same bucket; different names, different buckets.+ assert auth_route._bucket_key(None, huge.lower()) == (ip, name)+ assert auth_route._bucket_key(None, huge + "b")[1] != name+ # Normal usernames keep their casefolded key.+ assert auth_route._bucket_key(None, "Alice") == ("_unknown", "alice")+ assert auth_route._bucket_key(None, "x" * 256) == ("_unknown", "x" * 256)+++# Session log modes++[email protected](os.name == "nt", reason = "POSIX file modes")+def test_server_session_log_is_owner_only(tmp_path, monkeypatch):+ import faulthandler++ import run as run_mod++ home = tmp_path / "studio"+ old_dir = home / "logs" / "server"+ old_dir.mkdir(parents = True)+ os.chmod(old_dir, 0o755)+ old_log = old_dir / "server-20200101-000000-pid1.log"+ old_log.write_text("old session\n")+ os.chmod(old_log, 0o644)++ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(home))+ monkeypatch.delenv("UNSLOTH_STUDIO_NO_FILE_LOG", raising = False)+ monkeypatch.setattr(sys, "stdout", sys.stdout)+ monkeypatch.setattr(sys, "stderr", sys.stderr)+ previous = os.umask(0o022)+ try:+ log_path = run_mod._setup_server_disk_logging()+ # Idempotent: a second start leaves the same modes.+ second = run_mod._setup_server_disk_logging()+ finally:+ os.umask(previous)+ faulthandler.disable()+ assert log_path is not None and second is not None+ assert log_path.parent == old_dir+ for path in (log_path, second, old_log):+ assert stat.S_IMODE(path.stat().st_mode) & 0o077 == 0, path+ assert stat.S_IMODE(old_dir.stat().st_mode) & 0o077 == 0+ assert old_log.read_text() == "old session\n"+++# Vision probe argv+++def test_vision_probe_passes_the_token_in_env_not_argv(monkeypatch):+ from utils.models import model_config++ seen = {}++ def fake_run(command, **kwargs):+ seen["command"] = list(command)+ seen["env"] = dict(kwargs.get("env") or {})+ return subprocess.CompletedProcess(command, 0, stdout = '{"is_vision": false}', stderr = "")++ monkeypatch.setattr(model_config.subprocess, "run", fake_run)+ model_config._is_vision_model_subprocess("org/some-model", hf_token = "hf_secret_value_123")+ assert seen, "probe did not run"+ assert not any("hf_secret_value_123" in str(arg) for arg in seen["command"])+ # The argv slot stays so the child script's layout is unchanged.+ assert seen["command"][6] == ""+ assert seen["env"].get("HF_TOKEN") == "hf_secret_value_123"+++# llama-server Hub drafter and preset flags+++ "args",+ [+ ["-hfd", "owner/private-draft-GGUF"],+ ["-hfrd", "owner/private-draft-GGUF"],+ ["--hf-repo-draft=owner/private-draft-GGUF"],+ ["--spec-draft-hf", "owner/private-draft-GGUF"],+ ["--fim-qwen-1.5b-default"],+ ["--embd-gemma-default"],+ ["--gpt-oss-20b-default"],+ ["--vision-gemma-4b-default"],+ ["--fim-qwen-7b-spec"],+ ],+)+def test_hub_drafter_and_preset_flags_are_owner_only(args, monkeypatch):+ from core.inference import llama_server_args as lsa++ assert lsa.owner_only_path_flags(args), args++ inference_route = pytest.importorskip("routes.inference")+ monkeypatch.setattr(inference_route.account_access, "managed_account", lambda: True)+ monkeypatch.setattr(inference_route, "_owner_chosen_launch", lambda *a, **k: set())+ with pytest.raises(HTTPException) as exc:+ inference_route._refuse_managed_custom_projector(args, "org/model")+ assert exc.value.status_code == 403+++def test_spec_default_and_tuning_flags_stay_open():+ from core.inference import llama_server_args as lsa+ assert lsa.owner_only_path_flags(["--spec-default", "--ctx-size", "4096", "-ngl", "99"]) == []+++# Video data URI payload+++def test_video_data_uri_must_carry_payload_not_a_url():+ inference_route = pytest.importorskip("routes.inference")+ reject = inference_route._video_scheme_rejection+ for clip in (+ "data:video/mp4;base64,http://127.0.0.1:9/x.mp4",+ "data:video/mp4;base64,HTTPS://10.0.0.1/x.mp4",+ "data:video/mp4;base64,data:video/mp4;base64,http://127.0.0.1:9/x",+ "data:video/mp4;base64,file:///etc/passwd",+ "data:video/mp4;" + "x" * 300 + ",http://127.0.0.1:9/x.mp4",+ ):+ rejection = reject(clip)+ assert rejection is not None and rejection[0] == 400, clip+ # A real clip and the shapes handled elsewhere are unchanged.+ assert reject("data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28y" + "A" * 64) is None+ assert reject("") is None+ assert reject("http://example.com/x.mp4") is None+++# Managed embeddings input+++class _Request:+ def __init__(self, body):+ self._body = body+ self.method = "POST"+ self.url = SimpleNamespace(path = "/v1/embeddings")+ self.state = SimpleNamespace(skip_api_monitor = True)+ self.scope = {"type": "http", "path": "/v1/embeddings"}+ self.headers = {}++ async def json(self):+ return self._body++ async def is_disconnected(self):+ return False+++def _embeddings_proxy(monkeypatch, managed):+ import httpx++ inference_route = pytest.importorskip("routes.inference")+ posted = []++ class _Client:+ async def post(+ self,+ url,+ json = None,+ **_kwargs,+ ):+ posted.append(json)+ return httpx.Response(200, json = {"data": [{"embedding": [0.5]}]})++ async def aclose(self):+ return None++ async def passthrough(request, current_subject, **_kwargs):+ return await request.json()++ async def no_studio_request(request):+ return None++ monkeypatch.setattr(inference_route.account_access, "managed_account", lambda: managed)+ monkeypatch.setattr(inference_route, "_should_validate_before_switch", lambda: False)+ monkeypatch.setattr(inference_route, "_studio_embedder_request_body", no_studio_request)+ monkeypatch.setattr(inference_route, "_auto_switch_from_request_body", passthrough)+ monkeypatch.setattr(inference_route, "_cancelable_nonstreaming_client", _Client)+ monkeypatch.setattr(+ inference_route,+ "get_llama_cpp_backend",+ lambda: SimpleNamespace(+ is_loaded = True,+ is_embedding_gguf = True,+ base_url = "http://llama.test",+ context_length = 512,+ model_identifier = "org/E-GGUF",+ ),+ )+ monkeypatch.setattr(inference_route, "_resident_serves_embeddings", lambda backend: True)+ return inference_route, posted+++_IMAGE_ITEM = {+ "input": [+ {"content": [{"type": "image_url", "image_url": {"url": "http://127.0.0.1:9/a.png"}}]}+ ],+ "model": "org/E-GGUF",+}+++def test_managed_embeddings_refuse_multimodal_items(monkeypatch):+ inference_route, posted = _embeddings_proxy(monkeypatch, managed = True)+ with pytest.raises(HTTPException) as exc:+ asyncio.run(inference_route.openai_embeddings(_Request(dict(_IMAGE_ITEM)), "member"))+ assert exc.value.status_code == 400+ assert posted == []+ # Text still goes through for a managed account.+ asyncio.run(+ inference_route.openai_embeddings(+ _Request({"input": ["alpha"], "model": "org/E-GGUF"}), "member"+ )+ )+ assert posted and posted[-1]["input"] == ["alpha"]+++def test_owner_embeddings_keep_multimodal_items(monkeypatch):+ inference_route, posted = _embeddings_proxy(monkeypatch, managed = False)+ asyncio.run(inference_route.openai_embeddings(_Request(dict(_IMAGE_ITEM)), "owner"))+ assert posted and posted[-1]["input"] == _IMAGE_ITEM["input"]diff --git a/studio/backend/tests/test_vision_cache.py b/studio/backend/tests/test_vision_cache.pyindex cb826007fd7..de26a27f4ea 100644--- a/studio/backend/tests/test_vision_cache.py+++ b/studio/backend/tests/test_vision_cache.py@@ -619,7 +619,9 @@ class TestRevisionAwareVisionDetection:)is False)- assert run.call_args.args[0][-3:] == ["org/model", "hf_x", "commit-a"]+ # The token rides in the child env only; its argv slot stays, empty.+ assert run.call_args.args[0][-3:] == ["org/model", "", "commit-a"]+ assert run.call_args.kwargs["env"]["HF_TOKEN"] == "hf_x"assert 'kwargs["revision"] = revision' in run.call_args.args[0][2]diff --git a/studio/backend/utils/models/model_config.py b/studio/backend/utils/models/model_config.pyindex ed52b8967e9..e5dd412c495 100644--- a/studio/backend/utils/models/model_config.py+++ b/studio/backend/utils/models/model_config.py@@ -979,7 +979,7 @@ def _build_vision_check_inline_helpers() -> str:)-# Subprocess script run with transformers 5.x active: model_name + token via argv, JSON out.+# Subprocess script run with transformers 5.x active: model_name via argv, token via env, JSON out.def _build_vision_check_script() -> str:return (r"""@@ -1102,8 +1102,8 @@ def _is_vision_model_subprocess(or None for transient failures (timeouts, subprocess errors), which are notcached so they can be retried."""- # Only an explicit token travels in argv; the env below enforces the boundary.- token_arg = hf_token if isinstance(hf_token, str) else ""+ # Token only via the child env (argv is world-readable); the empty slot keeps the argv layout.+ token_arg = ""# Latest-only architectures need the latest sidecar for AutoConfig; other tiers keep 5.5.sidecar_dir = _VENV_T5_DIR