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.

fix(studio): resolve bare git on Windows sandbox PATH (#7323)

Souravrajvi0f5a0c2226b73
diff --git a/studio/backend/core/inference/tools.py b/studio/backend/core/inference/tools.py
index bc9ffe85c24..0ef6dd46cf6 100644
--- a/studio/backend/core/inference/tools.py
+++ b/studio/backend/core/inference/tools.py
@@ -18,6 +18,7 @@ import queue
import random
import re
import shlex
+import shutil
import ssl
import subprocess
import sys
@@ -328,6 +329,7 @@ def _find_blocked_commands(command: str) -> set[str]:
# Directory holding the sandbox ``sitecustomize.py`` shim (code-interpreter
# path remap); placed on the sandboxed child's PYTHONPATH in _build_safe_env.
_SANDBOX_SITE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sandbox_site")
+
# ── "Approve for me" (permission_mode="auto") safety detection ──────────────
# Auto mode pauses only calls classified here as potentially unsafe. The sandbox
# and hard blocks (blocklist, rlimits) still apply at run time; this gate only
@@ -2491,15 +2493,124 @@ def is_potentially_unsafe_tool_call(name: str, arguments: dict) -> bool:
return True
+def _canon_win_path(p: str) -> str:
+ """Canonical form for trust comparison: realpath (expands 8.3 aliases and
+ resolves junctions/symlinks) + normcase/normpath."""
+ return os.path.normcase(os.path.normpath(os.path.realpath(p)))
+
+
+def _augment_native_program_roots(roots: list[str]) -> list[str]:
+ """Add the native Program Files sibling for any x86 root by stripping the
+ `` (x86)`` suffix, so a 32-bit process (whose known-folder ids map only to
+ the x86 root) still trusts a 64-bit Git install."""
+ out = list(roots)
+ for root in roots:
+ base = root.rstrip("\\/")
+ if base.lower().endswith(" (x86)"):
+ native = base[: -len(" (x86)")]
+ if native and native not in out:
+ out.append(native)
+ return out
+
+
+def _windows_program_roots() -> list[str]:
+ """Program Files install roots, resolved ONLY from the Windows known-folder
+ API (SHGetKnownFolderPath). Fails closed (returns ``[]``) if the API is
+ unavailable: env vars (%ProgramFiles%, even %SystemDrive%) are caller-
+ overrideable and could relocate the trust boundary, so we never derive a
+ trusted root from them. On any real Windows host shell32 is present, so
+ this only returns empty in a broken/non-Windows environment where the
+ sandbox git-PATH feature is not needed anyway (#7317).
+ """
+ roots: list[str] = []
+ try:
+ import ctypes
+ from ctypes import wintypes
+
+ # FOLDERID_ProgramFiles, _ProgramFilesX86, _ProgramFilesX64. The X64
+ # id (Win10 1703+) yields the native root even from a 32-bit process,
+ # where the first two both map to Program Files (x86).
+ folder_ids = (
+ "{905e63b6-c1bf-494e-b29c-65b732d3d21a}",
+ "{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}",
+ "{6D809377-6AF0-444b-8957-A3773F02200E}",
+ )
+ _SHGet = ctypes.windll.shell32.SHGetKnownFolderPath
+ _CoTaskMemFree = ctypes.windll.ole32.CoTaskMemFree
+ for fid in folder_ids:
+ guid = ctypes.create_string_buffer(16)
+ ctypes.windll.ole32.CLSIDFromString(wintypes.LPCWSTR(fid), ctypes.byref(guid))
+ ptr = ctypes.c_wchar_p()
+ if _SHGet(ctypes.byref(guid), 0, None, ctypes.byref(ptr)) == 0:
+ if ptr.value:
+ roots.append(ptr.value)
+ _CoTaskMemFree(ptr)
+ except Exception:
+ return []
+ return _augment_native_program_roots(roots)
+
+
+def _resolve_trusted_windows_git() -> tuple[str, str]:
+ """Find a git launcher in a TRUSTED Program Files dir. Returns
+ ``(canonical_dir, ext)`` or ``("", "")``.
+
+ ``shutil.which`` returns only the first PATH match, which may be an
+ untrusted user shim; scan the remaining PATH entries for a later trusted
+ Git so bare ``git`` still resolves (#7317).
+ """
+ exts = [e for e in (os.environ.get("PATHEXT") or ".EXE;.CMD;.BAT;.COM").split(os.pathsep)]
+ candidates: list[str] = []
+ primary = shutil.which("git")
+ if primary:
+ candidates.append(primary)
+ for entry in (os.environ.get("PATH") or "").split(os.pathsep):
+ entry = entry.strip().strip('"')
+ if not entry or not os.path.isabs(entry):
+ continue
+ for ext in exts:
+ cand = os.path.join(entry, "git" + ext)
+ if os.path.isfile(cand):
+ candidates.append(cand)
+ for git_exe in candidates:
+ git_dir = os.path.dirname(git_exe)
+ if os.path.isabs(git_dir) and _is_trusted_windows_program_dir(git_dir):
+ return os.path.realpath(git_dir), os.path.splitext(git_exe)[1].upper()
+ return "", ""
+
+
+def _is_trusted_windows_program_dir(path: str) -> bool:
+ """True when ``path`` sits under a system-managed Program Files root.
+
+ Only the Program Files roots are trusted (admin-writable only), resolved
+ via the known-folder API so an overridden env var cannot relocate them,
+ never ``%SystemRoot%`` (Git does not install there and it holds
+ world-writable subdirs like ``Windows\\Temp``). Per-user managers
+ (Scoop/Choco shims under the profile) are refused. Paths are canonicalized
+ so 8.3 aliases and junctions still resolve to their real root (#7317).
+ """
+ norm = _canon_win_path(path)
+ for root in _windows_program_roots():
+ root_norm = _canon_win_path(root)
+ if norm == root_norm or norm.startswith(root_norm + os.sep):
+ return True
+ return False
+
+
def _build_safe_env(workdir: str) -> dict[str, str]:
"""Build a minimal, credential-free environment for sandboxed subprocesses.
Whitelist-built from scratch (parent env NOT inherited): only PATH/HOME/
TMPDIR/LANG/TERM/PYTHONIOENCODING/PYTHONPATH (+VIRTUAL_ENV or Windows
- SystemRoot) reach the child; all credential vars (HF_TOKEN, AWS_*, etc.)
- are absent. HOME points at the sandbox workdir so SDKs can't read the
+ 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.
+
+ PATH starts with the Studio interpreter / venv and OS system dirs so
+ ``python``/``pip`` stay pinned. On Windows only, Git-for-Windows install
+ dirs from the host PATH are appended so bare ``git`` resolves (#7317).
+ User-writable host PATH entries (venv, ``node_modules/.bin``, etc.) are
+ never inherited — they could shadow auto-safe terminal commands.
"""
# Start from the running interpreter's dir so 'python'/'pip' resolve to the
# same environment the Unsloth server runs in.
@@ -2519,6 +2630,20 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
else:
path_entries.extend(["/usr/local/bin", "/usr/bin", "/bin"])
+ # Windows Git installs live outside System32; inherit the dir of the git
+ # the HOST shell resolves, but ONLY when it sits under a system install
+ # root (Program Files, windir). A user-writable dir (Scoop/Choco shims)
+ # is refused: it would let an attacker drop rg.exe/jq.exe beside git and
+ # have an auto-approved bare command execute it (#7317).
+ git_ext = ""
+ if sys.platform == "win32":
+ # Append the CANONICAL (realpath) trusted git dir, scanning past any
+ # untrusted user shim that sorts first on PATH; the canonical path
+ # cannot be retargeted via a junction after the trust check.
+ _trusted_git_dir, git_ext = _resolve_trusted_windows_git()
+ if _trusted_git_dir:
+ path_entries.append(_trusted_git_dir)
+
# Deduplicate, preserving order.
deduped = list(dict.fromkeys(p for p in path_entries if p))
@@ -2538,6 +2663,15 @@ def _build_safe_env(workdir: str) -> dict[str, str]:
# Windows needs SystemRoot for Python/subprocess to work.
if sys.platform == "win32":
env["SystemRoot"] = os.environ.get("SystemRoot", r"C:\Windows")
+ # Restrict PATHEXT so cwd .BAT/.CMD cannot hijack bare names (#7317).
+ pathext = ".EXE;.COM"
+ if git_ext and git_ext not in (".EXE", ".COM"):
+ # Keep the host git launcher (e.g. a .CMD shim) resolvable.
+ pathext += ";" + git_ext
+ env["PATHEXT"] = pathext
+ # cmd/CreateProcess search cwd before PATH for bare names; disable so
+ # a workdir rg.exe/git.exe cannot shadow auto-approved commands.
+ env["NoDefaultCurrentDirectoryInExePath"] = "1"
return env
diff --git a/studio/backend/tests/test_sandbox_tools.py b/studio/backend/tests/test_sandbox_tools.py
index 2970b1a6bbf..64201477e31 100644
--- a/studio/backend/tests/test_sandbox_tools.py
+++ b/studio/backend/tests/test_sandbox_tools.py
@@ -297,6 +297,8 @@ class TestSandboxEnvIsolation:
"PYTHONPATH",
"VIRTUAL_ENV",
"SystemRoot",
+ "PATHEXT", # Windows only; minimal list so cwd scripts cannot hijack
+ "NoDefaultCurrentDirectoryInExePath", # Windows only; no cwd-first lookup
}
extras = set(env.keys()) - allowed
assert not extras, f"sandbox env added unexpected keys: {extras}"
@@ -305,6 +307,220 @@ class TestSandboxEnvIsolation:
assert env["PYTHONPATH"].endswith("sandbox_site")
assert "leak-me" not in env["PYTHONPATH"]
+ def test_host_git_dir_appended_after_curated(self, monkeypatch, tmp_path):
+ # #7317: Windows Git lives under Program Files, not System32. Sandbox
+ # PATH resolves bare `git` by appending the dir of the git the HOST
+ # shell resolves (shutil.which), after the curated prefix.
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ prog = tmp_path / "Program Files"
+ monkeypatch.setattr(tools_mod, "_windows_program_roots", lambda: [str(prog)])
+ git_dir = prog / "Git" / "cmd"
+ git_dir.mkdir(parents = True)
+ monkeypatch.setattr(tools_mod.shutil, "which", lambda name: str(git_dir / "git.exe"))
+ env = _build_safe_env(str(tmp_path))
+ parts = env["PATH"].split(os.pathsep)
+ assert str(git_dir) in parts
+ # Curated prefix stays ahead of host Git so Studio python/pip win.
+ assert parts.index(str(git_dir)) > 0
+
+ def test_host_path_dirs_not_inherited(self, monkeypatch, tmp_path):
+ """Host PATH dirs (user-writable, git-lookalike) are never inherited;
+ only the resolved git dir is. No git resolved -> nothing appended."""
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ venv_scripts = tmp_path / "venv" / "Scripts"
+ venv_scripts.mkdir(parents = True)
+ fake_git = tmp_path / "scratch" / "Git" / "cmd"
+ fake_git.mkdir(parents = True)
+ monkeypatch.setenv(
+ "PATH",
+ os.pathsep.join([str(venv_scripts), str(fake_git), os.environ.get("PATH", "")]),
+ )
+ monkeypatch.setattr(tools_mod.shutil, "which", lambda name: None)
+ env = _build_safe_env(str(tmp_path))
+ parts = env["PATH"].split(os.pathsep)
+ assert str(venv_scripts) not in parts
+ # A git-suffixed but unresolved (user-writable) dir is NOT trusted.
+ assert str(fake_git) not in parts
+
+ def test_git_cmd_shim_extension_added_to_pathext(self, monkeypatch, tmp_path):
+ """A host git resolved as a .cmd shim under a trusted root stays
+ resolvable under the restricted PATHEXT (cwd lookup disabled)."""
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ prog = tmp_path / "Program Files"
+ monkeypatch.setattr(tools_mod, "_windows_program_roots", lambda: [str(prog)])
+ git_dir = prog / "Git" / "cmd"
+ git_dir.mkdir(parents = True)
+ monkeypatch.setattr(tools_mod.shutil, "which", lambda name: str(git_dir / "git.cmd"))
+ env = _build_safe_env(str(tmp_path))
+ assert str(git_dir) in env["PATH"].split(os.pathsep)
+ assert env["PATHEXT"] == ".EXE;.COM;.CMD"
+
+ def test_user_writable_git_dir_refused(self, monkeypatch, tmp_path):
+ """Git resolved from a per-user manager (Scoop shims) is NOT trusted:
+ an attacker could drop rg.exe beside it and hit the auto-approve gate."""
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(
+ tools_mod, "_windows_program_roots", lambda: [str(tmp_path / "Program Files")]
+ )
+ shim_dir = tmp_path / "users" / "alice" / "scoop" / "shims"
+ shim_dir.mkdir(parents = True)
+ monkeypatch.setattr(tools_mod.shutil, "which", lambda name: str(shim_dir / "git.exe"))
+ env = _build_safe_env(str(tmp_path))
+ assert str(shim_dir) not in env["PATH"].split(os.pathsep)
+ # No trusted git launcher -> PATHEXT stays minimal.
+ assert env["PATHEXT"] == ".EXE;.COM"
+
+ def test_trust_uses_known_folder_not_env_override(self, monkeypatch, tmp_path):
+ """Trust is driven by the resolved Program Files roots, so a git under
+ an attacker-overridden %ProgramFiles% env value is still refused."""
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ real_prog = tmp_path / "RealProgramFiles"
+ (real_prog).mkdir()
+ evil = tmp_path / "attacker"
+ (evil / "Git" / "cmd").mkdir(parents = True)
+ # Resolver returns the genuine root; env is overridden to the evil dir.
+ monkeypatch.setattr(tools_mod, "_windows_program_roots", lambda: [str(real_prog)])
+ monkeypatch.setenv("ProgramFiles", str(evil))
+ monkeypatch.setattr(
+ tools_mod.shutil, "which", lambda name: str(evil / "Git" / "cmd" / "git.exe")
+ )
+ env = _build_safe_env(str(tmp_path))
+ assert str(evil / "Git" / "cmd") not in env["PATH"].split(os.pathsep)
+
+ def test_canonical_git_dir_appended(self, monkeypatch, tmp_path):
+ """The PATH entry is the realpath of the trusted dir, not a junction
+ alias, so it cannot be retargeted after the trust check."""
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ real_prog = tmp_path / "Program Files"
+ real_git = real_prog / "Git" / "cmd"
+ real_git.mkdir(parents = True)
+ link = tmp_path / "link"
+ try:
+ link.symlink_to(real_prog, target_is_directory = True)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlink unsupported in this environment")
+ monkeypatch.setattr(tools_mod, "_windows_program_roots", lambda: [str(real_prog)])
+ monkeypatch.setattr(
+ tools_mod.shutil,
+ "which",
+ lambda name: str(link / "Git" / "cmd" / "git.exe"),
+ )
+ env = _build_safe_env(str(tmp_path))
+ parts = env["PATH"].split(os.pathsep)
+ assert str(real_git) in parts # canonical, not the `link/...` alias
+
+ def test_windows_temp_git_dir_refused(self, monkeypatch, tmp_path):
+ """A git under a world-writable %SystemRoot% subdir (Windows\\Temp) is
+ NOT trusted, even though it sits under the Windows root."""
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(
+ tools_mod, "_windows_program_roots", lambda: [str(tmp_path / "Program Files")]
+ )
+ temp_git = tmp_path / "Windows" / "Temp" / "Git" / "cmd"
+ temp_git.mkdir(parents = True)
+ monkeypatch.setattr(tools_mod.shutil, "which", lambda name: str(temp_git / "git.exe"))
+ env = _build_safe_env(str(tmp_path))
+ assert str(temp_git) not in env["PATH"].split(os.pathsep)
+
+ def test_trusted_program_dir_matches_via_realpath(self, monkeypatch, tmp_path):
+ """The trust check canonicalizes paths, so a symlinked/short alias of
+ Program Files still matches (stand-in for 8.3 PROGRA~1 on Windows)."""
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ real_prog = tmp_path / "Program Files"
+ (real_prog / "Git" / "cmd").mkdir(parents = True)
+ alias = tmp_path / "PROGRA~1"
+ try:
+ alias.symlink_to(real_prog, target_is_directory = True)
+ except (OSError, NotImplementedError):
+ pytest.skip("symlink unsupported in this environment")
+ monkeypatch.setattr(tools_mod, "_windows_program_roots", lambda: [str(real_prog)])
+ git_via_alias = alias / "Git" / "cmd" / "git.exe"
+ monkeypatch.setattr(tools_mod.shutil, "which", lambda name: str(git_via_alias))
+ env = _build_safe_env(str(tmp_path))
+ parts = [os.path.normcase(os.path.realpath(p)) for p in env["PATH"].split(os.pathsep)]
+ assert os.path.normcase(str(real_prog / "Git" / "cmd")) in parts
+
+ def test_scan_past_untrusted_git_shim(self, monkeypatch, tmp_path):
+ """When an untrusted shim sorts first on PATH, the scan still finds a
+ later trusted Program Files git."""
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ prog = tmp_path / "Program Files"
+ trusted_git = prog / "Git" / "cmd"
+ trusted_git.mkdir(parents = True)
+ (trusted_git / "git.EXE").write_text("") # match PATHEXT case on this FS
+ shim = tmp_path / "scoop" / "shims"
+ shim.mkdir(parents = True)
+ (shim / "git.EXE").write_text("")
+ monkeypatch.setattr(tools_mod, "_windows_program_roots", lambda: [str(prog)])
+ # shutil.which returns the untrusted shim first.
+ monkeypatch.setattr(tools_mod.shutil, "which", lambda name: str(shim / "git.EXE"))
+ monkeypatch.setenv("PATH", os.pathsep.join([str(shim), str(trusted_git)]))
+ monkeypatch.setenv("PATHEXT", ".EXE")
+ env = _build_safe_env(str(tmp_path))
+ parts = env["PATH"].split(os.pathsep)
+ assert str(trusted_git) in parts
+ assert str(shim) not in parts
+
+ def test_program_roots_fails_closed_without_known_folder_api(self, monkeypatch):
+ """When the known-folder API is unavailable, no roots are trusted: env
+ vars (even %SystemDrive%) are caller-overrideable, so we never derive a
+ trusted root from them."""
+ import core.inference.tools as tools_mod
+
+ # ctypes fails on this Linux host, so the API path raises and we fail
+ # closed. Any attacker override of these env vars must be irrelevant.
+ monkeypatch.setenv("ProgramFiles", r"D:\attacker-writable")
+ monkeypatch.setenv("ProgramW6432", r"D:\attacker-writable")
+ monkeypatch.setenv("SystemDrive", "D:")
+ assert tools_mod._windows_program_roots() == []
+
+ def test_augment_native_program_roots_derives_native_sibling(self):
+ """A 32-bit process only sees the x86 root; the native sibling is
+ derived by stripping the ` (x86)` suffix."""
+ import core.inference.tools as tools_mod
+
+ roots = tools_mod._augment_native_program_roots([r"C:\Program Files (x86)"])
+ lowered = [r.lower() for r in roots]
+ assert r"c:\program files (x86)" in lowered
+ assert r"c:\program files" in lowered
+
+ def test_no_default_current_directory_in_exe_path_set_on_windows(self, monkeypatch, tmp_path):
+ """cmd/CreateProcess must not search cwd for bare names in the sandbox."""
+ import core.inference.tools as tools_mod
+ from core.inference.tools import _build_safe_env
+
+ monkeypatch.setattr(sys, "platform", "win32")
+ monkeypatch.setattr(tools_mod.shutil, "which", lambda name: None)
+ env = _build_safe_env(str(tmp_path))
+ assert env["NoDefaultCurrentDirectoryInExePath"] == "1"
+
def test_home_points_at_sandbox_workdir(self, tmp_path):
from core.inference.tools import _build_safe_env