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 STT: only load safetensors weights for custom dictation models (RCE fix) (#7364)

Daniel Han734cec9e7aef
diff --git a/studio/backend/core/inference/stt_sidecar.py b/studio/backend/core/inference/stt_sidecar.py
index 7ac7e93c876..edf57c16e37 100644
--- a/studio/backend/core/inference/stt_sidecar.py
+++ b/studio/backend/core/inference/stt_sidecar.py
@@ -49,8 +49,11 @@ _MAX_AUDIO_SECONDS = 30 * 60
_TARGET_SAMPLE_RATE = 16000
# Non-weight files WhisperProcessor/WhisperForConditionalGeneration may load.
-# Weight selection is built from pinned Hub metadata so repositories publishing
-# both formats do not download the same checkpoint twice.
+# Weight selection is built from pinned Hub metadata. A custom repo id is
+# attacker-controllable, so only safetensors weights are accepted: a
+# pytorch_model.bin is a pickle and executes code while Transformers
+# deserializes it (see utils/security/file_security.py), and this path skips
+# the malware gate the normal model loader applies.
_STT_SNAPSHOT_SUPPORT_FILES = (
"config.json",
"generation_config.json",
@@ -65,9 +68,7 @@ _STT_SNAPSHOT_SUPPORT_FILES = (
"added_tokens.json",
)
_STT_SAFETENSORS_INDEX = "model.safetensors.index.json"
-_STT_PYTORCH_INDEX = "pytorch_model.bin.index.json"
_STT_SAFETENSORS_WEIGHTS = "model.safetensors"
-_STT_PYTORCH_WEIGHTS = "pytorch_model.bin"
_STT_REVISION_RECORD_VERSION = 1
@@ -350,7 +351,9 @@ def _selected_file_from_sibling(sibling) -> _SelectedHubFile:
def _select_snapshot_files(info, load_index) -> tuple[_SelectedHubFile, ...]:
- """Select support files and exactly one complete Transformers weight format."""
+ """Select support files and one complete safetensors weight set. Pickle
+ (pytorch_model.bin) weights are never selected: they are an RCE sink on a
+ custom repo id (see _STT_SNAPSHOT_SUPPORT_FILES)."""
siblings = {
sibling.rfilename: sibling
for sibling in (getattr(info, "siblings", None) or [])
@@ -363,12 +366,11 @@ def _select_snapshot_files(info, load_index) -> tuple[_SelectedHubFile, ...]:
index_name = _STT_SAFETENSORS_INDEX
elif _STT_SAFETENSORS_WEIGHTS in siblings:
selected.add(_STT_SAFETENSORS_WEIGHTS)
- elif _STT_PYTORCH_INDEX in siblings:
- index_name = _STT_PYTORCH_INDEX
- elif _STT_PYTORCH_WEIGHTS in siblings:
- selected.add(_STT_PYTORCH_WEIGHTS)
else:
- raise SttModelCompatibilityError("The STT repository has no complete model weights.")
+ raise SttModelCompatibilityError(
+ "The STT repository has no safetensors model weights. Only safetensors "
+ "checkpoints are supported; convert the model with save_pretrained(safe_serialization=True)."
+ )
if index_name is not None:
weight_map = load_index(index_name).get("weight_map")
@@ -377,6 +379,14 @@ def _select_snapshot_files(info, load_index) -> tuple[_SelectedHubFile, ...]:
shards = set(weight_map.values())
if not all(isinstance(shard, str) and shard in siblings for shard in shards):
raise SttModelCompatibilityError(f"Checkpoint index '{index_name}' has missing shards.")
+ # The index JSON is attacker-controlled: a safetensors index can name
+ # pytorch_model-*.bin shards, which Transformers still loads through
+ # torch.load (pickle) since it dispatches per shard by file extension.
+ # Require every shard to be safetensors so no pickle file is selected.
+ if not all(shard.endswith(".safetensors") for shard in shards):
+ raise SttModelCompatibilityError(
+ f"Checkpoint index '{index_name}' references non-safetensors shards."
+ )
selected.add(index_name)
selected.update(shards)
@@ -441,24 +451,23 @@ def _snapshot_is_complete(snapshot: Path) -> bool:
tokenizer, and weights directly. is_file() follows cache symlinks, so a
link from an interrupted blob download does not count.
"""
- index = next(
- (
- snapshot / name
- for name in ("model.safetensors.index.json", "pytorch_model.bin.index.json")
- if (snapshot / name).is_file()
- ),
- None,
- )
- if index is not None:
- # Sharded checkpoint (safetensors or PyTorch): every shard must exist.
+ # Safetensors only: a cached pytorch_model.bin is a pickle load path and is
+ # never treated as a usable snapshot (a repo shipping only pickle weights
+ # re-resolves and fails closed in _select_snapshot_files).
+ index = snapshot / _STT_SAFETENSORS_INDEX
+ if index.is_file():
+ # Sharded safetensors checkpoint: every shard must exist and be
+ # safetensors (a safe index naming .bin shards would still pickle-load
+ # them, matching the _select_snapshot_files guard).
weight_map = _read_json_object(index).get("weight_map")
if not isinstance(weight_map, dict) or not weight_map:
return False
- has_weights = all((snapshot / shard).is_file() for shard in set(weight_map.values()))
+ shards = set(weight_map.values())
+ if not all(isinstance(shard, str) and shard.endswith(".safetensors") for shard in shards):
+ return False
+ has_weights = all((snapshot / shard).is_file() for shard in shards)
else:
- has_weights = any(
- (snapshot / name).is_file() for name in (_STT_SAFETENSORS_WEIGHTS, _STT_PYTORCH_WEIGHTS)
- )
+ has_weights = (snapshot / _STT_SAFETENSORS_WEIGHTS).is_file()
# WhisperProcessor needs the tokenizer: either the fast tokenizer.json or
# the slow vocab.json + merges.txt pair.
has_tokenizer = (snapshot / "tokenizer.json").is_file() or (
@@ -880,8 +889,11 @@ class WhisperSttSidecar:
try:
processor = WhisperProcessor.from_pretrained(snapshot_path, local_files_only = True)
self._raise_if_load_cancelled(cancel_event)
+ # use_safetensors forces the pickle-free load path even if a
+ # pytorch_model.bin somehow reached the cache; the selector and the
+ # completeness check already exclude pickle weights upstream.
model = WhisperForConditionalGeneration.from_pretrained(
- snapshot_path, torch_dtype = dtype, local_files_only = True
+ snapshot_path, torch_dtype = dtype, local_files_only = True, use_safetensors = True
)
self._raise_if_load_cancelled(cancel_event)
model.to(torch.device(device))
diff --git a/studio/backend/tests/test_stt_review_fixes_2.py b/studio/backend/tests/test_stt_review_fixes_2.py
index 130c43c9566..f0bdab42b5c 100644
--- a/studio/backend/tests/test_stt_review_fixes_2.py
+++ b/studio/backend/tests/test_stt_review_fixes_2.py
@@ -6,8 +6,8 @@
1. scripts/build_whisper_cpp.sh must not rm -rf a whisper.cpp/src tree under a
custom Studio home unless Studio itself created it (ownership marker), the
same policy studio/setup.sh applies before its destructive replacements.
-2. _snapshot_is_complete must validate every shard of a sharded PyTorch
- (pytorch_model.bin.index.json) checkpoint, like the safetensors path.
+2. _snapshot_is_complete must reject pickle (pytorch_model.bin) checkpoints
+ outright; only safetensors weights count as a usable snapshot.
3. _snapshot_is_complete must require tokenizer assets (tokenizer.json or
vocab.json + merges.txt); weights + config alone decode to blank text.
4. Custom-repo downloads must pin the revision validated beforehand and
@@ -143,7 +143,10 @@ def _base_snapshot(tmp_path: Path) -> Path:
return snap
-def test_sharded_pytorch_snapshot_requires_every_shard(tmp_path):
+def test_pickle_checkpoint_snapshot_is_never_complete(tmp_path):
+ # A cached pytorch_model.bin is a pickle RCE load path; the snapshot must
+ # read as incomplete no matter how many shards are present, so update
+ # re-resolves and _select_snapshot_files fails it closed.
snap = _base_snapshot(tmp_path)
index = {
"weight_map": {
@@ -153,14 +156,29 @@ def test_sharded_pytorch_snapshot_requires_every_shard(tmp_path):
}
(snap / "pytorch_model.bin.index.json").write_text(json.dumps(index))
(snap / "pytorch_model-00001-of-00002.bin").write_bytes(b"w" * 8)
-
- # One missing .bin shard must read as incomplete, like the safetensors path.
+ (snap / "pytorch_model-00002-of-00002.bin").write_bytes(b"w" * 8)
assert stt_sidecar_module._snapshot_is_complete(snap) is False
- (snap / "pytorch_model-00002-of-00002.bin").write_bytes(b"w" * 8)
+ # A single-file pickle checkpoint is likewise rejected; the safetensors
+ # equivalent in the same dir makes it complete.
+ (snap / "pytorch_model.bin").write_bytes(b"w" * 8)
+ assert stt_sidecar_module._snapshot_is_complete(snap) is False
+ (snap / "model.safetensors").write_bytes(b"w" * 8)
assert stt_sidecar_module._snapshot_is_complete(snap) is True
+def test_safe_index_naming_pickle_shards_is_not_complete(tmp_path):
+ # A safetensors index that references .bin shards would still pickle-load
+ # via Transformers' per-shard dispatch; the cached snapshot must read as
+ # incomplete so it re-resolves and fails closed at selection.
+ snap = _base_snapshot(tmp_path)
+ (snap / "model.safetensors.index.json").write_text(
+ json.dumps({"weight_map": {"a": "pytorch_model-00001-of-00001.bin"}})
+ )
+ (snap / "pytorch_model-00001-of-00001.bin").write_bytes(b"w" * 8)
+ assert stt_sidecar_module._snapshot_is_complete(snap) is False
+
+
def test_snapshot_without_tokenizer_assets_is_incomplete(tmp_path):
snap = _base_snapshot(tmp_path)
(snap / "model.safetensors").write_bytes(b"w" * 8)
diff --git a/studio/backend/tests/test_stt_sidecar.py b/studio/backend/tests/test_stt_sidecar.py
index 3f78845ac75..b138f463317 100644
--- a/studio/backend/tests/test_stt_sidecar.py
+++ b/studio/backend/tests/test_stt_sidecar.py
@@ -486,6 +486,9 @@ def test_load_uses_model_hub_cache_without_implicit_download(monkeypatch):
}
# Never fetch weights implicitly; the Model Hub owns downloads.
assert all(kwargs.get("local_files_only") is True for _, _, kwargs in calls)
+ # The weight load forces safetensors so a pickle checkpoint cannot execute.
+ model_kwargs = next(kwargs for kind, _, kwargs in calls if kind == "model")
+ assert model_kwargs.get("use_safetensors") is True
def test_model_cache_preflight_uses_shared_offline_resolver(monkeypatch):
@@ -1046,6 +1049,43 @@ def test_snapshot_selection_includes_every_indexed_shard():
}
+def test_snapshot_selection_rejects_pickle_only_weights():
+ # A custom repo shipping only pytorch_model.bin (pickle) must fail closed:
+ # selecting it would download a checkpoint that runs code at load time.
+ info = SimpleNamespace(
+ siblings = [
+ _sibling("config.json", 10, "config"),
+ _sibling("preprocessor_config.json", 20, "preprocessor"),
+ _sibling("tokenizer.json", 30, "tokenizer"),
+ _sibling("pytorch_model.bin", 110, "torch"),
+ ]
+ )
+
+ with pytest.raises(SttModelCompatibilityError, match = "safetensors"):
+ stt_sidecar_module._select_snapshot_files(
+ info, lambda _name: pytest.fail("pickle weights must not be selected")
+ )
+
+
+def test_snapshot_selection_rejects_safe_index_pointing_at_pickle_shards():
+ # A safetensors index can name .bin shards; Transformers dispatches shard
+ # loading by extension, so those shards would still pickle-load. The index
+ # is attacker-controlled, so a non-safetensors shard must fail closed.
+ info = SimpleNamespace(
+ siblings = [
+ _sibling("config.json", 10, "config"),
+ _sibling("model.safetensors.index.json", 5, "index"),
+ _sibling("pytorch_model-00001-of-00001.bin", 90, "shard"),
+ ]
+ )
+
+ with pytest.raises(SttModelCompatibilityError, match = "non-safetensors shards"):
+ stt_sidecar_module._select_snapshot_files(
+ info,
+ lambda _name: {"weight_map": {"a": "pytorch_model-00001-of-00001.bin"}},
+ )
+
+
def test_progress_counts_only_selected_blobs_and_caps_incomplete_files(monkeypatch, tmp_path):
monkeypatch.setenv("HF_HUB_CACHE", str(tmp_path / "hub"))
blobs = tmp_path / "hub" / "models--owner--whisper" / "blobs"