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: stop the sandbox workdir aliasing /tmp in git bash (#8897)

Maheswar Kumard56f14775359
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index 9941e01eba4..0edefc3fbea 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -6754,6 +6754,68 @@ def _is_trusted_windows_program_dir(path: str) -> bool:
return False
+# not dot-named: the walks skip dot-dirs, which would hide a model's /tmp write.
+# not "tmp": too common in a workspace, and adopting one is what broke the walks.
+_SANDBOX_TEMP_DIRNAME = "unsloth-tmp"
+
+
+def _sandbox_temp_dir(workdir: str) -> str:
+ """The scratch directory for a sandboxed child, created when missing.
+
+ Inside the workdir, not the workdir itself: Git for Windows mounts /tmp at
+ %TEMP% (the msys2 ``usertemp`` fstab entry), so pointing TEMP at the workdir
+ made /tmp its shortest POSIX name and ``pwd`` printed /tmp, leaving the user
+ no way to find the real folder (#8892). One level down still sits where the
+ listings reach, so a /tmp write is offered exactly as before.
+
+ Falls back to the workdir when the name is unusable, since a TMPDIR that
+ does not exist breaks every tempfile call in the child. os.mkdir, never
+ os.makedirs, so a workdir deleted mid-call is not silently recreated.
+ """
+ temp_dir = os.path.join(workdir, _SANDBOX_TEMP_DIRNAME)
+ try:
+ os.mkdir(temp_dir, 0o700)
+ except FileExistsError:
+ if not _reusable_sandbox_temp_dir(temp_dir, workdir):
+ return workdir
+ except OSError:
+ return workdir
+ return temp_dir
+
+
+def _is_sandbox_temp_dir(temp_dir: str, workdir: str) -> bool:
+ """Whether *temp_dir* is the workdir's own scratch directory.
+
+ Exact stored spelling, because the walks read the name off os.walk: on a
+ case-insensitive volume (default APFS, every NTFS) our lowercase probe lands
+ on a directory stored as ``TMP``, and realpath does not canonicalise case.
+ And the real directory, not a link or junction to one, since os.walk does
+ not follow links and the artifacts would land where both walks skip.
+ """
+ try:
+ with os.scandir(workdir) as entries:
+ if not any(entry.name == _SANDBOX_TEMP_DIRNAME for entry in entries):
+ return False
+ # realpath, not islink: a Windows junction is not a link to either.
+ if os.path.realpath(temp_dir) != os.path.join(
+ os.path.realpath(workdir), _SANDBOX_TEMP_DIRNAME
+ ):
+ return False
+ except OSError:
+ return False
+ return os.path.isdir(temp_dir)
+
+
+def _reusable_sandbox_temp_dir(temp_dir: str, workdir: str) -> bool:
+ """Whether an existing entry may serve as the scratch directory.
+
+ Identity plus writability, since tempfile abandons an unwritable TMPDIR for
+ the platform default. Path accounting asks _is_sandbox_temp_dir instead:
+ which directory a segment sits in does not depend on writability.
+ """
+ return _is_sandbox_temp_dir(temp_dir, workdir) and os.access(temp_dir, os.W_OK | os.X_OK)
+
+
def _build_safe_env(workdir: str) -> dict[str, str]:
"""Build a minimal, credential-free environment for sandboxed subprocesses.
@@ -6761,8 +6823,8 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
TMPDIR/LANG/TERM/PYTHONIOENCODING/PYTHONPATH (+VIRTUAL_ENV or Windows
SystemRoot and a minimal PATHEXT) reach the child; all credential vars
(HF_TOKEN, AWS_*, etc.) are absent. HOME points at the sandbox workdir so SDKs can't read the
- operator's cached creds. PYTHONPATH carries only the sandbox sitecustomize
- shim directory.
+ operator's cached creds, and the temp vars at _sandbox_temp_dir just inside
+ it. PYTHONPATH carries only the sandbox sitecustomize shim directory.
PATH starts with the Studio interpreter / venv and OS system dirs so
``python``/``pip`` stay pinned. On Windows only, Git-for-Windows install
@@ -6809,10 +6871,11 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
# Deduplicate, preserving order.
deduped = list(dict.fromkeys(p for p in path_entries if p))
+ temp_dir = _sandbox_temp_dir(workdir)
env = {
"PATH": os.pathsep.join(deduped),
"HOME": workdir,
- "TMPDIR": workdir,
+ "TMPDIR": temp_dir,
"LANG": os.environ.get("LANG", "C.UTF-8"),
"TERM": "dumb",
"PYTHONIOENCODING": "utf-8",
@@ -6829,8 +6892,8 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
env["SystemRoot"] = os.environ.get("SystemRoot", r"C:\Windows")
# Windows tempfile / native SDKs honour TEMP/TMP, not TMPDIR; without
# these a child falls back to GetTempPath and writes outside the workdir.
- env["TEMP"] = workdir
- env["TMP"] = workdir
+ env["TEMP"] = temp_dir
+ env["TMP"] = temp_dir
# Restrict PATHEXT so cwd .BAT/.CMD cannot hijack bare names (#7317).
pathext = ".EXE;.COM"
if git_ext and git_ext not in (".EXE", ".COM"):
@@ -6995,8 +7058,8 @@ def _is_secret_env_value(value: str) -> bool:
def _build_bypass_env(workdir: str) -> dict[str, str]:
- """Env for bypass exec: full host env minus credential vars, with HOME/TMPDIR
- repointed at the workdir so SDKs cannot read cached creds.
+ """Env for bypass exec: full host env minus credential vars, with HOME at the
+ workdir and TMPDIR just inside it so SDKs cannot read cached creds.
Stripping the child env is necessary but not sufficient (a same-UID child can
read the parent's env via procfs), so callers also harden the parent (see
@@ -7009,12 +7072,13 @@ def _build_bypass_env(workdir: str) -> dict[str, str]:
and not _is_secret_env_value(v)
and not _is_cred_location_env_name(k)
}
+ temp_dir = _sandbox_temp_dir(workdir)
env["HOME"] = workdir
- env["TMPDIR"] = workdir
+ env["TMPDIR"] = temp_dir
# Windows tempfile / SDKs honour TEMP/TMP, not TMPDIR; repoint all three so
# the bypassed tool writes under the per-session sandbox dir on every OS.
- env["TEMP"] = workdir
- env["TMP"] = workdir
+ env["TEMP"] = temp_dir
+ env["TMP"] = temp_dir
# sitecustomize path shim (see _build_safe_env). Bypass inherits the
# operator's PYTHONPATH, so prepend rather than replace.
inherited_pythonpath = env.get("PYTHONPATH", "")
@@ -9609,8 +9673,8 @@ def _to_full_access(description: str, tool_name: str) -> str:
Handing a model the sandboxed text in that mode makes it answer "I am
sandboxed and cannot see your files" to a question one tool call would have
answered. Untouched clauses are the ones still true in both modes: the
- workdir is the per-session dir either way (_build_bypass_env repoints HOME /
- TMPDIR / TEMP / TMP at it), and so is the download-link note.
+ workdir is the per-session dir either way (_build_bypass_env repoints HOME at
+ it and TMPDIR / TEMP / TMP just inside it), and so is the download-link note.
"""
clause = _FULL_ACCESS_CLAUSE[tool_name]
for sandboxed, full_access in _FULL_ACCESS_SUBSTITUTIONS:
@@ -15260,6 +15324,27 @@ _MAX_SNAPSHOT_FILES = 2000 # a shard-writing script must not blow up the result
_MAX_SNAPSHOT_DIRS = 2000 # nor a directory-writing one stall the next call
+def _user_path_parts(parts: "list[str]", root: "str | None" = None) -> "list[str]":
+ """The segments _MAX_SANDBOX_PATH_SEGMENTS applies to.
+
+ The scratch container is Studio's, not a name the model chose, and on
+ Windows it is what /tmp resolves to, so charging it a segment would drop one
+ level of the /tmp artifacts served before the workdir stopped being %TEMP%.
+
+ *root* is for callers that resolve the path afterwards. The walks read the
+ stored spelling off os.walk and never follow links; the download route
+ resolves, and without the root a link named unsloth-tmp (or a wrong-case
+ entry on NTFS or APFS) would take the discount for a tree neither walk lists.
+ """
+ if not parts or parts[0] != _SANDBOX_TEMP_DIRNAME:
+ return parts
+ if root is not None and not _is_sandbox_temp_dir(
+ os.path.join(root, _SANDBOX_TEMP_DIRNAME), root
+ ):
+ return parts
+ return parts[1:]
+
+
# The same allowlist the download route applies per segment, so a name that
# route would refuse never reaches a file chip.
_SERVABLE_SEGMENT_RE = re.compile(r"\A[^/\\\x00-\x1f]{1,255}\Z")
@@ -15378,7 +15463,8 @@ def _snapshot_workdir_files(workdir: str | None) -> "dict[str, tuple]":
if visited > _MAX_SNAPSHOT_DIRS:
return snapshot
# depth 0 is the workdir itself, whose files are one segment.
- depth = base[len(workdir) :].count(os.sep)
+ relative = base[len(workdir) :].strip(os.sep)
+ depth = len(_user_path_parts(relative.split(os.sep) if relative else []))
# Dot-directories stay out: .git, .cache and friends are where the noise
# lives. Dot-FILES are reported, since .gitignore is a real artifact.
dirs[:] = (
diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.py
index b4140cd8d18..466f1ff4900 100644
--- a/studio/backend/routes/inference.py
+++ b/studio/backend/routes/inference.py
@@ -18390,6 +18390,7 @@ from core.inference.tools import (
_MAX_SNAPSHOT_DIRS,
_MAX_SNAPSHOT_FILES,
_servable_segment,
+ _user_path_parts,
)
from utils.paths.path_utils import is_appledouble_metadata
@@ -18403,7 +18404,7 @@ def _contained_sandbox_path(session_id: str, filename: str) -> tuple[str, str]:
out of the sandbox is refused like any other escape.
"""
parts = [part for part in filename.replace("\\", "/").split("/") if part not in ("", ".")]
- if not parts or len(parts) > _MAX_SANDBOX_PATH_SEGMENTS:
+ if not parts or len(_user_path_parts(parts)) > _MAX_SANDBOX_PATH_SEGMENTS:
raise HTTPException(status_code = 404, detail = "Not found")
for part in parts:
# os.path.join would let an absolute segment (or a Windows drive) throw
@@ -18413,6 +18414,10 @@ def _contained_sandbox_path(session_id: str, filename: str) -> tuple[str, str]:
if not _re.fullmatch(r"[^/\\\x00-\x1f]{1,255}", part):
raise HTTPException(status_code = 404, detail = "Not found")
sandbox_dir = _sandbox_dir_for(session_id, create = False)
+ # The check above is lexical and stays in front of the loop for the cheap
+ # refusal; this one is the answer: only the real scratch dir skips a segment.
+ if len(_user_path_parts(parts, sandbox_dir)) > _MAX_SANDBOX_PATH_SEGMENTS:
+ raise HTTPException(status_code = 404, detail = "Not found")
file_path = os.path.realpath(os.path.join(sandbox_dir, *parts))
if file_path != sandbox_dir and not file_path.startswith(sandbox_dir + os.sep):
raise HTTPException(
@@ -18434,7 +18439,8 @@ def _sandbox_listing_names(sandbox_dir: str) -> "list[str]":
visited += 1
if visited > _MAX_SNAPSHOT_DIRS:
return names
- depth = base[len(sandbox_dir) :].count(os.sep)
+ relative = base[len(sandbox_dir) :].strip(os.sep)
+ depth = len(_user_path_parts(relative.split(os.sep) if relative else []))
# depth 0 is the sandbox itself, whose files are one segment.
# Segments the route would refuse are dropped here too, so the two walks agree.
dirs[:] = (
diff --git a/studio/backend/tests/test_bypass_permissions.py b/studio/backend/tests/test_bypass_permissions.py
index 56fd0468a39..8ffbe26ba0d 100644
--- a/studio/backend/tests/test_bypass_permissions.py
+++ b/studio/backend/tests/test_bypass_permissions.py
@@ -21,6 +21,7 @@ import pytest
import core.inference.tools as tools
from core.inference.tools import (
+ _SANDBOX_TEMP_DIRNAME,
_bash_exec,
_build_bypass_env,
_build_safe_env,
@@ -80,7 +81,7 @@ def test_bypass_env_keeps_benign_strips_secret_repoints_home(monkeypatch, tmp_pa
assert env.get("HOSTVAR") == "benign-123" # full host env inherited
assert "HF_TOKEN" not in env # ...minus secrets
assert env["HOME"] == str(tmp_path) # $HOME-based cred lookups defused
- assert env["TMPDIR"] == str(tmp_path)
+ assert env["TMPDIR"] == str(tmp_path / _SANDBOX_TEMP_DIRNAME)
def test_safe_env_excludes_host_and_secret(monkeypatch, tmp_path):
@@ -499,9 +500,10 @@ def test_bypass_env_repoints_all_temp_vars(monkeypatch, tmp_path):
monkeypatch.setenv("TEMP", "/host/tmp")
monkeypatch.setenv("TMP", "/host/tmp")
env = _build_bypass_env(str(tmp_path))
- assert env["TMPDIR"] == str(tmp_path)
- assert env["TEMP"] == str(tmp_path)
- assert env["TMP"] == str(tmp_path)
+ expected = str(tmp_path / _SANDBOX_TEMP_DIRNAME)
+ assert env["TMPDIR"] == expected
+ assert env["TEMP"] == expected
+ assert env["TMP"] == expected
# ── credential-location redirect vars are dropped (regression) ──────────
diff --git a/studio/backend/tests/test_full_access_tool_prompt.py b/studio/backend/tests/test_full_access_tool_prompt.py
index acf04ba2422..ba844444db9 100644
--- a/studio/backend/tests/test_full_access_tool_prompt.py
+++ b/studio/backend/tests/test_full_access_tool_prompt.py
@@ -80,8 +80,8 @@ def test_full_access_descriptions_drop_the_isolation_claim(tool):
# must not claim the two are the same.
assert "user's own machine" not in description
# The workdir really is still the per-session dir in bypass mode
- # (_build_bypass_env repoints HOME/TMPDIR/TEMP/TMP at it), so the relative
- # path advice and the download-link note both have to survive.
+ # (_build_bypass_env repoints HOME at it and TMPDIR/TEMP/TMP just inside it),
+ # so the relative path advice and the download-link note both have to survive.
assert "persists for this conversation" in description
assert "download link" in description
diff --git a/studio/backend/tests/test_sandbox_files_and_storage_roots.py b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
index 2a29c82f3c9..5d1646528bc 100644
--- a/studio/backend/tests/test_sandbox_files_and_storage_roots.py
+++ b/studio/backend/tests/test_sandbox_files_and_storage_roots.py
@@ -746,7 +746,8 @@ def test_a_symlinked_session_cannot_serve_files_outside_the_sandbox(tmp_path, mo
def test_the_executor_leaves_nothing_in_the_sandbox(tmp_path, monkeypatch):
"""Its scratch script lives outside the sandbox, so a chat whose tools only
- printed is still an empty folder and removable without the opt-in."""
+ printed holds just our bookkeeping and the empty TMPDIR dir, and is
+ removable without the opt-in."""
monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
from core.inference import tools
@@ -754,12 +755,38 @@ def test_the_executor_leaves_nothing_in_the_sandbox(tmp_path, monkeypatch):
tools._workdirs.clear()
workdir = Path(tools.get_sandbox_workdir("__LOCALID_scratch"))
tools._python_exec("print('hi')", session_id = "__LOCALID_scratch")
- assert [p.name for p in workdir.iterdir()] == [tools._SANDBOX_MARKER]
+ assert sorted(p.name for p in workdir.iterdir()) == [
+ tools._SANDBOX_MARKER,
+ tools._SANDBOX_TEMP_DIRNAME,
+ ]
+ assert list((workdir / tools._SANDBOX_TEMP_DIRNAME).iterdir()) == []
assert tools.remove_session_sandbox("__LOCALID_scratch") is True
assert not workdir.exists()
+def test_a_file_under_the_scratch_dir_is_listed_and_blocks_removal(tmp_path, monkeypatch):
+ """On Windows the scratch dir is what /tmp resolves to, so /tmp/report.csv
+ lands here and has to keep its listing and its delete prompt."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from core.inference import tools
+ from routes import inference
+
+ tools._workdirs.clear()
+ session = "__LOCALID_scratch3"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ scratch = Path(tools._sandbox_temp_dir(str(workdir)))
+ (scratch / "report.csv").write_text("x")
+
+ assert inference._sandbox_listing_names(str(workdir)) == [
+ f"{tools._SANDBOX_TEMP_DIRNAME}/report.csv"
+ ]
+ assert tools.session_sandbox_has_files(session) is True
+ assert tools.remove_session_sandbox(session) is False
+ assert (scratch / "report.csv").is_file()
+
+
def test_a_real_file_still_blocks_removal(tmp_path, monkeypatch):
"""Only scratch is ignored; the user's own files still need the opt-in."""
monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
@@ -775,6 +802,62 @@ def test_a_real_file_still_blocks_removal(tmp_path, monkeypatch):
assert (workdir / "sales.csv").is_file()
+def test_the_download_route_serves_the_full_depth_under_the_scratch_dir(tmp_path, monkeypatch):
+ """The card and the route enforce the same segment cap, so the route has to
+ discount the scratch container exactly as the snapshot walk does."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from fastapi import HTTPException
+
+ from core.inference import tools
+ from routes.inference import _contained_sandbox_path
+
+ tools._workdirs.clear()
+ session = "__LOCALID_depth1"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ scratch = Path(tools._sandbox_temp_dir(str(workdir)))
+ (scratch / "a/b/c").mkdir(parents = True)
+ (scratch / "a/b/c/result.csv").write_bytes(b"x")
+
+ _, path = _contained_sandbox_path(session, f"{tools._SANDBOX_TEMP_DIRNAME}/a/b/c/result.csv")
+ assert Path(path) == scratch / "a/b/c/result.csv"
+ with pytest.raises(HTTPException):
+ _contained_sandbox_path(session, f"{tools._SANDBOX_TEMP_DIRNAME}/a/b/c/d/toodeep.csv")
+
+
+def test_only_the_real_scratch_dir_skips_a_path_segment(tmp_path, monkeypatch):
+ """The walks read the stored spelling off os.walk and never follow links, so
+ the discount is the resolved directory's, not the name's. A model-made link
+ would otherwise serve a file neither walk lists, as a wrong-case entry does
+ on NTFS or APFS."""
+ monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
+
+ from fastapi import HTTPException
+
+ from core.inference import tools
+ from routes import inference
+
+ tools._workdirs.clear()
+ session = "__LOCALID_depth2"
+ workdir = Path(tools.get_sandbox_workdir(session))
+ (workdir / "out/a/b/c").mkdir(parents = True)
+ (workdir / "out/a/b/c/deep.csv").write_bytes(b"x")
+ (workdir / "out/a/b/shallow.csv").write_bytes(b"x")
+ try:
+ (workdir / tools._SANDBOX_TEMP_DIRNAME).symlink_to(
+ workdir / "out", target_is_directory = True
+ )
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks unavailable (Windows without developer mode)")
+
+ name = tools._SANDBOX_TEMP_DIRNAME
+ assert f"{name}/a/b/c/deep.csv" not in inference._sandbox_listing_names(str(workdir))
+ with pytest.raises(HTTPException):
+ inference._contained_sandbox_path(session, f"{name}/a/b/c/deep.csv")
+ # Only the extra segment is withdrawn; four still resolve through the link.
+ inference._contained_sandbox_path(session, f"{name}/a/b/shallow.csv")
+
+
def test_the_listing_drops_a_directory_the_route_would_refuse(tmp_path, monkeypatch):
monkeypatch.setenv("UNSLOTH_STUDIO_SANDBOX_HOME", str(tmp_path / "sb"))
@@ -1233,7 +1316,9 @@ def test_a_user_python_file_is_never_executor_scratch(tmp_path, monkeypatch):
workdir = Path(tools.get_sandbox_workdir(session))
# The executor left nothing of its own behind.
assert sorted(
- p.name for p in workdir.iterdir() if p.name not in tools._INTERNAL_SANDBOX_FILES
+ p.name
+ for p in workdir.iterdir()
+ if p.name not in tools._INTERNAL_SANDBOX_FILES and p.name != tools._SANDBOX_TEMP_DIRNAME
) == ["studio_exec_results.py"]
assert inference._sandbox_listing_names(str(workdir)) == ["studio_exec_results.py"]
# And a delete without the opt-in will not quietly take it.
@@ -1324,7 +1409,9 @@ def test_the_scratch_script_is_never_reported_as_a_file(tmp_path, monkeypatch):
workdir = Path(tools.get_sandbox_workdir(session))
# Only the user's file is left; the executor cleaned up after itself.
assert sorted(
- p.name for p in workdir.iterdir() if p.name not in tools._INTERNAL_SANDBOX_FILES
+ p.name
+ for p in workdir.iterdir()
+ if p.name not in tools._INTERNAL_SANDBOX_FILES and p.name != tools._SANDBOX_TEMP_DIRNAME
) == ["studio_exec_results.py"]
assert json.loads(files) == [{"name": "studio_exec_results.py", "size": 5}]
diff --git a/studio/backend/tests/test_sandbox_tools.py b/studio/backend/tests/test_sandbox_tools.py
index 5efb8c2772d..ad4e1a8e9b0 100644
--- a/studio/backend/tests/test_sandbox_tools.py
+++ b/studio/backend/tests/test_sandbox_tools.py
@@ -378,24 +378,167 @@ class TestSandboxEnvIsolation:
monkeypatch.setattr(tools_mod, "_windows_bash_userland_dirs", lambda: [])
assert _build_safe_env(str(tmp_path))["PATH"] == before
- def test_temp_and_tmp_point_at_the_workdir_on_windows(self, monkeypatch, tmp_path):
+ def test_temp_and_tmp_point_inside_the_workdir_on_windows(self, monkeypatch, tmp_path):
# Windows reads TEMP/TMP, not TMPDIR; without them a child writes
# outside the sandbox workdir.
- from core.inference.tools import _build_safe_env
+ from core.inference.tools import _SANDBOX_TEMP_DIRNAME, _build_safe_env
self._trusted_git_bash(monkeypatch, tmp_path)
env = _build_safe_env(str(tmp_path))
- assert env["TEMP"] == str(tmp_path)
- assert env["TMP"] == str(tmp_path)
+ expected = str(tmp_path / _SANDBOX_TEMP_DIRNAME)
+ assert env["TEMP"] == expected
+ assert env["TMP"] == expected
def test_temp_and_tmp_absent_on_posix(self, monkeypatch, tmp_path):
- from core.inference.tools import _build_safe_env
+ from core.inference.tools import _SANDBOX_TEMP_DIRNAME, _build_safe_env
monkeypatch.setattr(sys, "platform", "linux")
env = _build_safe_env(str(tmp_path))
assert "TEMP" not in env
assert "TMP" not in env
- assert env["TMPDIR"] == str(tmp_path)
+ assert env["TMPDIR"] == str(tmp_path / _SANDBOX_TEMP_DIRNAME)
+
+ def test_temp_dir_is_a_created_child_of_the_workdir(self, tmp_path):
+ """A temp var pointing AT the workdir made /tmp its shortest POSIX name
+ under msys2 ``usertemp``, so ``pwd`` printed /tmp (#8892). It must also
+ exist before the child starts, or every tempfile call fails.
+ """
+ from core.inference.tools import _sandbox_temp_dir
+
+ temp_dir = _sandbox_temp_dir(str(tmp_path))
+ assert temp_dir != str(tmp_path)
+ assert os.path.dirname(temp_dir) == str(tmp_path)
+ assert os.path.isdir(temp_dir)
+
+ def test_temp_dir_falls_back_to_the_workdir_when_unusable(self, tmp_path):
+ # a TMPDIR that does not exist fails every tempfile call in the child.
+ from core.inference.tools import _SANDBOX_TEMP_DIRNAME, _sandbox_temp_dir
+ (tmp_path / _SANDBOX_TEMP_DIRNAME).write_text("not a directory")
+ assert _sandbox_temp_dir(str(tmp_path)) == str(tmp_path)
+
+ def test_temp_dir_never_recreates_a_deleted_workdir(self, tmp_path):
+ # a chat deleted mid-call must not reappear as an empty folder.
+ from core.inference.tools import _sandbox_temp_dir
+
+ gone = tmp_path / "gone"
+ assert _sandbox_temp_dir(str(gone)) == str(gone)
+ assert not gone.exists()
+
+ def test_temp_dir_is_never_followed_out_of_the_workdir(self, tmp_path):
+ # tool code runs in the workdir and can replace the name with a link.
+ from core.inference.tools import _SANDBOX_TEMP_DIRNAME, _sandbox_temp_dir
+
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ workdir = tmp_path / "sandbox"
+ workdir.mkdir()
+ try:
+ (workdir / _SANDBOX_TEMP_DIRNAME).symlink_to(outside, target_is_directory = True)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks unavailable (Windows without developer mode)")
+ assert _sandbox_temp_dir(str(workdir)) == str(workdir)
+
+ def test_temp_dir_refuses_an_escape_islink_cannot_see(self, monkeypatch, tmp_path):
+ """A junction carries a different reparse tag, so os.path.islink is
+ False while os.path.isdir follows it. Blinding islink stands in for that:
+ containment is decided by the resolved path.
+ """
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _SANDBOX_TEMP_DIRNAME, _sandbox_temp_dir
+
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ workdir = tmp_path / "sandbox"
+ workdir.mkdir()
+ try:
+ (workdir / _SANDBOX_TEMP_DIRNAME).symlink_to(outside, target_is_directory = True)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks unavailable (Windows without developer mode)")
+ monkeypatch.setattr(tools_mod.os.path, "islink", lambda path: False)
+ assert _sandbox_temp_dir(str(workdir)) == str(workdir)
+
+ def test_temp_dir_refuses_a_link_even_inside_the_workdir(self, tmp_path):
+ """os.walk does not follow links, so `tmp -> .scratch` would send every
+ artifact where both walks skip. The test is being the real directory,
+ not containment.
+ """
+ from core.inference.tools import _SANDBOX_TEMP_DIRNAME, _sandbox_temp_dir
+
+ workdir = tmp_path / "sandbox"
+ (workdir / ".scratch").mkdir(parents = True)
+ try:
+ (workdir / _SANDBOX_TEMP_DIRNAME).symlink_to(
+ workdir / ".scratch", target_is_directory = True
+ )
+ except (OSError, NotImplementedError):
+ pytest.skip("symlinks unavailable (Windows without developer mode)")
+ assert _sandbox_temp_dir(str(workdir)) == str(workdir)
+
+ def test_temp_dir_refuses_an_entry_stored_under_another_case(self, tmp_path):
+ """On a case-insensitive volume (default APFS, every NTFS) the lowercase
+ probe resolves onto a directory stored as another case, and realpath does
+ not canonicalise it, so os.walk reports a spelling the discount misses.
+ """
+ from core.inference.tools import _SANDBOX_TEMP_DIRNAME, _sandbox_temp_dir
+
+ (tmp_path / _SANDBOX_TEMP_DIRNAME.upper()).mkdir()
+ if not (tmp_path / _SANDBOX_TEMP_DIRNAME).exists():
+ pytest.skip("case-sensitive volume, so the collision cannot arise")
+ assert _sandbox_temp_dir(str(tmp_path)) == str(tmp_path)
+
+ def test_temp_dir_refuses_an_unwritable_existing_directory(self, tmp_path):
+ """tempfile abandons an unwritable TMPDIR for the platform default,
+ putting the child's temporary data outside the session sandbox.
+ """
+ from core.inference.tools import _SANDBOX_TEMP_DIRNAME, _sandbox_temp_dir
+
+ scratch = tmp_path / _SANDBOX_TEMP_DIRNAME
+ scratch.mkdir()
+ scratch.chmod(0o500)
+ try:
+ if os.access(str(scratch), os.W_OK):
+ pytest.skip("mode bits not enforced here (running as root)")
+ assert _sandbox_temp_dir(str(tmp_path)) == str(tmp_path)
+ finally:
+ scratch.chmod(0o700)
+
+ def test_the_scratch_dir_does_not_spend_a_path_segment(self, tmp_path):
+ """/tmp/a/b/c/result.csv was a four-segment path and downloadable.
+ Nesting TMPDIR a level deeper must not push it past
+ _MAX_SANDBOX_PATH_SEGMENTS and drop it from the card.
+ """
+ from core.inference.tools import (
+ _SANDBOX_TEMP_DIRNAME,
+ _sandbox_temp_dir,
+ _snapshot_workdir_files,
+ )
+
+ scratch = Path(_sandbox_temp_dir(str(tmp_path)))
+ (scratch / "a/b/c").mkdir(parents = True)
+ (scratch / "a/b/c/result.csv").write_bytes(b"x")
+ (scratch / "a/b/c/d").mkdir()
+ (scratch / "a/b/c/d/toodeep.csv").write_bytes(b"x")
+ # the cap still applies, it is just measured from inside the scratch dir.
+ assert sorted(_snapshot_workdir_files(str(tmp_path))) == [
+ f"{_SANDBOX_TEMP_DIRNAME}/a/b/c/result.csv"
+ ]
+
+ def test_scratch_files_are_still_offered_as_artifacts(self, tmp_path):
+ """On Windows this is what /tmp resolves to, so /tmp/report.csv must
+ still get a download card. A dot-named scratch dir would be skipped by
+ the snapshot walk and the file would vanish.
+ """
+ from core.inference.tools import (
+ _SANDBOX_TEMP_DIRNAME,
+ _sandbox_temp_dir,
+ _snapshot_workdir_files,
+ )
+
+ temp_dir = _sandbox_temp_dir(str(tmp_path))
+ (Path(temp_dir) / "report.csv").write_bytes(b"x")
+ assert list(_snapshot_workdir_files(str(tmp_path))) == [
+ f"{_SANDBOX_TEMP_DIRNAME}/report.csv"
+ ]
def test_host_git_dir_appended_after_curated(self, monkeypatch, tmp_path):
# #7317: Windows Git lives under Program Files, not System32. Sandbox
@@ -621,11 +764,11 @@ class TestSandboxEnvIsolation:
assert env["NoDefaultCurrentDirectoryInExePath"] == "1"
def test_home_points_at_sandbox_workdir(self, tmp_path):
- from core.inference.tools import _build_safe_env
+ from core.inference.tools import _SANDBOX_TEMP_DIRNAME, _build_safe_env
env = _build_safe_env(str(tmp_path))
assert env["HOME"] == str(tmp_path)
- assert env["TMPDIR"] == str(tmp_path)
+ assert env["TMPDIR"] == str(tmp_path / _SANDBOX_TEMP_DIRNAME)
def test_term_is_dumb(self, tmp_path):
from core.inference.tools import _build_safe_env