~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
security: add path traversal protection for file reads (#1890)
LearningCircuit1ae979130b7a
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.pyindex 7eeec08cef..d218a8575b 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@@ -114,9 +114,12 @@ class DocumentDeletionService:file_path = get_absolute_path_from_settings(document.file_path)- result["file_deleted"] = (- CascadeHelper.delete_filesystem_file(str(file_path))- )+ if file_path:+ result["file_deleted"] = (+ CascadeHelper.delete_filesystem_file(+ str(file_path)+ )+ )except Exception:logger.exception("Failed to delete filesystem file")@@ -199,7 +202,7 @@ class DocumentDeletionService:file_path = get_absolute_path_from_settings(document.file_path)- if file_path.exists():+ if file_path and file_path.exists():result["bytes_freed"] = file_path.stat().st_sizeCascadeHelper.delete_filesystem_file(str(file_path)@@ -351,7 +354,10 @@ class DocumentDeletionService:file_path = get_absolute_path_from_settings(document.file_path)- CascadeHelper.delete_filesystem_file(str(file_path))+ if file_path:+ CascadeHelper.delete_filesystem_file(+ str(file_path)+ )except Exception:logger.exception("Failed to delete filesystem file")diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.pyindex 4767dd3c97..9dec0dc4e4 100644--- a/src/local_deep_research/research_library/services/download_service.py+++ b/src/local_deep_research/research_library/services/download_service.py@@ -28,6 +28,7 @@ from ...database.models.download_tracker import (DownloadTracker,)from ...security import redact_data, safe_get+from ...security.path_validator import PathValidatorfrom ...database.models.library import (Collection,Document as Document,@@ -217,12 +218,13 @@ class DownloadService:absolute_path = get_absolute_path_from_settings(tracker.file_path)- if absolute_path.exists():+ if absolute_path and absolute_path.exists():return True, str(absolute_path)- else:+ elif absolute_path:# File was deleted, mark as not downloadedtracker.is_downloaded = Falsesession.commit()+ # If absolute_path is None, path was blocked - treat as not downloadedreturn False, None@@ -1020,7 +1022,19 @@ class DownloadService:if not pdf_document or pdf_document.status != "completed":return None- pdf_path = Path(self.library_root) / pdf_document.file_path+ # Validate path to prevent path traversal attacks+ if not pdf_document.file_path:+ return None+ try:+ safe_path = PathValidator.validate_safe_path(+ pdf_document.file_path, str(self.library_root)+ )+ pdf_path = Path(safe_path)+ except ValueError as e:+ logger.warning(+ f"Path traversal blocked: {pdf_document.file_path} - {e}"+ )+ return Noneif not pdf_path.exists():return Nonediff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex cd7825c705..d66d0a1bdd 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -51,6 +51,24 @@ class LibraryService:is not None)+ def _get_safe_absolute_path(self, file_path: str) -> Optional[str]:+ """+ Get the absolute path for a file, safely handling invalid paths.++ Args:+ file_path: Relative file path from library root++ Returns:+ Absolute path as string, or None if path is invalid/unsafe+ """+ if not file_path or file_path in (+ "metadata_only",+ "text_only_not_stored",+ ):+ return None+ abs_path = get_absolute_path_from_settings(file_path)+ return str(abs_path) if abs_path else None+def _is_arxiv_url(self, url: str) -> bool:"""Check if URL is from arXiv domain."""try:@@ -286,9 +304,9 @@ class LibraryService:and doc.file_path != "metadata_only"and doc.file_path != "text_only_not_stored"):- file_absolute_path = str(- get_absolute_path_from_settings(doc.file_path)- )+ abs_path = get_absolute_path_from_settings(doc.file_path)+ if abs_path:+ file_absolute_path = str(abs_path)# Check if PDF is available (filesystem OR database)has_pdf = bool(file_absolute_path)@@ -618,13 +636,9 @@ class LibraryService:"original_url": doc.original_urlor (resource.url if resource else None),"file_path": doc.file_path,- "file_absolute_path": str(- get_absolute_path_from_settings(doc.file_path)- )- if doc.file_path- and doc.file_path- not in ("metadata_only", "text_only_not_stored")- else None,+ "file_absolute_path": self._get_safe_absolute_path(+ doc.file_path+ ),"file_name": Path(doc.file_path).nameif doc.file_pathand doc.file_path@@ -704,7 +718,7 @@ class LibraryService:file_path = get_absolute_path_from_settings(tracker.file_path)- if file_path.exists():+ if file_path and file_path.exists():file_path.unlink()logger.info(f"Deleted file: {file_path}")except Exception:@@ -741,6 +755,9 @@ class LibraryService:if tracker and tracker.file_path:# Validate path is within library root to prevent traversal attackslibrary_root = get_absolute_path_from_settings("")+ if not library_root:+ logger.warning("Could not determine library root")+ return Falsetry:validated_path = PathValidator.validate_safe_path(tracker.file_path, library_root, allow_absolute=False@@ -859,16 +876,18 @@ class LibraryService:file_path = get_absolute_path_from_settings(tracker.file_path)- if file_path.exists():+ if file_path and file_path.exists():stats["files_found"] += 1else:- # File missing - delete the document entry so it can be re-downloaded+ # File missing or path invalid - mark for re-downloadstats["files_missing"] += 1stats["missing_files"].append({"id": doc.id,"title": doc.title,- "path": str(file_path),+ "path": str(file_path)+ if file_path+ else "invalid","url": doc.original_url,})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.pyindex 77902e00b4..5bbfb90a0f 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@@ -35,7 +35,7 @@ class PDFStorageManager:storage_mode: One of 'none', 'filesystem', 'database'max_pdf_size_mb: Maximum PDF file size in MB (default 100)"""- self.library_root = Path(library_root)+ self.library_root = Path(library_root).resolve()self.storage_mode = storage_modeself.max_pdf_size_bytes = max_pdf_size_mb * 1024 * 1024@@ -45,6 +45,40 @@ class PDFStorageManager:)self.storage_mode = "none"+ def _get_safe_file_path(self, relative_path: str) -> Optional[Path]:+ """+ Safely resolve a relative path within the library root.++ Prevents path traversal attacks by validating the path stays within+ the library root directory.++ Args:+ relative_path: Relative path from database++ Returns:+ Validated absolute Path or None if path is invalid/unsafe+ """+ if not relative_path or relative_path in (+ "metadata_only",+ "text_only_not_stored",+ ):+ return None++ try:+ # Use PathValidator to safely join and validate the path+ safe_path = PathValidator.validate_safe_path(+ relative_path, str(self.library_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 as e:+ logger.warning(f"Path traversal blocked: {relative_path} - {e}")+ return None+def save_pdf(self,pdf_content: bytes,@@ -163,14 +197,10 @@ class PDFStorageManager:if has_blob:return True- # Check filesystem- if document.file_path and document.file_path not in (- "metadata_only",- "text_only_not_stored",- ):- file_path = self.library_root / document.file_path- if file_path.exists():- return True+ # Check filesystem (with path traversal protection)+ file_path = self._get_safe_file_path(document.file_path)+ if file_path and file_path.exists():+ return Truereturn False@@ -183,7 +213,10 @@ class PDFStorageManager:if hasattr(document, "blob") and document.blob:return "database"# If there's a file_path (and not 'metadata_only'), it's filesystem- if document.file_path and document.file_path != "metadata_only":+ if document.file_path and document.file_path not in (+ "metadata_only",+ "text_only_not_stored",+ ):return "filesystem"# Otherwise no storagereturn "none"@@ -217,9 +250,6 @@ class PDFStorageManager:required_extensions=(".pdf",),)- if not validated_path:- raise ValueError("Invalid file path")-# Write the PDF file with security verification# Pass current storage_mode as snapshot since we already validated itfrom ...security.file_write_verifier import write_file_verified@@ -267,12 +297,12 @@ class PDFStorageManager:logger.debug(f"Created new blob for document {document.id}")def _load_from_filesystem(self, document: Document) -> Optional[bytes]:- """Load PDF from filesystem."""- if not document.file_path or document.file_path == "metadata_only":+ """Load PDF from filesystem with path traversal protection."""+ # Use safe path resolution to prevent path traversal attacks+ file_path = self._get_safe_file_path(document.file_path)+ if not file_path:return None- file_path = self.library_root / document.file_path-if not file_path.exists():logger.warning(f"PDF file not found: {file_path}")return None@@ -344,11 +374,11 @@ class PDFStorageManager:try:if storage_mode == "filesystem":- if document.file_path and document.file_path != "metadata_only":- file_path = self.library_root / document.file_path- if file_path.exists():- file_path.unlink()- logger.info(f"Deleted PDF file: {file_path}")+ # Use safe path resolution to prevent path traversal attacks+ file_path = self._get_safe_file_path(document.file_path)+ if file_path and file_path.exists():+ file_path.unlink()+ logger.info(f"Deleted PDF file: {file_path}")document.file_path = Nonedocument.storage_mode = "none"return Truediff --git a/src/local_deep_research/research_library/utils/__init__.py b/src/local_deep_research/research_library/utils/__init__.pyindex d47109b553..f8a634f72e 100644--- a/src/local_deep_research/research_library/utils/__init__.py+++ b/src/local_deep_research/research_library/utils/__init__.py@@ -5,6 +5,7 @@ import osimport subprocessimport sysfrom pathlib import Path+from typing import Optionalfrom flask import jsonifyfrom loguru import logger@@ -141,30 +142,44 @@ def get_relative_library_path(absolute_path: str, username: str) -> str:return Path(absolute_path).name-def get_absolute_library_path(relative_path: str, username: str) -> Path:+def get_absolute_library_path(+ relative_path: str, username: str+) -> Optional[Path]:"""Get the absolute path from a relative library path.+ Uses PathValidator to prevent path traversal attacks.+Args:relative_path: The relative path from library rootusername: The usernameReturns:- The absolute path+ The absolute path, or None if the path is unsafe"""library_root = get_library_storage_path(username)- return library_root / relative_path+ try:+ # Use PathValidator to prevent path traversal attacks+ safe_path = PathValidator.validate_safe_path(+ relative_path, str(library_root)+ )+ return Path(safe_path)+ except ValueError as e:+ logger.warning(f"Path traversal blocked: {relative_path} - {e}")+ return None-def get_absolute_path_from_settings(relative_path: str) -> Path:+def get_absolute_path_from_settings(relative_path: str) -> Optional[Path]:"""Get absolute path using settings manager for library root.+ Uses PathValidator to prevent path traversal attacks.+Args:relative_path: The relative path from library rootReturns:- The absolute path+ The absolute path, or None if the path is unsafe"""from ...utilities.db_utils import get_settings_manager@@ -179,7 +194,15 @@ def get_absolute_path_from_settings(relative_path: str) -> Path:if not relative_path:return library_root- return library_root / relative_path+ try:+ # Use PathValidator to prevent path traversal attacks+ safe_path = PathValidator.validate_safe_path(+ relative_path, str(library_root)+ )+ return Path(safe_path)+ except ValueError as e:+ logger.warning(f"Path traversal blocked: {relative_path} - {e}")+ return Nonedef handle_api_error(operation: str, error: Exception, status_code: int = 500):diff --git a/tests/research_library/services/test_pdf_storage_manager.py b/tests/research_library/services/test_pdf_storage_manager.pyindex fbf36289ca..71db8313dd 100644--- a/tests/research_library/services/test_pdf_storage_manager.py+++ b/tests/research_library/services/test_pdf_storage_manager.py@@ -14,7 +14,7 @@ class TestPDFStorageManagerInit:def test_initializes_with_defaults(self, tmp_path):"""Should initialize with default settings."""manager = PDFStorageManager(tmp_path, "database")- assert manager.library_root == tmp_path+ assert manager.library_root == tmp_path.resolve()assert manager.storage_mode == "database"assert manager.max_pdf_size_bytes == 100 * 1024 * 1024diff --git a/tests/research_library/services/test_pdf_storage_manager_edge_cases.py b/tests/research_library/services/test_pdf_storage_manager_edge_cases.pyindex 8b35f97b42..1dc73c6bd7 100644--- a/tests/research_library/services/test_pdf_storage_manager_edge_cases.py+++ b/tests/research_library/services/test_pdf_storage_manager_edge_cases.py@@ -93,7 +93,7 @@ class TestHasPdfSentinel:)import inspect- source = inspect.getsource(PDFStorageManager.has_pdf)+ source = inspect.getsource(PDFStorageManager._get_safe_file_path)# Verify the sentinel value appears in the source code's exclusion checkassert "text_only_not_stored" in sourceassert "metadata_only" in source@@ -103,20 +103,14 @@ class TestInferStorageMode:"""Tests for _infer_storage_mode edge cases."""def test_infer_storage_mode_text_only_not_stored(self):- """Documents that _infer_storage_mode doesn't exclude 'text_only_not_stored'.-- The file_path 'text_only_not_stored' is not 'metadata_only', so- _infer_storage_mode returns 'filesystem' even though there's no actual file.- """+ """'text_only_not_stored' sentinel is correctly treated as no storage."""manager = _make_manager()document = Mock()document.file_path = "text_only_not_stored"document.blob = Noneresult = manager._infer_storage_mode(document)- # This is actually a potential bug: text_only_not_stored is not metadata_only- # so it falls through to 'filesystem' even though there's no file- assert result == "filesystem"+ assert result == "none"class TestSaveToDatabase:diff --git a/tests/research_library/test_utils.py b/tests/research_library/test_utils.pynew file mode 100644index 0000000000..f38ff15a01--- /dev/null+++ b/tests/research_library/test_utils.py@@ -0,0 +1,982 @@+"""+Tests for research_library.utils module.++Tests path traversal protection and utility functions.+"""++from pathlib import Path+from unittest.mock import patch, Mock+++class TestGetAbsoluteLibraryPath:+ """Tests for get_absolute_library_path function."""++ def test_valid_relative_path_returns_absolute_path(self, tmp_path):+ """Valid relative paths should return absolute paths."""+ from local_deep_research.research_library.utils import (+ get_absolute_library_path,+ )++ with patch(+ "local_deep_research.research_library.utils.get_library_storage_path"+ ) as mock_storage:+ mock_storage.return_value = tmp_path++ result = get_absolute_library_path("pdfs/test.pdf", "testuser")++ assert result is not None+ assert result == tmp_path / "pdfs/test.pdf"++ def test_path_traversal_with_dotdot_returns_none(self, tmp_path):+ """Path traversal attempts with .. should return None."""+ from local_deep_research.research_library.utils import (+ get_absolute_library_path,+ )++ with patch(+ "local_deep_research.research_library.utils.get_library_storage_path"+ ) as mock_storage:+ mock_storage.return_value = tmp_path++ result = get_absolute_library_path(+ "../../../etc/passwd", "testuser"+ )++ assert result is None++ def test_path_traversal_with_nested_dotdot_returns_none(self, tmp_path):+ """Path traversal with nested .. should return None."""+ from local_deep_research.research_library.utils import (+ get_absolute_library_path,+ )++ with patch(+ "local_deep_research.research_library.utils.get_library_storage_path"+ ) as mock_storage:+ mock_storage.return_value = tmp_path++ # Various traversal attempts using actual .. patterns+ traversal_paths = [+ "pdfs/../../secret.txt",+ "./../../etc/passwd",+ "subdir/../../../etc/passwd",+ ]++ for path in traversal_paths:+ result = get_absolute_library_path(path, "testuser")+ assert result is None, f"Path '{path}' should have been blocked"++ def test_absolute_path_outside_root_returns_none(self, tmp_path):+ """Absolute paths outside library root should return None."""+ from local_deep_research.research_library.utils import (+ get_absolute_library_path,+ )++ with patch(+ "local_deep_research.research_library.utils.get_library_storage_path"+ ) as mock_storage:+ mock_storage.return_value = tmp_path++ result = get_absolute_library_path("/etc/passwd", "testuser")++ assert result is None++ def test_empty_path_returns_none(self, tmp_path):+ """Empty path should return None."""+ from local_deep_research.research_library.utils import (+ get_absolute_library_path,+ )++ with patch(+ "local_deep_research.research_library.utils.get_library_storage_path"+ ) as mock_storage:+ mock_storage.return_value = tmp_path++ result = get_absolute_library_path("", "testuser")++ assert result is None++ def test_nested_valid_path_returns_correct_path(self, tmp_path):+ """Deeply nested valid paths should work correctly."""+ from local_deep_research.research_library.utils import (+ get_absolute_library_path,+ )++ with patch(+ "local_deep_research.research_library.utils.get_library_storage_path"+ ) as mock_storage:+ mock_storage.return_value = tmp_path++ result = get_absolute_library_path(+ "pdfs/2024/01/document.pdf", "testuser"+ )++ assert result is not None+ assert result == tmp_path / "pdfs/2024/01/document.pdf"+++class TestGetAbsolutePathFromSettings:+ """Tests for get_absolute_path_from_settings function."""++ def test_valid_relative_path_returns_absolute_path(self, tmp_path):+ """Valid relative paths should return absolute paths."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ result = get_absolute_path_from_settings("pdfs/test.pdf")++ assert result is not None+ assert result == tmp_path / "pdfs/test.pdf"++ def test_empty_path_returns_library_root(self, tmp_path):+ """Empty path should return the library root."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ result = get_absolute_path_from_settings("")++ assert result is not None+ assert result == tmp_path++ def test_path_traversal_returns_none(self, tmp_path):+ """Path traversal attempts should return None."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ traversal_paths = [+ "../../../etc/passwd",+ "pdfs/../../secret.txt",+ ]++ for path in traversal_paths:+ result = get_absolute_path_from_settings(path)+ assert result is None, f"Path '{path}' should have been blocked"+++class TestLibraryServiceSafeAbsolutePath:+ """Tests for LibraryService._get_safe_absolute_path method."""++ def test_metadata_only_returns_none(self):+ """metadata_only marker should return None."""+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ service = LibraryService("testuser")++ result = service._get_safe_absolute_path("metadata_only")++ assert result is None++ def test_text_only_not_stored_returns_none(self):+ """text_only_not_stored marker should return None."""+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ service = LibraryService("testuser")++ result = service._get_safe_absolute_path("text_only_not_stored")++ assert result is None++ def test_empty_path_returns_none(self):+ """Empty path should return None."""+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ service = LibraryService("testuser")++ result = service._get_safe_absolute_path("")++ assert result is None++ def test_none_path_returns_none(self):+ """None path should return None."""+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ service = LibraryService("testuser")++ result = service._get_safe_absolute_path(None)++ assert result is None++ def test_valid_path_returns_string(self, tmp_path):+ """Valid paths should return a string."""+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ service = LibraryService("testuser")++ result = service._get_safe_absolute_path("pdfs/test.pdf")++ assert result is not None+ assert isinstance(result, str)+ assert result == str(tmp_path / "pdfs/test.pdf")++ def test_path_traversal_returns_none(self, tmp_path):+ """Path traversal attempts should return None."""+ from local_deep_research.research_library.services.library_service import (+ LibraryService,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ service = LibraryService("testuser")++ result = service._get_safe_absolute_path("../../../etc/passwd")++ assert result is None+++class TestPDFStorageManagerSafeFilePath:+ """Tests for PDFStorageManager._get_safe_file_path method."""++ def test_valid_path_returns_path_object(self, tmp_path):+ """Valid relative paths should return Path objects."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="filesystem",+ )++ result = manager._get_safe_file_path("pdfs/test.pdf")++ assert result is not None+ assert isinstance(result, Path)+ assert result == tmp_path / "pdfs/test.pdf"++ def test_metadata_only_returns_none(self, tmp_path):+ """metadata_only marker should return None."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="filesystem",+ )++ result = manager._get_safe_file_path("metadata_only")++ assert result is None++ def test_text_only_not_stored_returns_none(self, tmp_path):+ """text_only_not_stored marker should return None."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="filesystem",+ )++ result = manager._get_safe_file_path("text_only_not_stored")++ assert result is None++ def test_empty_path_returns_none(self, tmp_path):+ """Empty path should return None."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="filesystem",+ )++ result = manager._get_safe_file_path("")++ assert result is None++ def test_path_traversal_returns_none(self, tmp_path):+ """Path traversal attempts should return None."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="filesystem",+ )++ traversal_paths = [+ "../../../etc/passwd",+ "pdfs/../../secret.txt",+ ]++ for path in traversal_paths:+ result = manager._get_safe_file_path(path)+ assert result is None, f"Path '{path}' should have been blocked"++ def test_none_path_returns_none(self, tmp_path):+ """None path should return None."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="filesystem",+ )++ result = manager._get_safe_file_path(None)++ assert result is None+++class TestPathTraversalIntegration:+ """Integration tests for path traversal protection across components."""++ def test_malicious_document_file_path_blocked_in_has_pdf(self, tmp_path):+ """PDFStorageManager.has_pdf should handle malicious paths safely."""+ from unittest.mock import patch++ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="filesystem",+ )++ # Create a mock document with malicious file_path+ mock_doc = Mock()+ mock_doc.file_type = "pdf"+ mock_doc.file_path = "../../../etc/passwd"++ mock_session = Mock()+ mock_session.query.return_value.filter_by.return_value.first.return_value = None++ # Patch DocumentBlob so its .id attribute is accessible outside SQLAlchemy+ mock_blob_class = Mock()+ with patch(+ "local_deep_research.database.models.library.DocumentBlob",+ mock_blob_class,+ ):+ # Should not raise an error, just return False+ result = manager.has_pdf(mock_doc, mock_session)++ assert result is False++ def test_malicious_document_file_path_blocked_in_load(self, tmp_path):+ """PDFStorageManager._load_from_filesystem should handle malicious paths."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="filesystem",+ )++ # Create a mock document with malicious file_path+ mock_doc = Mock()+ mock_doc.file_path = "../../../etc/passwd"++ # Should return None, not raise or attempt to read /etc/passwd+ result = manager._load_from_filesystem(mock_doc)++ assert result is None++ def test_malicious_document_file_path_blocked_in_delete(self, tmp_path):+ """PDFStorageManager.delete_pdf should handle malicious paths safely."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ manager = PDFStorageManager(+ library_root=tmp_path,+ storage_mode="filesystem",+ )++ # Create a mock document with malicious file_path+ mock_doc = Mock()+ mock_doc.file_path = "../../../etc/passwd"+ mock_doc.storage_mode = "filesystem"++ mock_session = Mock()+ mock_session.query.return_value.filter_by.return_value.first.return_value = None++ # Should not raise an error or delete /etc/passwd+ result = manager.delete_pdf(mock_doc, mock_session)++ # Should return True (successful "deletion" since there was nothing to delete)+ # The important thing is it doesn't try to delete outside the library+ assert result is True++ def test_is_already_downloaded_handles_malicious_path(self, tmp_path):+ """DownloadService.is_already_downloaded should not crash on malicious paths."""+ from local_deep_research.research_library.services.download_service import (+ DownloadService,+ )+ from local_deep_research.database.models.download_tracker import (+ DownloadTracker,+ )++ # Create a mock tracker with malicious file_path+ mock_tracker = Mock(spec=DownloadTracker)+ mock_tracker.file_path = "../../../etc/passwd"+ mock_tracker.is_downloaded = True++ mock_session = Mock()+ mock_session.query.return_value.filter_by.return_value.first.return_value = mock_tracker++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with (+ patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ),+ patch(+ "local_deep_research.research_library.services.download_service.get_user_db_session"+ ) as mock_db_session,+ ):+ # Make the context manager return our mock session+ mock_db_session.return_value.__enter__ = Mock(+ return_value=mock_session+ )+ mock_db_session.return_value.__exit__ = Mock(return_value=False)++ service = DownloadService.__new__(DownloadService)+ service.username = "testuser"+ service.password = None++ # Should not raise AttributeError on None.exists()+ # Should return (False, None) because path traversal is blocked+ result = service.is_already_downloaded(+ "https://example.com/doc.pdf"+ )++ assert result == (False, None)+++class TestPathTraversalAttackVectors:+ """Test various path traversal attack vectors are blocked."""++ def test_simple_dotdot_traversal(self, tmp_path):+ """Basic ../ traversal should be blocked."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ attacks = [+ "../secret.txt",+ "../../secret.txt",+ "../../../etc/passwd",+ "../../../../etc/shadow",+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ assert result is None, f"Attack '{attack}' should be blocked"++ def test_nested_traversal_escaping_root(self, tmp_path):+ """Traversal that escapes library root should be blocked."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # These paths escape the library root+ attacks = [+ "pdfs/../../../etc/passwd",+ "documents/subfolder/../../../../../../tmp/evil",+ "a/b/c/d/../../../../../../../../etc/passwd",+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ assert result is None, f"Attack '{attack}' should be blocked"++ def test_traversal_staying_in_root_is_allowed(self, tmp_path):+ """Traversal that stays within library root should be allowed."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # This path uses .. but stays within library root+ # valid/path/to/../../../outside resolves to "outside" which is in root+ result = get_absolute_path_from_settings(+ "valid/path/to/../../../outside"+ )+ # This is actually safe - resolves to tmp_path/outside+ assert result is not None+ assert result == tmp_path / "outside"++ def test_absolute_path_injection(self, tmp_path):+ """Absolute paths should be blocked."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ attacks = [+ "/etc/passwd",+ "/etc/shadow",+ "/root/.ssh/id_rsa",+ "/var/log/auth.log",+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ assert result is None, f"Attack '{attack}' should be blocked"++ def test_dot_current_dir_traversal(self, tmp_path):+ """Traversal using ./ patterns should be blocked when escaping."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ attacks = [+ "./../../../etc/passwd",+ "./././../../../etc/passwd",+ "././../secret.txt",+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ assert result is None, f"Attack '{attack}' should be blocked"++ def test_double_slash_traversal(self, tmp_path):+ """Double slashes with traversal should be handled."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # These should be blocked due to .. patterns+ attacks = [+ "..//..//etc/passwd",+ "pdfs//..//..//secret.txt",+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ assert result is None, f"Attack '{attack}' should be blocked"++ def test_backslash_traversal_windows_style(self, tmp_path):+ """Windows-style backslash traversal - safe on Linux, blocked on Windows.++ On Linux, backslashes are valid filename characters, not path separators.+ So '..\\..\\etc\\passwd' is treated as a literal filename, which is safe.+ On Windows, werkzeug's safe_join would block these.+ """+ import sys++ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ attacks = [+ "..\\..\\..\\etc\\passwd",+ "..\\..\\windows\\win.ini",+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ if sys.platform == "win32":+ # On Windows, these should be blocked+ assert result is None, (+ f"Attack '{attack}' should be blocked"+ )+ else:+ # On Linux, backslashes are literal - path stays in library+ if result is not None:+ assert str(tmp_path) in str(result)++ def test_mixed_slash_with_real_traversal(self, tmp_path):+ """Mixed slash patterns with real .. traversal should be blocked."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # These contain real forward-slash traversal that escapes root+ attacks = [+ "pdfs/../../../etc/passwd",+ "subdir/../../../../../../etc/passwd",+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ assert result is None, f"Attack '{attack}' should be blocked"++ def test_mangled_patterns_stay_in_library(self, tmp_path):+ """Mangled patterns like '..../' don't escape library.++ Pattern '....' is treated as a literal directory name, not traversal.+ These patterns are safe because they stay within the library root.+ """+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # These don't actually traverse - '....' is a literal dirname+ patterns = [+ "....//....//file.pdf",+ "..../file.pdf",+ ]+ for pattern in patterns:+ result = get_absolute_path_from_settings(pattern)+ # These are allowed because they stay in library+ if result is not None:+ assert str(tmp_path) in str(result)++ def test_null_byte_injection(self, tmp_path):+ """Null byte injection should be blocked or handled safely.++ Null bytes (%00) can truncate paths in some languages (PHP < 5.3.4).+ While Python handles this better, we should still test it.+ """+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # Null byte injection patterns+ attacks = [+ "../../../etc/passwd\x00.pdf",+ "pdfs/test.pdf\x00/../../../etc/passwd",+ "../../../etc/passwd%00.pdf", # URL-encoded null (if decoded)+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ assert result is None, (+ f"Null byte attack '{attack!r}' should be blocked"+ )++ def test_unc_path_injection_windows(self, tmp_path):+ """UNC paths (Windows network shares) should be blocked.++ UNC paths like \\\\server\\share can be used for SSRF or credential theft.+ """+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # UNC path patterns+ attacks = [+ "\\\\attacker.com\\share\\malicious.pdf",+ "\\\\localhost\\c$\\windows\\win.ini",+ "//attacker.com/share/file.pdf",+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ # Should be blocked or stay within library+ if result is not None:+ assert str(tmp_path) in str(result), (+ f"Attack '{attack}' resulted in path outside library"+ )++ def test_dot_segment_variations(self, tmp_path):+ """Various dot segment patterns should be handled.++ Tests patterns like '...' and '....' which some systems mishandle.+ """+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # Various dot patterns+ attacks = [+ ".../.../.../etc/passwd",+ "..../..../etc/passwd",+ "..;/..;/..;/etc/passwd", # Tomcat bypass+ ]+ for attack in attacks:+ result = get_absolute_path_from_settings(attack)+ # These are unusual patterns - should either be blocked or safe+ if result is not None:+ assert str(tmp_path) in str(result), (+ f"Attack '{attack}' resulted in path outside library"+ )+++class TestPathTraversalEdgeCases:+ """Test edge cases and boundary conditions."""++ def test_whitespace_paths(self, tmp_path):+ """Paths with only whitespace should be handled."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # Whitespace-only paths should return None or be sanitized+ whitespace_paths = [" ", "\t", "\n", " \t\n "]+ for path in whitespace_paths:+ result = get_absolute_path_from_settings(path)+ # After strip(), these become empty, which should return library_root+ # or None depending on implementation+ assert result is None or result == tmp_path++ def test_path_with_spaces(self, tmp_path):+ """Valid paths with spaces should work."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ result = get_absolute_path_from_settings("pdfs/my document.pdf")+ assert result is not None+ assert result == tmp_path / "pdfs/my document.pdf"++ def test_path_with_special_characters(self, tmp_path):+ """Paths with allowed special characters should work."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # Valid special characters+ valid_paths = [+ "pdfs/test-file.pdf",+ "pdfs/test_file.pdf",+ "pdfs/test.file.pdf",+ ]+ for path in valid_paths:+ result = get_absolute_path_from_settings(path)+ assert result is not None, f"Path '{path}' should be allowed"+ assert result == tmp_path / path++ def test_very_long_path(self, tmp_path):+ """Very long paths should be handled without crashing."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # Create a very long but valid path+ long_path = "/".join(["subdir"] * 50) + "/file.pdf"+ result = get_absolute_path_from_settings(long_path)+ # Should either work or fail gracefully (no crash)+ assert result is None or isinstance(result, Path)++ def test_unicode_path(self, tmp_path):+ """Unicode paths should be handled."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_settings = Mock()+ mock_settings.get_setting.return_value = str(tmp_path)++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=mock_settings,+ ):+ # Unicode filenames are common+ unicode_paths = [+ "pdfs/документ.pdf", # Russian+ "pdfs/文档.pdf", # Chinese+ "pdfs/ドキュメント.pdf", # Japanese+ ]+ for path in unicode_paths:+ # Should not crash - just verify no exception is raised+ _ = get_absolute_path_from_settings(path)+ # Result depends on filesystem support+++class TestCascadeHelperPathSafety:+ """Test CascadeHelper path handling."""++ def test_delete_filesystem_file_rejects_special_markers(self):+ """CascadeHelper should reject special path markers."""+ from local_deep_research.research_library.deletion.utils.cascade_helper import (+ CascadeHelper,+ )++ markers = ["metadata_only", "text_only_not_stored", "blob_deleted"]+ for marker in markers:+ result = CascadeHelper.delete_filesystem_file(marker)+ assert result is False, f"Marker '{marker}' should be rejected"++ def test_delete_filesystem_file_handles_none(self):+ """CascadeHelper should handle None path."""+ from local_deep_research.research_library.deletion.utils.cascade_helper import (+ CascadeHelper,+ )++ result = CascadeHelper.delete_filesystem_file(None)+ assert result is False++ def test_delete_filesystem_file_handles_empty_string(self):+ """CascadeHelper should handle empty string path."""+ from local_deep_research.research_library.deletion.utils.cascade_helper import (+ CascadeHelper,+ )++ result = CascadeHelper.delete_filesystem_file("")+ assert result is False++ def test_delete_filesystem_file_nonexistent_returns_false(self, tmp_path):+ """CascadeHelper should return False for nonexistent files."""+ from local_deep_research.research_library.deletion.utils.cascade_helper import (+ CascadeHelper,+ )++ result = CascadeHelper.delete_filesystem_file(+ str(tmp_path / "nonexistent.pdf")+ )+ assert result is False++ def test_delete_filesystem_file_deletes_valid_file(self, tmp_path):+ """CascadeHelper should delete valid files."""+ from local_deep_research.research_library.deletion.utils.cascade_helper import (+ CascadeHelper,+ )++ # Create a test file+ test_file = tmp_path / "test.pdf"+ test_file.write_text("test content")+ assert test_file.exists()++ result = CascadeHelper.delete_filesystem_file(str(test_file))++ assert result is True+ assert not test_file.exists()diff --git a/tests/security/test_pdf_path_traversal.py b/tests/security/test_pdf_path_traversal.pynew file mode 100644index 0000000000..5fa1794a44--- /dev/null+++ b/tests/security/test_pdf_path_traversal.py@@ -0,0 +1,129 @@+"""Tests for path traversal protection in PDF storage manager (PR #1890).++Verifies:+- _get_safe_file_path blocks traversal, symlinks, and sentinel values+- library_root is resolved on init+- get_absolute_path_from_settings validates resolved paths+"""++import pytest+from pathlib import Path+from unittest.mock import MagicMock, patch++from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+)+++class TestValidateFilesystemPath:+ """Test _get_safe_file_path blocks unsafe paths."""++ def setup_method(self):+ self.tmp = Path("/tmp/test_pdf_library")+ self.tmp.mkdir(exist_ok=True)+ self.manager = PDFStorageManager(+ library_root=str(self.tmp), storage_mode="filesystem"+ )++ def test_traversal_blocked(self):+ """Path with .. escaping library root returns None."""+ result = self.manager._get_safe_file_path("../../etc/passwd")+ assert result is None++ def test_valid_relative_path(self):+ """Valid relative path inside library root returns resolved Path."""+ sub = self.tmp / "docs"+ sub.mkdir(exist_ok=True)+ test_file = sub / "paper.pdf"+ test_file.write_text("pdf content")++ result = self.manager._get_safe_file_path("docs/paper.pdf")+ assert result is not None+ assert result.is_relative_to(self.tmp)++ def test_metadata_only_returns_none(self):+ result = self.manager._get_safe_file_path("metadata_only")+ assert result is None++ def test_text_only_returns_none(self):+ result = self.manager._get_safe_file_path("text_only_not_stored")+ assert result is None++ def test_empty_string_returns_none(self):+ result = self.manager._get_safe_file_path("")+ assert result is None++ def test_none_returns_none(self):+ result = self.manager._get_safe_file_path(None)+ assert result is None++ def test_symlink_blocked(self, tmp_path):+ """Symlinks are blocked before resolve() dereferences them."""+ manager = PDFStorageManager(+ library_root=str(tmp_path), storage_mode="filesystem"+ )++ # Create a symlink pointing outside library root+ link_path = tmp_path / "evil_link"+ try:+ link_path.symlink_to("/etc/passwd")+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")++ result = manager._get_safe_file_path("evil_link")+ assert result is None+++class TestLibraryRootResolved:+ """Verify library_root is resolved on init (prevents late traversal)."""++ def test_library_root_is_resolved(self, tmp_path):+ """library_root should be an absolute resolved path."""+ manager = PDFStorageManager(+ library_root=str(tmp_path), storage_mode="filesystem"+ )+ assert manager.library_root == tmp_path.resolve()+ assert manager.library_root.is_absolute()+++class TestGetAbsolutePathFromSettings:+ """Test path traversal protection in get_absolute_path_from_settings."""++ @patch("local_deep_research.utilities.db_utils.get_settings_manager")+ def test_traversal_returns_none(self, mock_settings_mgr, tmp_path):+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_mgr = MagicMock()+ mock_mgr.get_setting.return_value = str(tmp_path)+ mock_settings_mgr.return_value = mock_mgr++ result = get_absolute_path_from_settings("../../etc/passwd")+ assert result is None++ @patch("local_deep_research.utilities.db_utils.get_settings_manager")+ def test_valid_path_returns_resolved(self, mock_settings_mgr, tmp_path):+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_mgr = MagicMock()+ mock_mgr.get_setting.return_value = str(tmp_path)+ mock_settings_mgr.return_value = mock_mgr++ result = get_absolute_path_from_settings("docs/file.pdf")+ assert result.is_relative_to(tmp_path.resolve())++ @patch("local_deep_research.utilities.db_utils.get_settings_manager")+ def test_empty_path_returns_library_root(self, mock_settings_mgr, tmp_path):+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ mock_mgr = MagicMock()+ mock_mgr.get_setting.return_value = str(tmp_path)+ mock_settings_mgr.return_value = mock_mgr++ result = get_absolute_path_from_settings("")+ assert result == tmp_path.resolve()