Skip to content

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.

Studio: per-user temp folders, tighter tool sandbox grants, no UNC paths for managed accounts (#14461)

Daniel Hane3f5e60a3db1
diff --git a/studio/backend/core/inference/diffusion_nvfp4_install.py b/studio/backend/core/inference/diffusion_nvfp4_install.py
index 9c51c1c07eb..f6664e881a9 100644
--- a/studio/backend/core/inference/diffusion_nvfp4_install.py
+++ b/studio/backend/core/inference/diffusion_nvfp4_install.py
@@ -178,14 +178,16 @@ ENV_LOCK_TIMEOUT_S = 900.0
def _env_lock_path() -> str:
- """One lock file per environment: next to its site-packages when writable, else in the temp dir."""
+ """One lock file per environment: next to its site-packages when writable, else in a per-user temp folder."""
import hashlib
+ from utils.paths.private_tmp import private_tmp_dir
+
name = ".unsloth-flashinfer-install.lock"
if os.access(sys.prefix, os.W_OK):
return os.path.join(sys.prefix, name)
digest = hashlib.sha256(os.path.realpath(sys.prefix).encode()).hexdigest()[:16]
- return os.path.join(tempfile.gettempdir(), f"{name}.{digest}")
+ return os.path.join(private_tmp_dir("unsloth-flashinfer-lock"), f"{name}.{digest}")
@contextlib.contextmanager
diff --git a/studio/backend/core/inference/os_sandbox.py b/studio/backend/core/inference/os_sandbox.py
index c98a60198f5..721284bc790 100644
--- a/studio/backend/core/inference/os_sandbox.py
+++ b/studio/backend/core/inference/os_sandbox.py
@@ -661,6 +661,7 @@ def model_library_roots() -> tuple[str, ...]:
return ()
state = studio_state_roots()
forbidden = _never_a_model_library()
+ hf_homes = _hf_home_roots()
kept: list[str] = []
for path in candidates:
if not path or not os.path.isabs(path):
@@ -674,6 +675,9 @@ def model_library_roots() -> tuple[str, ...]:
# The approval gate still asks for a credential inside a model folder; a whole-folder grant would not.
if tool_path_approval._references_sensitive_path(real + os.sep):
continue
+ # The root check can't see an HF home's token / stored_tokens at this folder's top.
+ if any(_is_within(home, real) for home in hf_homes) or _holds_a_credential_file(real):
+ continue
if any(_paths_overlap(real, root) for root in state):
continue
if real not in kept:
@@ -681,6 +685,48 @@ def model_library_roots() -> tuple[str, ...]:
return tuple(kept)
+_CREDENTIAL_BASENAMES = (".env",) # plus the approval gate's own list, read at call time
+
+
+def _hf_home_roots() -> tuple[str, ...]:
+ homes: list[str] = []
+ try:
+ from utils.hf_cache_settings import known_hf_cache_homes
+
+ # Cache history and download homes often hold only hub bytes; a home counts once it holds a token.
+ for home in known_hf_cache_homes():
+ home = os.path.realpath(str(home))
+ if any(
+ os.path.lexists(os.path.join(home, name)) for name in ("token", "stored_tokens")
+ ):
+ homes.append(home)
+ except Exception: # noqa: BLE001 - never fail a launch over the cache settings
+ pass
+ # HF_TOKEN_PATH moves token, and stored_tokens beside it, out of the HF home.
+ token_path = os.environ.get("HF_TOKEN_PATH")
+ if token_path and token_path != os.devnull:
+ token_path = os.path.expanduser(os.path.expandvars(token_path))
+ if os.path.isabs(token_path):
+ homes.append(os.path.dirname(os.path.realpath(token_path)))
+ return tuple(homes)
+
+
+def _is_within(path: str, root: str) -> bool:
+ if sys.platform in ("darwin", "win32"):
+ # Case-insensitive volumes; over-matching on a case-sensitive one only skips a grant.
+ path, root = path.casefold(), root.casefold()
+ try:
+ return os.path.commonpath([path, root]) == root
+ except ValueError:
+ return False
+
+
+def _holds_a_credential_file(folder: str) -> bool:
+ from .tool_path_approval import _CREDENTIAL_BASENAMES as approval_names
+ names = (*_CREDENTIAL_BASENAMES, *sorted(approval_names))
+ return any(os.path.lexists(os.path.join(folder, name)) for name in names)
+
+
def _is_filesystem_root(path: str, pathmod: Any = None) -> bool:
"""Whether *path* is a filesystem root; not ``path == os.sep``, which misses Windows drive roots."""
return (pathmod or os.path).dirname(path) == path
@@ -994,7 +1040,7 @@ def capability_snapshot(
environment_fingerprint = identity,
remediation = (
"Python and Terminal run with OS isolation. The network is not confined; a tool "
- "call can still reach the internet."
+ "call can still reach the internet and services listening on this machine's loopback."
),
)
diff --git a/studio/backend/core/inference/tool_confinement.py b/studio/backend/core/inference/tool_confinement.py
index f7c8315b414..424f7efda57 100644
--- a/studio/backend/core/inference/tool_confinement.py
+++ b/studio/backend/core/inference/tool_confinement.py
@@ -40,7 +40,9 @@ _FS_MAKE_SYM = 1 << 12
_FS_REFER = 1 << 13 # ABI 2
_FS_TRUNCATE = 1 << 14 # ABI 3
_FS_IOCTL_DEV = 1 << 15 # ABI 5
-_SCOPE_SIGNAL = 1 << 1 # ABI 6: signals confined to the same domain
+# ABI 6: scope abstract AF_UNIX sockets and signals. Pathname sockets need ABI 9's RESOLVE_UNIX.
+_SCOPE_ABSTRACT_UNIX_SOCKET = 1 << 0
+_SCOPE_SIGNAL = 1 << 1
_FS_ABI1_MASK = (1 << 13) - 1
_SYSTEM_READ_ROOTS = (
@@ -463,7 +465,9 @@ def _linux_confinement(sandbox_site_dir: str) -> Optional[Confinement]:
rules = _landlock_rules(abi, sandbox_site_dir)
return Confinement(
mechanism = f"landlock-abi{abi}",
- preexec = partial(_landlock_preexec, handled, rules, _SCOPE_SIGNAL),
+ preexec = partial(
+ _landlock_preexec, handled, rules, _SCOPE_SIGNAL | _SCOPE_ABSTRACT_UNIX_SOCKET
+ ),
)
diff --git a/studio/backend/core/inference/video_ltx25.py b/studio/backend/core/inference/video_ltx25.py
index ea7043a7592..07ada73b195 100644
--- a/studio/backend/core/inference/video_ltx25.py
+++ b/studio/backend/core/inference/video_ltx25.py
@@ -562,7 +562,9 @@ def ltx25_transformer_config_dir() -> str:
import json
import tempfile
- root = Path(tempfile.gettempdir()) / "unsloth_ltx25_config"
+ from utils.paths.private_tmp import private_tmp_dir
+
+ root = private_tmp_dir("unsloth_ltx25_config")
target = root / "transformer" / "config.json"
payload = json.dumps(
{"_class_name": "LTX2VideoTransformer3DModel", **LTX25_TRANSFORMER_CONFIG},
diff --git a/studio/backend/core/training/account_jobs.py b/studio/backend/core/training/account_jobs.py
index 25b09a82747..a20a8faecea 100644
--- a/studio/backend/core/training/account_jobs.py
+++ b/studio/backend/core/training/account_jobs.py
@@ -90,7 +90,11 @@ def account_path(
if not value or not managed_account():
return value
raw = str(value)
- from utils.paths.path_utils import normalize_path
+ from utils.paths.path_utils import is_network_or_device_path, normalize_path
+
+ # Before any exists()/resolve(): touching a share path is already an outbound SMB sign-in.
+ if is_network_or_device_path(raw):
+ raise HTTPException(status_code = 403, detail = "Path is outside this account's workspace")
normalized = normalize_path(raw)
if normalized != raw:
diff --git a/studio/backend/hub/services/models/account_access.py b/studio/backend/hub/services/models/account_access.py
index f339a3b09c7..9124d2c1667 100644
--- a/studio/backend/hub/services/models/account_access.py
+++ b/studio/backend/hub/services/models/account_access.py
@@ -923,6 +923,11 @@ def model_visible(
def _model_visible(reference: str, grants, repo_type: str, offline: bool) -> bool:
access_options = {"offline": True} if offline else {}
+ from utils.paths.path_utils import is_network_or_device_path
+
+ # Before any exists()/resolve(): touching a share path is already an outbound SMB sign-in.
+ if is_network_or_device_path(reference):
+ return False
path = Path(reference).expanduser()
if path.is_absolute() or reference.startswith(("./", "../", "~")) or path.exists():
try:
@@ -960,7 +965,12 @@ def require_model_access(
) -> None:
access_options = {"offline": True} if offline else {}
if not model_visible(reference, repo_type = repo_type, **access_options):
- if repo_type == "model":
+ from utils.paths.path_utils import is_network_or_device_path
+
+ # The allowlist check below resolves the reference on disk: not for a share path.
+ if repo_type == "model" and not (
+ isinstance(reference, str) and is_network_or_device_path(reference)
+ ):
require_model_allowed(reference)
raise HTTPException(status_code = 404, detail = "Model not found")
@@ -1001,8 +1011,13 @@ def private_directory(path: str, folder: str) -> str:
"""Rebase import-time owner defaults; refuse account-external scans."""
if not managed_account():
return path
+ from utils.paths.path_utils import is_network_or_device_path
from utils.paths.storage_roots import studio_root
+ # Before resolve(): touching a share path is already an outbound SMB sign-in.
+ if is_network_or_device_path(path):
+ raise HTTPException(status_code = 404, detail = "Directory not found")
+
normalized = normalize_path(path)
if normalized != path:
# Scanners open the forward-slash spelling, so it must be the account's own too.
@@ -1040,6 +1055,21 @@ def authorize_download(repo_id: str, repo_type: str, hf_token) -> None:
def require_media_references(request) -> None:
+ from utils.paths.path_utils import is_network_or_device_path
+
+ # Before the resolve()/is_dir() calls below: touching a share path is already an outbound SMB sign-in.
+ fields = (
+ "model_path",
+ "gguf_filename",
+ "transformer_prequant_path",
+ "text_encoder_file",
+ "vae_file",
+ )
+ for name in fields:
+ value = getattr(request, name, None)
+ for item in value if isinstance(value, (list, tuple)) else [value]:
+ if isinstance(item, str) and is_network_or_device_path(item):
+ raise HTTPException(status_code = 404, detail = "Model not found")
require_media_adapters(request)
for name in ("gguf_filename", "transformer_prequant_path"):
reference = getattr(request, name, None)
diff --git a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/impl.py b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/impl.py
index 97411c57f73..6fc610c5b49 100644
--- a/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/impl.py
+++ b/studio/backend/plugins/data-designer-github-repo-seed/src/data_designer_github_repo_seed/impl.py
@@ -4,7 +4,6 @@
from __future__ import annotations
import hashlib
-import tempfile
import threading
from pathlib import Path
from typing import Optional
@@ -58,7 +57,10 @@ class GitHubRepoSeedReader(SeedReader[GitHubRepoSeedSource]):
return lazy.duckdb.connect()
def get_dataset_uri(self) -> str:
- out_dir = Path(tempfile.gettempdir()) / "studio-github-repo-seed"
+ from utils.paths.private_tmp import private_tmp_dir
+
+ # Private: a token-backed scrape can hold a private repo's issues and PRs.
+ out_dir = private_tmp_dir("studio-github-repo-seed")
cfg = ScrapeConfig(
repos = list(self.source.repos),
token = self.source.token,
diff --git a/studio/backend/routes/training.py b/studio/backend/routes/training.py
index 24032a68a5a..5a665072964 100644
--- a/studio/backend/routes/training.py
+++ b/studio/backend/routes/training.py
@@ -3609,6 +3609,11 @@ def _resolve_diffusion_data_dir(raw: str) -> Path:
from utils.paths import datasets_root
value = str(raw or "").strip()
+ from utils.paths.path_utils import is_network_or_device_path
+
+ # Before dataset resolution touches the disk: a share path is already an outbound SMB sign-in.
+ if is_network_or_device_path(value) and managed_account():
+ raise HTTPException(status_code = 403, detail = "Path is outside this account's workspace")
if value and "\x00" not in value:
p = Path(value)
# A single component that is not "..", so joining under datasets_root() cannot escape it.
diff --git a/studio/backend/tests/test_account_tool_confinement.py b/studio/backend/tests/test_account_tool_confinement.py
index 121681234de..7a05dd85158 100644
--- a/studio/backend/tests/test_account_tool_confinement.py
+++ b/studio/backend/tests/test_account_tool_confinement.py
@@ -161,7 +161,7 @@ def test_macos_profile_hides_other_accounts_temporary_roots(tmp_path, monkeypatc
(run_as(BOB, storage_roots.tmp_root) / "dataset.jsonl").write_text("BOB_PRIVATE")
profile = run_as(ALICE, tools._account_confinement).wrap(["bash"])[2]
- base = str((shared_tmp / "unsloth-studio").resolve())
+ base = str(storage_roots.shared_tmp_root().resolve())
alice_tmp = str(run_as(ALICE, storage_roots.tmp_root).resolve())
bob_tmp = str(run_as(BOB, storage_roots.tmp_root).resolve())
@@ -666,7 +666,7 @@ def test_default_layout_denies_exactly_the_previous_macos_roots(tmp_path, monkey
assert denied == {
"/private/var/folders",
str((tmp_path / "studio").resolve()),
- str((shared_tmp / "unsloth-studio").resolve()),
+ str(storage_roots.shared_tmp_root().resolve()),
str(home.resolve()),
}
diff --git a/studio/backend/tests/test_account_tool_confinement_abstract_unix.py b/studio/backend/tests/test_account_tool_confinement_abstract_unix.py
new file mode 100644
index 00000000000..6799900abd7
--- /dev/null
+++ b/studio/backend/tests/test_account_tool_confinement_abstract_unix.py
@@ -0,0 +1,68 @@
+# 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 Landlock ruleset scopes abstract AF_UNIX sockets as well as signals."""
+
+import os
+import socket
+import subprocess
+import sys
+
+import pytest
+
+from core.inference import tool_confinement
+
+
+def test_the_managed_ruleset_scopes_abstract_unix_sockets(monkeypatch):
+ monkeypatch.setattr(tool_confinement, "landlock_abi", lambda: 6)
+ monkeypatch.setattr(tool_confinement, "_landlock_rules", lambda abi, site: [])
+ confinement = tool_confinement._linux_confinement("/tmp/site")
+ assert confinement is not None
+ scope = confinement.preexec.args[2]
+ abstract_unix = 1 << 0 # LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET
+ signal = 1 << 1 # LANDLOCK_SCOPE_SIGNAL
+ assert scope & abstract_unix
+ assert scope & signal
+
+
+_live = pytest.mark.skipif(
+ sys.platform != "linux" or tool_confinement.landlock_abi() < 6,
+ reason = "needs a kernel able to apply the ABI 6 scopes",
+)
+
+_CONNECT = (
+ "import socket, sys\n"
+ "s = socket.socket(socket.AF_UNIX)\n"
+ "try:\n"
+ " s.connect(sys.argv[1].replace('@', chr(0), 1)); print('CONNECTED')\n"
+ "except OSError as e:\n"
+ " print('refused', e.errno)\n"
+)
+
+
+def _confined_connect(monkeypatch, address):
+ # Read-only `/` stands in for the account's rules, which need a configured Unsloth Studio home.
+ tc = tool_confinement
+ read_only = tc._FS_EXECUTE | tc._FS_READ_FILE | tc._FS_READ_DIR
+ monkeypatch.setattr(tc, "_landlock_rules", lambda abi, site: [("/", read_only)])
+ confinement = tool_confinement._linux_confinement("/tmp/site")
+ assert confinement is not None
+ return subprocess.run(
+ [sys.executable, "-c", _CONNECT, address],
+ preexec_fn = confinement.preexec,
+ capture_output = True,
+ text = True,
+ timeout = 30,
+ ).stdout.strip()
+
+
+@_live
+def test_a_confined_child_cannot_reach_an_outside_abstract_socket(monkeypatch):
+ name = f"unsloth-abstract-probe-{os.getpid()}"
+ server = socket.socket(socket.AF_UNIX)
+ server.bind("\0" + name)
+ server.listen(1)
+ try:
+ assert _confined_connect(monkeypatch, "@" + name).startswith("refused")
+ finally:
+ server.close()
diff --git a/studio/backend/tests/test_managed_unc_paths.py b/studio/backend/tests/test_managed_unc_paths.py
new file mode 100644
index 00000000000..ad1f681885c
--- /dev/null
+++ b/studio/backend/tests/test_managed_unc_paths.py
@@ -0,0 +1,165 @@
+# 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 path checks refuse a UNC or device path before touching the disk."""
+
+import errno
+import os
+from pathlib import Path
+
+import pytest
+from fastapi import HTTPException
+
+from core.training import account_jobs
+from hub.services.models import account_access
+from utils.account_context import AccountContext, bind_account, reset_account
+
+ALICE = AccountContext("a" * 32, "alice")
+UNC = "\\\\attacker.invalid\\share\\m"
+# Win32 hands a \\??\\ path to the NT namespace unchanged, so this is a UNC share too.
+NT_UNC = "\\??\\UNC\\attacker.invalid\\share\\m"
+UNC_PREFIXES = ("\\\\", "//", "\\??\\")
+
+
+def studio_home(tmp_path, monkeypatch):
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path / "studio"))
+ return tmp_path
+
+
+def unc_calls(monkeypatch):
+ calls = []
+ real_exists, real_realpath, real_resolve = os.path.exists, os.path.realpath, Path.resolve
+ real_stat = Path.stat
+
+ def exists(p):
+ if str(p).startswith(UNC_PREFIXES):
+ calls.append(("exists", str(p)))
+ return False
+ return real_exists(p)
+
+ def realpath(p, *a, **k):
+ if str(p).startswith(UNC_PREFIXES):
+ calls.append(("realpath", str(p)))
+ return str(p)
+ return real_realpath(p, *a, **k)
+
+ def resolve(self, *a, **k):
+ if str(self).startswith(UNC_PREFIXES):
+ calls.append(("resolve", str(self)))
+ return self
+ return real_resolve(self, *a, **k)
+
+ def stat(self, *a, **k):
+ if str(self).startswith(UNC_PREFIXES):
+ calls.append(("stat", str(self)))
+ raise FileNotFoundError(errno.ENOENT, "not found", str(self))
+ return real_stat(self, *a, **k)
+
+ monkeypatch.setattr(os.path, "exists", exists)
+ monkeypatch.setattr(os.path, "realpath", realpath)
+ monkeypatch.setattr(Path, "resolve", resolve)
+ monkeypatch.setattr(Path, "stat", stat)
+ return calls
+
+
[email protected]("unc", [UNC, NT_UNC])
+def test_account_checks_refuse_a_unc_path_before_resolving_it(studio_home, unc_calls, unc):
+ token = bind_account(ALICE)
+ try:
+ for reference in (False, True):
+ with pytest.raises(HTTPException) as info:
+ account_jobs.account_path(unc, reference = reference)
+ assert info.value.status_code == 403
+ assert account_access.model_visible(unc) is False
+ finally:
+ reset_account(token)
+ assert unc_calls == []
+
+
+def test_a_path_inside_the_workspace_still_passes(studio_home):
+ from utils.paths.storage_roots import workspace_root
+ token = bind_account(ALICE)
+ try:
+ inside = workspace_root() / "data" / "file.jsonl"
+ assert account_jobs.account_path(str(inside)) == str(inside)
+ finally:
+ reset_account(token)
+
+
+ "value",
+ [
+ "\\\\host\\share",
+ "//host/share",
+ "\\\\?\\C:\\x",
+ "\\\\.\\PhysicalDrive0",
+ "\\/host/share",
+ "\\??\\UNC\\host\\share",
+ ],
+)
+def test_network_and_device_spellings_are_recognised(value):
+ from utils.paths.path_utils import is_network_or_device_path
+ assert is_network_or_device_path(value)
+
+
+def test_local_spellings_are_not_network_paths():
+ from utils.paths.path_utils import is_network_or_device_path
+ assert not is_network_or_device_path("C:\\Users\\x")
+ assert not is_network_or_device_path("/home/x")
+
+
+def test_the_allowlist_fallback_does_not_touch_a_unc_path(studio_home, unc_calls, monkeypatch):
+ # The allowlist check resolves paths on disk, which a share path must never reach.
+ monkeypatch.setattr(account_access, "model_allowlist", lambda: {"org/allowed"})
+ token = bind_account(ALICE)
+ try:
+ with pytest.raises(HTTPException) as info:
+ account_access.require_model_access(UNC)
+ assert info.value.status_code == 404
+ finally:
+ reset_account(token)
+ assert unc_calls == []
+
+
+def test_a_folder_scan_refuses_a_unc_path_before_resolving_it(studio_home, unc_calls):
+ token = bind_account(ALICE)
+ try:
+ with pytest.raises(HTTPException) as info:
+ account_access.private_directory(UNC, "models")
+ assert info.value.status_code == 404
+ finally:
+ reset_account(token)
+ assert unc_calls == []
+
+
+ "field", ["model_path", "transformer_prequant_path", "text_encoder_file", "vae_file"]
+)
+def test_media_references_refuse_a_unc_path_before_resolving_it(studio_home, unc_calls, field):
+ from types import SimpleNamespace
+
+ request = SimpleNamespace(model_path = "org/model", adapters = None)
+ setattr(request, field, [UNC] if field == "text_encoder_file" else UNC)
+ token = bind_account(ALICE)
+ try:
+ with pytest.raises(HTTPException) as info:
+ account_access.require_media_references(request)
+ assert info.value.status_code == 404
+ finally:
+ reset_account(token)
+ assert unc_calls == []
+
+
+def test_a_diffusion_data_dir_refuses_a_unc_path_before_resolving_it(studio_home, unc_calls):
+ from routes import training
+
+ token = bind_account(ALICE)
+ try:
+ with pytest.raises(HTTPException) as info:
+ training._resolve_diffusion_data_dir(UNC)
+ assert info.value.status_code == 403
+ finally:
+ reset_account(token)
+ assert unc_calls == []
diff --git a/studio/backend/tests/test_owner_sandbox_grants.py b/studio/backend/tests/test_owner_sandbox_grants.py
new file mode 100644
index 00000000000..cf4dc0590e9
--- /dev/null
+++ b/studio/backend/tests/test_owner_sandbox_grants.py
@@ -0,0 +1,118 @@
+# 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 model folder granted to the jails whole must not be (or hold) an HF home."""
+
+import os
+
+import pytest
+
+from core.inference import os_sandbox, tool_path_approval
+
+
+def roots(monkeypatch, tmp_path):
+ def register(*folders, hf_homes = ()):
+ monkeypatch.setattr(
+ tool_path_approval, "_scan_folder_roots", lambda: tuple(map(str, folders))
+ )
+ monkeypatch.setattr(
+ "utils.paths.storage_roots.well_known_model_dirs", lambda: (), raising = False
+ )
+ monkeypatch.setattr(
+ "utils.hf_cache_settings.known_hf_cache_homes", lambda: list(hf_homes), raising = False
+ )
+ return os_sandbox.model_library_roots()
+
+ return register
+
+
+def test_a_registered_hf_home_is_not_granted(roots, tmp_path):
+ hf_home = tmp_path / "hf"
+ (hf_home / "hub").mkdir(parents = True)
+ (hf_home / "token").write_text("hf_FAKE")
+ assert roots(hf_home, hf_homes = [hf_home]) == ()
+
+
+def test_a_folder_holding_an_hf_home_is_not_granted(roots, tmp_path):
+ cache = tmp_path / "cache"
+ hf_home = cache / "huggingface"
+ hf_home.mkdir(parents = True)
+ (hf_home / "stored_tokens").write_text("[]")
+ assert roots(cache, hf_homes = [hf_home]) == ()
+
+
+def test_a_folder_holding_a_cache_only_home_is_still_granted(roots, tmp_path):
+ models = tmp_path / "models"
+ (models / "hf" / "hub").mkdir(parents = True)
+ assert roots(models, hf_homes = [models / "hf"]) == (os.path.realpath(models),)
+
+
[email protected]("name", ["token", "stored_tokens", ".env", ".git-credentials", ".netrc"])
+def test_a_folder_with_a_credential_file_at_its_top_is_not_granted(roots, tmp_path, name):
+ folder = tmp_path / "models"
+ folder.mkdir()
+ (folder / name).write_text("FAKE")
+ assert roots(folder) == ()
+
+
+def test_a_folder_holding_the_hf_token_path_is_not_granted(roots, tmp_path, monkeypatch):
+ folder = tmp_path / "models"
+ (folder / "secrets").mkdir(parents = True)
+ (folder / "secrets" / "hf-token").write_text("hf_FAKE")
+ monkeypatch.setenv("HF_TOKEN_PATH", str(folder / "secrets" / "hf-token"))
+ assert roots(folder) == ()
+
+
+def _native(*parts):
+ return os.path.join(os.sep, *parts)
+
+
[email protected]("platform", ["darwin", "win32"])
+def test_an_hf_home_spelled_in_another_case_is_still_inside(monkeypatch, platform):
+ # macOS realpath keeps the spelling it was given, so /users/alice/models must still hold /Users/Alice/....
+ monkeypatch.setattr(os_sandbox.sys, "platform", platform)
+ home, library = (
+ _native("Users", "Alice", "models", "huggingface"),
+ _native("users", "alice", "models"),
+ )
+ assert os_sandbox._is_within(home, library)
+
+
+def test_case_still_counts_on_linux(monkeypatch):
+ monkeypatch.setattr(os_sandbox.sys, "platform", "linux")
+ home, library = (
+ _native("Users", "Alice", "models", "huggingface"),
+ _native("users", "alice", "models"),
+ )
+ assert not os_sandbox._is_within(home, library)
+
+
+def test_an_ordinary_model_folder_and_the_hub_under_an_hf_home_are_granted(roots, tmp_path):
+ models = tmp_path / "models"
+ models.mkdir()
+ (models / "model.gguf").write_text("x")
+ hub = tmp_path / "hf" / "hub"
+ hub.mkdir(parents = True)
+ granted = roots(models, hub, hf_homes = [tmp_path / "hf"])
+ assert granted == (os.path.realpath(models), os.path.realpath(hub))
+
+
[email protected]("platform", ["linux", "darwin"])
+def test_the_capability_text_says_loopback_is_reachable(monkeypatch, platform):
+ # Imported under the real platform first, so nothing caches the faked one.
+ from core.inference import sandbox_linux, sandbox_macos, sandbox_probe # noqa: F401
+
+ monkeypatch.setattr(os_sandbox.sys, "platform", platform)
+ monkeypatch.setattr(os_sandbox, "_runtime_identity", lambda: "id")
+ monkeypatch.setattr(sandbox_probe, "probe", lambda backend, force = False: (True, "ok"))
+ capability = os_sandbox.capability_snapshot()
+ assert capability.available
+ assert "loopback" in capability.remediation
+
+
[email protected]("name", ["credentials", "auth.db", ".pypirc", ".npmrc", "id_ed25519"])
+def test_a_folder_holding_any_approval_gated_credential_is_not_granted(tmp_path, name):
+ from core.inference import os_sandbox
+ (tmp_path / name).write_text("secret")
+ assert os_sandbox._holds_a_credential_file(str(tmp_path))
diff --git a/studio/backend/tests/test_private_tmp_dirs.py b/studio/backend/tests/test_private_tmp_dirs.py
new file mode 100644
index 00000000000..ee292807bb7
--- /dev/null
+++ b/studio/backend/tests/test_private_tmp_dirs.py
@@ -0,0 +1,187 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Studio's folders in a shared system temp dir must be per user and refuse a planted link or foreign owner."""
+
+from __future__ import annotations
+
+import importlib
+import os
+import stat
+import sys
+import tempfile
+import types
+from pathlib import Path
+
+import pytest
+
+pytestmark = pytest.mark.skipif(not hasattr(os, "getuid"), reason = "POSIX owner and mode checks")
+
+_SEED_SRC = (
+ Path(__file__).resolve().parents[1] / "plugins" / "data-designer-github-repo-seed" / "src"
+)
+
+
+def _plant(tmp: Path, base: str) -> Path:
+ """A link at both the old shared name and the per-user name, pointing at a folder we watch."""
+ decoy = tmp / "decoy"
+ decoy.mkdir(exist_ok = True)
+ for name in (base, f"{base}-{os.getuid()}"):
+ (tmp / name).symlink_to(decoy, target_is_directory = True)
+ return decoy
+
+
+def _open_dir(tmp: Path, base: str) -> None:
+ for name in (base, f"{base}-{os.getuid()}"):
+ (tmp / name).mkdir()
+ os.chmod(tmp / name, 0o777)
+
+
+def _private(path) -> bool:
+ return stat.S_IMODE(os.lstat(path).st_mode) & 0o077 == 0
+
+
+def tmp(monkeypatch, tmp_path):
+ root = tmp_path / "tmp"
+ root.mkdir()
+ monkeypatch.setattr(tempfile, "gettempdir", lambda: str(root))
+ return root
+
+
+def _ltx():
+ from core.inference import video_ltx25
+ return video_ltx25.ltx25_transformer_config_dir
+
+
+def _tmp_root():
+ from utils.paths import storage_roots
+ return storage_roots.tmp_root
+
+
+def _flashinfer_lock(monkeypatch):
+ from core.inference import diffusion_nvfp4_install as inst
+
+ real_access = os.access
+ monkeypatch.setattr(
+ inst.os, "access", lambda p, m: False if p == sys.prefix else real_access(p, m)
+ )
+ return lambda: os.path.dirname(inst._env_lock_path())
+
+
+def _seed_reader(monkeypatch):
+ try:
+ importlib.import_module("data_designer.engine.resources.seed_reader")
+ except ImportError:
+
+ class SeedReader:
+ def __class_getitem__(cls, item):
+ return cls
+
+ stubs = {
+ "data_designer": {},
+ "data_designer.lazy_heavy_imports": {},
+ "data_designer.engine": {},
+ "data_designer.engine.resources": {},
+ "data_designer.engine.resources.seed_reader": {"SeedReader": SeedReader},
+ "data_designer_github_repo_seed.config": {"GitHubRepoSeedSource": object},
+ }
+ for name, attrs in stubs.items():
+ module = types.ModuleType(name)
+ module.__dict__.update(attrs)
+ monkeypatch.setitem(sys.modules, name, module)
+ for name in stubs:
+ parent, _, child = name.rpartition(".")
+ if parent in stubs:
+ setattr(sys.modules[parent], child, sys.modules[name])
+ monkeypatch.syspath_prepend(str(_SEED_SRC))
+ for name in [m for m in sys.modules if m.startswith("data_designer_github_repo_seed")]:
+ if name != "data_designer_github_repo_seed.config":
+ monkeypatch.delitem(sys.modules, name)
+ impl = importlib.import_module("data_designer_github_repo_seed.impl")
+ seen = []
+
+ def materialize(cfg, out_dir):
+ out_dir.mkdir(parents = True, exist_ok = True)
+ seen.append(out_dir)
+ out = out_dir / "rows.jsonl"
+ out.write_text("{}\n", encoding = "utf-8")
+ return out
+
+ monkeypatch.setattr(impl, "materialize_to_jsonl", materialize)
+ monkeypatch.setattr(impl, "_SCRAPE_CACHE", {})
+ reader = impl.GitHubRepoSeedReader.__new__(impl.GitHubRepoSeedReader)
+ reader.source = types.SimpleNamespace(
+ repos = ["o/r"],
+ token = "t",
+ item_types = ["issues"],
+ limit = 1,
+ include_comments = False,
+ max_comments_per_item = 0,
+ )
+
+ def call():
+ reader.get_dataset_uri()
+ return seen[-1]
+
+ return call
+
+
+SITES = {
+ "ltx25_config": ("unsloth_ltx25_config", lambda mp: _ltx()),
+ "tmp_root": ("unsloth-studio", lambda mp: _tmp_root()),
+ "flashinfer_lock": ("unsloth-flashinfer-lock", _flashinfer_lock),
+ "github_seed": ("studio-github-repo-seed", _seed_reader),
+}
+
+
[email protected]("site", sorted(SITES))
+def test_planted_link_is_refused(site, tmp, monkeypatch):
+ base, make = SITES[site]
+ call = make(monkeypatch)
+ decoy = _plant(tmp, base)
+ with pytest.raises(PermissionError):
+ call()
+ assert list(decoy.iterdir()) == []
+
+
[email protected]("site", sorted(SITES))
+def test_folder_of_another_owner_is_refused(site, tmp, monkeypatch):
+ base, make = SITES[site]
+ call = make(monkeypatch)
+ for name in (base, f"{base}-{os.getuid() + 1}"):
+ (tmp / name).mkdir(mode = 0o700)
+ monkeypatch.setattr(os, "getuid", lambda real = os.getuid(): real + 1)
+ with pytest.raises(PermissionError):
+ call()
+
+
[email protected]("site", sorted(SITES))
+def test_open_modes_are_taken_away(site, tmp, monkeypatch):
+ base, make = SITES[site]
+ call = make(monkeypatch)
+ _open_dir(tmp, base)
+ folder = Path(call())
+ assert folder.name == f"{base}-{os.getuid()}" and _private(folder)
+
+
[email protected]("site", sorted(SITES))
+def test_fresh_folder_is_private_and_per_user(site, tmp, monkeypatch):
+ base, make = SITES[site]
+ call = make(monkeypatch)
+ old = os.umask(0o022)
+ try:
+ folder = Path(call())
+ finally:
+ os.umask(old)
+ assert folder.parent == tmp and folder.name == f"{base}-{os.getuid()}"
+ assert _private(folder)
+
+
+def test_mode_that_will_not_go_is_refused(tmp, monkeypatch):
+ from utils.paths import private_tmp
+
+ _open_dir(tmp, "probe")
+ monkeypatch.setattr(private_tmp.os, "chmod", lambda *a, **k: None)
+ with pytest.raises(PermissionError):
+ private_tmp.private_tmp_dir("probe")
diff --git a/studio/backend/utils/paths/path_utils.py b/studio/backend/utils/paths/path_utils.py
index a8f269552d3..8c623293cfd 100644
--- a/studio/backend/utils/paths/path_utils.py
+++ b/studio/backend/utils/paths/path_utils.py
@@ -334,6 +334,14 @@ def is_path_within(
return common == base and (allow_root or candidate != base)
+def is_network_or_device_path(value) -> bool:
+ """A UNC share (``\\\\host\\share``, ``//host/share``) or a ``\\\\?\\`` / ``\\\\.\\`` / ``\\??\\`` device path.
+ Any filesystem call on one makes Windows reach out over SMB with the service account's
+ credentials, so managed-account checks refuse it before touching the disk."""
+ text = str(value).strip()
+ return text.startswith(("\\\\", "//", "\\/", "/\\", "\\??\\"))
+
+
def same_path(
left,
right,
diff --git a/studio/backend/utils/paths/private_tmp.py b/studio/backend/utils/paths/private_tmp.py
new file mode 100644
index 00000000000..6722fde13e1
--- /dev/null
+++ b/studio/backend/utils/paths/private_tmp.py
@@ -0,0 +1,43 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Per-user folders in the system temp dir, for hosts where that dir is shared between accounts."""
+
+from __future__ import annotations
+
+import errno
+import os
+import stat
+import tempfile
+from pathlib import Path
+
+
+def private_tmp_path(name: str) -> Path:
+ """Where ``private_tmp_dir(name)`` lives; no I/O. Windows ``%TEMP%`` is already per user."""
+ if hasattr(os, "getuid"):
+ name = f"{name}-{os.getuid()}"
+ return Path(tempfile.gettempdir()) / name
+
+
+def private_tmp_dir(name: str) -> Path:
+ """Create (or reuse) a 0700 per-user temp folder; refuse a link, foreign owner or lingering g/o write."""
+ path = private_tmp_path(name)
+ path.mkdir(mode = 0o700, parents = True, exist_ok = True)
+ if not hasattr(os, "getuid"):
+ return path
+ info = os.lstat(path)
+ if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid():
+ raise PermissionError(
+ errno.EPERM, "refusing a temp folder that is a link or owned by another user", str(path)
+ )
+ if stat.S_IMODE(info.st_mode) & 0o077:
+ try:
+ os.chmod(path, 0o700)
+ except OSError:
+ pass
+ # Re-read: some network and FUSE mounts ignore chmod and report success.
+ if stat.S_IMODE(os.lstat(path).st_mode) & 0o022:
+ raise PermissionError(
+ errno.EPERM, "refusing a group- or world-writable temp folder", str(path)
+ )
+ return path
diff --git a/studio/backend/utils/paths/storage_roots.py b/studio/backend/utils/paths/storage_roots.py
index b84e8e5151a..6c693de2be5 100644
--- a/studio/backend/utils/paths/storage_roots.py
+++ b/studio/backend/utils/paths/storage_roots.py
@@ -21,6 +21,7 @@ import tempfile
from loggers import get_logger
from utils.account_context import current_account, is_owner_context
from utils.paths.path_utils import drop_appledouble_metadata, host_normalize_path
+from utils.paths.private_tmp import private_tmp_dir, private_tmp_path
logger = get_logger(__name__)
@@ -416,11 +417,12 @@ def project_workspaces_root() -> Path:
def shared_tmp_root() -> Path:
- return Path(tempfile.gettempdir()) / "unsloth-studio"
+ return private_tmp_path("unsloth-studio")
def tmp_root() -> Path:
- root = shared_tmp_root()
+ # Created and checked here: on a shared /tmp another account could own or plant the root.
+ root = private_tmp_dir("unsloth-studio")
if is_owner_context():
return root
return root / "accounts" / current_account().account_id