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.

fix(security): enforce realpath containment in validate_safe_path (GHSA-gv87-qcw7-gjr8) (#6883)

LearningCircuit4dd2692f774d
diff --git a/changelog.d/6883.bugfix.md b/changelog.d/6883.bugfix.md
new file mode 100644
index 0000000000..506209e8f0
--- /dev/null
+++ b/changelog.d/6883.bugfix.md
@@ -0,0 +1,4 @@
+Deleting a document, removing only its PDF, or removing a document from its
+last collection now deletes the PDF file when the library's `pdfs` directory
+is a symlink onto another disk. Previously the PDF file was left behind on
+that disk.
diff --git a/changelog.d/6883.security.md b/changelog.d/6883.security.md
new file mode 100644
index 0000000000..00b565e616
--- /dev/null
+++ b/changelog.d/6883.security.md
@@ -0,0 +1 @@
+Enforce realpath containment in validate_safe_path (GHSA-gv87-qcw7-gjr8). When a path is validated, a symlinked directory or leaf inside the base directory that resolves outside it is refused, including one reached through a symlink chain whose resolved path is longer than PATH_MAX, so it can no longer be traversed to read or write files outside the base. Symlinks resolving within the base (bind mounts, macOS /tmp layouts) and the sanctioned `pdfs`-onto-a-larger-disk storage layout keep working. The document-deletion unlink re-check, report deletion and storage, the backup file checks, local model paths, the built frontend asset check and directory creation resolve paths the same strict way before their containment checks. Deleting a document, removing only its PDF, or removing a document from its last collection also checks the file against its boundary as resolved before the file was validated, so a `pdfs` directory swapped for a symlink after that is refused.
diff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.py
index 670cbb6ab9..675b05b0ef 100644
--- a/src/local_deep_research/database/backup/backup_service.py
+++ b/src/local_deep_research/database/backup/backup_service.py
@@ -185,13 +185,27 @@ def is_safe_glob_result(path: Path, base_dir: Path) -> bool:
path: The path returned by glob to validate.
base_dir: The directory the path must reside within.
+ Both sides are resolved with ``resolve_allow_missing()``, never a bare
+ non-strict ``resolve()``, so a path that cannot be fully resolved (a
+ loop, a symlink chain whose resolved form outgrows PATH_MAX) is
+ rejected instead of being compared half resolved.
+
Returns:
True if the path is a regular (non-symlink) file that resolves
to a location within base_dir.
"""
- return not path.is_symlink() and path.resolve().is_relative_to(
- base_dir.resolve()
- )
+ # Lazy import: keeps the security package out of this database
+ # module's import-time graph (the database package loads at bootstrap).
+ from ...security.path_validator import resolve_allow_missing
+
+ if path.is_symlink():
+ return False
+ try:
+ return resolve_allow_missing(path).is_relative_to(
+ resolve_allow_missing(base_dir)
+ )
+ except OSError:
+ return False
def pop_user_lock(username: str) -> None:
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 f6a7659861..5da6e306b9 100644
--- a/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
+++ b/src/local_deep_research/embeddings/providers/implementations/sentence_transformers.py
@@ -535,6 +535,11 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
if not text:
return None
+ from ....security.path_validator import (
+ PathValidator,
+ resolve_allow_missing,
+ )
+
try:
if models_dir is None:
from ....config.paths import get_models_directory
@@ -561,12 +566,10 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
# place of ``.resolve()`` so the lexical comparison below stays
# symlink-agnostic.
models_root_lexical = Path(models_dir).absolute()
- models_root = Path(models_dir).resolve()
+ models_root = resolve_allow_missing(Path(models_dir))
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
@@ -585,7 +588,7 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
models_root_lexical
):
return None
- candidate = lexical.resolve()
+ candidate = resolve_allow_missing(lexical)
else:
# Relative reference: safe_join confines it under the models
# dir, rejecting traversal / absolute inputs (returns None or
@@ -596,13 +599,15 @@ class SentenceTransformersProvider(BaseEmbeddingProvider):
confined = PathValidator.validate_safe_path(text, models_root)
if confined is None:
return None
- candidate = confined.resolve()
+ candidate = resolve_allow_missing(confined)
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``.
+ # resolve_allow_missing() raises OSError for a symlink LOOP
+ # (e.g. a -> b -> a), for a symlink chain whose resolved form
+ # outgrows PATH_MAX, and for any other component it cannot
+ # resolve, where a bare non-strict resolve() would return a
+ # half-resolved path. RuntimeError is still caught defensively.
+ # Every case fails closed with a clean refusal instead of
+ # propagating out of this function / ``create_embeddings``.
return None
# Secondary post-resolution escape re-check (defence in depth): both
diff --git a/src/local_deep_research/research_library/deletion/services/document_deletion.py b/src/local_deep_research/research_library/deletion/services/document_deletion.py
index 3b0b8ef6d5..4a44efa6c7 100644
--- a/src/local_deep_research/research_library/deletion/services/document_deletion.py
+++ b/src/local_deep_research/research_library/deletion/services/document_deletion.py
@@ -234,9 +234,34 @@ class DocumentDeletionService:
effective_storage_mode(document) == "filesystem"
and document.file_path
):
- from ...utils import get_absolute_path_from_settings
+ from ...utils import (
+ get_absolute_path_from_settings,
+ get_containment_root_from_settings,
+ )
try:
+ # Re-check the unlink against the directory the
+ # resolver confines file_path to: this user's root,
+ # or <root>/pdfs for a stored pdfs/... path. The bare
+ # library root would refuse every PDF in the
+ # sanctioned layout that symlinks pdfs onto a larger
+ # disk, and orphan it there. The boundary is resolved
+ # (pinned) BEFORE the file is, and the re-check does
+ # not resolve it again (allowed_root_is_resolved), so
+ # a pdfs directory swapped for a symlink after this
+ # point moves only the file, which is then refused
+ # (#5481). The boundary is None only when the root
+ # lookup or its resolution fails.
+ # _resolved_containment_ok() treats allowed_root=None
+ # as "no boundary enforced" for callers that can't
+ # cheaply supply a root (e.g. the FAISS sweeps),
+ # which is fine there but would be a silent fail-open
+ # here. Fail closed instead of unlinking with no
+ # containment boundary.
+ allowed_root = get_containment_root_from_settings(
+ document.file_path,
+ self.username,
+ )
# Delete only within this user's own root — never the
# legacy shared root, where a colliding relative path
# can resolve to another tenant's file (#5521).
@@ -244,21 +269,12 @@ class DocumentDeletionService:
document.file_path,
self.username,
)
- # get_absolute_path_from_settings("") returns the
- # library root (its `if not relative_path` branch),
- # never None, so this can't currently trip. Guarded
- # anyway: _resolved_containment_ok() treats
- # allowed_root=None as "no boundary enforced" for
- # callers that can't cheaply supply a root (e.g. the
- # FAISS sweeps), which is fine there but would be a
- # silent fail-open here. Fail closed instead of
- # unlinking with no containment boundary.
- allowed_root = get_absolute_path_from_settings("")
if file_path and allowed_root is not None:
result["file_deleted"] = (
CascadeHelper.delete_filesystem_file(
str(file_path),
allowed_root=allowed_root,
+ allowed_root_is_resolved=True,
)
)
elif file_path:
@@ -462,23 +478,29 @@ class DocumentDeletionService:
elif storage_mode == "filesystem":
# Delete filesystem file
- from ...utils import get_absolute_path_from_settings
+ from ...utils import (
+ get_absolute_path_from_settings,
+ get_containment_root_from_settings,
+ )
if document.file_path:
try:
+ # See the boundary and fail-closed comment on the
+ # equivalent guard in _delete_document_locked()
+ # above: the boundary is pinned before the file
+ # is resolved, and a destructive unlink must not
+ # silently fall back to a boundary-less
+ # containment check if it is ever None.
+ allowed_root = get_containment_root_from_settings(
+ document.file_path,
+ self.username,
+ )
# Own-root only: never unlink via the legacy
# shared root (cross-tenant collision, #5521).
file_path = get_absolute_path_from_settings(
document.file_path,
self.username,
)
- # See the fail-closed comment on the equivalent
- # guard in _delete_document_locked() above:
- # allowed_root should never be None here, but a
- # destructive unlink must not silently fall back
- # to a boundary-less containment check if it
- # ever were.
- allowed_root = get_absolute_path_from_settings("")
if (
file_path
and file_path.is_file()
@@ -488,6 +510,7 @@ class DocumentDeletionService:
CascadeHelper.delete_filesystem_file(
str(file_path),
allowed_root=allowed_root,
+ allowed_root_is_resolved=True,
)
elif file_path and file_path.is_file():
logger.error(
@@ -720,26 +743,33 @@ class DocumentDeletionService:
effective_storage_mode(document) == "filesystem"
and document.file_path
):
- from ...utils import get_absolute_path_from_settings
+ from ...utils import (
+ get_absolute_path_from_settings,
+ get_containment_root_from_settings,
+ )
try:
+ # See the boundary and fail-closed comment on the
+ # equivalent guard in _delete_document_locked()
+ # above: the boundary is pinned before the file
+ # is resolved, and a destructive unlink must not
+ # silently fall back to a boundary-less
+ # containment check if it is ever None.
+ allowed_root = get_containment_root_from_settings(
+ document.file_path,
+ self.username,
+ )
# Own-root only: never unlink via the legacy
# shared root (cross-tenant collision, #5521).
file_path = get_absolute_path_from_settings(
document.file_path,
self.username,
)
- # See the fail-closed comment on the equivalent
- # guard in _delete_document_locked() above:
- # allowed_root should never be None here, but a
- # destructive unlink must not silently fall back
- # to a boundary-less containment check if it
- # ever were.
- allowed_root = get_absolute_path_from_settings("")
if file_path and allowed_root is not None:
CascadeHelper.delete_filesystem_file(
str(file_path),
allowed_root=allowed_root,
+ allowed_root_is_resolved=True,
)
elif file_path:
logger.error(
diff --git a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
index 66a9188030..84934e10c4 100644
--- a/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
+++ b/src/local_deep_research/research_library/deletion/utils/cascade_helper.py
@@ -321,15 +321,28 @@ class CascadeHelper:
@staticmethod
def _resolved_containment_ok(
- path: Path, allowed_root: Optional[Union[str, Path]]
+ path: Path,
+ allowed_root: Optional[Union[str, Path]],
+ *,
+ allowed_root_is_resolved: bool = False,
) -> bool:
"""Return True if `path`'s fully-resolved real location stays under
`allowed_root`.
- `Path.resolve()` follows every symlink in the chain -- not just the
+ Resolution follows every symlink in the chain -- not just the
final component -- so this also catches an escape via a symlinked
*ancestor* directory (e.g. a library subfolder swapped for a symlink
pointing outside the library root between validation and delete).
+ It uses `resolve_allow_missing()`, never a bare non-strict
+ `resolve()`: that one ignores ENAMETOOLONG, so a symlink chain
+ whose resolved form outgrows PATH_MAX could hide an escape.
+
+ `allowed_root` is resolved here too, unless the caller passes
+ `allowed_root_is_resolved=True`. In that case it was already
+ resolved before the path was validated, and it is compared as
+ given. Resolving it again would let a boundary directory swapped
+ for a symlink after validation move the boundary along with the
+ file.
When `allowed_root` is None, no containment boundary is enforced
here; callers that can't cheaply supply a root still get the
@@ -338,9 +351,14 @@ class CascadeHelper:
"""
if allowed_root is None:
return True
+ from ....security.path_validator import resolve_allow_missing
+
try:
- resolved_path = path.resolve(strict=False)
- resolved_root = Path(allowed_root).resolve(strict=False)
+ resolved_path = resolve_allow_missing(path)
+ if allowed_root_is_resolved:
+ resolved_root = Path(allowed_root)
+ else:
+ resolved_root = resolve_allow_missing(Path(allowed_root))
except OSError:
# Can't resolve (e.g. a broken component) -- refuse rather than
# risk unlinking something outside the intended root.
@@ -351,6 +369,8 @@ class CascadeHelper:
def delete_filesystem_file(
file_path: Optional[str],
allowed_root: Optional[Union[str, Path]] = None,
+ *,
+ allowed_root_is_resolved: bool = False,
) -> bool:
"""
Delete a file from the filesystem.
@@ -362,6 +382,12 @@ class CascadeHelper:
refused. Defense-in-depth against a symlink planted at (or
swapped in for) `file_path` redirecting the unlink to an
arbitrary file elsewhere on disk -- see #5481.
+ allowed_root_is_resolved: True when `allowed_root` was resolved
+ before `file_path` was validated, as
+ `get_containment_root_from_settings` returns it. It is then
+ compared as given instead of being resolved again, so a
+ boundary directory swapped for a symlink since then cannot
+ move the boundary along with the file.
Returns:
True if file was deleted, False otherwise
@@ -386,7 +412,11 @@ class CascadeHelper:
)
return False
- if not CascadeHelper._resolved_containment_ok(path, allowed_root):
+ if not CascadeHelper._resolved_containment_ok(
+ path,
+ allowed_root,
+ allowed_root_is_resolved=allowed_root_is_resolved,
+ ):
logger.warning(
f"Refusing to delete filesystem file outside allowed root: {file_path}"
)
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 27da388288..b9a86b0fd2 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -79,6 +79,7 @@ from ...library.download_management.models import (
)
from ...config.paths import get_library_directory
from ..utils import (
+ _TRUSTED_STORAGE_LEAF,
apply_user_subdir,
document_awaits_pdf,
download_claim_is_live,
@@ -425,7 +426,7 @@ class DownloadService:
# Only create the root and pdfs folder - flat structure.
paths = [
self.library_root,
- str(Path(self.library_root) / "pdfs"),
+ str(Path(self.library_root) / _TRUSTED_STORAGE_LEAF),
]
for path in paths:
create_directory(
diff --git a/src/local_deep_research/research_library/services/pdf_storage_manager.py b/src/local_deep_research/research_library/services/pdf_storage_manager.py
index 795f791231..146506e556 100644
--- a/src/local_deep_research/research_library/services/pdf_storage_manager.py
+++ b/src/local_deep_research/research_library/services/pdf_storage_manager.py
@@ -20,7 +20,7 @@ from sqlalchemy.orm import Session
from ...constants import FILE_PATH_SENTINELS
from ...utilities.arxiv import extract_arxiv_id
from ...database.models.library import Document, DocumentBlob
-from ...security.path_validator import PathValidator
+from ...security.path_validator import PathValidator, resolve_allow_missing
# Default storage cap for individual PDFs (megabytes). Mirrors the
@@ -153,21 +153,19 @@ class PDFStorageManager:
) -> Optional[Path]:
"""Validate ``relative_path`` inside ``root`` (traversal + symlink
safe). Returns the validated Path (which may not exist), or None if
- the path is invalid/unsafe."""
- try:
- # Use PathValidator to safely join and validate the path
- safe_path = PathValidator.validate_safe_path(
- relative_path, str(root)
- )
- safe_path = Path(safe_path)
- # Block symbolic links to prevent symlink-based escapes
- if safe_path.is_symlink():
- logger.warning(f"Symlink blocked: {relative_path}")
- return None
- return safe_path
- except ValueError:
- logger.warning(f"Path traversal blocked: {relative_path}")
- return None
+ the path is invalid/unsafe.
+
+ Thin delegate to the shared research-library implementation
+ (``research_library.utils._resolve_within_root``): the sanctioned
+ trusted-"pdfs" leaf layout (a symlinked pdfs directory onto a
+ larger disk) must resolve identically on the storage-manager side
+ and through every settings-based resolver, so the containment
+ rule — including its carve-out — lives in exactly one place
+ (GHSA-gv87-qcw7-gjr8).
+ """
+ from ..utils import _resolve_within_root
+
+ return _resolve_within_root(relative_path, root)
def _get_safe_file_path(self, relative_path: str) -> Optional[Path]:
"""Resolve only inside this manager's library root.
@@ -353,20 +351,35 @@ class PDFStorageManager:
# Create simple flat directory structure - all PDFs in one folder
from ...security.directory_creation import create_directory
+ from ..utils import _TRUSTED_STORAGE_LEAF
- pdf_path = self.library_root / "pdfs"
+ pdf_path = self.library_root / _TRUSTED_STORAGE_LEAF
create_directory(
pdf_path,
context="library PDF storage directory",
)
- # Use PathValidator with relative path from library_root
- relative_path = f"pdfs/{filename}"
- validated_path = PathValidator.validate_safe_path(
- relative_path,
- base_dir=str(self.library_root),
+ # Validate the filename against the pdfs directory itself: the
+ # hard-coded "pdfs" leaf is the sanctioned operator symlink layout
+ # (see _safe_path_in_root), so containment runs against the
+ # resolved directory rather than library_root. The validated name
+ # is then re-joined on the *lexical* pdfs path so the stored
+ # relative path stays expressible against library_root. Stripping
+ # leading slashes preserves the old "pdfs/" + filename join's
+ # normalization of absolute-looking inputs INTO the store.
+ validated_name = PathValidator.validate_safe_path(
+ filename.lstrip("/"),
+ base_dir=str(pdf_path),
required_extensions=(".pdf",),
)
+ # Re-express the validated remainder (which comes back under the
+ # RESOLVED pdfs directory) on the *lexical* pdfs path, so the
+ # stored relative path stays expressible against library_root and
+ # sub-directory-carrying names keep their shape. The directory is
+ # resolved exactly as validate_safe_path resolved its base.
+ validated_path = pdf_path / validated_name.relative_to(
+ resolve_allow_missing(pdf_path)
+ )
# Write the PDF file with security verification
# Pass current storage_mode as snapshot since we already validated it
diff --git a/src/local_deep_research/research_library/utils/__init__.py b/src/local_deep_research/research_library/utils/__init__.py
index 661b74fb9d..643f7e88d8 100644
--- a/src/local_deep_research/research_library/utils/__init__.py
+++ b/src/local_deep_research/research_library/utils/__init__.py
@@ -1,7 +1,9 @@
"""Shared utility functions for the Research Library."""
import ipaddress
+import ntpath
import os
+import posixpath
import socket
import subprocess
import sys
@@ -32,7 +34,7 @@ from ...utilities.download_url import (
)
from ...security.ip_ranges import PRIVATE_IP_RANGES
from ...security.network_utils import is_private_ip
-from ...security.path_validator import PathValidator
+from ...security.path_validator import PathValidator, resolve_allow_missing
def escape_like(text: str) -> str:
@@ -665,7 +667,9 @@ def get_absolute_library_path(
"""
Get the absolute path from a relative library path.
- Uses PathValidator to prevent path traversal attacks.
+ Uses PathValidator to prevent path traversal attacks, with the same
+ trusted-storage-leaf carve-out as every other library resolver (see
+ ``_resolve_within_root``).
Args:
relative_path: The relative path from library root
@@ -675,35 +679,85 @@ def get_absolute_library_path(
The absolute path, or None if the path is unsafe
"""
library_root = get_library_storage_path(username)
- try:
- # Use PathValidator to prevent path traversal attacks
- safe_path = PathValidator.validate_safe_path(
- relative_path, str(library_root)
- )
- if safe_path is None:
- return None
- result = Path(safe_path)
- if result.is_symlink():
- logger.warning(f"Symlink blocked: {relative_path}")
- return None
- return result
- except ValueError:
- logger.warning(f"Path traversal blocked: {relative_path}")
- return None
+ return _resolve_within_root(relative_path, library_root)
+
+
+# The one sanctioned operator storage layout: the hard-coded "pdfs"
+# leaf under the library root is commonly a symlink onto a larger
+# disk (pinned by test_saves_to_symlinked_pdfs_directory). Containment
+# for stored paths under this leaf is enforced against the *resolved*
+# pdfs directory; every other stored path is confined to the root
+# itself (GHSA-gv87-qcw7-gjr8). This is the single shared
+# implementation of that rule: PDFStorageManager._safe_path_in_root
+# and every settings-based resolver below resolve through it, so the
+# write side and the read/delete side can never drift apart.
+_TRUSTED_STORAGE_LEAF = "pdfs"
+
+# The path module whose separator stored library paths are written with.
+# PDFStorageManager stores ``str(path.relative_to(library_root))``, so a
+# stored path separates its segments with "/" on POSIX, where a backslash
+# is an ordinary filename character, and with a backslash on Windows.
+_STORED_PATH_MODULE = ntpath if os.name == "nt" else posixpath
+
+
+def _containment_base(
+ relative_path: str, library_root: Path
+) -> tuple[Path, str]:
+ """Return ``(base, remainder)`` for checking a stored library path.
+
+ ``base`` is the directory ``relative_path`` must stay inside and
+ ``remainder`` is the part of it validated against ``base``. A path
+ whose first segment is the trusted ``pdfs`` leaf
+ (``_TRUSTED_STORAGE_LEAF``) is checked against ``library_root / "pdfs"``
+ when that leaf resolves to a directory; containment then runs against
+ the directory the leaf resolves to. The leaf test reads the path as
+ ``validate_safe_path`` does (surrounding whitespace stripped, then
+ ``posixpath.normpath``), so ``pdfs//x.pdf``, `` pdfs/x.pdf`` and
+ ``pdfs/../pdfs/x.pdf`` count as ``pdfs/x.pdf``. On Windows a backslash
+ is first read as "/", because the store writes ``pdfs\\x.pdf`` there,
+ so the remainder returned with the pdfs base uses "/" only, the one
+ separator werkzeug's ``safe_join`` accepts on Windows. Every other
+ path, and any value that is not a string, is checked unchanged against
+ ``library_root`` itself. ``library_root`` must already be a ``Path``.
+ """
+ if isinstance(relative_path, str):
+ normalized = relative_path.strip()
+ if _STORED_PATH_MODULE.sep != "/":
+ normalized = normalized.replace(_STORED_PATH_MODULE.sep, "/")
+ normalized = posixpath.normpath(normalized)
+ first, sep, rest = normalized.partition("/")
+ if first == _TRUSTED_STORAGE_LEAF and sep and rest:
+ trusted = library_root / first
+ try:
+ resolved_trusted = resolve_allow_missing(trusted)
+ except OSError:
+ resolved_trusted = None
+ if resolved_trusted is not None and resolved_trusted.is_dir():
+ return trusted, rest
+ return library_root, relative_path
def _resolve_within_root(
relative_path: str, library_root: Path
) -> Optional[Path]:
"""Validate ``relative_path`` inside ``library_root`` (traversal + symlink
- safe). Returns the absolute path, or ``None`` if unsafe."""
+ safe). Returns the absolute path, or ``None`` if unsafe.
+
+ For a stored path whose FIRST segment is the sanctioned ``pdfs``
+ leaf (``_TRUSTED_STORAGE_LEAF``), containment is checked against
+ the RESOLVED pdfs target directory rather than the library root —
+ exactly as PDFStorageManager does on the write side. No other path
+ shape is loosened: symlink escapes anywhere else still fail closed,
+ and a second-level escape planted inside the resolved pdfs target
+ is caught by the same realpath containment. ``_containment_base``
+ decides which directory applies, and states the accepted spellings.
+ """
+ base, remainder = _containment_base(relative_path, Path(library_root))
try:
- safe_path = PathValidator.validate_safe_path(
- relative_path, str(library_root)
- )
- if safe_path is None:
- return None
+ # Use PathValidator to safely join and validate the path
+ safe_path = PathValidator.validate_safe_path(remainder, str(base))
result = Path(safe_path)
+ # Block symbolic links to prevent symlink-based escapes
if result.is_symlink():
logger.warning(f"Symlink blocked: {relative_path}")
return None
@@ -773,6 +827,49 @@ def get_absolute_path_from_settings(
return _resolve_within_root(relative_path, per_user_root)
+def get_containment_root_from_settings(
+ relative_path: str,
+ username: Optional[str] = None,
+ *,
+ settings_manager=None,
+) -> Optional[Path]:
+ """Return the resolved directory a stored library path is confined to.
+
+ This is the directory ``get_absolute_path_from_settings`` validates
+ ``relative_path`` against for the same ``username``: ``<root>/pdfs``
+ for a stored ``pdfs/...`` path when that leaf resolves to a directory
+ (including the sanctioned layout that symlinks it onto a larger disk),
+ and ``<root>`` itself for every other path, where ``<root>`` is what
+ ``get_absolute_path_from_settings("", username)`` returns. The bare
+ library root cannot serve as the unlink boundary: in the symlinked
+ layout every PDF's real location is on the other disk, so the re-check
+ would refuse the delete and leave the file orphaned there.
+
+ The directory is returned fully resolved, as it is at the time of the
+ call. Destructive callers call this BEFORE resolving the file, and pass
+ the result as the ``allowed_root`` of
+ ``CascadeHelper.delete_filesystem_file`` with
+ ``allowed_root_is_resolved=True``. The unlink re-check then compares
+ the file's real location with this pinned boundary instead of resolving
+ the boundary again. Otherwise a ``pdfs`` directory swapped for a symlink
+ between validation and delete would move the boundary along with the
+ file (the #5481 swap).
+
+ Returns None if the library root lookup returns None, or if the
+ directory cannot be resolved safely.
+ """
+ library_root = get_absolute_path_from_settings(
+ "", username, settings_manager=settings_manager
+ )
+ if library_root is None:
+ return None
+ base = _containment_base(relative_path, library_root)[0]
+ try:
+ return resolve_allow_missing(base)
+ except OSError:
+ return None
+
+
def handle_api_error(operation: str, error: Exception, status_code: int = 500):
"""
Handle API errors consistently - log internally, return generic message to user.
diff --git a/src/local_deep_research/security/directory_creation.py b/src/local_deep_research/security/directory_creation.py
index 1a493fb922..b7e05c1ce6 100644
--- a/src/local_deep_research/security/directory_creation.py
+++ b/src/local_deep_research/security/directory_creation.py
@@ -62,6 +62,9 @@ def create_directory(
DirectoryCreationSecurityError: If the path contains a null byte, a
raw ``..`` traversal segment, or (when ``root`` is given) resolves
outside ``root``.
+ OSError: If ``path`` or ``root`` cannot be fully resolved (a symlink
+ loop, a symlink chain whose resolved form outgrows PATH_MAX, an
+ unreadable component), or if the mkdir itself fails.
Example:
>>> create_directory(data_dir / "cache", context="rag cache")
@@ -84,17 +87,23 @@ def create_directory(
f"Refusing to create directory with '..' traversal segment: {path} ({context})"
)
- # resolve() follows symlinks, so a symlinked parent directory that
+ # Resolution follows symlinks, so a symlinked parent directory that
# escapes the root is caught here. It also works for paths that do not
- # yet exist.
- p = Path(path).resolve()
+ # yet exist. resolve_allow_missing() tolerates only missing components
+ # and raises OSError for anything else it cannot resolve (a loop, or a
+ # symlink chain whose resolved form outgrows PATH_MAX), where a bare
+ # non-strict resolve() would return a half-resolved path. Lazy import:
+ # this module is imported very early during bootstrap.
+ from .path_validator import resolve_allow_missing
+
+ p = resolve_allow_missing(Path(path))
if root is not None:
# Opt-in containment: require the target to resolve inside the given
- # root. resolve() above already followed symlinks, so a symlinked
- # parent that escapes the root is caught here too. (A path is
- # is_relative_to itself, so creating the root itself is allowed.)
- root_resolved = Path(root).resolve()
+ # root. The resolution above already followed symlinks, so a
+ # symlinked parent that escapes the root is caught here too. (A path
+ # is is_relative_to itself, so creating the root itself is allowed.)
+ root_resolved = resolve_allow_missing(Path(root))
if not p.is_relative_to(root_resolved):
raise DirectoryCreationSecurityError(
f"Refusing to create directory outside {root_resolved}: {p} ({context})"
diff --git a/src/local_deep_research/security/path_validator.py b/src/local_deep_research/security/path_validator.py
index 654877b891..b08e933312 100644
--- a/src/local_deep_research/security/path_validator.py
+++ b/src/local_deep_research/security/path_validator.py
@@ -5,7 +5,10 @@ This module provides secure path validation to prevent path traversal attacks
and other filesystem-based security vulnerabilities.
"""
+import errno
+import ntpath
import os
+import posixpath
import re
import unicodedata
from pathlib import Path
@@ -76,6 +79,74 @@ def _has_unicode_traversal(text: str) -> bool:
)
+# ``os.path.ALLOW_MISSING`` exists on Python 3.14 and was backported to
+# 3.12.11 and 3.13.4. Older patch releases use the fallback below. It is
+# read from the platform's path module, picked the way ``os`` picks
+# ``os.path``, because the check-pathlib-usage hook forbids ``os.path``
+# and the sentinel has no pathlib spelling.
+_PLATFORM_PATH_MODULE = ntpath if os.name == "nt" else posixpath
+_ALLOW_MISSING = getattr(_PLATFORM_PATH_MODULE, "ALLOW_MISSING", None)
+
+
+def resolve_allow_missing(path: Union[str, Path]) -> Path:
+ """Resolve every symlink in ``path``. Only a missing tail is tolerated.
+
+ Use this, never a bare ``Path.resolve()``, wherever a resolved path is
+ compared against a containment boundary. Non-strict ``resolve()``
+ ignores every ``OSError`` that ``lstat`` raises, not only "does not
+ exist". A short in-base symlink to a deep in-base directory chain makes
+ the resolved prefix longer than PATH_MAX, so every later ``lstat`` fails
+ with ENAMETOOLONG. The remaining components, including a symlink that
+ leaves the base, are then appended without being resolved. The result
+ looks contained, but the kernel resolves the short path without that
+ limit and follows the link out (the CVE-2025-4517 class).
+
+ Here a component that does not exist is appended as written, so a leaf
+ that has not been created yet still resolves. Any other failure raises
+ ``OSError``: ENAMETOOLONG, ELOOP (a symlink loop), EACCES, and ENOTDIR
+ (a path that continues below a regular file). Python 3.12 reports a
+ loop as ``RuntimeError``, which is re-raised as ``OSError(ELOOP)``.
+
+ Without ``os.path.ALLOW_MISSING`` the longest prefix whose last entry
+ exists is resolved strictly and the missing tail is appended. A dangling
+ symlink, or a ``..`` in the missing tail, raises there as well. Both
+ are refusals that the ``ALLOW_MISSING`` path would not make, so the
+ fallback is only ever stricter.
+ """
+ if isinstance(path, str):
+ path = Path(path)
+ try:
+ if _ALLOW_MISSING is not None:
+ return path.resolve(strict=_ALLOW_MISSING)
+ return _resolve_allow_missing_fallback(path)
+ except RuntimeError as exc:
+ raise OSError(errno.ELOOP, "Symlink loop", str(path)) from exc
+
+
+def _resolve_allow_missing_fallback(path: Path) -> Path:
+ """``resolve_allow_missing`` for a Python without ``ALLOW_MISSING``."""
+ path = path.absolute()
+ missing: list[str] = []
+ head = path
+ while True:
+ try:
+ # lstat, not exists(): only ENOENT means "missing". Every
+ # other error (ENAMETOOLONG, ENOTDIR, EACCES) propagates.
+ os.lstat(head)
+ break
+ except FileNotFoundError:
+ if head.parent == head:
+ raise
+ missing.append(head.name)
+ head = head.parent
+ if ".." in missing:
+ # ".." below a missing component cannot be resolved against the
+ # filesystem, and is_relative_to() would compare it lexically.
+ raise OSError(errno.ENOENT, "Unresolvable '..' segment", str(path))
+ # strict=True raises for a dangling symlink, a loop and ENAMETOOLONG.
+ return head.resolve(strict=True).joinpath(*reversed(missing))
+
+
class PathValidator:
"""Centralized path validation for security."""
@@ -102,7 +173,7 @@ class PathValidator:
required_extensions: Tuple of required file extensions (e.g., ('.json', '.yaml'))
Returns:
- Path object if valid, None if invalid
+ The validated Path. It is never None: every rejection raises.
Raises:
ValueError: If the path is invalid or unsafe
@@ -146,8 +217,16 @@ class PathValidator:
)
# Use werkzeug's safe_join for secure path joining
- # This handles path traversal attempts automatically
- base_dir = Path(base_dir).resolve()
+ # This handles path traversal attempts automatically. The base is
+ # resolved the same way as the joined path below, so the
+ # containment comparison is between two fully resolved paths.
+ try:
+ base_dir = resolve_allow_missing(Path(base_dir))
+ except OSError:
+ logger.warning("Path validation base directory is unresolvable")
+ raise ValueError(
+ "Invalid base directory - could not be resolved safely"
+ )
try:
# safe_join returns None if the path tries to escape base_dir
@@ -168,6 +247,45 @@ class PathValidator:
result_path = Path(safe_path)
+ # Filesystem-level containment (GHSA-gv87-qcw7-gjr8). safe_join is
+ # a *string* operation: it rejects ``..`` and absolute inputs but
+ # never touches the filesystem, so a symlinked directory or leaf
+ # inside base_dir that points outside it is joined and returned
+ # verbatim — the caller then reads through the link, outside the
+ # base. Resolve the joined path and require its real location to
+ # stay under the (already resolved) base. This is deliberately
+ # NOT #3090's removed check: that one rejected *every* symlink
+ # and broke legitimate layouts (bind mounts, macOS
+ # /tmp -> /private/tmp); containment accepts any symlink whose
+ # target resolves within base_dir and refuses only the escapes.
+ # resolve_allow_missing() tolerates only a missing component, so
+ # a not-yet-existing leaf is fine. Every other resolution error
+ # raises and fails closed here: a symlink loop (ELOOP), a path
+ # below a regular file (ENOTDIR), and ENAMETOOLONG. A bare
+ # non-strict resolve() ignores ENAMETOOLONG (and, on 3.13+, a
+ # loop) and appends the rest of the path unresolved, so a symlink
+ # chain whose resolved form outgrows PATH_MAX could hide an escape.
+ try:
+ resolved_path = resolve_allow_missing(result_path)
+ except OSError:
+ logger.warning(
+ f"Path resolution failed for input {redact_and_bound_for_log(user_input, 200)!r}"
+ )
+ raise ValueError("Invalid path - could not be resolved safely")
+ if not resolved_path.is_relative_to(base_dir):
+ logger.warning(
+ f"Symlink containment violation blocked: {redact_and_bound_for_log(user_input, 200)!r}"
+ )
+ raise ValueError(
+ "Invalid path - resolved path escapes base directory"
+ )
+ # Return the *lexical* (pre-resolve) path, not the resolved one:
+ # the containment check has already run, and callers key external
+ # behaviour off the requested name (e.g. FileResponse guesses the
+ # content type from the served filename, and the storage manager
+ # stores paths relative to the library root it passed in). Callers
+ # that need the real location resolve it themselves.
+
# Check extensions if required
if (
required_extensions
diff --git a/src/local_deep_research/storage/file.py b/src/local_deep_research/storage/file.py
index b8ce6bcd0d..53cba66221 100644
--- a/src/local_deep_research/storage/file.py
+++ b/src/local_deep_research/storage/file.py
@@ -44,23 +44,36 @@ class FileReportStorage(ReportStorage):
# private, before any new write.
restrict_directory_to_owner(self.base_dir)
- def _get_report_path(self, research_id: str) -> Path:
- """Get the file path for a report."""
- candidate = (self.base_dir / f"{research_id}.md").resolve()
- if not candidate.is_relative_to(self.base_dir.resolve()):
+ def _contained_path(self, research_id: str, filename: str) -> Path:
+ """Return ``base_dir / filename`` resolved, or raise ValueError.
+
+ Both sides are resolved with resolve_allow_missing(), never a bare
+ non-strict resolve(), which can leave part of the path unresolved
+ (a symlink chain whose resolved form outgrows PATH_MAX) and so hide
+ an escape.
+ """
+ from ..security.path_validator import resolve_allow_missing
+
+ try:
+ candidate = resolve_allow_missing(self.base_dir / filename)
+ base = resolve_allow_missing(self.base_dir)
+ except OSError:
+ raise ValueError(
+ f"Unresolvable report path for research_id: {research_id!r}"
+ )
+ if not candidate.is_relative_to(base):
raise ValueError(
f"Path traversal attempt with research_id: {research_id!r}"
)
return candidate
+ def _get_report_path(self, research_id: str) -> Path:
+ """Get the file path for a report."""
+ return self._contained_path(research_id, f"{research_id}.md")
+
def _get_metadata_path(self, research_id: str) -> Path:
"""Get the file path for report metadata."""
- candidate = (self.base_dir / f"{research_id}_metadata.json").resolve()
- if not candidate.is_relative_to(self.base_dir.resolve()):
- raise ValueError(
- f"Path traversal attempt with research_id: {research_id!r}"
- )
- return candidate
+ return self._contained_path(research_id, f"{research_id}_metadata.json")
def save_report(
self,
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 80af450fd1..cac4627f09 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -1820,10 +1820,13 @@ def _unlink_report_file_if_inside_root(report_path: Optional[str]) -> bool:
path refuses symlinks for the same reason.
* Containment is decided on the resolved location, which also catches an
escape through a symlinked *ancestor* directory -- one already swapped in
- before the check. An ancestor swapped in between the resolve() and the
- unlink() can still redirect the unlink, since the unlink re-traverses the
- path; that residual race needs local write access to the reports tree
- mid-request and is outside this guard's threat model.
+ before the check. Both sides are resolved with resolve_allow_missing(),
+ so a path that cannot be fully resolved (a symlink chain whose resolved
+ form outgrows PATH_MAX, a loop) is refused rather than compared
+ half-resolved. An ancestor swapped in between the resolve and the
+ unlink() can still redirect the unlink, since the unlink re-traverses
+ the path; that residual race needs local write access to the reports
+ tree mid-request and is outside this guard's threat model.
* The unlink targets the path as given -- never a resolved copy -- and
tolerates a missing file, so there is no separate
exists()-before-unlink() window.
@@ -1836,8 +1839,9 @@ def _unlink_report_file_if_inside_root(report_path: Optional[str]) -> bool:
return False
try:
from ...config.paths import get_research_outputs_directory
+ from ...security.path_validator import resolve_allow_missing
- reports_root = get_research_outputs_directory().resolve()
+ reports_root = resolve_allow_missing(get_research_outputs_directory())
path = Path(report_path)
if path.is_symlink():
@@ -1847,7 +1851,11 @@ def _unlink_report_file_if_inside_root(report_path: Optional[str]) -> bool:
)
return False
- if not path.resolve().is_relative_to(reports_root):
+ try:
+ contained = resolve_allow_missing(path).is_relative_to(reports_root)
+ except OSError:
+ contained = False
+ if not contained:
logger.warning(
"Refusing to unlink a report path outside the reports root"
)
diff --git a/src/local_deep_research/web/utils/vite_helper.py b/src/local_deep_research/web/utils/vite_helper.py
index 54237918c7..ba73935d4b 100644
--- a/src/local_deep_research/web/utils/vite_helper.py
+++ b/src/local_deep_research/web/utils/vite_helper.py
@@ -623,11 +623,16 @@ class ViteHelper:
return False
if PureWindowsPath(relative_path).drive:
return False
+ from ...security.path_validator import resolve_allow_missing
+
try:
# URL paths use UTF-8; a filesystem surrogate cannot be served
# through that encoding even if this host can store its bytes.
relative_path.encode("utf-8")
- target = (dist_root / relative_path).resolve()
+ # resolve_allow_missing(), not a bare resolve(): an unresolvable
+ # path (a loop, a symlink chain whose resolved form outgrows
+ # PATH_MAX) raises instead of coming back half resolved.
+ target = resolve_allow_missing(dist_root / relative_path)
return target.is_relative_to(dist_root) and target.is_file()
except (OSError, ValueError):
return False
@@ -681,8 +686,12 @@ class ViteHelper:
manifest = state.manifest
dist_root = None
if self._manifest_path is not None:
+ from ...security.path_validator import resolve_allow_missing
+
try:
- dist_root = self._manifest_path.parent.parent.resolve()
+ dist_root = resolve_allow_missing(
+ self._manifest_path.parent.parent
+ )
except OSError:
return "the dist/ directory could not be resolved"
diff --git a/tests/database/backup/test_backup_service.py b/tests/database/backup/test_backup_service.py
index 7e9dd894da..d45527dac9 100644
--- a/tests/database/backup/test_backup_service.py
+++ b/tests/database/backup/test_backup_service.py
@@ -6114,6 +6114,25 @@ class TestIsSafeGlobResult:
assert not via_link.is_symlink()
assert is_safe_glob_result(via_link, symlinked_base) is True
+ def test_rejects_an_escape_behind_a_path_max_symlink_chain(self, tmp_path):
+ """Non-strict resolution stops following symlinks once the resolved
+ prefix outgrows PATH_MAX, so this path looked inside base_dir."""
+ from local_deep_research.database.backup.backup_service import (
+ is_safe_glob_result,
+ )
+ from tests.security.path_max_fixtures import build_path_max_escape
+
+ base_dir = tmp_path / "backups"
+ base_dir.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "ldr_backup_20250101_120000.db").write_bytes(b"secret")
+ link = build_path_max_escape(base_dir, outside)
+
+ escaping = base_dir / link / "ldr_backup_20250101_120000.db"
+ assert not escaping.is_symlink()
+ assert is_safe_glob_result(escaping, base_dir) is False
+
class TestGlobHardeningIntegration:
"""End-to-end checks that the glob hardening is wired into the service."""
diff --git a/tests/research_library/deletion/services/test_document_deletion.py b/tests/research_library/deletion/services/test_document_deletion.py
index c6d2ea92f8..449be2751a 100644
--- a/tests/research_library/deletion/services/test_document_deletion.py
+++ b/tests/research_library/deletion/services/test_document_deletion.py
@@ -1,9 +1,12 @@
"""Tests for DocumentDeletionService."""
+import shutil
import threading
from concurrent.futures import ThreadPoolExecutor
+from types import SimpleNamespace
from unittest.mock import MagicMock, Mock, patch
+import pytest
from local_deep_research.database.models.library import (
Document,
@@ -13,6 +16,10 @@ from local_deep_research.database.models.library import (
from local_deep_research.research_library.deletion.services.document_deletion import (
DocumentDeletionService,
)
+from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+)
+from tests.security.path_max_fixtures import build_path_max_escape
class TestDocumentDeletionServiceInit:
@@ -602,3 +609,215 @@ class TestDocumentDeletionServiceNoteRefusal:
# No chunks deleted and no actual unlink performed.
mock_helper.delete_document_chunks.assert_not_called()
unlink_session.delete.assert_not_called()
+
+
+_DELETION_MODULE = (
+ "local_deep_research.research_library.deletion.services.document_deletion"
+)
+_FLOWS = ["delete_document", "delete_blob_only", "remove_from_collection"]
+
+
+class TestSanctionedPdfsLayoutDeletion:
+ """Deleting a document stored in the sanctioned pdfs layout removes its
+ file from the larger disk.
+
+ In that layout ``<user root>/pdfs`` is a symlink onto another disk. The
+ resolver confines a stored ``pdfs/<name>`` path to the directory that
+ link resolves to, and each DocumentDeletionService unlink re-checks the
+ resolved file against get_containment_root_from_settings. With the bare
+ library root as that boundary the re-check refused every such file: the
+ row went away and the PDF stayed on the big disk.
+
+ The database is a mock. Path resolution, the boundary and
+ CascadeHelper.delete_filesystem_file run for real against files on disk.
+ """
+
+ @staticmethod
+ def _symlinked_layout(tmp_path):
+ library_root = tmp_path / "library"
+ user_root = library_root / "alice"
+ user_root.mkdir(parents=True)
+ big_disk = tmp_path / "big_disk_pdfs"
+ big_disk.mkdir()
+ try:
+ (user_root / "pdfs").symlink_to(big_disk, target_is_directory=True)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create directory symlinks in this environment")
+ return library_root, big_disk
+
+ @staticmethod
+ def _run(flow, library_root, stored_path):
+ service = DocumentDeletionService(username="alice")
+ document = SimpleNamespace(
+ id="doc-12345678",
+ title="Stored PDF",
+ filename="5.pdf",
+ storage_mode="filesystem",
+ file_path=stored_path,
+ source_type_id="research-source",
+ )
+ collection = SimpleNamespace(
+ id="col-12345678", collection_type="default"
+ )
+ session = MagicMock()
+ session.get.side_effect = lambda model, _id: (
+ document if model is Document else collection
+ )
+ session_cm = MagicMock()
+ session_cm.__enter__ = Mock(return_value=session)
+ session_cm.__exit__ = Mock(return_value=None)
+ settings = Mock()
+ settings.get_setting.side_effect = lambda key, default=None: (
+ str(library_root)
+ if key == "research_library.storage_path"
+ else default
+ )
+ with (
+ patch(
+ f"{_DELETION_MODULE}.get_user_db_session",
+ return_value=session_cm,
+ ),
+ patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=settings,
+ ),
+ patch.object(
+ CascadeHelper, "get_document_collections", return_value=[]
+ ),
+ patch.object(
+ CascadeHelper, "get_document_blob_size", return_value=0
+ ),
+ patch.object(CascadeHelper, "update_download_tracker"),
+ patch.object(
+ CascadeHelper, "count_document_in_collections", return_value=0
+ ),
+ patch.object(
+ CascadeHelper, "delete_document_completely", return_value=True
+ ),
+ patch.object(service, "_purge_document_rag"),
+ ):
+ if flow == "delete_document":
+ return service.delete_document(document.id)
+ if flow == "delete_blob_only":
+ return service.delete_blob_only(document.id)
+ return service.remove_from_collection(document.id, collection.id)
+
+ @pytest.mark.parametrize("flow", _FLOWS)
+ def test_the_pdf_on_the_larger_disk_is_deleted(self, tmp_path, flow):
+ library_root, big_disk = self._symlinked_layout(tmp_path)
+ stored = big_disk / "5.pdf"
+ stored.write_bytes(b"%PDF-1.4 sanctioned layout")
+
+ result = self._run(flow, library_root, "pdfs/5.pdf")
+
+ assert not stored.exists(), "the PDF was left on the larger disk"
+ if flow == "delete_document":
+ assert result["deleted"] is True
+ assert result["file_deleted"] is True
+ elif flow == "delete_blob_only":
+ assert result["deleted"] is True
+ assert result["bytes_freed"] == len(b"%PDF-1.4 sanctioned layout")
+ else:
+ assert result["unlinked"] is True
+ assert result["document_deleted"] is True
+
+ @pytest.mark.parametrize("flow", _FLOWS)
+ def test_a_leaf_symlink_out_of_the_larger_disk_is_not_followed(
+ self, tmp_path, flow
+ ):
+ """A leaf symlink on the larger disk that points out is never
+ followed. The resolver refuses it before any unlink is attempted,
+ and delete_filesystem_file refuses a leaf symlink on its own too.
+ This does not exercise the unlink boundary itself; that is
+ test_a_pdfs_directory_swapped_after_validation_is_refused."""
+ library_root, big_disk = self._symlinked_layout(tmp_path)
+ outside = tmp_path / "outside.pdf"
+ outside.write_bytes(b"ORIGINAL")
+ try:
+ (big_disk / "5.pdf").symlink_to(outside)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ self._run(flow, library_root, "pdfs/5.pdf")
+
+ assert (big_disk / "5.pdf").is_symlink()
+ assert outside.read_bytes() == b"ORIGINAL"
+
+ @pytest.mark.parametrize("flow", _FLOWS)
+ def test_a_pdfs_directory_swapped_after_validation_is_refused(
+ self, tmp_path, flow
+ ):
+ """The unlink boundary is pinned before the file is validated.
+
+ The file resolves in a plain layout, then ``pdfs`` is swapped for a
+ symlink to a directory holding a file of the same name. Resolving
+ the boundary again at unlink time would follow the swap together
+ with the file and delete that file (#5481). The pinned boundary
+ refuses it.
+ """
+ from local_deep_research.research_library import utils
+
+ library_root = tmp_path / "library"
+ pdfs = library_root / "alice" / "pdfs"
+ pdfs.mkdir(parents=True)
+ (pdfs / "5.pdf").write_bytes(b"%PDF-1.4 own file")
+ victim_dir = tmp_path / "victim"
+ victim_dir.mkdir()
+ victim = victim_dir / "5.pdf"
+ victim.write_bytes(b"do not delete me")
+ try:
+ (tmp_path / "probe").symlink_to(
+ victim_dir, target_is_directory=True
+ )
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create directory symlinks in this environment")
+
+ real_resolve = utils.get_absolute_path_from_settings
+
+ def resolve_then_swap(relative_path, *args, **kwargs):
+ resolved = real_resolve(relative_path, *args, **kwargs)
+ if relative_path == "pdfs/5.pdf":
+ shutil.rmtree(pdfs)
+ pdfs.symlink_to(victim_dir, target_is_directory=True)
+ return resolved
+
+ with patch.object(
+ utils, "get_absolute_path_from_settings", resolve_then_swap
+ ):
+ self._run(flow, library_root, "pdfs/5.pdf")
+
+ assert pdfs.is_symlink(), "the swap did not happen"
+ assert victim.read_bytes() == b"do not delete me"
+
+ @pytest.mark.parametrize("flow", _FLOWS)
+ def test_an_escape_behind_a_path_max_symlink_chain_is_not_deleted(
+ self, tmp_path, flow
+ ):
+ """Non-strict resolution hid this escape from both the resolver
+ and the unlink re-check, and the file outside was deleted."""
+ library_root = tmp_path / "library"
+ user_root = library_root / "alice"
+ user_root.mkdir(parents=True)
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ victim = outside / "victim.pdf"
+ victim.write_bytes(b"do not delete me")
+ link = build_path_max_escape(user_root, outside)
+
+ self._run(flow, library_root, f"{link}/victim.pdf")
+
+ assert victim.read_bytes() == b"do not delete me"
+
+ @pytest.mark.parametrize("stored_path", ["pdfs/5.pdf", "notes/5.pdf"])
+ def test_files_in_a_plain_user_root_are_still_deleted(
+ self, tmp_path, stored_path
+ ):
+ library_root = tmp_path / "library"
+ target = library_root / "alice" / stored_path
+ target.parent.mkdir(parents=True)
+ target.write_bytes(b"%PDF-1.4 plain layout")
+
+ result = self._run("delete_document", library_root, stored_path)
+
+ assert result["file_deleted"] is True
+ assert not target.exists()
diff --git a/tests/research_library/deletion/utils/test_cascade_helper.py b/tests/research_library/deletion/utils/test_cascade_helper.py
index a1ecd7d7d8..e3fddca7e0 100644
--- a/tests/research_library/deletion/utils/test_cascade_helper.py
+++ b/tests/research_library/deletion/utils/test_cascade_helper.py
@@ -1,7 +1,9 @@
"""Tests for CascadeHelper utility."""
+import shutil
from unittest.mock import MagicMock, patch
+import pytest
from local_deep_research.constants import (
FILE_PATH_SENTINELS,
@@ -9,6 +11,7 @@ from local_deep_research.constants import (
from local_deep_research.research_library.deletion.utils.cascade_helper import (
CascadeHelper,
)
+from tests.security.path_max_fixtures import build_path_max_escape
class TestCascadeHelperDeleteDocumentChunks:
@@ -200,6 +203,54 @@ class TestCascadeHelperDeleteFilesystemFileSymlinkGuard:
assert result is False
assert secret.exists()
+ def test_refuses_an_escape_behind_a_path_max_symlink_chain(self, tmp_path):
+ """Non-strict resolution stops following symlinks once the resolved
+ prefix outgrows PATH_MAX, so the re-check saw a path inside
+ allowed_root while the unlink reached the file outside it."""
+ library_root = tmp_path / "library"
+ library_root.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ victim = outside / "victim.pdf"
+ victim.write_bytes(b"do not delete me")
+ link = build_path_max_escape(library_root, outside)
+
+ result = CascadeHelper.delete_filesystem_file(
+ str(library_root / link / "victim.pdf"), allowed_root=library_root
+ )
+
+ assert result is False
+ assert victim.exists()
+
+ def test_a_resolved_allowed_root_is_not_resolved_again(self, tmp_path):
+ """With allowed_root_is_resolved=True the boundary is compared as
+ given: a boundary directory swapped for a symlink after it was
+ resolved cannot move the boundary along with the file (#5481)."""
+ library_root = tmp_path / "library"
+ pdfs = library_root / "pdfs"
+ pdfs.mkdir(parents=True)
+ (pdfs / "5.pdf").write_bytes(b"own file")
+ victim_dir = tmp_path / "victim"
+ victim_dir.mkdir()
+ victim = victim_dir / "5.pdf"
+ victim.write_bytes(b"do not delete me")
+ pinned = pdfs.resolve()
+
+ shutil.rmtree(pdfs)
+ try:
+ pdfs.symlink_to(victim_dir, target_is_directory=True)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create directory symlinks in this environment")
+
+ result = CascadeHelper.delete_filesystem_file(
+ str(pdfs / "5.pdf"),
+ allowed_root=pinned,
+ allowed_root_is_resolved=True,
+ )
+
+ assert result is False
+ assert victim.read_bytes() == b"do not delete me"
+
def test_allows_legitimate_delete_within_allowed_root(self, tmp_path):
"""A real file directly under allowed_root is still deletable."""
library_root = tmp_path / "library"
@@ -293,6 +344,23 @@ class TestCascadeHelperDeleteFaissIndexFiles:
assert result is False
assert secret_faiss.exists()
+ def test_refuses_an_escape_behind_a_path_max_symlink_chain(self, tmp_path):
+ """Same PATH_MAX chain as the filesystem-file case, for an index."""
+ rag_root = tmp_path / "rag_indices"
+ rag_root.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ secret_faiss = outside / "index.faiss"
+ secret_faiss.write_bytes(b"do not delete me")
+ link = build_path_max_escape(rag_root, outside)
+
+ result = CascadeHelper.delete_faiss_index_files(
+ str(rag_root / link / "index"), allowed_root=rag_root
+ )
+
+ assert result is False
+ assert secret_faiss.exists()
+
def test_refuses_to_delete_symlinked_faiss_file(self, tmp_path):
"""A symlinked .faiss file itself must not be unlinked/followed."""
outside = tmp_path / "outside"
diff --git a/tests/research_library/services/test_pdf_storage_manager.py b/tests/research_library/services/test_pdf_storage_manager.py
index 9dfdbc072d..ceca01550e 100644
--- a/tests/research_library/services/test_pdf_storage_manager.py
+++ b/tests/research_library/services/test_pdf_storage_manager.py
@@ -612,6 +612,137 @@ class TestPDFStorageManagerFilesystemWrite:
# newly created under library_root.
assert big_disk_pdfs in result_path.resolve().parents
+ def test_resolves_stored_path_from_symlinked_pdfs_directory(
+ self, tmp_path, mock_pdf_content
+ ):
+ """Should resolve a stored ``pdfs/<name>`` path when
+ ``<library_root>/pdfs`` is a symlink.
+
+ Load-side parity with test_saves_to_symlinked_pdfs_directory:
+ the trusted-leaf carve-out now lives in the shared
+ ``research_library.utils._resolve_within_root`` implementation
+ that ``_safe_path_in_root`` delegates to, so a PDF saved into
+ the sanctioned layout must also resolve back (not return None)
+ through the storage manager.
+ """
+ library_root = tmp_path / "library"
+ library_root.mkdir()
+ big_disk_pdfs = tmp_path / "big_disk_pdfs"
+ big_disk_pdfs.mkdir()
+ try:
+ (library_root / "pdfs").symlink_to(
+ big_disk_pdfs, target_is_directory=True
+ )
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create directory symlinks in this environment")
+ stored = big_disk_pdfs / "symlinked_test.pdf"
+ stored.write_bytes(mock_pdf_content)
+
+ manager = PDFStorageManager(library_root, "filesystem")
+
+ result_path = manager._get_safe_file_path("pdfs/symlinked_test.pdf")
+
+ assert result_path is not None
+ assert result_path.is_file()
+ assert result_path == stored.resolve()
+ assert result_path.read_bytes() == mock_pdf_content
+
+ def test_refuses_outside_pdf_leaf_without_nofollow(
+ self, tmp_path, monkeypatch, mock_pdf_content
+ ):
+ """Realpath validation protects writes when O_NOFOLLOW is unavailable."""
+ from local_deep_research.security import file_write_verifier
+
+ library_root = tmp_path / "library"
+ pdf_dir = library_root / "pdfs"
+ pdf_dir.mkdir(parents=True)
+ outside_pdf = tmp_path / "outside.pdf"
+ outside_pdf.write_bytes(b"ORIGINAL")
+ content_hash = hashlib.sha256(mock_pdf_content).hexdigest()
+ symlink = pdf_dir / f"evil_{content_hash}.pdf"
+ try:
+ symlink.symlink_to(outside_pdf)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ # Simulate platforms where the verified writer cannot use O_NOFOLLOW.
+ # The filesystem-level path check must still reject the planted leaf.
+ monkeypatch.setattr(file_write_verifier, "_O_NOFOLLOW", 0)
+ manager = PDFStorageManager(library_root, "filesystem")
+
+ with pytest.raises(ValueError, match="escapes base directory"):
+ manager._save_to_filesystem(mock_pdf_content, "evil.pdf")
+
+ assert symlink.is_symlink()
+ assert outside_pdf.read_bytes() == b"ORIGINAL"
+
+ def test_save_pdf_round_trips_through_symlinked_pdfs_layout(
+ self, tmp_path, mock_pdf_content
+ ):
+ """save_pdf stores ``pdfs/<name>`` relative to the library root
+ when ``<library_root>/pdfs`` is a symlink onto a larger disk, and
+ load_pdf reads the bytes back through that stored path.
+
+ validate_safe_path returns the name joined onto the RESOLVED pdfs
+ directory; _save_to_filesystem re-expresses it on the lexical
+ ``pdfs`` path. Without that step save_pdf's
+ ``relative_to(self.library_root)`` raises in this layout.
+ """
+ library_root = tmp_path / "library"
+ library_root.mkdir()
+ big_disk_pdfs = tmp_path / "big_disk_pdfs"
+ big_disk_pdfs.mkdir()
+ try:
+ (library_root / "pdfs").symlink_to(
+ big_disk_pdfs, target_is_directory=True
+ )
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create directory symlinks in this environment")
+ manager = PDFStorageManager(library_root, "filesystem")
+ document = MagicMock()
+ document.id = "doc-123"
+ document.file_type = "pdf"
+ session = MagicMock()
+ # No blob, so load_pdf has to read the file.
+ session.query.return_value.filter_by.return_value.first.return_value = (
+ None
+ )
+
+ stored_path, size = manager.save_pdf(
+ mock_pdf_content, document, session, "paper.pdf"
+ )
+
+ name = f"paper_{hashlib.sha256(mock_pdf_content).hexdigest()}.pdf"
+ assert stored_path == f"pdfs/{name}"
+ assert size == len(mock_pdf_content)
+ assert document.file_path == stored_path
+ assert document.storage_mode == "filesystem"
+ # The bytes landed on the larger disk, not in a new library dir.
+ assert (big_disk_pdfs / name).read_bytes() == mock_pdf_content
+ assert manager.load_pdf(document, session) == mock_pdf_content
+
+ def test_save_pdf_keeps_an_absolute_looking_name_inside_the_store(
+ self, tmp_path, mock_pdf_content
+ ):
+ """An absolute-looking filename is stored under ``pdfs/``, as the
+ old ``"pdfs/" + filename`` join stored it, instead of being
+ rejected: _save_to_filesystem strips the leading slash before
+ validating the name against the pdfs directory."""
+ manager = PDFStorageManager(tmp_path, "filesystem")
+ document = MagicMock()
+ session = MagicMock()
+
+ stored_path, _ = manager.save_pdf(
+ mock_pdf_content, document, session, "/evil.pdf"
+ )
+
+ name = f"evil_{hashlib.sha256(mock_pdf_content).hexdigest()}.pdf"
+ assert stored_path == f"pdfs/{name}"
+ assert (tmp_path / "pdfs" / name).read_bytes() == mock_pdf_content
+ # Nothing was written anywhere else.
+ assert [p.name for p in tmp_path.iterdir()] == ["pdfs"]
+ assert [p.name for p in (tmp_path / "pdfs").iterdir()] == [name]
+
class TestPDFStorageManagerGenerateFilename:
"""Tests for _generate_filename method."""
diff --git a/tests/research_library/test_utils.py b/tests/research_library/test_utils.py
index 381563afde..083b1e857d 100644
--- a/tests/research_library/test_utils.py
+++ b/tests/research_library/test_utils.py
@@ -7,6 +7,8 @@ Tests path traversal protection and utility functions.
from pathlib import Path
from unittest.mock import patch, Mock
+import pytest
+
from local_deep_research.constants import (
FILE_PATH_METADATA_ONLY,
FILE_PATH_TEXT_ONLY,
@@ -1046,3 +1048,518 @@ class TestCascadeHelperPathSafety:
assert result is True
assert not test_file.exists()
+
+
+def _symlinked_pdfs_library(tmp_path, username=None):
+ """Create the sanctioned "<library_root>/pdfs onto a bigger disk" layout.
+
+ Returns ``(library_root, big_disk_pdfs)`` with the ``pdfs`` symlink
+ under the optional per-user directory, mirroring the layout
+ pinned on the save side by
+ ``test_saves_to_symlinked_pdfs_directory``. Skips the test when the
+ environment cannot create directory symlinks.
+ """
+ library_root = tmp_path / "library"
+ library_root.mkdir()
+ user_root = library_root / username if username else library_root
+ user_root.mkdir(exist_ok=True)
+ big_disk_pdfs = tmp_path / "big_disk_pdfs"
+ big_disk_pdfs.mkdir()
+ try:
+ (user_root / "pdfs").symlink_to(big_disk_pdfs, target_is_directory=True)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create directory symlinks in this environment")
+ return library_root, big_disk_pdfs
+
+
+class TestTrustedPdfsSymlinkLayout:
+ """The sanctioned pdfs-symlink layout must keep resolving via utils.
+
+ The GHSA-gv87-qcw7-gjr8 realpath containment in validate_safe_path
+ refuses a stored ``pdfs/<name>`` path whose ``<root>/pdfs`` is a
+ symlink out of the root — the trusted-leaf carve-out must therefore
+ apply to the settings/utils resolution path (deletion, download
+ dedupe, text extraction, open-location, integrity sweep), not only
+ to PDFStorageManager on the write side.
+ """
+
+ def test_get_absolute_library_path_resolves_stored_pdfs_path(
+ self, tmp_path
+ ):
+ """A stored "pdfs/<name>" path resolves (not None) through
+ get_absolute_library_path, against the RESOLVED pdfs target."""
+ from local_deep_research.research_library.utils import (
+ get_absolute_library_path,
+ )
+
+ library_root, big_disk_pdfs = _symlinked_pdfs_library(tmp_path)
+ stored = big_disk_pdfs / "stored.pdf"
+ stored.write_bytes(b"%PDF-1.4 fake")
+
+ with patch(
+ "local_deep_research.research_library.utils.get_library_storage_path"
+ ) as mock_storage:
+ mock_storage.return_value = library_root
+
+ result = get_absolute_library_path("pdfs/stored.pdf", "testuser")
+
+ assert result is not None
+ assert result.is_file()
+ # Containment ran against the resolved pdfs directory, so the
+ # returned path is the real location on the bigger disk.
+ assert result == stored.resolve()
+
+ def test_get_absolute_path_from_settings_resolves_stored_pdfs_path(
+ self, tmp_path
+ ):
+ """A stored "pdfs/<name>" path resolves (not None) through
+ get_absolute_path_from_settings (download dedupe, text
+ extraction, integrity sweep all resolve through here)."""
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ )
+
+ library_root, big_disk_pdfs = _symlinked_pdfs_library(
+ tmp_path, username="alice"
+ )
+ stored = big_disk_pdfs / "stored.pdf"
+ stored.write_bytes(b"%PDF-1.4 fake")
+
+ mock_settings = Mock()
+ mock_settings.get_setting.side_effect = lambda key, default=None: (
+ str(library_root)
+ if key == "research_library.storage_path"
+ else default
+ )
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=mock_settings,
+ ):
+ result = get_absolute_path_from_settings("pdfs/stored.pdf", "alice")
+
+ assert result is not None
+ assert result.is_file()
+ assert result == stored.resolve()
+
+ def test_utils_resolved_deletion_path_unlinks_real_file(self, tmp_path):
+ """The utils-resolved path names the REAL file on the bigger disk.
+
+ Resolver half only. LibraryService.delete_document unlinks the
+ path get_absolute_path_from_settings returns; without the
+ trusted-leaf carve-out the realpath containment makes that
+ resolution return None, so the unlink is skipped and the PDF is
+ left on the big disk. DocumentDeletionService additionally
+ re-checks its unlink against get_containment_root_from_settings;
+ that flow is pinned end to end by TestSanctionedPdfsLayoutDeletion
+ in tests/research_library/deletion/services/test_document_deletion.py.
+ """
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ )
+
+ library_root, big_disk_pdfs = _symlinked_pdfs_library(
+ tmp_path, username="alice"
+ )
+ stored = big_disk_pdfs / "5.pdf"
+ stored.write_bytes(b"%PDF-1.4 fake")
+
+ mock_settings = Mock()
+ mock_settings.get_setting.side_effect = lambda key, default=None: (
+ str(library_root)
+ if key == "research_library.storage_path"
+ else default
+ )
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=mock_settings,
+ ):
+ file_path = get_absolute_path_from_settings("pdfs/5.pdf", "alice")
+
+ assert file_path is not None
+ assert file_path.is_file()
+ file_path.unlink()
+ assert not stored.exists()
+
+ def test_escape_symlink_outside_trusted_leaf_still_blocked(self, tmp_path):
+ """A symlink NOT under the trusted pdfs leaf still fails closed."""
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ )
+
+ library_root, _ = _symlinked_pdfs_library(tmp_path, username="alice")
+ try:
+ (library_root / "alice" / "evil").symlink_to("/etc")
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ mock_settings = Mock()
+ mock_settings.get_setting.side_effect = lambda key, default=None: (
+ str(library_root)
+ if key == "research_library.storage_path"
+ else default
+ )
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=mock_settings,
+ ):
+ result = get_absolute_path_from_settings("evil/passwd", "alice")
+
+ assert result is None
+
+ def test_second_level_escape_inside_resolved_pdfs_still_blocked(
+ self, tmp_path
+ ):
+ """A symlink planted INSIDE the resolved pdfs target and pointing
+ outside it still fails closed (containment against the resolved
+ pdfs directory, not a blanket trust of the big disk)."""
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ )
+
+ library_root, big_disk_pdfs = _symlinked_pdfs_library(
+ tmp_path, username="alice"
+ )
+ try:
+ (big_disk_pdfs / "evil").symlink_to("/etc")
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ mock_settings = Mock()
+ mock_settings.get_setting.side_effect = lambda key, default=None: (
+ str(library_root)
+ if key == "research_library.storage_path"
+ else default
+ )
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=mock_settings,
+ ):
+ result = get_absolute_path_from_settings(
+ "pdfs/evil/passwd", "alice"
+ )
+
+ assert result is None
+
+
+def _settings_with_storage_path(library_root):
+ """A settings manager whose library storage path is ``library_root``."""
+ settings = Mock()
+ settings.get_setting.side_effect = lambda key, default=None: (
+ str(library_root) if key == "research_library.storage_path" else default
+ )
+ return settings
+
+
+class TestStoredPdfsPathSpellings:
+ """The trusted-leaf test reads a stored path as validate_safe_path
+ does, so redundant separators, surrounding whitespace and ``.``/``..``
+ segments that collapse to ``pdfs/<name>`` still resolve in the
+ symlinked layout, as they did before the containment check."""
+
+ @pytest.mark.parametrize(
+ "stored",
+ ["pdfs//5.pdf", " pdfs/5.pdf", "pdfs/../pdfs/5.pdf", "pdfs/./5.pdf"],
+ )
+ def test_equivalent_spellings_resolve_to_the_stored_file(
+ self, tmp_path, stored
+ ):
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ )
+
+ library_root, big_disk_pdfs = _symlinked_pdfs_library(
+ tmp_path, username="alice"
+ )
+ target = big_disk_pdfs / "5.pdf"
+ target.write_bytes(b"%PDF-1.4 fake")
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=_settings_with_storage_path(library_root),
+ ):
+ resolved = get_absolute_path_from_settings(stored, "alice")
+
+ assert resolved == target.resolve()
+
+ @pytest.mark.parametrize(
+ "stored",
+ [
+ "pdfs/../../5.pdf",
+ "pdfs//..//..//5.pdf",
+ "pdfs/./../../5.pdf",
+ "/pdfs/5.pdf",
+ ],
+ )
+ def test_traversal_spellings_still_fail_closed(self, tmp_path, stored):
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ )
+
+ library_root, big_disk_pdfs = _symlinked_pdfs_library(
+ tmp_path, username="alice"
+ )
+ (big_disk_pdfs / "5.pdf").write_bytes(b"%PDF-1.4 fake")
+ # A file where the traversal lands (outside alice's root).
+ (library_root / "5.pdf").write_bytes(b"another user's file")
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=_settings_with_storage_path(library_root),
+ ):
+ resolved = get_absolute_path_from_settings(stored, "alice")
+
+ assert resolved is None
+
+
+class TestWindowsStoredPdfsPaths:
+ """PDFStorageManager stores ``str(path.relative_to(library_root))``,
+ which is ``pdfs\\<name>`` on Windows. The trusted-leaf test must split
+ that on the backslash, as it splits ``pdfs/<name>`` on POSIX. When it
+ split on "/" only, the read resolver and the unlink boundary both used
+ the library root for such a path, so in the symlinked layout the PDF
+ was refused. ``_STORED_PATH_MODULE`` is set to ``ntpath`` here to read
+ stored paths the way a Windows host does."""
+
+ @pytest.fixture
+ def windows_separators(self, monkeypatch):
+ import ntpath
+
+ from local_deep_research.research_library import utils
+
+ monkeypatch.setattr(utils, "_STORED_PATH_MODULE", ntpath)
+
+ @pytest.mark.parametrize(
+ "stored",
+ [
+ "pdfs\\5.pdf",
+ "pdfs\\\\5.pdf",
+ " pdfs\\5.pdf",
+ "pdfs\\..\\pdfs\\5.pdf",
+ "pdfs\\.\\5.pdf",
+ "pdfs/5.pdf",
+ ],
+ )
+ def test_the_stored_pdf_and_its_boundary_use_the_pdfs_directory(
+ self, tmp_path, windows_separators, stored
+ ):
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ get_containment_root_from_settings,
+ )
+
+ library_root, big_disk_pdfs = _symlinked_pdfs_library(
+ tmp_path, username="alice"
+ )
+ target = big_disk_pdfs / "5.pdf"
+ target.write_bytes(b"%PDF-1.4 fake")
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=_settings_with_storage_path(library_root),
+ ):
+ resolved = get_absolute_path_from_settings(stored, "alice")
+ boundary = get_containment_root_from_settings(stored, "alice")
+
+ assert resolved == target.resolve()
+ assert boundary == big_disk_pdfs.resolve()
+
+ def test_the_remainder_uses_forward_slashes_only(
+ self, tmp_path, windows_separators
+ ):
+ """werkzeug's safe_join refuses a backslash on Windows, so the part
+ validated against the pdfs directory must not carry one."""
+ from local_deep_research.research_library.utils import (
+ _containment_base,
+ )
+
+ user_root = tmp_path / "alice"
+ (user_root / "pdfs").mkdir(parents=True)
+
+ assert _containment_base("pdfs\\sub\\5.pdf", user_root) == (
+ user_root / "pdfs",
+ "sub/5.pdf",
+ )
+
+ @pytest.mark.parametrize(
+ "stored",
+ [
+ "pdfs\\..\\..\\5.pdf",
+ "pdfs\\\\..\\\\..\\\\5.pdf",
+ "pdfs\\.\\..\\..\\5.pdf",
+ "pdfs\\sub\\..\\..\\..\\5.pdf",
+ "..\\pdfs\\5.pdf",
+ "\\pdfs\\5.pdf",
+ "\\\\pdfs\\5.pdf",
+ "pdfs\\..",
+ "pdfs\\",
+ ],
+ )
+ def test_traversal_spellings_skip_the_carve_out(
+ self, tmp_path, windows_separators, stored
+ ):
+ """They are checked unchanged against the user root, where
+ werkzeug's safe_join refuses any backslash on Windows."""
+ from local_deep_research.research_library.utils import (
+ _containment_base,
+ )
+
+ user_root = tmp_path / "alice"
+ (user_root / "pdfs").mkdir(parents=True)
+
+ assert _containment_base(stored, user_root) == (user_root, stored)
+
+ def test_an_escape_inside_the_resolved_pdfs_target_is_refused(
+ self, tmp_path, windows_separators
+ ):
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ )
+
+ library_root, big_disk_pdfs = _symlinked_pdfs_library(
+ tmp_path, username="alice"
+ )
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "secret.pdf").write_bytes(b"outside the pdfs directory")
+ try:
+ (big_disk_pdfs / "evil").symlink_to(
+ outside, target_is_directory=True
+ )
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=_settings_with_storage_path(library_root),
+ ):
+ resolved = get_absolute_path_from_settings(
+ "pdfs\\evil\\secret.pdf", "alice"
+ )
+
+ assert resolved is None
+
+ def test_a_backslash_stays_a_filename_character_on_posix(
+ self, tmp_path, monkeypatch
+ ):
+ import posixpath
+
+ from local_deep_research.research_library import utils
+
+ monkeypatch.setattr(utils, "_STORED_PATH_MODULE", posixpath)
+ user_root = tmp_path / "alice"
+ (user_root / "pdfs").mkdir(parents=True)
+
+ assert utils._containment_base("pdfs\\5.pdf", user_root) == (
+ user_root,
+ "pdfs\\5.pdf",
+ )
+
+
+class TestContainmentRootFromSettings:
+ """get_containment_root_from_settings returns, already resolved, the
+ directory the resolver confines a stored path to. DocumentDeletionService
+ passes it to CascadeHelper.delete_filesystem_file as ``allowed_root``
+ with ``allowed_root_is_resolved=True``."""
+
+ def test_pdfs_paths_use_the_pdfs_directory_and_others_the_user_root(
+ self, tmp_path
+ ):
+ from local_deep_research.research_library.deletion.utils.cascade_helper import (
+ CascadeHelper,
+ )
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ get_containment_root_from_settings,
+ )
+
+ library_root, big_disk_pdfs = _symlinked_pdfs_library(
+ tmp_path, username="alice"
+ )
+ user_root = library_root.resolve() / "alice"
+ (big_disk_pdfs / "5.pdf").write_bytes(b"%PDF-1.4 fake")
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=_settings_with_storage_path(library_root),
+ ):
+ file_path = get_absolute_path_from_settings("pdfs/5.pdf", "alice")
+ pdfs_root = get_containment_root_from_settings(
+ "pdfs/5.pdf", "alice"
+ )
+ other_root = get_containment_root_from_settings(
+ "notes/5.pdf", "alice"
+ )
+
+ # The boundary comes back resolved: the pdfs link's target.
+ assert pdfs_root == big_disk_pdfs.resolve()
+ assert other_root == user_root
+ # The unlink re-check accepts the PDF against its own boundary...
+ assert CascadeHelper._resolved_containment_ok(
+ file_path, pdfs_root, allowed_root_is_resolved=True
+ )
+ # ...but the big disk is not trusted for any other stored path.
+ assert not CascadeHelper._resolved_containment_ok(
+ file_path, other_root, allowed_root_is_resolved=True
+ )
+
+ @pytest.mark.parametrize("leaf", ["regular-file", "dangling-symlink"])
+ def test_a_pdfs_leaf_that_is_not_a_directory_keeps_the_user_root(
+ self, tmp_path, leaf
+ ):
+ from local_deep_research.research_library.utils import (
+ get_absolute_path_from_settings,
+ get_containment_root_from_settings,
+ )
+
+ library_root = tmp_path / "library"
+ user_root = library_root / "alice"
+ user_root.mkdir(parents=True)
+ if leaf == "regular-file":
+ (user_root / "pdfs").write_bytes(b"not a directory")
+ else:
+ try:
+ (user_root / "pdfs").symlink_to(
+ tmp_path / "missing", target_is_directory=True
+ )
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ with patch(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ return_value=_settings_with_storage_path(library_root),
+ ):
+ boundary = get_containment_root_from_settings("pdfs/5.pdf", "alice")
+ resolved = get_absolute_path_from_settings("pdfs/5.pdf", "alice")
+
+ assert boundary == user_root.resolve()
+ # Either way resolution fails closed: the dangling link leaves the
+ # user root, and a path below a regular file cannot be resolved
+ # (ENOTDIR) and so is refused rather than compared half resolved.
+ assert resolved is None
+
+ def test_an_unresolvable_pdfs_leaf_keeps_the_user_root(
+ self, tmp_path, monkeypatch
+ ):
+ from local_deep_research.research_library.utils import (
+ _containment_base,
+ )
+
+ user_root = tmp_path / "alice"
+ (user_root / "pdfs").mkdir(parents=True)
+ real_resolve = Path.resolve
+
+ def resolve(path, *args, **kwargs):
+ if path == user_root / "pdfs":
+ raise OSError("unresolvable leaf")
+ return real_resolve(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "resolve", resolve)
+
+ assert _containment_base("pdfs/5.pdf", user_root) == (
+ user_root,
+ "pdfs/5.pdf",
+ )
diff --git a/tests/security/path_max_fixtures.py b/tests/security/path_max_fixtures.py
new file mode 100644
index 0000000000..0be1f6fa0a
--- /dev/null
+++ b/tests/security/path_max_fixtures.py
@@ -0,0 +1,63 @@
+"""A symlink escape that non-strict ``Path.resolve()`` cannot see.
+
+``build_path_max_escape(base, outside)`` plants, inside ``base``:
+
+* a chain of 16 nested directories with 254-character names, created
+ through ``dir_fd`` so that no syscall ever receives a path longer than
+ PATH_MAX;
+* ``base/L1``, a relative symlink to the deepest directory of that chain
+ (its target is 4079 characters, under the 4095-character limit);
+* ``<deepest>/esc``, a symlink to ``outside``.
+
+``base/L1/esc/<name>`` is short, and the kernel opens it as
+``outside/<name>``. Resolving it in user space instead builds a prefix
+longer than PATH_MAX, so every later ``lstat`` fails with ENAMETOOLONG.
+Non-strict ``resolve()`` ignores that error and appends ``esc/<name>``
+without following ``esc``. The result is lexically inside ``base``,
+which is how a containment check built on it was bypassed.
+"""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+import pytest
+
+_DEPTH = 16
+_NAME_LENGTH = 254
+_PATH_MAX_STRING = 4095
+
+
+def build_path_max_escape(base: Path, outside: Path) -> str:
+ """Plant the chain under ``base`` and return ``"L1/esc"``.
+
+ ``base/L1/esc`` reaches ``outside`` through the kernel. Skips the
+ calling test where the platform cannot build the layout, or where
+ ``base`` is too short for the resolved prefix to outgrow PATH_MAX.
+ """
+ names = [chr(ord("a") + i) * _NAME_LENGTH for i in range(_DEPTH)]
+ target = "/".join(names)
+ resolved_prefix = len(str(base.resolve())) + 1 + len(target)
+ if resolved_prefix + len("/esc") <= _PATH_MAX_STRING:
+ pytest.skip("base path too short to outgrow PATH_MAX")
+ try:
+ fd = os.open(base, os.O_RDONLY | os.O_DIRECTORY)
+ except (OSError, AttributeError):
+ pytest.skip("directory file descriptors are not available")
+ try:
+ for name in names:
+ os.mkdir(name, dir_fd=fd)
+ child = os.open(name, os.O_RDONLY | os.O_DIRECTORY, dir_fd=fd)
+ os.close(fd)
+ fd = child
+ os.symlink(str(outside), "esc", dir_fd=fd)
+ except (OSError, NotImplementedError):
+ pytest.skip("cannot build a PATH_MAX symlink chain here")
+ finally:
+ os.close(fd)
+ try:
+ (base / "L1").symlink_to(target, target_is_directory=True)
+ except (OSError, NotImplementedError):
+ pytest.skip("cannot create symlinks in this environment")
+ return "L1/esc"
diff --git a/tests/security/test_guard_internals.py b/tests/security/test_guard_internals.py
index 28ccea9fa8..72dfcaef20 100644
--- a/tests/security/test_guard_internals.py
+++ b/tests/security/test_guard_internals.py
@@ -100,7 +100,7 @@ def _is_confined(base, user_input):
class TestValidateSafePathContainment:
- """``validate_safe_path`` joins safely but never resolves.
+ """``validate_safe_path`` confines the *resolved* path to ``base_dir``.
``werkzeug.safe_join`` is a *string* operation: it rejects ``..``
segments and absolute inputs, and that is all it claims to do. The
@@ -108,7 +108,12 @@ class TestValidateSafePathContainment:
traversal attacks and other filesystem-based security
vulnerabilities" — and a ``confine_to_base()`` helper that did the
realpath containment check was removed (see the comment referencing
- #4868 in ``path_validator.py``). Nothing replaced it.
+ #4868 in ``path_validator.py``). The realpath containment was
+ restored (GHSA-gv87-qcw7-gjr8): the joined path is resolved and
+ required to stay under the resolved base, so a symlink inside
+ ``base_dir`` is accepted only when its target is inside too —
+ #3090's bind-mount / macOS ``/tmp`` layouts keep working, and only
+ the escapes are refused.
"""
def test_a_path_inside_the_base_is_accepted(self, confined_tree):
@@ -135,35 +140,25 @@ class TestValidateSafePathContainment:
with pytest.raises(ValueError, match="traversal"):
PathValidator.validate_safe_path(str(outside / "secret.txt"), base)
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT (security): validate_safe_path performs no realpath "
- "containment. A symlinked directory inside base_dir is "
- "traversed straight through, and the returned Path reads a "
- "file outside base_dir. safe_join only rejects literal '..' "
- "and absolute inputs -- it never touches the filesystem."
- ),
- )
def test_a_symlinked_directory_does_not_escape_the_base(
self, confined_tree
):
- """``linkdir/secret.txt`` must not resolve outside ``base``."""
+ """``linkdir/secret.txt`` must not resolve outside ``base``.
+
+ Resolved-state contract (GHSA-gv87-qcw7-gjr8): the guard either
+ refuses the input or confines its real location — a symlinked
+ directory inside ``base_dir`` can no longer be traversed
+ straight through to a file outside it.
+ """
base, _ = confined_tree
assert _is_confined(base, "linkdir/secret.txt"), (
"validate_safe_path returned a path whose real location is "
"outside base_dir"
)
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT (security): same root cause as the directory case -- "
- "a leaf symlink is returned verbatim, so the caller reads "
- "the link target."
- ),
- )
def test_a_leaf_symlink_does_not_escape_the_base(self, confined_tree):
+ """A leaf symlink resolving outside ``base`` is refused or
+ confined (same root cause as the directory case)."""
base, _ = confined_tree
assert _is_confined(base, "leaflink")
@@ -234,16 +229,13 @@ class TestLibraryCallSiteInheritsTheGap:
assert resolved is not None
assert resolved.read_text(encoding="utf-8") == "INSIDE"
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT (security): the leaf-only is_symlink() check misses a "
- "symlinked intermediate directory, so _resolve_within_root "
- "hands back a path that reads outside the per-user library "
- "root."
- ),
- )
def test_an_intermediate_symlink_is_not_caught(self, confined_tree):
+ """Resolved-state contract: with realpath containment inside
+ ``validate_safe_path`` (GHSA-gv87-qcw7-gjr8), an intermediate
+ symlinked directory can no longer smuggle a read outside the
+ per-user library root — the guard itself refuses it, so the
+ call site's leaf-only ``is_symlink()`` check is no longer the
+ only line of defence."""
from local_deep_research.research_library.utils import (
_resolve_within_root,
)
diff --git a/tests/security/test_path_validator.py b/tests/security/test_path_validator.py
index c44a6ed030..067b1d1077 100644
--- a/tests/security/test_path_validator.py
+++ b/tests/security/test_path_validator.py
@@ -2,13 +2,17 @@
Tests for PathValidator security module.
"""
+import errno
import sys
import tempfile
from pathlib import Path
+from unittest.mock import Mock
import pytest
+from local_deep_research.security import path_validator
from local_deep_research.security.path_validator import PathValidator
+from tests.security.path_max_fixtures import build_path_max_escape
class TestValidateSafePath:
@@ -89,6 +93,243 @@ class TestValidateSafePath:
result = PathValidator.validate_safe_path(" file.txt ", temp_base_dir)
assert result.name == "file.txt"
+ @pytest.mark.parametrize(
+ ("failure", "error_text", "log_text"),
+ [
+ (
+ errno.EACCES,
+ "could not be resolved safely",
+ "Path resolution failed",
+ ),
+ (
+ errno.ELOOP,
+ "could not be resolved safely",
+ "Path resolution failed",
+ ),
+ (None, "escapes base directory", "Symlink containment violation"),
+ ],
+ ids=["io-error", "resolution-loop", "outside-base"],
+ )
+ @pytest.mark.parametrize("padding", ["", "x" * 4096], ids=["short", "long"])
+ def test_resolution_rejection_logs_are_redacted_and_bounded(
+ self,
+ tmp_path,
+ monkeypatch,
+ resolver_mode,
+ failure,
+ error_text,
+ log_text,
+ padding,
+ ):
+ """Rejection messages must be safe before the global logger patcher.
+
+ The candidate's outcome is injected at resolve_allow_missing, which
+ both resolvers share. A ``Path.resolve`` stub keyed on the candidate
+ is never reached by the fallback: it lstats the missing candidate
+ and strictly resolves only the directory that exists.
+ """
+ from local_deep_research.security import path_validator
+
+ secret = "log-test-secret-1234567890"
+ user_input = (
+ f"file\nFORGED\rheader?api_key={secret}&name=visible {padding}end"
+ )
+ candidate = tmp_path / user_input
+ real_resolve = path_validator.resolve_allow_missing
+
+ def resolve(path):
+ if Path(path) == candidate:
+ if failure is not None:
+ raise OSError(failure, "unresolvable input")
+ return tmp_path.parent / "outside"
+ return real_resolve(path)
+
+ warning = Mock()
+ monkeypatch.setattr(path_validator, "resolve_allow_missing", resolve)
+ monkeypatch.setattr(path_validator, "logger", Mock(warning=warning))
+
+ with pytest.raises(ValueError, match=error_text):
+ PathValidator.validate_safe_path(user_input, tmp_path)
+
+ warning.assert_called_once()
+ message = warning.call_args.args[0]
+ assert log_text in message
+ assert secret not in message
+ assert "[REDACTED]" in message
+ assert "\n" not in message
+ assert "\r" not in message
+ assert len(message) < 300
+
+
[email protected](params=["allow-missing", "fallback"])
+def resolver_mode(request, monkeypatch):
+ """Run a test against ``os.path.ALLOW_MISSING`` and against the
+ fallback used on Python releases that lack it."""
+ if request.param == "allow-missing":
+ if path_validator._ALLOW_MISSING is None:
+ pytest.skip("os.path.ALLOW_MISSING is not available")
+ else:
+ monkeypatch.setattr(path_validator, "_ALLOW_MISSING", None)
+ return request.param
+
+
+class TestPathMaxSymlinkChain:
+ """An escape hidden behind a symlink chain longer than PATH_MAX.
+
+ Non-strict ``Path.resolve()`` ignores the ENAMETOOLONG that ``lstat``
+ raises once the resolved prefix outgrows PATH_MAX, and appends the
+ rest of the path without following the escaping symlink, so the
+ result looked contained. ``validate_safe_path`` must refuse it.
+ """
+
+ @pytest.fixture
+ def escape(self, tmp_path):
+ base = tmp_path / "base"
+ base.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "secret.txt").write_text("OUTSIDE")
+ return base, outside, build_path_max_escape(base, outside)
+
+ def test_the_short_path_reaches_the_outside_file(self, escape):
+ """Control: the kernel opens the short path outside ``base``."""
+ base, _, link = escape
+ assert (base / link / "secret.txt").read_text() == "OUTSIDE"
+
+ def test_validate_safe_path_refuses_the_escape(self, escape):
+ base, _, link = escape
+ with pytest.raises(ValueError, match="could not be resolved safely"):
+ PathValidator.validate_safe_path(f"{link}/secret.txt", base)
+
+ def test_a_missing_leaf_behind_the_escape_is_refused(self, escape):
+ """The write side: the leaf would be created outside ``base``."""
+ base, outside, link = escape
+ with pytest.raises(ValueError, match="could not be resolved safely"):
+ PathValidator.validate_safe_path(f"{link}/new.pdf", base)
+ assert not (outside / "new.pdf").exists()
+
+ @pytest.mark.parametrize("leaf", ["secret.txt", "new.pdf"])
+ def test_the_fallback_refuses_the_escape_too(
+ self, escape, monkeypatch, leaf
+ ):
+ """Python releases without os.path.ALLOW_MISSING."""
+ monkeypatch.setattr(path_validator, "_ALLOW_MISSING", None)
+ base, _, link = escape
+ with pytest.raises(ValueError, match="could not be resolved safely"):
+ PathValidator.validate_safe_path(f"{link}/{leaf}", base)
+
+ @pytest.mark.parametrize("leaf", ["secret.txt", "new.pdf"])
+ def test_resolve_allow_missing_raises_for_the_chain(
+ self, escape, resolver_mode, leaf
+ ):
+ """Both resolvers raise ENAMETOOLONG, for the existing leaf and for
+ a missing one, instead of returning the half-resolved path."""
+ base, _, link = escape
+ with pytest.raises(OSError) as raised:
+ path_validator.resolve_allow_missing(base / link / leaf)
+ assert raised.value.errno == errno.ENAMETOOLONG
+
+
+class TestResolveAllowMissing:
+ """``resolve_allow_missing`` tolerates only a missing tail."""
+
+ def test_missing_components_are_appended(self, tmp_path, resolver_mode):
+ base = tmp_path.resolve() / "base"
+ (base / "dir").mkdir(parents=True)
+
+ assert path_validator.resolve_allow_missing(
+ base / "dir" / "new" / "x.pdf"
+ ) == (base / "dir" / "new" / "x.pdf")
+ assert path_validator.resolve_allow_missing(str(base / "new.pdf")) == (
+ base / "new.pdf"
+ )
+
+ def test_in_base_symlinks_are_followed(self, tmp_path, resolver_mode):
+ base = tmp_path.resolve() / "base"
+ (base / "dir").mkdir(parents=True)
+ (base / "dir" / "f.txt").write_text("x")
+ try:
+ (base / "link").symlink_to(base / "dir", target_is_directory=True)
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ assert path_validator.resolve_allow_missing(
+ base / "link" / "f.txt"
+ ) == (base / "dir" / "f.txt")
+ assert path_validator.resolve_allow_missing(
+ base / "link" / "new.pdf"
+ ) == (base / "dir" / "new.pdf")
+
+ @pytest.mark.parametrize(
+ ("shape", "expected_errno"),
+ [
+ ("loop", errno.ELOOP),
+ ("loop-leaf", errno.ELOOP),
+ ("below-a-file", errno.ENOTDIR),
+ ],
+ ids=["loop", "loop-leaf", "below-a-file"],
+ )
+ def test_unresolvable_paths_raise_oserror(
+ self, tmp_path, resolver_mode, shape, expected_errno
+ ):
+ """Both resolvers raise the same errno for each shape."""
+ if shape.startswith("loop"):
+ try:
+ (tmp_path / "loop_a").symlink_to(tmp_path / "loop_b")
+ (tmp_path / "loop_b").symlink_to(tmp_path / "loop_a")
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+ path = tmp_path / "loop_a"
+ if shape == "loop":
+ path = path / "x.pdf"
+ else:
+ (tmp_path / "f.txt").write_text("x")
+ path = tmp_path / "f.txt" / "x.pdf"
+
+ with pytest.raises(OSError) as raised:
+ path_validator.resolve_allow_missing(path)
+ assert raised.value.errno == expected_errno
+
+ def test_a_loop_reported_as_runtime_error_raises_eloop(
+ self, tmp_path, monkeypatch, resolver_mode
+ ):
+ """Python 3.12's resolve() reports a symlink loop as RuntimeError.
+
+ Both resolvers re-raise it as OSError(ELOOP). The target exists, so
+ the fallback strictly resolves the whole path, as ALLOW_MISSING does.
+ """
+ target = tmp_path / "f.txt"
+ target.write_text("x")
+ real_resolve = Path.resolve
+
+ def resolve(path, *args, **kwargs):
+ if path == target:
+ raise RuntimeError("Symlink loop")
+ return real_resolve(path, *args, **kwargs)
+
+ monkeypatch.setattr(Path, "resolve", resolve)
+
+ with pytest.raises(OSError) as raised:
+ path_validator.resolve_allow_missing(target)
+ assert raised.value.errno == errno.ELOOP
+
+ def test_the_fallback_also_refuses_dangling_links_and_dotdot(
+ self, tmp_path, monkeypatch
+ ):
+ """The fallback is stricter than ALLOW_MISSING, never looser."""
+ monkeypatch.setattr(path_validator, "_ALLOW_MISSING", None)
+ try:
+ (tmp_path / "dangling").symlink_to(tmp_path / "nowhere")
+ except (OSError, NotImplementedError):
+ pytest.skip("Cannot create symlinks in this environment")
+
+ with pytest.raises(OSError):
+ path_validator.resolve_allow_missing(tmp_path / "dangling")
+ with pytest.raises(OSError):
+ path_validator.resolve_allow_missing(
+ tmp_path / "missing" / ".." / "x.pdf"
+ )
+
class TestValidateLocalFilesystemPath:
"""Tests for PathValidator.validate_local_filesystem_path()."""
@@ -490,15 +731,24 @@ class TestSecurityScenarios:
)
def test_symlink_escape_prevention(self, temp_base_dir):
- """Path resolution prevents symlink escapes."""
+ """Path resolution prevents symlink escapes.
+
+ A symlink under base_dir pointing outside it is refused outright:
+ ``validate_safe_path`` resolves the joined path and requires the
+ real location to stay under the resolved base
+ (GHSA-gv87-qcw7-gjr8). Previously the *lexical* path was
+ returned — "within base_dir" as a string — while any read
+ through it followed the link outside; that interim behaviour is
+ what this test used to pin.
+ """
# Create a symlink pointing outside base dir
symlink_path = temp_base_dir / "escape"
try:
symlink_path.symlink_to("/etc")
- # Attempting to access via symlink should work for the symlink itself
- # but not for paths through it
- result = PathValidator.validate_safe_path("escape", temp_base_dir)
- # The result should be within base_dir (the symlink itself)
- assert str(temp_base_dir) in str(result)
+ with pytest.raises(ValueError):
+ PathValidator.validate_safe_path("escape", temp_base_dir)
+ # and through it, for a path with a leaf component
+ with pytest.raises(ValueError):
+ PathValidator.validate_safe_path("escape/passwd", temp_base_dir)
except OSError:
pytest.skip("Symlink creation not supported")
diff --git a/tests/storage/test_file_storage.py b/tests/storage/test_file_storage.py
index f4cb106da7..dd05b121cc 100644
--- a/tests/storage/test_file_storage.py
+++ b/tests/storage/test_file_storage.py
@@ -87,6 +87,23 @@ class TestPathTraversalContainment:
assert path.is_relative_to(tmp_path.resolve())
assert path.name == "9f8e-uuid-1234.md"
+ def test_rejects_an_escape_behind_a_path_max_symlink_chain(self, tmp_path):
+ """Non-strict resolution stops following symlinks once the resolved
+ prefix outgrows PATH_MAX, so this path looked inside base_dir."""
+ from tests.security.path_max_fixtures import build_path_max_escape
+
+ base = tmp_path / "reports"
+ base.mkdir()
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ link = build_path_max_escape(base, outside)
+ storage = FileReportStorage(base_dir=base)
+
+ with pytest.raises(ValueError):
+ storage._get_report_path(f"{link}/stolen")
+ with pytest.raises(ValueError):
+ storage._get_metadata_path(f"{link}/stolen")
+
class TestSaveReport:
"""Tests for save_report method."""
diff --git a/tests/web/routers/test_report_unlink_guard.py b/tests/web/routers/test_report_unlink_guard.py
index aa57ad3aab..ca6face91e 100644
--- a/tests/web/routers/test_report_unlink_guard.py
+++ b/tests/web/routers/test_report_unlink_guard.py
@@ -33,6 +33,8 @@ from unittest.mock import patch
import pytest
+from tests.security.path_max_fixtures import build_path_max_escape
+
_RR = "local_deep_research.web.routers.research"
_PATHS = "local_deep_research.config.paths"
@@ -119,6 +121,20 @@ def test_refuses_an_escape_through_a_symlinked_ancestor(
assert (outside_dir / "report.md").exists()
+def test_refuses_an_escape_behind_a_path_max_symlink_chain(
+ guard, reports_root, tmp_path
+):
+ """Non-strict resolution stops following symlinks once the resolved
+ prefix outgrows PATH_MAX, so this path looked inside the root while
+ the unlink reached the file outside it."""
+ outside_dir = tmp_path / "outside"
+ (outside_dir / "report.md").write_text("out of root")
+ link = build_path_max_escape(reports_root, outside_dir)
+
+ assert guard(str(reports_root / link / "report.md")) is False
+ assert (outside_dir / "report.md").exists()
+
+
def test_missing_file_is_not_an_error(guard, reports_root):
"""No separate exists()-before-unlink() window: the delete itself is
allowed to report "already gone"."""