~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
fix(security): centralize filename sanitization in security module (#3236)
LearningCircuit3ec02cb294c4
diff --git a/src/local_deep_research/document_loaders/bytes_loader.py b/src/local_deep_research/document_loaders/bytes_loader.pyindex 3ea471b424..ecb961ab98 100644--- a/src/local_deep_research/document_loaders/bytes_loader.py+++ b/src/local_deep_research/document_loaders/bytes_loader.py@@ -12,6 +12,8 @@ from typing import Optionalfrom langchain_core.documents import Documentfrom loguru import logger+from local_deep_research.security.filename_sanitizer import sanitize_filename+from .loader_registry import (get_loader_class_for_extension,is_extension_supported,@@ -42,6 +44,13 @@ def load_from_bytes(Raises:ValueError: If the extension is not supported"""+ # Defense in depth: re-sanitize filename even though callers+ # should have sanitized already+ try:+ filename = sanitize_filename(filename)+ except Exception:+ filename = "upload"+# Normalize extensionext = (extension.lower()diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 365cc0a399..18215cea2d 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -1356,7 +1356,7 @@ def delete_collection(collection_id):def upload_to_collection(collection_id):"""Upload files to a collection."""from ...database.session_context import get_user_db_session- from werkzeug.utils import secure_filename+ from ...security import sanitize_filename, UnsafeFilenameErrorfrom pathlib import Pathimport hashlibimport uuid@@ -1423,6 +1423,17 @@ def upload_to_collection(collection_id):if not file.filename:continue+ try:+ filename = sanitize_filename(file.filename)+ except UnsafeFilenameError:+ errors.append(+ {+ "filename": "rejected",+ "error": "Invalid or unsafe filename",+ }+ )+ continue+try:# Read file contentfile_content = file.read()@@ -1500,7 +1511,6 @@ def upload_to_collection(collection_id):is_extension_supported,)- filename = secure_filename(file.filename)file_extension = Path(filename).suffix.lower()# Validate extension is supported before extraction@@ -1648,11 +1658,11 @@ def upload_to_collection(collection_id):except Exception:errors.append({- "filename": file.filename,+ "filename": filename,"error": "Failed to upload file",})- logger.exception(f"Error uploading file {file.filename}")+ logger.exception(f"Error uploading file {filename}")db_session.commit()diff --git a/src/local_deep_research/security/__init__.py b/src/local_deep_research/security/__init__.pyindex cbe5f2e850..9d366ff792 100644--- a/src/local_deep_research/security/__init__.py+++ b/src/local_deep_research/security/__init__.py@@ -20,6 +20,7 @@ from .url_validator import URLValidatorfrom .account_lockout import AccountLockoutManager, get_account_lockout_managerfrom .password_validator import PasswordValidatorfrom .log_sanitizer import sanitize_for_log, strip_control_chars+from .filename_sanitizer import sanitize_filename, UnsafeFilenameErrorfrom .module_whitelist import (get_safe_module_class,ModuleNotAllowedError,@@ -73,4 +74,6 @@ __all__ = ["PasswordValidator","sanitize_for_log","strip_control_chars",+ "sanitize_filename",+ "UnsafeFilenameError",]diff --git a/src/local_deep_research/security/filename_sanitizer.py b/src/local_deep_research/security/filename_sanitizer.pynew file mode 100644index 0000000000..91f3a36797--- /dev/null+++ b/src/local_deep_research/security/filename_sanitizer.py@@ -0,0 +1,77 @@+"""Filename sanitization for file uploads.++Wraps werkzeug's secure_filename with additional safety checks.+All file upload endpoints should use sanitize_filename() instead of+importing secure_filename directly.+"""++from __future__ import annotations++from typing import Optional++from werkzeug.utils import secure_filename++# Maximum filename length (including extension)+MAX_FILENAME_LENGTH = 255+++class UnsafeFilenameError(ValueError):+ """Raised when a filename cannot be sanitized to a safe value."""+++def sanitize_filename(+ filename: Optional[str],+ *,+ allowed_extensions: Optional[set[str]] = None,+ max_length: int = MAX_FILENAME_LENGTH,+) -> str:+ """Sanitize an uploaded filename for safe filesystem storage.++ Args:+ filename: Raw filename from the upload.+ allowed_extensions: Optional set of allowed extensions+ (lowercase, with dot, e.g. {".pdf", ".txt"}).+ If None, all extensions are allowed.+ max_length: Maximum allowed filename length.++ Returns:+ Sanitized filename safe for filesystem use.++ Raises:+ UnsafeFilenameError: If the filename is empty, becomes empty+ after sanitization, or has a disallowed extension.+ """+ if not filename:+ raise UnsafeFilenameError("No filename provided")++ # Strip null bytes before passing to secure_filename+ cleaned = filename.replace("\x00", "")++ # Apply werkzeug's path traversal protection+ safe_name = secure_filename(cleaned)++ if not safe_name:+ raise UnsafeFilenameError(+ "Filename contains no safe characters after sanitization"+ )++ # Enforce length limit+ if len(safe_name) > max_length:+ # Preserve extension when truncating+ dot_idx = safe_name.rfind(".")+ if dot_idx > 0:+ ext = safe_name[dot_idx:]+ safe_name = safe_name[: max_length - len(ext)] + ext+ else:+ safe_name = safe_name[:max_length]++ # Validate extension if allowlist provided+ if allowed_extensions is not None:+ dot_idx = safe_name.rfind(".")+ ext = safe_name[dot_idx:].lower() if dot_idx > 0 else ""+ # Normalize allowlist for case-insensitive comparison+ normalized = {e.lower() for e in allowed_extensions}+ if ext not in normalized:+ raise UnsafeFilenameError("File type not allowed")++ return safe_namediff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex e580474abd..78aecc10f5 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -22,7 +22,9 @@ from ...config.constants import DEFAULT_OLLAMA_URLfrom ...constants import ResearchStatusfrom ...security import (FileUploadValidator,+ UnsafeFilenameError,filter_research_metadata,+ sanitize_filename,strip_settings_snapshot,)from ...security.rate_limiter import (@@ -1582,24 +1584,32 @@ def upload_pdf():errors.append("Unnamed file: Skipped")continue+ try:+ filename = sanitize_filename(+ file.filename, allowed_extensions={".pdf"}+ )+ except UnsafeFilenameError:+ errors.append("Rejected file: invalid or disallowed filename")+ continue+try:# Read file content (with disk spooling, large files are read from temp file)pdf_content = file.read()# Comprehensive validationis_valid, error_msg = FileUploadValidator.validate_upload(- filename=file.filename,+ filename=filename,file_content=pdf_content,content_length=file.content_length,)if not is_valid:- errors.append(f"{file.filename}: {error_msg}")+ errors.append(f"{filename}: {error_msg}")continue# Extract text and metadata in single pass (performance fix)result = pdf_service.extract_text_and_metadata(- pdf_content, file.filename+ pdf_content, filename)if result["success"]:@@ -1613,11 +1623,11 @@ def upload_pdf():)processed_files += 1else:- errors.append(f"{file.filename}: {result['error']}")+ errors.append(f"{filename}: {result['error']}")except Exception:- logger.exception(f"Error processing {file.filename}")- errors.append(f"{file.filename}: Error processing file")+ logger.exception(f"Error processing {filename}")+ errors.append(f"{filename}: Error processing file")finally:# Close the file stream to release resourcestry:diff --git a/src/local_deep_research/web/services/pdf_extraction_service.py b/src/local_deep_research/web/services/pdf_extraction_service.pyindex 283bd08569..42e6897119 100644--- a/src/local_deep_research/web/services/pdf_extraction_service.py+++ b/src/local_deep_research/web/services/pdf_extraction_service.py@@ -11,6 +11,8 @@ from typing import Any, Dict, Listimport pdfplumberfrom loguru import logger+from local_deep_research.security.filename_sanitizer import sanitize_filename+class PDFExtractionService:"""Service for extracting text and metadata from PDF files."""@@ -42,6 +44,13 @@ class PDFExtractionService:Raises:No exceptions - errors are captured in return dict"""+ # Defense in depth: re-sanitize even though callers should+ # have sanitized already — guards against new callers that forget+ try:+ filename = sanitize_filename(filename)+ except Exception:+ filename = "unnamed.pdf"+try:with pdfplumber.open(io.BytesIO(pdf_content)) as pdf:# Get pages list oncediff --git a/tests/security/test_filename_sanitizer.py b/tests/security/test_filename_sanitizer.pynew file mode 100644index 0000000000..23c3ed1464--- /dev/null+++ b/tests/security/test_filename_sanitizer.py@@ -0,0 +1,69 @@+"""Tests for filename sanitization."""++import pytest++from local_deep_research.security.filename_sanitizer import (+ UnsafeFilenameError,+ sanitize_filename,+)+++class TestSanitizeFilename:+ """Tests for sanitize_filename()."""++ def test_normal_filename(self):+ assert sanitize_filename("report.pdf") == "report.pdf"++ def test_path_traversal(self):+ result = sanitize_filename("../../etc/passwd.pdf")+ assert ".." not in result+ assert result == "etc_passwd.pdf"++ def test_null_bytes_stripped(self):+ result = sanitize_filename("file\x00name.pdf")+ assert "\x00" not in result+ assert result == "filename.pdf"++ def test_empty_filename_raises(self):+ with pytest.raises(UnsafeFilenameError, match="No filename"):+ sanitize_filename("")++ def test_none_filename_raises(self):+ with pytest.raises(UnsafeFilenameError, match="No filename"):+ sanitize_filename(None)++ def test_sanitizes_to_empty_raises(self):+ with pytest.raises(UnsafeFilenameError, match="no safe characters"):+ sanitize_filename("../../../")++ def test_allowed_extensions_pass(self):+ result = sanitize_filename("doc.pdf", allowed_extensions={".pdf"})+ assert result == "doc.pdf"++ def test_disallowed_extension_raises(self):+ with pytest.raises(UnsafeFilenameError, match="not allowed"):+ sanitize_filename("script.exe", allowed_extensions={".pdf", ".txt"})++ def test_extension_check_case_insensitive(self):+ result = sanitize_filename("doc.PDF", allowed_extensions={".pdf"})+ assert result == "doc.PDF"++ def test_max_length_truncates(self):+ long_name = "a" * 300 + ".pdf"+ result = sanitize_filename(long_name, max_length=50)+ assert len(result) <= 50+ assert result.endswith(".pdf")++ def test_max_length_no_extension(self):+ long_name = "a" * 300+ result = sanitize_filename(long_name, max_length=50)+ assert len(result) <= 50++ def test_spaces_in_filename(self):+ result = sanitize_filename("my report file.pdf")+ assert result == "my_report_file.pdf"++ def test_special_characters(self):+ result = sanitize_filename("file@#$%.pdf")+ assert result # should not be empty+ assert ".." not in result