Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

harden(embeddings): confine local model paths to the models directory (#5550)

LearningCircuite5d10d25b900
diff --git a/changelog.d/+embedding-model-path-confinement.security.md b/changelog.d/+embedding-model-path-confinement.security.md
new file mode 100644
index 0000000000..322e27e894
--- /dev/null
+++ b/changelog.d/+embedding-model-path-confinement.security.md
@@ -0,0 +1 @@
+Confined the Sentence Transformers embedding-model setting to the app's models directory. Previously any authenticated user could set `local_search_embedding_model` to an arbitrary absolute server path, turning it into a filesystem existence/structure probe and an arbitrary local-model loader. A value is now treated as a local model only when it resolves under the models directory; anything else is handled as a HuggingFace model id, and a path that escapes the models directory is rejected.
diff --git a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
index 2e27ed267e..2c828f3bef 100644
--- a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
+++ b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
@@ -1,7 +1,8 @@
"""Sentence Transformers embedding provider."""
+import re
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Union
from langchain_core.embeddings import Embeddings
from ....security.secure_logging import logger
@@ -92,6 +93,30 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
f"Creating SentenceTransformerEmbeddings with model={model}, device={device}"
)
+ # Path confinement (security): the embedding model setting is
+ # user-editable free text. ``SentenceTransformer`` loads ANY value
+ # that resolves to an existing filesystem path (its ``os.path.exists``
+ # branch), so without a guard an authenticated user could point this
+ # setting at an arbitrary absolute server path — turning it into a
+ # whole-filesystem existence/structure probe and an arbitrary
+ # local-model loader. Classify the value ONCE:
+ # * a file/dir confined UNDER the app's models directory is a
+ # legitimate local model -> load it from its safe absolute path;
+ # * a filesystem-path-shaped value that ESCAPES the models dir is
+ # refused outright (never handed to the loader);
+ # * anything else is treated as a HuggingFace repo id (default).
+ local_model_path = cls._confined_local_model_path(model)
+ if local_model_path is None and cls._looks_like_filesystem_path(model):
+ logger.bind(policy_audit=True).warning(
+ "refusing sentence-transformers embedding model {!r}: "
+ "filesystem paths must resolve under the app models directory",
+ model,
+ )
+ raise ValueError(
+ "Invalid embedding model path: local model paths must "
+ "resolve under the application's models directory."
+ )
+
# Egress policy: if the user opted into local-only embeddings,
# refuse to trigger a HuggingFace download on first use. The
# SentenceTransformer constructor reaches out to huggingface.co
@@ -161,41 +186,51 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
# the pre-flight already proved the model fully local.
model_kwargs["local_files_only"] = True
+ # Load a confined local model from its safe absolute path; otherwise
+ # hand the (repo-id) value to the loader unchanged.
return SentenceTransformerEmbeddings(
- model_name=model,
+ model_name=(
+ str(local_model_path) if local_model_path is not None else model
+ ),
model_kwargs=model_kwargs,
)
- @staticmethod
- def _is_model_cached_locally(model_name: str) -> bool:
- """Best-effort check whether ``model_name`` is already cached.
-
- Probes the HuggingFace hub cache for both the bare and the
- ``sentence-transformers/``-namespaced forms of the name (the
- two cache keys the SentenceTransformer loader can request for
- a bare input). Returns False if the lookup itself fails, which
- fails closed under ``require_local=True``. A degenerate
- model_name (None, empty, whitespace) also fails closed: the
- cache probe below either raises — caught by the broad except —
- or misses, so no special-casing is needed.
+ @classmethod
+ def _is_model_cached_locally(cls, model_name: str) -> bool:
+ """Best-effort check whether ``model_name`` is available WITHOUT any
+ network access.
+
+ Admissible in two ordered cases:
+
+ 1. ``model_name`` resolves to an existing file/dir CONFINED under the
+ application's models directory (see
+ :meth:`_confined_local_model_path`). Such a model is already on
+ disk and ``SentenceTransformer.__init__`` loads it via its
+ ``os.path.exists`` branch without touching the network.
+
+ Security: the confinement check decides containment lexically and
+ NEVER probes an arbitrary user-supplied path with
+ ``Path(model_name).exists()``. A path outside the models dir can
+ therefore no longer be used as a whole-filesystem existence oracle.
+
+ 2. Otherwise ``model_name`` is treated as a HuggingFace repo id and the
+ hub cache is probed for both the bare and the
+ ``sentence-transformers/``-namespaced forms (the two cache keys the
+ loader can request for a bare input).
+
+ Returns False if the lookup itself fails, which fails closed under
+ ``require_local=True``. A degenerate model_name (None, empty,
+ whitespace) also fails closed.
"""
try:
- # A model configured as an existing local path is already on
- # disk: ``SentenceTransformer.__init__`` takes its
- # ``os.path.exists`` branch and never touches the network, so
- # it's admissible under require_local. Mirror that guard first
- # — before treating the name as an HF repo_id, since a path
- # with "/" would otherwise be probed as a repo_id and rejected
- # as malformed (a false ``embeddings_model_not_cached``).
- #
- # The ``model_name and`` guard is load-bearing: ``Path("")``
- # normalises to ``.`` (the cwd, which exists), so a blank
- # config would wrongly admit — whereas the loader's
- # ``os.path.exists("")`` returns False. The truthiness check
- # restores fail-closed parity for the degenerate empty name.
- if model_name and Path(model_name).exists():
+ # 1. A legitimate local model confined under the app models dir.
+ if cls._confined_local_model_path(model_name) is not None:
return True
+ # 2. Treat the value as an HF repo id and probe the hub cache
+ # ONLY. try_to_load_from_cache keys on the string as a repo_id
+ # inside the HF cache directory, so a non-confined path is never
+ # reached on the real filesystem here.
from huggingface_hub import try_to_load_from_cache
# Probe both the bare and the namespaced cache keys when the
@@ -236,6 +271,147 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
except Exception: # pragma: no cover - defensive
return False
+ @classmethod
+ def _confined_local_model_path(
+ cls,
+ model_name: Optional[str],
+ models_dir: Optional[Union[str, Path]] = None,
+ ) -> Optional[Path]:
+ """Resolve ``model_name`` to a real local model path IFF it denotes an
+ EXISTING location confined UNDER the application's models directory.
+
+ Returns the resolved :class:`~pathlib.Path` for a legitimate local
+ model (a file or directory living under the models dir), or ``None``
+ for everything else — HuggingFace repo ids and, crucially, any
+ absolute/relative path that escapes the models directory.
+
+ Security: a value that is NOT confined under the models dir is
+ rejected by LEXICAL containment (``is_relative_to``) and is never
+ probed on disk with ``Path(model_name).exists()``. This is what closes
+ the arbitrary-filesystem existence oracle. Only a value already
+ confined under the models dir is resolved and stat-ed.
+ """
+ if not isinstance(model_name, str):
+ return None
+ text = model_name.strip()
+ if not text:
+ return None
+
+ try:
+ if models_dir is None:
+ from ....config.paths import get_models_directory
+
+ models_dir = get_models_directory()
+ # Two views of the models root are needed:
+ # * ``models_root_lexical`` -- absolute + lexically normalized
+ # but NOT symlink-resolved. Used for the LEXICAL containment
+ # check on absolute inputs so a legitimate in-tree model still
+ # matches when an ANCESTOR of the models dir is a symlink
+ # (NFS-mounted homes, a symlinked ``LDR_DATA_DIR``, macOS
+ # ``/tmp`` -> ``/private/tmp``). Resolving the root but NOT the
+ # user path is precisely the mismatch that wrongly refused
+ # legitimate models.
+ # * ``models_root`` -- fully symlink-resolved. Used ONLY for the
+ # secondary post-resolution escape re-check below, which
+ # collapses any symlink in the confined candidate and confirms
+ # it still lands inside the resolved tree (catches an in-tree
+ # symlink that points OUT of the models dir).
+ #
+ # ``.absolute()`` makes the path absolute WITHOUT resolving
+ # symlinks (pathlib already collapses ``.`` and redundant
+ # separators on construction); it is used deliberately here in
+ # place of ``.resolve()`` so the lexical comparison below stays
+ # symlink-agnostic.
+ models_root_lexical = Path(models_dir).absolute()
+ models_root = Path(models_dir).resolve()
+ except Exception: # pragma: no cover - defensive
+ return None
+
+ from ....security.path_validator import PathValidator
+
+ try:
+ if Path(text).is_absolute():
+ # Absolute reference: decide containment LEXICALLY first so a
+ # path outside the models dir is rejected without any
+ # filesystem access. Compare ABSOLUTE-but-UN-RESOLVED paths on
+ # BOTH sides (``lexical`` here vs ``models_root_lexical`` above,
+ # never ``.resolve()``) so a symlinked ANCESTOR of the models
+ # dir does not spuriously break the match for a legitimate
+ # in-tree model. The ``..`` guard runs first, on the parts,
+ # so a traversal segment is refused regardless. Only a path
+ # already lexically inside is then resolved (collapsing any
+ # symlink escape) and re-checked against the resolved root
+ # below.
+ lexical = Path(text)
+ if ".." in lexical.parts or not lexical.is_relative_to(
+ models_root_lexical
+ ):
+ return None
+ candidate = lexical.resolve()
+ else:
+ # Relative reference: safe_join confines it under the models
+ # dir, rejecting traversal / absolute inputs (returns None or
+ # raises ValueError). A bare HF id like "all-MiniLM-L6-v2" or
+ # "sentence-transformers/all-MiniLM-L6-v2" confines cleanly but
+ # simply won't exist under the models dir -> falls through to
+ # None and is handled as a repo id by the caller.
+ confined = PathValidator.validate_safe_path(text, models_root)
+ if confined is None:
+ return None
+ candidate = confined.resolve()
+ except (ValueError, OSError, RuntimeError):
+ # RuntimeError: ``.resolve()`` raises this (not OSError) when it
+ # detects a symlink LOOP (e.g. a -> b -> a) while collapsing the
+ # path. Caught here so a loop fails closed with a clean refusal
+ # instead of propagating an uncaught RuntimeError out of this
+ # function / ``create_embeddings``.
+ return None
+
+ # Secondary post-resolution escape re-check (defence in depth): both
+ # ``candidate`` (each branch above resolved it) and ``models_root`` are
+ # fully symlink-resolved here, so this catches an in-tree symlink whose
+ # target points OUT of the models dir — which the lexical check above
+ # deliberately cannot see. Also require a STRICT subpath (never the
+ # models root itself). is_relative_to stays a pure lexical check.
+ if candidate == models_root or not candidate.is_relative_to(
+ models_root
+ ):
+ return None
+
+ try:
+ if candidate.exists():
+ return candidate
+ except OSError: # pragma: no cover - defensive
+ return None
+ return None
+
+ @staticmethod
+ def _looks_like_filesystem_path(model_name: Optional[str]) -> bool:
+ """Pure string classification: does ``model_name`` look like a
+ filesystem path rather than a HuggingFace repo id?
+
+ Returns True only for the unambiguous path shapes used to escape the
+ models directory — absolute paths, home-relative (``~``) refs, Windows
+ drive paths, and any reference containing a parent-traversal (``..``)
+ segment. HuggingFace repo ids such as ``all-MiniLM-L6-v2`` or
+ ``sentence-transformers/all-MiniLM-L6-v2`` return False. Performs no
+ filesystem access.
+ """
+ if not isinstance(model_name, str):
+ return False
+ text = model_name.strip()
+ if not text:
+ return False
+ if text.startswith(("/", "\\", "~")) or Path(text).is_absolute():
+ return True
+ # Windows drive-letter absolute path, e.g. "C:\\models".
+ if len(text) >= 2 and text[1] == ":":
+ return True
+ # Parent-directory traversal in any separator form.
+ if ".." in re.split(r"[\\/]+", text):
+ return True
+ return False
+
@classmethod
def is_available(
cls, settings_snapshot: Optional[Dict[str, Any]] = None
diff --git a/tests/embeddings/test_sentence_transformers.py b/tests/embeddings/test_sentence_transformers.py
index cf24df9b86..41ce6b9140 100644
--- a/tests/embeddings/test_sentence_transformers.py
+++ b/tests/embeddings/test_sentence_transformers.py
@@ -8,8 +8,11 @@ Tests cover:
- Class attributes and metadata
"""
+import pathlib
from unittest.mock import patch, MagicMock
+import pytest
+
class TestSentenceTransformersProviderMetadata:
"""Tests for SentenceTransformersProvider class metadata."""
@@ -328,3 +331,334 @@ class TestSentenceTransformersProviderGetAvailableModels:
expected_model
) in SentenceTransformersProvider.AVAILABLE_MODELS.keys():
assert expected_model in model_values
+
+
+class TestSentenceTransformersProviderPathConfinement:
+ """Security regression tests for embedding-model path confinement.
+
+ ``local_search_embedding_model`` is user-editable free text. Without
+ confinement, ``SentenceTransformer`` loads ANY value that resolves to an
+ existing filesystem path, so an authenticated user could set an arbitrary
+ absolute server path and (a) probe the filesystem for existence/structure
+ and (b) load an arbitrary local model directory. The provider now treats a
+ value as a LOCAL model only when it resolves UNDER the app's models
+ directory; everything else is a HuggingFace repo id (and an escaping,
+ path-shaped value is refused outright).
+ """
+
+ def _provider(self):
+ from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
+ SentenceTransformersProvider,
+ )
+
+ return SentenceTransformersProvider
+
+ # ---- (a) arbitrary path outside the models dir --------------------------
+
+ def test_arbitrary_absolute_path_not_treated_as_local_model(self, tmp_path):
+ """An arbitrary absolute path OUTSIDE the models dir (``/etc``) is not
+ classified as a local model, and is NOT probed with a raw
+ ``Path(...).exists()`` filesystem call. This is the core fix: the value
+ can no longer be used as a whole-filesystem existence oracle.
+ """
+ provider = self._provider()
+ # Resolve tmp_path so the test does not silently depend on an
+ # un-symlinked /tmp: on platforms where the temp root has a symlinked
+ # ancestor (e.g. macOS /tmp -> /private/tmp) an UN-resolved models_dir
+ # would not match the resolved models root computed internally.
+ tmp_path = tmp_path.resolve()
+ models_dir = tmp_path / "models"
+ models_dir.mkdir()
+
+ arbitrary = "/etc" # exists on the host, but outside the models dir
+ probed = []
+ real_exists = pathlib.Path.exists
+
+ def spy_exists(self):
+ probed.append(str(self))
+ return real_exists(self)
+
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ):
+ with patch(
+ "huggingface_hub.try_to_load_from_cache", return_value=None
+ ):
+ with patch.object(pathlib.Path, "exists", spy_exists):
+ # Not confined -> not a local model...
+ assert (
+ provider._confined_local_model_path(arbitrary) is None
+ )
+ # ...and not admitted as "cached locally".
+ assert provider._is_model_cached_locally(arbitrary) is False
+
+ # No raw existence probe was performed on the arbitrary path or its
+ # children. On the pre-fix code the guard did ``Path("/etc").exists()``
+ # and admitted it as local, so this assertion (and the one above)
+ # fail there — the differential that proves the fix.
+ assert not any(
+ p == arbitrary or p.startswith(arbitrary + "/") for p in probed
+ )
+
+ def test_create_embeddings_refuses_arbitrary_absolute_path(self, tmp_path):
+ """``create_embeddings`` refuses a filesystem-path-shaped value that
+ escapes the models dir and never hands it to the loader — so an
+ arbitrary server path is neither probed nor loaded.
+ """
+ provider = self._provider()
+ tmp_path = tmp_path.resolve()
+ models_dir = tmp_path / "models"
+ models_dir.mkdir()
+
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ):
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as mock_st:
+ with pytest.raises(ValueError):
+ provider.create_embeddings(
+ model="/etc/passwd", device="cpu"
+ )
+ mock_st.assert_not_called()
+
+ def test_parent_traversal_value_refused(self, tmp_path):
+ """A relative value containing ``..`` (attempting to climb out of the
+ models dir) is path-shaped, not confined, and refused.
+ """
+ provider = self._provider()
+ tmp_path = tmp_path.resolve()
+ models_dir = tmp_path / "models"
+ models_dir.mkdir()
+
+ assert provider._looks_like_filesystem_path("../../etc/passwd") is True
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ):
+ assert (
+ provider._confined_local_model_path("../../etc/passwd") is None
+ )
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as mock_st:
+ with pytest.raises(ValueError):
+ provider.create_embeddings(
+ model="../../etc/passwd", device="cpu"
+ )
+ mock_st.assert_not_called()
+
+ # ---- (b) a path INSIDE the models dir still resolves as local -----------
+
+ def test_path_inside_models_dir_is_local_model(self, tmp_path):
+ """A model directory genuinely UNDER the app's models dir still loads:
+ it is classified as local (by absolute and by relative reference) and
+ admitted without an HF cache probe.
+ """
+ provider = self._provider()
+ tmp_path = tmp_path.resolve()
+ models_dir = tmp_path / "models"
+ model_dir = models_dir / "custom-st-model"
+ model_dir.mkdir(parents=True)
+
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ):
+ # Absolute path under the models dir resolves to the model dir.
+ assert (
+ provider._confined_local_model_path(str(model_dir))
+ == model_dir.resolve()
+ )
+ # A path relative to the models dir resolves the same way.
+ assert (
+ provider._confined_local_model_path("custom-st-model")
+ == model_dir.resolve()
+ )
+ with patch("huggingface_hub.try_to_load_from_cache") as mock_cache:
+ assert provider._is_model_cached_locally(str(model_dir)) is True
+ mock_cache.assert_not_called()
+
+ def test_create_embeddings_loads_confined_local_model_by_abs_path(
+ self, tmp_path
+ ):
+ """``create_embeddings`` loads a confined local model from its safe
+ ABSOLUTE path (so the loader takes its local-path branch even when the
+ user referenced the model by a name relative to the models dir).
+ """
+ provider = self._provider()
+ tmp_path = tmp_path.resolve()
+ models_dir = tmp_path / "models"
+ model_dir = models_dir / "custom-st-model"
+ model_dir.mkdir(parents=True)
+
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ):
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=MagicMock(),
+ ) as mock_st:
+ provider.create_embeddings(
+ model="custom-st-model", device="cpu"
+ )
+ assert mock_st.call_args.kwargs["model_name"] == str(
+ model_dir.resolve()
+ )
+
+ # ---- (b') a symlinked ancestor must not refuse a legit model ------------
+
+ def test_symlinked_models_dir_ancestor_still_loads_confined_model(
+ self, tmp_path
+ ):
+ """A legitimate in-tree absolute model still loads when an ANCESTOR of
+ the models dir is a symlink (NFS-mounted homes, a symlinked
+ ``LDR_DATA_DIR``, macOS ``/tmp`` -> ``/private/tmp``).
+
+ Regression test for over-strict confinement: the lexical containment
+ check must compare the UN-resolved user path against an UN-resolved
+ models root. If it instead compares the un-resolved user path against a
+ RESOLVED root, a symlinked ancestor makes every in-tree absolute model
+ fail the lexical match and be wrongly refused. The secondary
+ post-resolution re-check must still refuse an in-tree symlink whose
+ target ESCAPES the models dir.
+ """
+ provider = self._provider()
+ # Real tree (fully resolved), plus a symlinked view of its parent so
+ # that referencing the model through the symlink exercises the
+ # symlinked-ancestor case explicitly rather than relying on the host's
+ # /tmp being (or not being) a symlink.
+ real_root = tmp_path.resolve()
+ models_dir = real_root / "data" / "models"
+ model_dir = models_dir / "custom-st-model"
+ model_dir.mkdir(parents=True)
+
+ link_root = real_root / "linked" # linked -> data (symlinked ancestor)
+ try:
+ link_root.symlink_to(real_root / "data")
+ except (OSError, NotImplementedError): # pragma: no cover - platform
+ pytest.skip("symlinks not supported on this platform")
+
+ linked_models_dir = link_root / "models"
+ linked_model_dir = linked_models_dir / "custom-st-model"
+ # The symlinked reference resolves to the real in-tree model.
+ assert linked_model_dir.resolve() == model_dir.resolve()
+
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=linked_models_dir,
+ ):
+ # Admitted and resolved to its real path. Pre-fix (un-resolved user
+ # path vs resolved root) this returned None -> wrongly refused.
+ assert (
+ provider._confined_local_model_path(str(linked_model_dir))
+ == model_dir.resolve()
+ )
+ # ...and create_embeddings hands the loader that safe absolute path.
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=MagicMock(),
+ ) as mock_st:
+ provider.create_embeddings(
+ model=str(linked_model_dir), device="cpu"
+ )
+ assert mock_st.call_args.kwargs["model_name"] == str(
+ model_dir.resolve()
+ )
+
+ # An in-tree symlink whose TARGET escapes the models dir is still
+ # refused by the secondary post-resolution re-check (the lexical
+ # relaxation must not open a symlink-escape hole).
+ escape = models_dir / "escape"
+ try:
+ escape.symlink_to(real_root.parent)
+ except (OSError, NotImplementedError): # pragma: no cover
+ pytest.skip("symlinks not supported on this platform")
+ assert (
+ provider._confined_local_model_path(
+ str(linked_models_dir / "escape")
+ )
+ is None
+ )
+
+ # ---- (b'') a symlink LOOP must fail closed, not raise uncaught ----------
+
+ def test_symlink_loop_fails_closed(self, tmp_path):
+ """A symlink LOOP under the models dir (``loop_a`` -> ``loop_b`` ->
+ ``loop_a``) must fail CLOSED with a clean refusal, not leak an
+ uncaught ``RuntimeError``.
+
+ ``pathlib.Path.resolve()`` raises ``RuntimeError`` (NOT ``OSError``)
+ when it detects a symlink loop while collapsing a path. Regression
+ test for the file's fail-closed invariant: a loop must be caught and
+ translated into the same "not a local model" refusal as any other
+ unconfined/unresolvable value, never propagate an uncaught
+ ``RuntimeError`` out of ``_confined_local_model_path`` /
+ ``create_embeddings``.
+ """
+ provider = self._provider()
+ tmp_path = tmp_path.resolve()
+ models_dir = tmp_path / "models"
+ models_dir.mkdir()
+
+ loop_a = models_dir / "loop_a"
+ loop_b = models_dir / "loop_b"
+ try:
+ loop_a.symlink_to(loop_b)
+ loop_b.symlink_to(loop_a)
+ except (OSError, NotImplementedError): # pragma: no cover - platform
+ pytest.skip("symlinks not supported on this platform")
+
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ):
+ # The loop must resolve to "not a local model", not raise.
+ assert provider._confined_local_model_path(str(loop_a)) is None
+
+ # create_embeddings must refuse it with the same clean, generic
+ # ValueError as any other unconfined/unresolvable value -- never
+ # an uncaught RuntimeError.
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings"
+ ) as mock_st:
+ with pytest.raises(ValueError):
+ provider.create_embeddings(model=str(loop_a), device="cpu")
+ mock_st.assert_not_called()
+
+ # ---- (c) a normal HF id still works -------------------------------------
+
+ def test_hf_id_treated_as_repo_id(self, tmp_path):
+ """A normal HuggingFace id — bare, or ``org/name`` containing ``/`` but
+ not a filesystem path — is NOT classified as a local path and is passed
+ through to the loader unchanged as a repo id.
+ """
+ provider = self._provider()
+ tmp_path = tmp_path.resolve()
+ models_dir = tmp_path / "models"
+ models_dir.mkdir()
+
+ namespaced = "sentence-transformers/all-MiniLM-L6-v2"
+ assert provider._looks_like_filesystem_path("all-MiniLM-L6-v2") is False
+ assert provider._looks_like_filesystem_path(namespaced) is False
+
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ):
+ # Confines lexically but does not exist under the models dir, so it
+ # is handled as a repo id, not a local path.
+ assert (
+ provider._confined_local_model_path("all-MiniLM-L6-v2") is None
+ )
+ assert provider._confined_local_model_path(namespaced) is None
+
+ with patch(
+ "langchain_community.embeddings.SentenceTransformerEmbeddings",
+ return_value=MagicMock(),
+ ) as mock_st:
+ provider.create_embeddings(model=namespaced, device="cpu")
+ assert mock_st.call_args.kwargs["model_name"] == namespaced
diff --git a/tests/security/test_egress_policy.py b/tests/security/test_egress_policy.py
index 6979d1810e..5e115c42b7 100644
--- a/tests/security/test_egress_policy.py
+++ b/tests/security/test_egress_policy.py
@@ -2179,30 +2179,50 @@ def test_sbert_cache_check_treats_non_string_returns_as_misses(miss_value):
)
-def test_sbert_cache_check_admits_existing_local_path(tmp_path):
- """A model configured as an existing local directory is already on
- disk — the loader takes its ``os.path.exists`` branch and never hits
- the network, so it must be admitted under require_local without an
- HF cache probe. Before this guard the path was probed as an HF
- repo_id, raised HFValidationError, was swallowed, and false-denied
- with ``embeddings_model_not_cached``. Differential: returns False on
- the pre-guard code.
+def test_sbert_cache_check_admits_local_model_confined_under_models_dir(
+ tmp_path,
+):
+ """A model configured as an existing directory CONFINED UNDER the app's
+ models directory is already on disk — the loader takes its
+ ``os.path.exists`` branch and never hits the network, so it must be
+ admitted under require_local without an HF cache probe.
+
+ Confinement is what makes this safe: only paths under the models dir are
+ admitted (both an absolute path under it and a path relative to it),
+ whereas an arbitrary server path is rejected (see
+ ``tests/embeddings/test_sentence_transformers.py`` for the escape cases).
+ The admit checks only that the confined path exists (no config.json /
+ model-structure validation), mirroring the loader's os.path.exists guard.
"""
from local_deep_research.embeddings.providers.implementations.sentence_transformers import (
SentenceTransformersProvider,
)
- # tmp_path is an existing directory. The admit checks only that the
- # path exists (no config.json / model-structure validation), so a
- # bare existing dir is sufficient — mirroring the loader's
- # os.path.exists guard, which likewise does not inspect contents.
- with patch("huggingface_hub.try_to_load_from_cache") as mock_cache:
- assert (
- SentenceTransformersProvider._is_model_cached_locally(str(tmp_path))
- is True
- )
- # Local-path admission short-circuits before any HF cache probe.
- mock_cache.assert_not_called()
+ models_dir = tmp_path / "models"
+ model_dir = models_dir / "my-local-model"
+ model_dir.mkdir(parents=True)
+
+ with patch(
+ "local_deep_research.config.paths.get_models_directory",
+ return_value=models_dir,
+ ):
+ with patch("huggingface_hub.try_to_load_from_cache") as mock_cache:
+ # Absolute path under the models dir.
+ assert (
+ SentenceTransformersProvider._is_model_cached_locally(
+ str(model_dir)
+ )
+ is True
+ )
+ # Path relative to the models dir.
+ assert (
+ SentenceTransformersProvider._is_model_cached_locally(
+ "my-local-model"
+ )
+ is True
+ )
+ # Confined-local admission short-circuits before any HF cache probe.
+ mock_cache.assert_not_called()
def test_sbert_cache_check_blank_name_not_treated_as_existing_path():
@@ -2217,9 +2237,9 @@ def test_sbert_cache_check_blank_name_not_treated_as_existing_path():
)
assert SentenceTransformersProvider._is_model_cached_locally("") is False
- # Whitespace is truthy, so unlike "" it DOES reach Path.exists() — it
- # must still miss (no such path) and fall through to fail-closed,
- # rather than being admitted as a local path.
+ # Whitespace strips to empty in the confinement check, so it is never
+ # admitted as a local path; it falls through to the HF cache probe, which
+ # misses and fail-closes rather than admitting a blank/whitespace config.
with patch("huggingface_hub.try_to_load_from_cache", return_value=None):
assert (
SentenceTransformersProvider._is_model_cached_locally(" ")