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: never follow a symlink when linking a file into a tool workspace (#13513)

Daniel Han27ee3d38425e
diff --git a/studio/backend/core/inference/diffusion_multistage.py b/studio/backend/core/inference/diffusion_multistage.py
index 8320ff83e2b..7550b7bf5b9 100644
--- a/studio/backend/core/inference/diffusion_multistage.py
+++ b/studio/backend/core/inference/diffusion_multistage.py
@@ -30,7 +30,6 @@ def module_bytes(module: Any) -> int:
def _denoisers(pipe: Any) -> list:
try:
from .diffusion_cuda_graph import _denoiser_modules
-
return list(_denoiser_modules(pipe))
except Exception: # noqa: BLE001 -- no denoiser found: nothing to hold
return []
@@ -55,7 +54,11 @@ def companions_fit_beside_denoiser(pipe: Any, companions: Iterable[Any]) -> bool
@contextlib.contextmanager
-def hold_denoiser_between_calls(pipe: Any, runner: Any, companions: Iterable[Any] = ()):
+def hold_denoiser_between_calls(
+ pipe: Any,
+ runner: Any,
+ companions: Iterable[Any] = (),
+):
"""Around a pipeline call that another call of the same request follows. ``pipe`` owns the offload hooks
(``enable_model_cpu_offload``); ``runner`` is the pipeline actually called (``pipe`` or a pipeline derived from
its modules, which has no hook list of its own and so never offloads at its end). Without hooks: a no-op.
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 91f14662c33..4e791d97d4f 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -21525,6 +21525,14 @@ _DIR_FD_WRITES = (
)
+# A tool sharing the directory can swap an in-flight temp name for a symlink. Linking must not follow it, or the
+# backend hard-links the symlink's target (any host file it can read) into the sandbox. Windows hard links never
+# follow a symlink source, and os.link there takes no such flag.
+_LINK_NOFOLLOW = (
+ {"follow_symlinks": False} if os.link in getattr(os, "supports_follow_symlinks", set()) else {}
+)
+
+
def _write_spill_file(target_dir: str, name: str, body: str) -> "str | None":
"""Write one spill into ``target_dir``, without following a link at any point.
@@ -21559,7 +21567,7 @@ def _write_spill_file(target_dir: str, name: str, body: str) -> "str | None":
) as handle:
handle.write(body)
installed = os.path.join(target_dir, name)
- os.link(tmp, installed)
+ os.link(tmp, installed, **_LINK_NOFOLLOW)
_quiet_unlink(tmp)
return _spill_stamp(installed)
except OSError:
@@ -21576,7 +21584,7 @@ def _write_spill_file(target_dir: str, name: str, body: str) -> "str | None":
handle.write(body)
# `os.link` rather than a rename: rename replaces the destination silently on POSIX, and the name may have
# been taken since the caller looked. link fails with EEXIST instead, which is the answer this wants.
- os.link(tmp_name, name, src_dir_fd = dir_fd, dst_dir_fd = dir_fd)
+ os.link(tmp_name, name, src_dir_fd = dir_fd, dst_dir_fd = dir_fd, **_LINK_NOFOLLOW)
_quiet_unlink(tmp_name, dir_fd = dir_fd)
# Through the same descriptor, so it is the file just linked rather than whatever the name resolves to by the
# time this returns.
@@ -21702,7 +21710,7 @@ def _install_attachment_copy(workdir: str, relative: str, source: Path) -> None:
):
shutil.copyfileobj(src, out, 1 << 20)
with contextlib.suppress(FileExistsError):
- os.link(tmp, os.path.join(target, name))
+ os.link(tmp, os.path.join(target, name), **_LINK_NOFOLLOW)
finally:
_quiet_unlink(tmp)
return
@@ -21722,7 +21730,7 @@ def _install_attachment_copy(workdir: str, relative: str, source: Path) -> None:
):
shutil.copyfileobj(src, out, 1 << 20)
with contextlib.suppress(FileExistsError):
- os.link(tmp, name, src_dir_fd = fds[-1], dst_dir_fd = fds[-1])
+ os.link(tmp, name, src_dir_fd = fds[-1], dst_dir_fd = fds[-1], **_LINK_NOFOLLOW)
finally:
_quiet_unlink(tmp, dir_fd = fds[-1])
finally:
@@ -21798,7 +21806,7 @@ def _install_upload(workdir: str, name: str, chunks: "Iterable[bytes]", overwrit
if not existed:
try:
# link, not rename: it fails when a tool took the name since the check.
- os.link(tmp, dest, **pair)
+ os.link(tmp, dest, **pair, **_LINK_NOFOLLOW)
return False
except FileExistsError:
if not overwrite:
@@ -22200,7 +22208,7 @@ def _restore_pruned_path(private: str, path: str) -> None:
last resort is to leave the data under the private name and say where it went, rather than
unlink it."""
try:
- os.link(private, path)
+ os.link(private, path, **_LINK_NOFOLLOW)
_quiet_unlink(private)
return
except OSError:
diff --git a/studio/backend/tests/test_diffusion_multistage.py b/studio/backend/tests/test_diffusion_multistage.py
index bf88e6951fb..369e0b374a9 100644
--- a/studio/backend/tests/test_diffusion_multistage.py
+++ b/studio/backend/tests/test_diffusion_multistage.py
@@ -44,7 +44,9 @@ def test_encode_once_shares_the_first_encode_and_isolates_in_place_edits():
other = pipe.encode_prompt(prompt = "q", device = "cpu")
tensor_arg = pipe.encode_prompt(prompt = "p", prompt_embeds = torch.zeros(1))
assert pipe.encodes == 3 and torch.equal(b[0], torch.ones(1, 2)) and c is b
- assert torch.equal(other[0], torch.full((1, 2), 2.0)) and torch.equal(tensor_arg[0], torch.full((1, 2), 3.0))
+ assert torch.equal(other[0], torch.full((1, 2), 2.0)) and torch.equal(
+ tensor_arg[0], torch.full((1, 2), 3.0)
+ )
assert "encode_prompt" not in pipe.__dict__
# an instance attribute (a remote encoder, a cache wrapper) comes back as it was
own = lambda **kw: (torch.zeros(1), None) # noqa: E731
diff --git a/studio/backend/tests/test_diffusion_preview.py b/studio/backend/tests/test_diffusion_preview.py
index 8d833ced7d2..4b985f69a0c 100644
--- a/studio/backend/tests/test_diffusion_preview.py
+++ b/studio/backend/tests/test_diffusion_preview.py
@@ -342,7 +342,11 @@ def test_a_half_size_stage_unpacks_with_its_own_grid(monkeypatch):
try:
half = torch.randn(1, 16 * 11 * 20, 128, device = "cuda")
# Full-size grid: 880 tokens per frame divides the 3520 of 16 half-size frames, so it "fits" but is wrong.
- assert tuple(DP.latent_grid(half, prev.spec, prev.height, prev.width).shape) == (22, 40, 128)
+ assert tuple(DP.latent_grid(half, prev.spec, prev.height, prev.width).shape) == (
+ 22,
+ 40,
+ 128,
+ )
prev._prev = object()
prev.set_render_size(352, 640)
assert (prev.height, prev.width) == (352, 640) and prev._prev is None
diff --git a/studio/backend/tests/test_sandbox_upload_link_race.py b/studio/backend/tests/test_sandbox_upload_link_race.py
new file mode 100644
index 00000000000..be30bb1b070
--- /dev/null
+++ b/studio/backend/tests/test_sandbox_upload_link_race.py
@@ -0,0 +1,56 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""An upload into a sandbox never hard-links a host file in, even if a tool swaps the in-flight temp name for a
+symlink while the bytes are being written."""
+
+import os
+from pathlib import Path
+
+import pytest
+
+from core.inference import tools
+
+pytestmark = pytest.mark.skipif(
+ not hasattr(os, "symlink") or os.name == "nt", reason = "needs POSIX symlinks"
+)
+
+
+def _swapping_chunks(workdir: Path, secret: Path):
+ yield b"first "
+ # What a tool running in the sandbox can do mid-upload: replace the temp name with a link to a host file.
+ (tmp,) = [p for p in workdir.iterdir() if p.name.startswith(".tmp-")]
+ tmp.unlink()
+ tmp.symlink_to(secret)
+ yield b"second"
+
+
+def test_a_swapped_temp_symlink_is_not_followed_into_the_sandbox(tmp_path):
+ workdir = tmp_path / "sandbox"
+ workdir.mkdir()
+ secret = tmp_path / "auth.db"
+ secret.write_bytes(b"JWT-SECRET")
+
+ try:
+ tools._install_upload(str(workdir), "up.txt", _swapping_chunks(workdir, secret), False)
+ except Exception:
+ pass # refusing the upload is fine too; what must not happen is the link below
+
+ dest = workdir / "up.txt"
+ if os.path.lexists(dest):
+ assert os.lstat(dest).st_ino != os.stat(secret).st_ino
+ assert not (dest.is_file() and not dest.is_symlink() and dest.read_bytes() == b"JWT-SECRET")
+ assert secret.read_bytes() == b"JWT-SECRET"
+ assert os.stat(secret).st_nlink == 1
+
+
+def test_a_normal_upload_is_a_regular_file(tmp_path):
+ workdir = tmp_path / "sandbox"
+ workdir.mkdir()
+ assert (
+ tools._install_upload(str(workdir), "up.txt", iter([b"hello ", b"world"]), False) is False
+ )
+ dest = workdir / "up.txt"
+ assert dest.is_file() and not dest.is_symlink()
+ assert dest.read_bytes() == b"hello world"
+ assert [p.name for p in workdir.iterdir()] == ["up.txt"]
diff --git a/studio/backend/tests/test_video_ltx25.py b/studio/backend/tests/test_video_ltx25.py
index b40ca4fd277..e22510b188c 100644
--- a/studio/backend/tests/test_video_ltx25.py
+++ b/studio/backend/tests/test_video_ltx25.py
@@ -1232,11 +1232,22 @@ def test_each_stage_names_its_size_before_it_runs(monkeypatch):
# Live previews unpack the packed latents with the stage size: half for stage 1, full for stage 2.
pipe = _FakePipe(SimpleNamespace(keep_tokens = None))
stages = []
- v25.render(pipe, _kwargs(), dev = False, upsampler = _Upsampler(), on_stage = lambda w, h: stages.append((w, h)))
+ v25.render(
+ pipe,
+ _kwargs(),
+ dev = False,
+ upsampler = _Upsampler(),
+ on_stage = lambda w, h: stages.append((w, h)),
+ )
assert stages == [(640, 352), (1280, 704)]
# dev: one full-size stage
stages.clear()
- v25.render(pipe, dict(_kwargs(), num_inference_steps = 30), dev = True, on_stage = lambda w, h: stages.append((w, h)))
+ v25.render(
+ pipe,
+ dict(_kwargs(), num_inference_steps = 30),
+ dev = True,
+ on_stage = lambda w, h: stages.append((w, h)),
+ )
assert stages == [(1280, 704)]
# a failing hint never fails the render
@@ -1268,7 +1279,9 @@ class _OffloadedPipe(_FakePipe):
@pytest.mark.parametrize("fits", [True, False])
-def test_model_offload_holds_the_dit_across_the_stage_boundary_only_when_stage_two_fits(monkeypatch, fits):
+def test_model_offload_holds_the_dit_across_the_stage_boundary_only_when_stage_two_fits(
+ monkeypatch, fits
+):
# Stage 1's call ends by offloading every component; stage 2 then re-uploaded the whole DiT.
monkeypatch.setattr(MS, "companions_fit_beside_denoiser", lambda pipe, companions: fits)
pipe = _OffloadedPipe(SimpleNamespace(keep_tokens = None))
@@ -1279,7 +1292,9 @@ def test_model_offload_holds_the_dit_across_the_stage_boundary_only_when_stage_t
assert "maybe_free_model_hooks" not in pipe.__dict__
# No model offload: nothing is patched or checked.
plain = _FakePipe(SimpleNamespace(keep_tokens = None))
- monkeypatch.setattr(MS, "companions_fit_beside_denoiser", lambda *a: pytest.fail("checked without offload"))
+ monkeypatch.setattr(
+ MS, "companions_fit_beside_denoiser", lambda *a: pytest.fail("checked without offload")
+ )
v25.render(plain, _kwargs(), dev = False, upsampler = _Upsampler())
assert plain.freed == 0
@@ -1318,7 +1333,11 @@ def test_a_text_render_cancelled_between_stages_resets_the_offload_hooks(monkeyp
def test_the_hold_passes_the_connectors_and_the_upsampler_as_companions(monkeypatch):
seen = []
- monkeypatch.setattr(MS, "companions_fit_beside_denoiser", lambda pipe, companions: seen.append(companions) or True)
+ monkeypatch.setattr(
+ MS,
+ "companions_fit_beside_denoiser",
+ lambda pipe, companions: seen.append(companions) or True,
+ )
pipe = _OffloadedPipe(SimpleNamespace(keep_tokens = None))
pipe.connectors = object()
up = _Upsampler()
@@ -1336,14 +1355,21 @@ class _EncodingPipe(_FakePipe):
def encode_prompt(self, **kw):
import torch
-
self.encodes += 1
return torch.full((1, 2, 3), float(self.encodes)), torch.ones(1, 2), None, None
- def __call__(self, prompt = None, **kw):
- embeds = self.encode_prompt(prompt = prompt, negative_prompt = None, device = "cpu", prompt_embeds = None)
+ def __call__(
+ self,
+ prompt = None,
+ **kw,
+ ):
+ embeds = self.encode_prompt(
+ prompt = prompt, negative_prompt = None, device = "cpu", prompt_embeds = None
+ )
self.got.append(embeds[0].clone())
- embeds[0].add_(100) # a stage editing its own tensors in place must not reach the next stage
+ embeds[0].add_(
+ 100
+ ) # a stage editing its own tensors in place must not reach the next stage
return super().__call__(prompt = prompt, **kw)
@@ -1353,7 +1379,9 @@ def test_both_stages_share_one_encode():
pipe = _EncodingPipe(SimpleNamespace(keep_tokens = None))
v25.render(pipe, _kwargs(), dev = False, upsampler = _Upsampler())
assert pipe.encodes == 1 and len(pipe.got) == 2
- assert torch.equal(pipe.got[0], pipe.got[1]) and torch.equal(pipe.got[1], torch.full((1, 2, 3), 1.0))
+ assert torch.equal(pipe.got[0], pipe.got[1]) and torch.equal(
+ pipe.got[1], torch.full((1, 2, 3), 1.0)
+ )
assert "encode_prompt" not in pipe.__dict__
# A later request encodes again (the memo lives for one render), and a dev render never memoises.
v25.render(pipe, _kwargs(), dev = False, upsampler = _Upsampler())