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: judge a weight name's .. where the filesystem sends it, not by its text (#14800)

Daniel Han1610b38cc4fc
diff --git a/studio/backend/tests/test_account_path_confinement.py b/studio/backend/tests/test_account_path_confinement.py
index f6f429c5698..84b5626d327 100644
--- a/studio/backend/tests/test_account_path_confinement.py
+++ b/studio/backend/tests/test_account_path_confinement.py
@@ -196,6 +196,114 @@ def test_normal_weight_index_is_clean(tmp_path):
assert escaping_weight_references(folder) == []
+@symlinks
+ "files",
+ [
+ {"model.safetensors.index.json": {"weight_map": {"w": "bridge/../model.safetensors"}}},
+ {"config.json": {"transformers_weights": "bridge/../model.safetensors"}},
+ {
+ "modules.json": [{"idx": 0, "name": "0", "path": "0_Transformer"}],
+ "0_Transformer/model.safetensors.index.json": {
+ "weight_map": {"w": "../bridge/../model.safetensors"}
+ },
+ },
+ {"modules.json": [{"idx": 0, "name": "0", "path": "bridge/../nested"}]},
+ ],
+ ids = ["index", "transformers_weights", "module_index", "module_path"],
+)
+def test_a_dotdot_after_a_linked_directory_is_judged_where_it_lands(tmp_path, files):
+ from utils.security.file_security import escaping_weight_references
+
+ victim = tmp_path / "victim"
+ (victim / "nested").mkdir(parents = True)
+ (victim / "model.safetensors").write_text("victim")
+ folder = _write(tmp_path / "m", files)
+ (folder / "bridge").symlink_to(victim / "nested", target_is_directory = True)
+ assert escaping_weight_references(folder)
+
+
+@symlinks
+def test_links_that_do_not_change_where_dotdot_lands_still_pass(tmp_path):
+ from utils.security.file_security import escaping_weight_references
+
+ real = tmp_path / "real-model"
+ _write(
+ real,
+ {
+ "model.safetensors.index.json": {
+ "weight_map": {
+ "a": "model-00001-of-00002.safetensors",
+ "b": "sub/../sub/model-00002-of-00002.safetensors",
+ "c": "inner/model-00003-of-00003.safetensors",
+ }
+ },
+ },
+ )
+ (real / "sub").mkdir()
+ (real / "inner").symlink_to(real / "sub", target_is_directory = True)
+ linked = tmp_path / "linked-model"
+ linked.symlink_to(real, target_is_directory = True)
+ assert escaping_weight_references(real) == []
+ assert escaping_weight_references(linked) == []
+
+
+@symlinks
+ "files",
+ [
+ {"model.safetensors.index.json": {"weight_map": {"w": "alias/../model.safetensors"}}},
+ {"config.json": {"transformers_weights": "alias/../model.safetensors"}},
+ {"modules.json": [{"idx": 0, "name": "0", "path": "alias/../more"}]},
+ ],
+ ids = ["index", "transformers_weights", "module_path"],
+)
+def test_a_dotdot_through_a_link_that_stays_in_the_folder_passes(tmp_path, files):
+ # alias/../x opens actual/x: not where the text says, but still inside the model.
+ from utils.security.file_security import escaping_weight_references
+
+ folder = _write(tmp_path / "m", files)
+ (folder / "actual" / "nested").mkdir(parents = True)
+ (folder / "actual" / "more").mkdir()
+ (folder / "actual" / "model.safetensors").write_text("w")
+ (folder / "alias").symlink_to(folder / "actual" / "nested", target_is_directory = True)
+ assert escaping_weight_references(folder) == []
+ # The same layout with the link pointing out of the folder is still flagged.
+ victim = tmp_path / "victim"
+ (victim / "nested").mkdir(parents = True)
+ (folder / "alias").unlink()
+ (folder / "alias").symlink_to(victim / "nested", target_is_directory = True)
+ assert escaping_weight_references(folder)
+
+
+@symlinks
+def test_a_hub_cache_snapshot_with_blob_links_passes(tmp_path):
+ from utils.security.file_security import escaping_weight_references
+
+ repo = tmp_path / "hub" / "models--org--name"
+ snapshot = repo / "snapshots" / "abc123"
+ blobs = repo / "blobs"
+ (snapshot / "sub").mkdir(parents = True)
+ blobs.mkdir()
+ index = {
+ "weight_map": {
+ "a": "model-00001-of-00002.safetensors",
+ "b": "sub/../sub/model-00002-of-00002.safetensors",
+ }
+ }
+ for name, blob, payload in (
+ ("config.json", "c0", json.dumps({"model_type": "llama"})),
+ ("model.safetensors.index.json", "i0", json.dumps(index)),
+ ("model-00001-of-00002.safetensors", "w1", "w1"),
+ ("sub/model-00002-of-00002.safetensors", "w2", "w2"),
+ ):
+ (blobs / blob).write_text(payload)
+ depth = "../" * (name.count("/") + 2)
+ (snapshot / name).symlink_to(f"{depth}blobs/{blob}")
+ assert (snapshot / "sub/../sub/model-00002-of-00002.safetensors").read_text() == "w2"
+ assert escaping_weight_references(snapshot) == []
+
+
# Export: what loads is what was checked.
diff --git a/studio/backend/utils/security/file_security.py b/studio/backend/utils/security/file_security.py
index 5d828892bea..33c8ada266d 100644
--- a/studio/backend/utils/security/file_security.py
+++ b/studio/backend/utils/security/file_security.py
@@ -4,6 +4,7 @@
"""Malware / unsafe-file gate for model loads. The ``trust_remote_code`` consent gate covers the ``auto_map`` Python vector; this covers the other one, a malicious pickle inside a weight file, which executes during ``from_pretrained`` deserialization even with ``trust_remote_code=False``. It reads Hugging Face's OWN scan (picklescan + ClamAV) via ``model_info(securityStatus=True).security_repo_status``. METADATA-ONLY: it never downloads, opens, or unpickles the flagged files. Policy: a hard, non-approvable block whenever ``filesWithIssues`` lists a non-``safe`` level, regardless of ``scansDone`` (often false even for clean repos); unknown/future levels fail CLOSED so Hub schema drift cannot silently allow a bad verdict, and only a small allowlist of clean / not-yet-scanned levels is non-blocking, while an unavailable status falls back to local inspection for a pinned cache snapshot and otherwise fails open. Scoped to the load-path RCE vector: a root-level (or load-subdir-level) code-executing file, since inert formats (safetensors / gguf / config / text) and subdirectory pickles that no root weight-index references are not loaded and do not block, while an index-referenced shard does, wherever it lives. That blocks real malware (eicar's root ``*.pkl``/``*.dat``) without false-blocking repos like ``nvidia/Nemotron-H-8B-Base-8K`` (flagged NeMo pickles under ``nemo/`` that no index lists). No first-party exemption (scoping is by load path/format, not org), and local paths are skipped (no Hub scan) while a remote ``*.gguf``-named repo is still scanned so a repo cannot dodge the gate by suffixing its name."""
import json
+import os
import posixpath
import re
from dataclasses import dataclass, field
@@ -74,6 +75,43 @@ def _escapes_folder(name: str) -> bool:
return normalized == ".." or normalized.startswith("../")
+def _confinement_roots(folder: Path) -> list:
+ # Plus a Hub snapshot's models--org--repo folder: its files link into that repo's blobs.
+ root = os.path.realpath(folder)
+ roots = [root]
+ ref = _hf_cache_snapshot_ref(root)
+ if ref is not None:
+ roots.append(os.path.realpath(ref[2].parent.parent))
+ return roots
+
+
+def _within(path: str, root: str) -> bool:
+ path, root = os.path.normcase(path), os.path.normcase(root)
+ try:
+ return os.path.commonpath([path, root]) == root
+ except ValueError:
+ return False
+
+
+def _climbs_through_link(folder: Path, name: str) -> bool:
+ # POSIX follows a link before applying "..", so link/../x opens x beside the link's target.
+ # Windows (and ntpath.realpath) collapse ".." first, so both sides agree there.
+ parts = name.replace("\\", "/").split("/")
+ if ".." not in parts:
+ return False
+ head = "/".join(parts[: len(parts) - parts[::-1].index("..")])
+ try:
+ landing = os.path.realpath(os.path.join(folder, head))
+ roots = _confinement_roots(folder)
+ except (OSError, ValueError):
+ return True
+ return not any(_within(landing, root) for root in roots)
+
+
+def _escapes(folder: Path, name: str) -> bool:
+ return _escapes_folder(name) or _climbs_through_link(folder, name)
+
+
def _in_subfolder(sub: str, name: str) -> str:
# A rooted or drive-qualified name ignores the subfolder it is joined onto.
spelled = name.replace("\\", "/")
@@ -104,7 +142,7 @@ def _weight_names(folder: Path) -> list:
continue
names.append(name)
# A custom index named here is read like the standard ones.
- if name.endswith(".index.json") and not _escapes_folder(name):
+ if name.endswith(".index.json") and not _escapes(folder, name):
try:
payload = json.loads((folder / name).read_text(encoding = "utf-8-sig"))
except (OSError, ValueError):
@@ -117,9 +155,10 @@ def _weight_names(folder: Path) -> list:
def escaping_weight_references(folder) -> list:
"""Weight names a local model folder's index files or config.json ``transformers_weights``
- give that point outside the folder: transformers joins each onto the folder as is. Text only,
- so Hub cache snapshots whose files link into the blob store still pass. A Sentence Transformers
- folder's modules.json module folders are read too, judged against the model folder."""
+ give that point outside the folder: transformers joins each onto the folder as is. Judged by
+ the text, so Hub cache snapshots whose files link into the blob store still pass, except that
+ a ``..`` is judged where the kernel sends it. A Sentence Transformers folder's modules.json
+ module folders are read too, judged against the model folder."""
try:
folder = Path(str(folder)).expanduser()
if not folder.is_dir():
@@ -136,7 +175,7 @@ def escaping_weight_references(folder) -> list:
if not isinstance(sub, str):
continue
# Before the self-folder skip: "..", "../.." and "/" are only dots and slashes too.
- if _escapes_folder(sub):
+ if _escapes(folder, sub):
names.append(sub)
continue
# Sentence Transformers opens Path(folder, sub): "\\" separates on Windows only, so judge
@@ -154,7 +193,7 @@ def escaping_weight_references(folder) -> list:
# Spark-TTS / BiCodec load their transformers model from LLM/.
if (folder / "LLM").is_dir():
names.extend(_in_subfolder("LLM", name) for name in _weight_names(folder / "LLM"))
- return [name for name in dict.fromkeys(names) if _escapes_folder(name)]
+ return [name for name in dict.fromkeys(names) if _escapes(folder, name)]
def _normalize_repo_path(path: str) -> str: