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: do not lend the backend's HF_TOKEN to API key callers (#8433)
Daniel Han6b3868ab131d
diff --git a/studio/backend/auth/authentication.py b/studio/backend/auth/authentication.pyindex b5214f6ac16..768a15a836b 100644--- a/studio/backend/auth/authentication.py+++ b/studio/backend/auth/authentication.py@@ -186,6 +186,17 @@ async def authenticated_via_api_key(return bool(credentials and credentials.credentials.startswith(API_KEY_PREFIX))+async def allow_ambient_hf_token(via_api_key: bool = Depends(authenticated_via_api_key)) -> bool:+ """Whether a download this caller starts may fall back to the backend's own HF_TOKEN.++ A UI session already gets the saved token from Settings, so the ambient one grants it+ nothing new. ``require_ui_session`` refuses an sk-unsloth API key that same token, so it+ must not reach private repos by naming one in a download instead; it sends its own token+ in ``X-Unsloth-HF-Token``.+ """+ return not via_api_key++async def authenticated_via_desktop_jwt(credentials: HTTPAuthorizationCredentials = Depends(security),) -> bool:diff --git a/studio/backend/hub/routes/datasets.py b/studio/backend/hub/routes/datasets.pyindex 380090691c1..7bfa1af9f81 100644--- a/studio/backend/hub/routes/datasets.py+++ b/studio/backend/hub/routes/datasets.py@@ -9,7 +9,7 @@ from typing import Optionalfrom fastapi import APIRouter, Body, Depends, File, Form, Query, UploadFile-from auth.authentication import get_current_subject+from auth.authentication import allow_ambient_hf_token, get_current_subjectfrom hub.dependencies import get_hf_tokenfrom hub.schemas.datasets import (AiAssistMappingRequest,@@ -97,9 +97,14 @@ async def get_dataset_download_progress(async def download_dataset(body: DownloadDatasetRequest,hf_token: Optional[str] = Depends(get_hf_token),+ allow_ambient_token: bool = Depends(allow_ambient_hf_token),current_subject: str = Depends(get_current_subject),):- return await downloads.download_dataset_response(body, hf_token)+ return await downloads.download_dataset_response(+ body,+ hf_token,+ allow_ambient_token = allow_ambient_token,+ )@router.post("/download/cancel", response_model = CancelDatasetDownloadResponse, status_code = 202)diff --git a/studio/backend/hub/routes/inventory.py b/studio/backend/hub/routes/inventory.pyindex b3bc0b310da..a6fd8055538 100644--- a/studio/backend/hub/routes/inventory.py+++ b/studio/backend/hub/routes/inventory.py@@ -9,7 +9,7 @@ from typing import Optionalfrom fastapi import APIRouter, Body, Depends, Query-from auth.authentication import get_current_subject+from auth.authentication import allow_ambient_hf_token, get_current_subjectfrom hub.dependencies import get_hf_tokenfrom hub.schemas.downloads import (ActiveDownloadsResponse,@@ -125,9 +125,14 @@ async def get_gguf_variants(async def download_model(body: DownloadModelRequest,hf_token: Optional[str] = Depends(get_hf_token),+ allow_ambient_token: bool = Depends(allow_ambient_hf_token),current_subject: str = Depends(get_current_subject),):- return await downloads.download_model_response(body, hf_token)+ return await downloads.download_model_response(+ body,+ hf_token,+ allow_ambient_token = allow_ambient_token,+ )@router.post("/download/cancel", response_model = CancelDownloadResponse, status_code = 202)diff --git a/studio/backend/hub/services/datasets/downloads.py b/studio/backend/hub/services/datasets/downloads.pyindex 5b31013069f..ddd90c4b675 100644--- a/studio/backend/hub/services/datasets/downloads.py+++ b/studio/backend/hub/services/datasets/downloads.py@@ -144,9 +144,16 @@ def _dataset_status(key: str, *, repo_id: Optional[str] = None) -> DatasetDownloasync def download_dataset_response(- body: DownloadDatasetRequest, hf_token: Optional[str] = None+ body: DownloadDatasetRequest,+ hf_token: Optional[str] = None,+ *,+ allow_ambient_token: bool = True,) -> dict:- """Start a background download for a HuggingFace dataset."""+ """Start a background download for a HuggingFace dataset.++ ``allow_ambient_token=False`` keeps the worker anonymous when the caller sent no token, for+ repos named over the API rather than chosen here.+ """repo_id = body.repo_id.strip()if not _is_valid_repo_id(repo_id):raise HTTPException(@@ -210,8 +217,10 @@ async def download_dataset_response(hf_token,use_xet = use_xet,cache_env = cache_env,+ allow_ambient_token = allow_ambient_token,),hf_token = hf_token,+ allow_ambient_token = allow_ambient_token,label = repo_id,log_prefix = "Dataset download",logger = logger,diff --git a/studio/backend/hub/services/download_lifecycle.py b/studio/backend/hub/services/download_lifecycle.pyindex 5dc4b0763ab..4b61ceb49d7 100644--- a/studio/backend/hub/services/download_lifecycle.py+++ b/studio/backend/hub/services/download_lifecycle.py@@ -460,6 +460,7 @@ def _try_transport_retry(xet_attempt: int = 1,pending_xet_failure: Optional[str] = None,bytes_before: "Optional[int]" = _UNSAMPLED,+ allow_ambient_token: bool = True,) -> bool:"""Reclaim *key* under *retry_transport* and spawn a recovery worker.@@ -474,6 +475,9 @@ def _try_transport_retry(the stall retry: same transport, same marker, one more child, bounded by*xet_attempt* rather than by the transport check that stops the HTTP one.+ *allow_ambient_token* rides along unchanged, so a job that started anonymous cannot pick+ the backend's own HF_TOKEN up on a lower rung.+*pending_xet_failure* is a stall verdict held back from the health trackerand carried into the next worker, so a download that recovers on its secondXet attempt reports nothing and one that does not reports exactly one@@ -649,6 +653,7 @@ def _try_transport_retry(spawn_kwargs = {"use_xet": retry_over_xet,"protected_blob_hashes": peer_hashes or None,+ "allow_ambient_token": allow_ambient_token,}if cache_env is not None:spawn_kwargs["cache_env"] = cache_env@@ -691,6 +696,7 @@ def _try_transport_retry(xet_attempt = xet_attempt,pending_xet_failure = pending_xet_failure,bytes_before = bytes_before,+ allow_ambient_token = allow_ambient_token,)_give_up()_set_retry_failure_state(@@ -721,6 +727,7 @@ def _try_transport_retry(xet_attempt = xet_attempt,pending_xet_failure = pending_xet_failure,bytes_before = bytes_before,+ allow_ambient_token = allow_ambient_token,)@@ -930,13 +937,15 @@ def register_worker(bytes_before: "Optional[int]" = _UNSAMPLED,xet_attempt: int = 1,pending_xet_failure: Optional[str] = None,+ allow_ambient_token: bool = True,) -> bool:"""Watch *proc* to completion and drive the recovery ladder off its exit.*xet_attempt* (1-based) bounds the XET->XET stall retry, the way ``transport == TRANSPORT_XET``bounds the terminal XET->HTTP one. *pending_xet_failure* is an earlier attempt's stall verdict,held back from the health tracker until the XET phase ends so one download can never spend the- two consecutive failures that demote a machine.+ two consecutive failures that demote a machine. *allow_ambient_token* is the token policy this+ job was started under, carried onto every rung of the ladder."""if not registry.register_process(key, proc):kill_and_reap_process(proc, label = label, logger = logger)@@ -1102,6 +1111,7 @@ def register_worker(# The ORIGINAL pre-Xet baseline: resampling would fold the killed worker's# partial writes in, so a recovered attempt would read as a cached no-op.bytes_before = _bytes_before,+ allow_ambient_token = allow_ambient_token,)except Exception:if watchdog_stop is not None:@@ -1191,6 +1201,7 @@ def launch_worker(repo_id: str,transport: str,watch_name: str,+ allow_ambient_token: bool = True,) -> str:# Only the Xet success-recording consumes this, and sampling lazy-loads unsloth_zoo (so torch# and transformers) on the request path. An HTTP start skips it entirely.@@ -1237,6 +1248,7 @@ def launch_worker(transport = transport,watch_name = watch_name,bytes_before = _baseline,+ allow_ambient_token = allow_ambient_token,)return registry.get_job(key).statediff --git a/studio/backend/hub/services/models/downloads.py b/studio/backend/hub/services/models/downloads.pyindex 6802f091d92..00ffaf54996 100644--- a/studio/backend/hub/services/models/downloads.py+++ b/studio/backend/hub/services/models/downloads.py@@ -343,6 +343,7 @@ async def download_model_response(allow_ambient_token = allow_ambient_token,),hf_token = hf_token,+ allow_ambient_token = allow_ambient_token,label = label,log_prefix = "Download",logger = logger,diff --git a/studio/backend/hub/tests/test_download_lifecycle.py b/studio/backend/hub/tests/test_download_lifecycle.pyindex 9e646117003..159e299c42e 100644--- a/studio/backend/hub/tests/test_download_lifecycle.py+++ b/studio/backend/hub/tests/test_download_lifecycle.py@@ -87,6 +87,7 @@ def test_xet_failure_retries_over_http_for_model_and_dataset(monkeypatch, tmp_pa*,use_xet,protected_blob_hashes = None,+ allow_ambient_token = True,):spawned.append((args, use_xet, protected_blob_hashes))return _Proc(0)@@ -154,6 +155,7 @@ def test_a_stalled_xet_worker_respawns_over_xet_keeping_its_claim(monkeypatch, t*,use_xet,protected_blob_hashes = None,+ allow_ambient_token = True,):spawned.append((args, use_xet))return _Proc(0)@@ -249,13 +251,17 @@ def test_a_verdict_carried_onto_the_http_rung_is_still_charged(monkeypatch, tmp_on_stall(verdict)return None+ spawned = []+def flaky_spawn(args,_token,*,use_xet,protected_blob_hashes = None,+ **_kwargs,):+ spawned.append(use_xet)if use_xet:raise OSError("cannot fork")return _Proc(0) # the HTTP worker starts and completes@@ -289,6 +295,10 @@ def test_a_verdict_carried_onto_the_http_rung_is_still_charged(monkeypatch, tmp_transport = download_registry.TRANSPORT_XET,watch_name = "model-watch",)+ # Before the verdict: a double whose signature has fallen behind spawn_worker raises+ # TypeError at the call, which reads as a spawn failure and still records the verdict via+ # _give_up() -- green while this path never ran. Assert the HTTP worker actually started.+ assert spawned == [True, False], "the HTTP rung never ran, so the verdict proves nothing"assert recorded == [verdict], "a real Xet stall was dropped when HTTP finished the download"diff --git a/studio/backend/tests/test_hub_download_ambient_token.py b/studio/backend/tests/test_hub_download_ambient_token.pynew file mode 100644index 00000000000..a3030a80c5c--- /dev/null+++ b/studio/backend/tests/test_hub_download_ambient_token.py@@ -0,0 +1,232 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The backend's own HF_TOKEN is the operator's credential, not a shared service credential.++The Studio UI sends the user's saved token in ``X-Unsloth-HF-Token`` on every hub download, so+only a caller that has none reaches the ambient fallback. A UI session is the installation's+owner and keeps it (Settings hands that session the saved token anyway). An sk-unsloth API key+is the lesser credential -- Settings refuses it the saved token -- so it must not reach private+repos by naming one in a download request instead.+"""++import asyncio+import io+import logging++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth.authentication import (+ allow_ambient_hf_token,+ authenticated_via_api_key,+ get_current_subject,+)+from hub.routes import datasets as datasets_routes+from hub.routes import inventory as inventory_routes+from hub.services import download_lifecycle+from hub.services.datasets import downloads as dataset_downloads+from hub.services.models import downloads as model_downloads+from hub.utils import download_registry, state_dir+++class _Proc:+ pid = 4242++ def __init__(+ self,+ rc,+ stderr = b"",+ ):+ self.rc = rc+ self.stderr = io.BytesIO(stderr)+ self.waited = False++ def poll(self):+ return self.rc if self.waited else None++ def wait(self, timeout = None):+ self.waited = True+ return self.rc++ def kill(self):+ pass+++class _ImmediateThread:+ def __init__(self, *, target, **_kwargs):+ self.target = target++ def start(self):+ self.target()+++def _client(via_api_key: bool) -> TestClient:+ app = FastAPI()+ app.include_router(inventory_routes.router, prefix = "/api/hub")+ app.include_router(datasets_routes.router, prefix = "/api/hub/datasets")+ app.dependency_overrides[get_current_subject] = lambda: "alice"+ app.dependency_overrides[authenticated_via_api_key] = lambda: via_api_key+ return TestClient(app)++[email protected]("via_api_key, expected", [(True, False), (False, True)])+def test_only_a_ui_session_may_borrow_the_backend_token(via_api_key, expected):+ assert asyncio.run(allow_ambient_hf_token(via_api_key = via_api_key)) is expected++[email protected]("via_api_key, expected", [(True, False), (False, True)])+def test_model_download_route_gates_the_ambient_token(monkeypatch, via_api_key, expected):+ seen = {}++ async def _fake(+ body,+ hf_token = None,+ *,+ allow_ambient_token = True,+ ):+ seen["repo_id"] = body.repo_id+ seen["allow_ambient_token"] = allow_ambient_token+ return {"job_key": "k", "state": "running", "accepted": True, "generation": 1}++ monkeypatch.setattr(model_downloads, "download_model_response", _fake)++ response = _client(via_api_key).post(+ "/api/hub/download",+ json = {"repo_id": "attacker/private-model"},+ headers = {"Authorization": "Bearer token"},+ )++ assert response.status_code == 202, response.text+ assert seen["repo_id"] == "attacker/private-model"+ assert seen["allow_ambient_token"] is expected++[email protected]("via_api_key, expected", [(True, False), (False, True)])+def test_dataset_download_route_gates_the_ambient_token(monkeypatch, via_api_key, expected):+ seen = {}++ async def _fake(+ body,+ hf_token = None,+ *,+ allow_ambient_token = True,+ ):+ seen["repo_id"] = body.repo_id+ seen["allow_ambient_token"] = allow_ambient_token+ return {"repo_id": body.repo_id, "state": "running", "accepted": True, "generation": 1}++ monkeypatch.setattr(dataset_downloads, "download_dataset_response", _fake)++ response = _client(via_api_key).post(+ "/api/hub/datasets/download",+ json = {"repo_id": "attacker/private-dataset"},+ headers = {"Authorization": "Bearer token"},+ )++ assert response.status_code == 202, response.text+ assert seen["repo_id"] == "attacker/private-dataset"+ assert seen["allow_ambient_token"] is expected+++def _spawn_env(monkeypatch, hf_token, **kwargs):+ """Run the real spawn_worker against a fake Popen and return the child's environment."""+ captured = {}++ class _Fake:+ pass++ def _fake_popen(*_args, **popen_kwargs):+ captured.update(popen_kwargs["env"])+ return _Fake()++ monkeypatch.setattr(download_lifecycle.subprocess, "Popen", _fake_popen)+ download_lifecycle.spawn_worker(+ ["--repo-id", "attacker/private-model"],+ hf_token,+ use_xet = False,+ **kwargs,+ )+ return captured+++def test_an_api_caller_does_not_borrow_the_backend_hf_token(monkeypatch):+ """A caller the route marked as not allowed the ambient token gets an anonymous worker, even+ though the backend process has an HF_TOKEN of its own."""+ monkeypatch.setenv("HF_TOKEN", "operator-secret-token")++ env = _spawn_env(monkeypatch, None, allow_ambient_token = False)++ assert "HF_TOKEN" not in env+ assert env["HF_HUB_DISABLE_IMPLICIT_TOKEN"] == "1"+++def test_the_ui_still_falls_back_to_the_backend_hf_token(monkeypatch):+ """The other half: a UI session keeps the fallback, so a private repo stays downloadable for+ an install whose token lives in the environment rather than in Settings."""+ monkeypatch.setenv("HF_TOKEN", "operator-secret-token")++ env = _spawn_env(monkeypatch, None, allow_ambient_token = True)++ assert env["HF_TOKEN"] == "operator-secret-token"+ assert env["HF_HUB_DISABLE_IMPLICIT_TOKEN"] == "0"+++def test_an_explicit_request_token_wins_over_the_backend_one(monkeypatch):+ monkeypatch.setenv("HF_TOKEN", "operator-secret-token")++ env = _spawn_env(monkeypatch, "request-token", allow_ambient_token = True)++ assert env["HF_TOKEN"] == "request-token"+++def test_an_anonymous_job_stays_anonymous_on_the_http_retry(monkeypatch, tmp_path):+ """The recovery ladder must carry the token policy: a job started without the ambient token+ must not pick it up when the Xet worker fails and the HTTP one takes over."""+ monkeypatch.setattr(state_dir, "cache_root", lambda: tmp_path / "state")+ monkeypatch.setattr(download_lifecycle.threading, "Thread", _ImmediateThread)+ monkeypatch.setattr(download_lifecycle, "_start_stall_watchdog", lambda *a, **k: None)+ register_worker = download_lifecycle.register_worker++ registry = download_registry.DownloadRegistry()+ key = download_registry.normalize_job_key("Org/Model")+ assert registry.claim(+ key,+ download_registry.TRANSPORT_XET,+ repo_type = "model",+ repo_id = "Org/Model",+ variant = None,+ blob_hashes = frozenset({"blob"}),+ )[0]+ retried = []++ def fake_spawn(+ _args,+ _token,+ *,+ use_xet,+ allow_ambient_token = True,+ **_kwargs,+ ):+ retried.append(allow_ambient_token)+ return _Proc(0)++ monkeypatch.setattr(download_lifecycle, "spawn_worker", fake_spawn)+ monkeypatch.setattr(download_lifecycle, "register_worker", lambda *a, **k: True)+ assert register_worker(+ registry,+ key,+ _Proc(1, b"xet failed"),+ hf_token = None,+ label = "Org/Model",+ log_prefix = "Download",+ logger = logging.getLogger("test"),+ repo_type = "model",+ repo_id = "Org/Model",+ transport = download_registry.TRANSPORT_XET,+ watch_name = "model-watch",+ allow_ambient_token = False,+ )++ assert retried == [False], "the HTTP retry regained the backend's token"