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: managed-account paths are checked as they are opened (#14428)
Daniel Hane08466e82550
diff --git a/studio/backend/core/export/decision.py b/studio/backend/core/export/decision.pyindex 0106d52a973..ef4bc498fc9 100644--- a/studio/backend/core/export/decision.py+++ b/studio/backend/core/export/decision.py@@ -181,6 +181,31 @@ def normalize_decision_quants(quantization_method) -> list:return chosen or [DECISION_GGUF_QUANTIZATIONS[0]]+def adapter_load_bases(folder) -> list[str]:+ """Every base a local adapter folder's loaders follow: the decision config's ``base_model``+ (preferred by the decision loader) and adapter_config.json's ``base_model_name_or_path``."""+ folder = Path(str(folder)).expanduser()+ if not (folder / "adapter_config.json").is_file():+ return []+ bases = []+ for name, key in (+ ("unsloth_decision_config.json", "base_model"),+ ("adapter_config.json", "base_model_name_or_path"),+ ):+ try:+ value = json.loads((folder / name).read_text(encoding = "utf-8-sig")).get(key)+ except (OSError, ValueError, AttributeError):+ value = None+ if value and str(value) not in bases:+ bases.append(str(value))+ return bases+++def adapter_base_changed(folder, pinned: str) -> bool:+ """Whether the folder now names a base other than the one authorized for it."""+ return any(base != pinned for base in adapter_load_bases(folder))++def adapter_base(checkpoint_path) -> str:"""The base an adapter-only decision folder loads; both configs must name the same one."""folder = Path(str(checkpoint_path)).expanduser()diff --git a/studio/backend/core/export/export.py b/studio/backend/core/export/export.pyindex 9ffad4cd05e..493519b11f7 100644--- a/studio/backend/core/export/export.py+++ b/studio/backend/core/export/export.py@@ -729,6 +729,22 @@ def _publish_unsloth_model_card(hf_api, repo_id, model, hf_token):logger.warning(f"Could not publish the model card: {exception}")+def _checkpoint_load_refusal(checkpoint_path, pinned_base) -> Optional[str]:+ """Why a local checkpoint must not load now: a pinned adapter base it no longer names, or+ weight entries that point outside the folder."""+ from core.export.decision import adapter_base_changed+ from utils.security.file_security import escaping_weight_references++ if pinned_base and adapter_base_changed(checkpoint_path, pinned_base):+ return "The adapter's base model changed after it was checked. Load it again."+ if escaping_weight_references(checkpoint_path):+ return "This checkpoint's weight index names files outside its folder."+ # A local base loads too: its own index must stay inside its folder as well.+ if pinned_base and os.path.isdir(pinned_base) and escaping_weight_references(pinned_base):+ return "The base model's weight index names files outside its folder."+ return None++class ExportBackend:# {"layout", "adapter_only"} for a decision checkpoint (GGUF only), else None.decision: Optional[dict] = None@@ -822,6 +838,7 @@ class ExportBackend:# Loaders only: the probes' cache guards refuse an anonymous read, which offline# misreads a cached VLM as a text model.probe_token = token or None+ pinned_base = base_modeltry:logger.info(f"Loading checkpoint: {checkpoint_path}")@@ -840,6 +857,11 @@ class ExportBackend:base_model = base_model,)+ # The decision loader above checks its own base against the pin.+ refusal = _checkpoint_load_refusal(checkpoint_path, pinned_base)+ if refusal:+ return False, refusal+checkpoint_path_obj = Path(checkpoint_path)adapter_config = checkpoint_path_obj / "adapter_config.json"@@ -890,6 +912,11 @@ class ExportBackend:# DiffusionGemma ships a vision tower; its text-diffusion load is FastModel's.self.is_vision = False+ # Again right before the load: the folder may have been edited during the probes.+ refusal = _checkpoint_load_refusal(checkpoint_path, pinned_base)+ if refusal:+ return False, refusal+if self._audio_type == "csm":from unsloth import FastModelfrom transformers import CsmForConditionalGeneration@@ -1159,6 +1186,8 @@ class ExportBackend:except DecisionExportError as exc:return False, str(exc)self.decision = {"layout": layout, "adapter_only": adapter_only}+ # The base is loaded only at export: kept here and rechecked right before that load.+ self._decision_base_pin = resolved if adapter_only else None# An adapter folder loads its base at export time, under the credential of this load.self._decision_token = tokenself.is_vision = False@@ -1184,8 +1213,23 @@ class ExportBackend:"Decision model GGUF export does not support imatrix or Q4NX conversion.",None,)- from core.export.decision import DecisionExportError, run_decision_gguf_export+ from core.export.decision import DecisionExportError, adapter_base, run_decision_gguf_export+ pinned = getattr(self, "_decision_base_pin", None)+ if pinned:+ try:+ current = adapter_base(self.current_checkpoint)+ except DecisionExportError as exc:+ return False, str(exc), None+ if current != pinned:+ return (+ False,+ "The adapter's base model changed after it was loaded. Load it again.",+ None,+ )+ refusal = _checkpoint_load_refusal(self.current_checkpoint, pinned)+ if refusal:+ return False, refusal, Nonetry:data = run_decision_gguf_export(self.current_checkpoint,diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex b4bbf31cd19..6df1c5af6fa 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -820,6 +820,13 @@ def _handle_load(backend, config: dict, resp_queue: Any) -> None:load_kwargs["spec_draft_model"] = config.get("spec_draft_model")load_kwargs["spec_drafters_allowed"] = config.get("spec_drafters_allowed")load_kwargs["chat_template_override"] = config.get("chat_template_override")+ from utils.security.file_security import escaping_weight_references++ # Right before the load: the folder may have been edited since the route checked it.+ lora_base = getattr(mc, "base_model", None) if mc.is_lora else None+ for folder in (config["model_name"], lora_base):+ if folder and escaping_weight_references(folder):+ raise ValueError("This model's weight index names files outside its folder.")success = backend.load_model(**load_kwargs)finally:heartbeat_stop.set()diff --git a/studio/backend/core/training/account_jobs.py b/studio/backend/core/training/account_jobs.pyindex fdcccefe0f1..25b09a82747 100644--- a/studio/backend/core/training/account_jobs.py+++ b/studio/backend/core/training/account_jobs.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport importlibimport os+import sysimport threadingimport weakreffrom functools import wraps@@ -48,6 +49,37 @@ def account_key(value: str):return value if account.is_owner else (account.account_id, value)+# Packaged ``datasets`` builders resolve before the Hub and read local files from the server's cwd.+_BUILTIN_DATASET_BUILDERS = frozenset(+ (+ "arrow", "audiofolder", "cache", "csv", "eval", "generator", "hdf5", "imagefolder",+ "json", "lance", "niftifolder", "pandas", "parquet", "pdffolder", "spark", "sql", "text",+ "videofolder", "webdataset", "xml",+ )+) # fmt: skip+++def _dataset_builder_name(name: str) -> bool:+ builders = _BUILTIN_DATASET_BUILDERS+ # Only when datasets is already loaded: validating a reference must not import it.+ packaged = sys.modules.get("datasets.packaged_modules")+ builders |= set(getattr(packaged, "_PACKAGED_DATASETS_MODULES", None) or ())+ return name in builders or name.lower() in builders+++def _root_spellings(roots) -> list:+ """Each root as given, resolved, and through the owner's own studio home link."""+ spellings = [spelling for root in roots for spelling in (root, root.resolve())]+ override = (+ os.environ.get("UNSLOTH_STUDIO_HOME") or os.environ.get("STUDIO_HOME") or ""+ ).strip()+ if override:+ from utils.paths.storage_roots import studio_root+ home, link = studio_root(), Path(os.path.abspath(Path(override).expanduser()))+ spellings += [link / root.relative_to(home) for root in roots if root.is_relative_to(home)]+ return spellings++def account_path(value,*,@@ -58,6 +90,12 @@ def account_path(if not value or not managed_account():return valueraw = str(value)+ from utils.paths.path_utils import normalize_path++ normalized = normalize_path(raw)+ if normalized != raw:+ # Loaders open the forward-slash spelling, so it must pass too.+ account_path(normalized, reference = reference, shared_cache = shared_cache)path = Path(raw).expanduser()if reference and not path.is_absolute() and not path.exists():parts = raw.split("/")@@ -68,15 +106,20 @@ def account_path(for part in parts)and not raw.startswith((".", "~"))+ and not (len(parts) == 1 and _dataset_builder_name(raw))):return valueresolved = path.resolve()+ # Callers reopen the name itself, so every link it walks through must sit inside the roots too.+ lexical = Path(os.path.abspath(path))roots = (workspace_root(), project_workspaces_root(), tmp_root())if shared_cache:from utils.hf_cache_settings import active_hf_hub_cacheroots += (Path(active_hf_hub_cache()),)- if not any(resolved.is_relative_to(root.resolve()) for root in roots):+ if not any(resolved.is_relative_to(root.resolve()) for root in roots) or not any(+ lexical.is_relative_to(root) for root in _root_spellings(roots)+ ):raise HTTPException(status_code = 403, detail = "Path is outside this account's workspace")return valuediff --git a/studio/backend/core/training/worker.py b/studio/backend/core/training/worker.pyindex f5997565794..4288a6f51d3 100644--- a/studio/backend/core/training/worker.py+++ b/studio/backend/core/training/worker.py@@ -170,11 +170,22 @@ def _adapter_base_changed_error(config: dict) -> str | None:return Nonefrom utils.models.model_config import get_base_model_from_lora- if (get_base_model_from_lora(str(config.get("model_name") or "")) or "") != pinned:+ # The folder the loader reads: a cached Hub snapshot, not the repo id it came from.+ if (+ get_base_model_from_lora(str(_resolve_cached_model_load_name(config) or "")) or ""+ ) != pinned:return "The adapter's base model changed after the run was checked. Start the run again."return None+def _escaping_weights_error(config: dict) -> str | None:+ from utils.security.file_security import escaping_weight_references+ for key in ("model_name", "model_local_path", "model_snapshot_path", "adapter_base_pin"):+ if config.get(key) and escaping_weight_references(config[key]):+ return "This model's weight index names files outside its folder."+ return None++def _untrainable_model_format_error(config: dict) -> str | None:model_format = str(config.get("model_format") or "").strip().lower()if model_format == "gguf":@@ -4185,6 +4196,11 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->if not _validate_training_worker_config(config, event_queue):return+ # Before any backend dispatch: the MLX, decision and embedding runners load these weights too.+ weights_error = _escaping_weights_error(config)+ if weights_error:+ event_queue.put({"type": "error", "error": weights_error, "stack": "", "ts": time.time()})+ returnmodel_name = config["model_name"]model_load_target = _resolve_cached_model_load_name(config)@@ -5082,7 +5098,7 @@ def run_training_process(*, event_queue: Any, stop_queue: Any, config: dict) ->from utils.hf_xet_fallback import start_watchdog# Recheck right before the load: the adapter folder may have been edited since start (#13140).- base_error = _adapter_base_changed_error(config)+ base_error = _adapter_base_changed_error(config) or _escaping_weights_error(config)if base_error:event_queue.put({"type": "error", "error": base_error, "stack": "", "ts": time.time()})returndiff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.pyindex cda199fe709..ca2a4a80d96 100644--- a/studio/backend/hub/services/models/account_access.py+++ b/studio/backend/hub/services/models/account_access.py@@ -28,6 +28,7 @@ from auth import policyfrom core.inference.gpu_arbiter import GpuBusyForAnotherAccountErrorfrom storage.studio_db import connect_studio_dbfrom utils.paths import storage_roots+from utils.paths.path_utils import normalize_pathfrom utils.paths.storage_roots import project_workspaces_root, studio_db_path, workspace_rootfrom utils.account_context import (@@ -878,6 +879,16 @@ def model_visible(if not isinstance(reference, str) or not reference:return Falsereference = reference.strip()+ normalized = normalize_path(reference)+ if normalized != reference:+ # Loaders open the forward-slash spelling, so both must be visible.+ return _model_visible(reference, grants, repo_type, offline) and _model_visible(+ normalized, grants, repo_type, offline+ )+ return _model_visible(reference, grants, repo_type, offline)+++def _model_visible(reference: str, grants, repo_type: str, offline: bool) -> bool:access_options = {"offline": True} if offline else {}path = Path(reference).expanduser()if path.is_absolute() or reference.startswith(("./", "../", "~")) or path.exists():@@ -925,9 +936,12 @@ def require_model_allowed(reference) -> None:"""The allowlist alone, for routes that fetch a Hub model without the visibility gate."""if not isinstance(reference, str) or model_allowlist() is None:return- repo_id = _reference_repo_id(reference.strip())- if repo_id is not None and not model_allowed(repo_id):- raise HTTPException(status_code = 403, detail = MODEL_NOT_ALLOWED)+ reference = reference.strip()+ # Loaders open the forward-slash spelling, so both must be allowed.+ for spelling in dict.fromkeys((reference, normalize_path(reference))):+ repo_id = _reference_repo_id(spelling)+ if repo_id is not None and not model_allowed(repo_id):+ raise HTTPException(status_code = 403, detail = MODEL_NOT_ALLOWED)def _row_reference(row):@@ -956,6 +970,10 @@ def private_directory(path: str, folder: str) -> str:return pathfrom utils.paths.storage_roots import studio_root+ normalized = normalize_path(path)+ if normalized != path:+ # Scanners open the forward-slash spelling, so it must be the account's own too.+ private_directory(normalized, folder)legacy = studio_root() / foldertarget = workspace_root() / folder if Path(path).resolve() == legacy.resolve() else Path(path)# The project workspace counts as the account's own, matching within_account().diff --git a/studio/backend/routes/export.py b/studio/backend/routes/export.pyindex 3ab6c69bea2..03a49895149 100644--- a/studio/backend/routes/export.py+++ b/studio/backend/routes/export.py@@ -113,10 +113,14 @@ def _authorized_adapter_base(checkpoint_path: str) -> Optional[str]:if not account_access.managed_account():return Nonefrom utils.models import get_base_model_from_lora-- base = get_base_model_from_lora(checkpoint_path)- if base:- account_access.require_model_access(base)+ from core.export.decision import adapter_load_bases++ bases = adapter_load_bases(checkpoint_path)+ base = get_base_model_from_lora(checkpoint_path) or next(iter(bases), None)+ # The decision loader prefers its own config's base, so every base named is checked.+ for name in dict.fromkeys([base, *bases]):+ if name:+ account_access.require_model_access(name)return base or Nonediff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.pyindex c379da6a4bf..894fd393a95 100644--- a/studio/backend/routes/training.py+++ b/studio/backend/routes/training.py@@ -1259,6 +1259,9 @@ def _reject_untrainable_model_request("training_remote_model_not_decision",f"{request.model_name} is not a decision model (Laya or Clef).",)+ if _is_decision_checkpoint(request) and managed_account():+ # A Hub decision adapter loads its base as well: authorize it like any adapter.+ _authorize_adapter_base(request.model_name, hf_token)return _ModelPreflightResult(model_name, model_local_path, cached_model_pin)if remote_format == "gguf":raise _training_start_error(@@ -1293,9 +1296,27 @@ def _reject_untrainable_model_request("needs joint_head.safetensors and joint_head_config.json beside config.json ""(or LoRA adapters).",)+ if managed_account() and _has_adapter_metadata(folder):+ # FastDecisionModel loads the adapter's base: check and pin it like any adapter.+ from core.export.decision import DecisionExportError, adapter_base++ try:+ adapter_base(folder)+ except DecisionExportError as exc:+ raise _training_start_error(400, "training_decision_adapter_base", str(exc))+ base = _authorize_adapter_base(str(folder), hf_token)+ # The worker re-reads the pin at the model root, so pin only a root adapter.+ pin = None if request.model_subfolder else base or ""+ return _ModelPreflightResult(model_name, model_local_path, None, adapter_base_pin = pin)return _ModelPreflightResult(model_name, model_local_path, None)has_trainable_weights = _has_trainable_local_weights(path, request.model_name)if has_trainable_weights:+ if managed_account() and _has_adapter_metadata(path):+ # The loader still follows adapter_config.json to its base, so check and pin it.+ adapter_base = _authorize_adapter_base(str(path), hf_token)+ return _ModelPreflightResult(+ model_name, model_local_path, cached_model_pin, adapter_base_pin = adapter_base or ""+ )return _ModelPreflightResult(model_name, model_local_path, cached_model_pin)if _has_adapter_metadata(path) or (model_format == "adapter" and _has_local_adapter_weights(path)diff --git a/studio/backend/tests/test_account_path_confinement.py b/studio/backend/tests/test_account_path_confinement.pynew file mode 100644index 00000000000..c4b6c4a9950--- /dev/null+++ b/studio/backend/tests/test_account_path_confinement.py@@ -0,0 +1,366 @@+# 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 managed account's paths, model references and checkpoint loads stay inside what it may read."""++import contextlib+import json+import os+import sys+import types+from pathlib import Path++import pytest+from fastapi import HTTPException++_TESTS_DIR = Path(__file__).resolve().parent+if str(_TESTS_DIR) not in sys.path:+ sys.path.insert(0, str(_TESTS_DIR))++from auth import policy # noqa: E402+from core.training.account_jobs import account_path # noqa: E402+from hub.services.models import account_access # noqa: E402+from utils.account_context import OWNER, AccountContext, run_as # noqa: E402+from utils.paths import storage_roots # noqa: E402++ALICE = AccountContext("alice-confine", "alice")+BOB = AccountContext("bob-confine", "bob")++symlinks = pytest.mark.skipif(sys.platform == "win32", reason = "symlinks need privileges on Windows")++[email protected](autouse = True)+def studio(tmp_path, monkeypatch):+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))+ monkeypatch.setenv("UNSLOTH_STUDIO_PROJECTS_HOME", str(tmp_path / "projects"))+ monkeypatch.setattr(policy, "installation_is_multi_user", lambda: True)+ monkeypatch.setattr(policy, "installation_has_managed_accounts", lambda: True, raising = False)+ elsewhere = tmp_path / "server-cwd"+ elsewhere.mkdir()+ monkeypatch.chdir(elsewhere)+ return tmp_path / "studio"+++def _workspace(account):+ root = run_as(account, storage_roots.workspace_root)+ root.mkdir(parents = True, exist_ok = True)+ return root+++def _refused(call, *args, **kwargs):+ with pytest.raises(HTTPException) as exc:+ call(*args, **kwargs)+ return exc.value.status_code+++# account_path: the name itself, not only its target, must sit inside the account.+++@symlinks+def test_outside_link_into_own_workspace_is_refused(tmp_path):+ ws = _workspace(ALICE)+ (ws / "data.jsonl").write_text("{}")+ link = tmp_path / "outside-link"+ link.symlink_to(ws, target_is_directory = True)+ assert _refused(run_as, ALICE, account_path, str(link / "data.jsonl")) == 403++[email protected](not Path("/proc/self/cwd").exists(), reason = "needs procfs")+def test_proc_cwd_spelling_is_refused(monkeypatch):+ ws = _workspace(ALICE)+ (ws / "data.jsonl").write_text("{}")+ monkeypatch.chdir(ws)+ assert _refused(run_as, ALICE, account_path, "/proc/self/cwd/data.jsonl") == 403+++@symlinks+def test_workspace_paths_through_a_linked_studio_home_still_pass(tmp_path, monkeypatch):+ real_home = tmp_path / "real-home"+ real_home.mkdir()+ linked_home = tmp_path / "linked-home"+ linked_home.symlink_to(real_home, target_is_directory = True)+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(linked_home))+ ws = _workspace(ALICE)+ (ws / "data.jsonl").write_text("{}")+ for spelling in (+ ws / "data.jsonl",+ real_home / "accounts" / ALICE.account_id / "data.jsonl",+ linked_home / "accounts" / ALICE.account_id / "data.jsonl",+ ):+ assert run_as(ALICE, account_path, str(spelling)) == str(spelling)+++def test_plain_workspace_path_and_owner_unchanged(tmp_path):+ ws = _workspace(ALICE)+ assert run_as(ALICE, account_path, str(ws / "x.jsonl")) == str(ws / "x.jsonl")+ assert run_as(OWNER, account_path, "/proc/self/cwd/x") == "/proc/self/cwd/x"+++# account_path reference mode: packaged datasets builders are not Hub ids.++[email protected]("name", ["pandas", "json", "csv", "text", "parquet", "arrow"])+def test_packaged_builder_names_are_not_hub_references(name):+ assert _refused(run_as, ALICE, account_path, name, reference = True) == 403+ assert run_as(OWNER, account_path, name, reference = True) == name++[email protected]("name", ["imdb", "org/dataset", "unsloth/Llama-3.2-1B"])+def test_real_hub_ids_still_pass_reference_mode(name):+ assert run_as(ALICE, account_path, name, reference = True) == name+++# Backslash spellings: the gate judges what the loader opens after normalizing separators.+++def _backslash_escape():+ alice_ws = _workspace(ALICE)+ bob_ws = _workspace(BOB)+ (bob_ws / "m.gguf").write_bytes(b"GGUF")+ return f"{alice_ws}/\\..\\{bob_ws.name}\\m.gguf", alice_ws++[email protected](os.sep == "\\", reason = "a backslash is a separator on Windows")+def test_backslash_spelling_of_another_workspace_is_refused():+ reference, alice_ws = _backslash_escape()+ assert run_as(ALICE, account_access.model_visible, reference) is False+ assert _refused(run_as, ALICE, account_path, reference) == 403+ assert _refused(run_as, ALICE, account_access.private_directory, reference, "models") == 404+ (alice_ws / "sub").mkdir()+ assert run_as(ALICE, account_access.model_visible, str(alice_ws / "sub" / "x.gguf")) is True+++# Weight index entries pointing outside the model folder.+++def _write(folder, files):+ folder.mkdir(parents = True, exist_ok = True)+ for name, payload in files.items():+ (folder / name).parent.mkdir(parents = True, exist_ok = True)+ (folder / name).write_text(json.dumps(payload) if not isinstance(payload, str) else payload)+ return folder+++ "files",+ [+ {"model.safetensors.index.json": {"weight_map": {"w": "../victim/model.safetensors"}}},+ {"pytorch_model.bin.index.json": {"weight_map": {"w": "/abs/pytorch_model.bin"}}},+ {"config.json": {"transformers_weights": "../victim/model.safetensors.index.json"}},+ {+ "LLM/model.safetensors.index.json": {+ "weight_map": {"w": "../../victim/model.safetensors"}+ }+ },+ {+ "config.json": {"transformers_weights": "custom.safetensors.index.json"},+ "custom.safetensors.index.json": {"weight_map": {"w": "../victim/model.safetensors"}},+ },+ {+ "modules.json": [{"idx": 0, "name": "0", "path": "0_Transformer"}],+ "0_Transformer/model.safetensors.index.json": {+ "weight_map": {"w": "D:\\victim\\model.safetensors"}+ },+ },+ ],+ ids = [+ "safetensors_dotdot",+ "bin_absolute",+ "transformers_weights",+ "bicodec_llm_subfolder",+ "custom_index",+ "module_shard_on_a_drive",+ ],+)+def test_escaping_weight_references_flagged(tmp_path, files):+ from utils.security.file_security import escaping_weight_references+ assert escaping_weight_references(_write(tmp_path / "m", files))+++def test_normal_weight_index_is_clean(tmp_path):+ from utils.security.file_security import escaping_weight_references+ folder = _write(+ tmp_path / "m",+ {+ "config.json": {"model_type": "llama"},+ "model.safetensors.index.json": {+ "weight_map": {+ "a": "model-00001-of-00002.safetensors",+ "b": "sub/model-00002-of-00002.safetensors",+ # Walks back up but lands inside the folder, where the loader reads it.+ "c": "sub/../model-00001-of-00002.safetensors",+ }+ },+ },+ )+ assert escaping_weight_references(folder) == []+++# Export: what loads is what was checked.+++class _RecordingLoader:+ calls: list = []++ @classmethod+ def from_pretrained(cls, **kwargs):+ cls.calls.append(kwargs)+ return types.SimpleNamespace(), types.SimpleNamespace()+++def _export_backend(monkeypatch):+ from test_export_absolute_paths import _install_export_backend_stubs, _load_module++ _install_export_backend_stubs(monkeypatch)+ mod = _load_module("test_core_export_backend_confinement", "core/export/export.py", monkeypatch)+ _RecordingLoader.calls = []+ monkeypatch.setattr(mod, "FastLanguageModel", _RecordingLoader)+ monkeypatch.setattr(mod, "detect_audio_type", lambda *a, **k: None)+ monkeypatch.setattr(mod, "is_vision_model", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_hf_offline", lambda *a, **k: False)+ monkeypatch.setattr(mod, "_offline_window_if", lambda flag: contextlib.nullcontext())+ monkeypatch.setattr(mod, "_multi_gpu_device_map_kwargs", lambda: {})+ backend = mod.ExportBackend.__new__(mod.ExportBackend)+ backend.cleanup_memory = lambda: None+ return backend+++def test_export_refuses_an_adapter_whose_base_changed_after_the_check(monkeypatch, tmp_path):+ backend = _export_backend(monkeypatch)+ checkpoint = _write(+ tmp_path / "ckpt",+ {"adapter_config.json": {"base_model_name_or_path": "other/private-base"}},+ )+ ok, _ = backend.load_checkpoint(str(checkpoint), base_model = "alice/checked-base")+ assert not ok+ assert _RecordingLoader.calls == []+++def test_export_refuses_a_weight_index_outside_the_checkpoint(monkeypatch, tmp_path):+ backend = _export_backend(monkeypatch)+ checkpoint = _write(+ tmp_path / "ckpt",+ {"model.safetensors.index.json": {"weight_map": {"w": "../victim/model.safetensors"}}},+ )+ ok, _ = backend.load_checkpoint(str(checkpoint))+ assert not ok+ assert _RecordingLoader.calls == []+++def test_export_still_loads_an_unchanged_adapter(monkeypatch, tmp_path):+ backend = _export_backend(monkeypatch)+ checkpoint = _write(+ tmp_path / "ckpt",+ {"adapter_config.json": {"base_model_name_or_path": "alice/checked-base"}},+ )+ ok, message = backend.load_checkpoint(str(checkpoint), base_model = "alice/checked-base")+ assert ok, message+ assert len(_RecordingLoader.calls) == 1+++def test_export_route_authorizes_the_decision_config_base(tmp_path):+ from routes import export as export_routes++ ws = _workspace(ALICE)+ own_base = _write(ws / "base", {"config.json": {"model_type": "llama"}})+ foreign = _write(tmp_path / "foreign-base", {"config.json": {"model_type": "llama"}})+ checkpoint = _write(+ ws / "outputs" / "run",+ {+ "adapter_config.json": {"base_model_name_or_path": str(own_base)},+ "unsloth_decision_config.json": {"base_model": str(foreign)},+ },+ )+ (checkpoint / "adapter_model.safetensors").write_bytes(b"x")+ assert _refused(run_as, ALICE, export_routes._authorized_adapter_base, str(checkpoint)) == 404+ del_decision = checkpoint / "unsloth_decision_config.json"+ del_decision.unlink()+ assert run_as(ALICE, export_routes._authorized_adapter_base, str(checkpoint)) == str(own_base)+++# Training: a folder with full weights and an adapter config still has its base authorized.+++def test_training_preflight_authorizes_adapter_base_beside_full_weights(tmp_path, monkeypatch):+ from models.training import TrainingStartRequest+ from routes import training++ ws = _workspace(ALICE)+ foreign = _write(tmp_path / "owner-base", {"config.json": {"model_type": "llama"}})+ (foreign / "model.safetensors").write_bytes(b"x" * 16)+ folder = _write(+ ws / "models" / "mixed",+ {+ "config.json": {"model_type": "llama"},+ "adapter_config.json": {"base_model_name_or_path": str(foreign)},+ },+ )+ (folder / "model.safetensors").write_bytes(b"x" * 16)+ (folder / "adapter_model.safetensors").write_bytes(b"x" * 16)+ monkeypatch.setattr(training, "_has_trainable_local_weights", lambda *a, **k: True)+ request = TrainingStartRequest(+ model_name = str(folder),+ dataset_name = "public/set",+ hf_token = "x",+ training_type = "LoRA/QLoRA",+ format_type = "alpaca",+ )+ assert _refused(run_as, ALICE, training._reject_untrainable_model_request, request) == 403+ result = run_as(OWNER, training._reject_untrainable_model_request, request)+ assert result.adapter_base_pin is None+++def test_a_cached_snapshot_adapter_pin_is_rechecked_against_the_snapshot(tmp_path):+ import json++ from core.training import worker++ snapshot = tmp_path / "snapshot"+ snapshot.mkdir()+ (snapshot / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "org/base"})+ )+ config = {+ "model_name": "org/finetune",+ "model_snapshot_path": str(snapshot),+ "adapter_base_pin": "org/base",+ }+ assert worker._adapter_base_changed_error(config) is None+ assert worker._adapter_base_changed_error({**config, "adapter_base_pin": "org/other"})+++def test_a_sentence_transformers_module_index_outside_the_model_is_flagged(tmp_path):+ from utils.security.file_security import escaping_weight_references++ folder = _write(+ tmp_path / "st",+ {"modules.json": [{"idx": 0, "name": "0", "path": "0_Transformer", "type": "x"}]},+ )+ _write(+ folder / "0_Transformer",+ {"model.safetensors.index.json": {"weight_map": {"w": "../../victim/model.safetensors"}}},+ )+ assert escaping_weight_references(folder)+ _write(+ folder / "0_Transformer",+ {+ "model.safetensors.index.json": {+ "weight_map": {"w": "../0_Transformer/model.safetensors"}+ }+ },+ )+ assert escaping_weight_references(folder) == []+++def test_an_export_base_whose_index_escapes_is_refused(tmp_path):+ from core.export.export import _checkpoint_load_refusal++ adapter = _write(+ tmp_path / "adapter", {"adapter_config.json": {"base_model_name_or_path": "x"}}+ )+ base = _write(+ tmp_path / "base",+ {"model.safetensors.index.json": {"weight_map": {"w": "../victim/model.safetensors"}}},+ )+ (adapter / "adapter_config.json").write_text(json.dumps({"base_model_name_or_path": str(base)}))+ assert _checkpoint_load_refusal(str(adapter), str(base))diff --git a/studio/backend/tests/test_decision_training_route.py b/studio/backend/tests/test_decision_training_route.pyindex 79d80114d65..7eed2295c84 100644--- a/studio/backend/tests/test_decision_training_route.py+++ b/studio/backend/tests/test_decision_training_route.py@@ -674,3 +674,43 @@ def test_clef_training_is_refused_without_an_nvidia_or_amd_gpu(route, device, tmrequest = _request(model_name = str(folder))route._validate_decision_request(request)assert request.decision_layout == {"c": "clef", "l": "llm"}[folder.name]+++def _clef_adapter_folder(folder: Path, base: str) -> Path:+ folder.mkdir(parents = True)+ files = {+ "adapter_config.json": {"base_model_name_or_path": base},+ "joint_head_config.json": {},+ }+ for name, content in files.items():+ (folder / name).write_text(json.dumps(content), encoding = "utf-8")+ for name in ("adapter_model.safetensors", "joint_head.safetensors"):+ (folder / name).write_bytes(b"x")+ return folder+++def test_a_managed_decision_adapter_authorizes_and_pins_its_base(route, tmp_path, monkeypatch):+ adapter = _clef_adapter_folder(tmp_path / "clef_adapter", "owner/private-model")+ checked = []+ monkeypatch.setattr(route, "managed_account", lambda: True)+ monkeypatch.setattr(route, "account_path", lambda path, **kwargs: Path(path).resolve())+ monkeypatch.setattr(+ route,+ "_authorize_adapter_base",+ lambda name, token: checked.append(name) or "owner/private-model",+ )++ result = route._reject_untrainable_model_request(_request(model_name = str(adapter)))++ assert checked == [str(adapter.resolve())]+ assert result.adapter_base_pin == "owner/private-model"+++def test_a_managed_hub_decision_adapter_authorizes_its_base(route, monkeypatch):+ checked = []+ monkeypatch.setattr(route, "managed_account", lambda: True)+ monkeypatch.setattr(route, "is_decision_model", lambda *a, **k: True)+ monkeypatch.setattr(route, "_authorize_adapter_base", lambda name, token: checked.append(name))+ with patch.object(route, "_remote_untrainable_model_format", return_value = None):+ route._reject_untrainable_model_request(_request(model_name = "org/clef-adapter"))+ assert checked == ["org/clef-adapter"]diff --git a/studio/backend/tests/test_export_absolute_paths.py b/studio/backend/tests/test_export_absolute_paths.pyindex 456cc0deb15..9756f03e9ea 100644--- a/studio/backend/tests/test_export_absolute_paths.py+++ b/studio/backend/tests/test_export_absolute_paths.py@@ -156,6 +156,12 @@ def _install_lightweight_backend_stubs(monkeypatch):utils_utils.anonymous_and_offline = lambda _hf_token: Falseutils_utils.safe_error_detail = lambda value: str(value)monkeypatch.setitem(sys.modules, "utils.utils", utils_utils)+ utils_security = types.ModuleType("utils.security")+ utils_security.__path__ = []+ monkeypatch.setitem(sys.modules, "utils.security", utils_security)+ utils_security.file_security = _load_module(+ "utils.security.file_security", "utils/security/file_security.py", monkeypatch+ )utils_models = types.ModuleType("utils.models")utils_models.__path__ = []diff --git a/studio/backend/tests/test_export_decision_backend.py b/studio/backend/tests/test_export_decision_backend.pyindex 5a55ba3facc..543e8ac5594 100644--- a/studio/backend/tests/test_export_decision_backend.py+++ b/studio/backend/tests/test_export_decision_backend.py@@ -405,3 +405,35 @@ def test_a_decision_adapter_loads_only_the_authorized_base(env, tmp_path):ok, message = backend.load_checkpoint(str(folder), base_model = "unsloth/Qwen3.5-0.8B")assert not ok and "two different base models" in messageassert _exports(lib) == []+++def test_a_decision_adapter_whose_base_changed_after_loading_does_not_export(env, tmp_path):+ mod, lib = env+ folder = _clef_adapter(tmp_path)+ backend = mod.ExportBackend()+ ok, message = backend.load_checkpoint(str(folder), base_model = "unsloth/Qwen3.5-0.8B")+ assert ok, message+ (folder / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": "owner/private-model"}), encoding = "utf-8"+ )+ ok, message, _ = backend.export_gguf("x", "q8_0")+ assert not ok and "changed after it was loaded" in message+ assert _exports(lib) == []+++def test_a_decision_adapter_whose_local_base_index_escapes_does_not_export(env, tmp_path):+ mod, lib = env+ base = _write(+ tmp_path / "base",+ {"model.safetensors.index.json": {"weight_map": {"w": "../victim/model.safetensors"}}},+ )+ folder = _clef_adapter(tmp_path)+ (folder / "adapter_config.json").write_text(+ json.dumps({"base_model_name_or_path": str(base)}), encoding = "utf-8"+ )+ backend = mod.ExportBackend()+ ok, message = backend.load_checkpoint(str(folder), base_model = str(base))+ assert ok, message+ ok, message, _ = backend.export_gguf("x", "q8_0")+ assert not ok and "outside its folder" in message+ assert _exports(lib) == []diff --git a/studio/backend/utils/security/file_security.py b/studio/backend/utils/security/file_security.pyindex 6fac12fb165..38bb1a55377 100644--- a/studio/backend/utils/security/file_security.py+++ b/studio/backend/utils/security/file_security.py@@ -3,6 +3,8 @@"""Malware / unsafe-file gate for model loads. The ``trust_remote_code`` consent gate covers the ``auto_map`` Python vector; this covers the other one, a malicious pickle inside a weight file, which executes during ``from_pretrained`` deserialization even with ``trust_remote_code=False``. It reads Hugging Face's OWN scan (picklescan + ClamAV) via ``model_info(securityStatus=True).security_repo_status``. METADATA-ONLY: it never downloads, opens, or unpickles the flagged files. Policy: a hard, non-approvable block whenever ``filesWithIssues`` lists a non-``safe`` level, regardless of ``scansDone`` (often false even for clean repos); unknown/future levels fail CLOSED so Hub schema drift cannot silently allow a bad verdict, and only a small allowlist of clean / not-yet-scanned levels is non-blocking, while an unavailable status falls back to local inspection for a pinned cache snapshot and otherwise fails open. Scoped to the load-path RCE vector: a root-level (or load-subdir-level) code-executing file, since inert formats (safetensors / gguf / config / text) and subdirectory pickles that no root weight-index references are not loaded and do not block, while an index-referenced shard does, wherever it lives. That blocks real malware (eicar's root ``*.pkl``/``*.dat``) without false-blocking repos like ``nvidia/Nemotron-H-8B-Base-8K`` (flagged NeMo pickles under ``nemo/`` that no index lists). No first-party exemption (scoping is by load path/format, not org), and local paths are skipped (no Hub scan) while a remote ``*.gguf``-named repo is still scanned so a repo cannot dodge the gate by suffixing its name."""+import json+import posixpathimport refrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -63,6 +65,86 @@ _TRANSFORMERS_INDEX_FILES = ()+def _escapes_folder(name: str) -> bool:+ spelled = name.replace("\\", "/")+ if spelled.startswith("/") or (len(spelled) > 1 and spelled[1] == ":"):+ return True+ # weights/../weights/shard.bin stays inside; only a name that normalizes above the folder escapes.+ normalized = posixpath.normpath(spelled)+ return normalized == ".." or normalized.startswith("../")+++def _in_subfolder(sub: str, name: str) -> str:+ # A rooted or drive-qualified name ignores the subfolder it is joined onto.+ spelled = name.replace("\\", "/")+ if spelled.startswith("/") or name[1:2] == ":":+ return name+ return posixpath.join(sub.replace("\\", "/"), name)+++def _weight_names(folder: Path) -> list:+ names = []+ for index_name in _TORCH_INDEX_FILES:+ try:+ payload = json.loads((folder / index_name).read_text(encoding = "utf-8-sig"))+ except (OSError, ValueError):+ continue+ weight_map = payload.get("weight_map") if isinstance(payload, dict) else None+ if isinstance(weight_map, dict):+ names.extend(v for v in weight_map.values() if isinstance(v, str))+ try:+ config = json.loads((folder / "config.json").read_text(encoding = "utf-8-sig"))+ except (OSError, ValueError):+ config = None+ weights = config.get("transformers_weights") if isinstance(config, dict) else None+ if isinstance(weights, str):+ weights = [weights]+ for name in weights if isinstance(weights, (list, tuple)) else []:+ if not isinstance(name, str):+ continue+ names.append(name)+ # A custom index named here is read like the standard ones.+ if name.endswith(".index.json") and not _escapes_folder(name):+ try:+ payload = json.loads((folder / name).read_text(encoding = "utf-8-sig"))+ except (OSError, ValueError):+ continue+ weight_map = payload.get("weight_map") if isinstance(payload, dict) else None+ if isinstance(weight_map, dict):+ names.extend(v for v in weight_map.values() if isinstance(v, str))+ return names+++def escaping_weight_references(folder) -> list:+ """Weight names a local model folder's index files or config.json ``transformers_weights``+ give that point outside the folder: transformers joins each onto the folder as is. Text only,+ so Hub cache snapshots whose files link into the blob store still pass. A Sentence Transformers+ folder's modules.json module folders are read too, judged against the model folder."""+ try:+ folder = Path(str(folder)).expanduser()+ if not folder.is_dir():+ return []+ except (OSError, ValueError):+ return []+ names = _weight_names(folder)+ try:+ modules = json.loads((folder / "modules.json").read_text(encoding = "utf-8-sig"))+ except (OSError, ValueError):+ modules = None+ for module in modules if isinstance(modules, list) else []:+ sub = module.get("path") if isinstance(module, dict) else None+ if not isinstance(sub, str) or not sub.strip("./\\"):+ continue+ if _escapes_folder(sub):+ names.append(sub)+ continue+ names.extend(_in_subfolder(sub, name) for name in _weight_names(folder / sub))+ # Spark-TTS / BiCodec load their transformers model from LLM/.+ if (folder / "LLM").is_dir():+ names.extend(_in_subfolder("LLM", name) for name in _weight_names(folder / "LLM"))+ return [name for name in dict.fromkeys(names) if _escapes_folder(name)]++def _normalize_repo_path(path: str) -> str:"""Strip ``./`` prefixes and normalize separators for repo-relative comparison."""p = (path or "").strip().replace("\\", "/")diff --git a/tests/test_st_modules_json_folder_containment.py b/tests/test_st_modules_json_folder_containment.pynew file mode 100644index 00000000000..26eff0a7bd0--- /dev/null+++ b/tests/test_st_modules_json_folder_containment.py@@ -0,0 +1,69 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""modules.json module folders must stay inside the model folder."""++import json++import pytest++pytest.importorskip("sentence_transformers")++from unsloth import FastSentenceTransformer # noqa: E402+++def _model(tmp_path, modules):+ model = tmp_path / "model"+ model.mkdir()+ (model / "modules.json").write_text(json.dumps(modules), encoding = "utf-8")+ return str(model)+++ "path,type_",+ [+ ("../victim", "sentence_transformers.models.Transformer"),+ ("/abs/victim", "sentence_transformers.models.Router"),+ ("sub/../../victim", "sentence_transformers.models.Pooling"),+ ("D:victim", "sentence_transformers.models.Pooling"),+ ],+ ids = ["transformer_dotdot", "router_absolute", "pooling_nested_dotdot", "drive_relative"],+)+def test_module_folder_outside_the_model_is_refused(tmp_path, path, type_):+ model = _model(tmp_path, [{"idx": 0, "name": "0", "path": path, "type": type_}])+ with pytest.raises(ValueError, match = "outside the model"):+ FastSentenceTransformer._check_modules_json_types(model, None, False)+++def test_stock_layout_still_passes(tmp_path):+ model = _model(+ tmp_path,+ [+ {"idx": 0, "name": "0", "path": "", "type": "sentence_transformers.models.Transformer"},+ {+ "idx": 1,+ "name": "1",+ "path": "1_Pooling",+ "type": "sentence_transformers.models.Pooling",+ },+ ],+ )+ (tmp_path / "model" / "1_Pooling").mkdir()+ FastSentenceTransformer._check_modules_json_types(model, None, False)+++def test_a_module_folder_that_walks_back_inside_passes(tmp_path):+ model = _model(+ tmp_path,+ [+ {"idx": 0, "name": "0", "path": "", "type": "sentence_transformers.models.Transformer"},+ {+ "idx": 1,+ "name": "1",+ "path": "modules/../1_Pooling",+ "type": "sentence_transformers.models.Pooling",+ },+ ],+ )+ (tmp_path / "model" / "1_Pooling").mkdir()+ FastSentenceTransformer._check_modules_json_types(model, None, False)diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex 1cf1ce2b0ca..9a6b6cde6dd 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -30,6 +30,7 @@ from ._utils import (import inspectimport jsonimport os+import posixpathimport threadingimport typesfrom huggingface_hub import hf_hub_download@@ -1899,6 +1900,22 @@ class FastSentenceTransformer(FastModel):for module_config in modules_config:if not isinstance(module_config, dict):continue+ folder = module_config.get("path")+ # modules/../1_Pooling stays inside: only a folder that normalizes above the model escapes.+ normalized = (+ posixpath.normpath(folder.replace("\\", "/")) if isinstance(folder, str) else ""+ )+ if isinstance(folder, str) and (+ os.path.isabs(folder)+ or folder.startswith(("/", "\\"))+ or folder[1:2] == ":"+ or normalized == ".."+ or normalized.startswith("../")+ ):+ raise ValueError(+ f"Unsloth: {model_name} names the module folder {folder!r}, which is "+ f"outside the model. Module folders must stay inside the model folder."+ )class_ref = module_config.get("type")if FastSentenceTransformer._is_transformer_module_ref(class_ref):continue