~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: round 4 remaining hardening fixes (#3135)
LearningCircuitc8855be731ce
diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex dbbab3e02f..4223bb9704 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -62,6 +62,31 @@ class DatabaseInitializationError(Exception):"""+def _best_effort_chmod(path, mode: int, *, warn: bool = False) -> None:+ """Tighten permissions on ``path`` to ``mode``, never raising.++ Permission hardening must NOT be able to break database creation. On+ filesystems that don't support POSIX chmod — some Docker bind mounts and+ network/FUSE volumes, notably Docker Desktop on macOS/Windows — os.chmod+ can raise OSError even for the file's owner. In that case we leave the+ path at its default (umask) mode rather than failing registration/login.++ ``warn=True`` surfaces the failure at warning level: a silent downgrade+ leaves the path group/world-readable, which matters for DB files holding+ user data (the unencrypted fallback is plaintext). The owner-only+ directory chmod is defense-in-depth, so it stays at debug.+ """+ try:+ os.chmod(str(path), mode)+ except OSError:+ log = logger.warning if warn else logger.debug+ log(+ f"Could not set permissions {oct(mode)} on {path}; "+ "left at filesystem default",+ exc_info=True,+ )++class DatabaseManager:"""Manages encrypted SQLCipher databases for each user."""@@ -75,6 +100,13 @@ class DatabaseManager:self._init_locks: Dict[str, threading.Lock] = {}self.data_dir = get_data_directory() / "encrypted_databases"self.data_dir.mkdir(parents=True, exist_ok=True)+ # Restrict the per-user DB directory to the owner (0o700). Belt-and-+ # suspenders with the per-file 0o600 chmod: it also covers SQLite's+ # WAL/SHM sidecars and any temp files (which the unencrypted fallback+ # writes in PLAINTEXT and which SQLite may recreate at umask perms on+ # each connect), so no sibling-readable user data is exposed to other+ # local accounts regardless of per-file modes.+ _best_effort_chmod(self.data_dir, 0o700)# Check SQLCipher availabilityself.has_encryption = self._check_encryption_available()@@ -413,6 +445,7 @@ class DatabaseManager:"check_same_thread": False,},)+ _best_effort_chmod(db_path, 0o600, warn=True)try:# Get the CREATE TABLE statements from SQLAlchemy modelsfrom sqlalchemy.dialects import sqlite@@ -561,6 +594,16 @@ class DatabaseManager:db_path.unlink(missing_ok=True)raise+ # Restrict DB file to owner-only (0o600). The encrypted branch+ # chmod's right after create_sqlcipher_connection, but the+ # unencrypted fallback creates the file lazily on first connect+ # (during initialize_database above), so it is only guaranteed to+ # exist here. This file holds PLAINTEXT user data — leaving it at+ # umask-default perms (commonly 0o644) would expose it to other+ # local accounts.+ if not self.has_encryption and db_path.exists():+ _best_effort_chmod(db_path, 0o600, warn=True)+# Store connection AFTER migrations completewith self._connections_lock:self.connections[username] = enginediff --git a/src/local_deep_research/news/flask_api.py b/src/local_deep_research/news/flask_api.pyindex bd8627c7a5..4babcc63d4 100644--- a/src/local_deep_research/news/flask_api.py+++ b/src/local_deep_research/news/flask_api.py@@ -19,6 +19,13 @@ from ..security import safe_postfrom ..llm.providers.base import normalize_providerfrom ..security.decorators import require_json_body+# Hard ceiling for user-supplied ``limit`` query params on the news+# endpoints in this module. Matches the ``max_value`` of the+# ``news.feed.default_limit`` setting so a direct API caller cannot request a+# larger page than the UI can configure. Shared by the feed and+# subscription-history endpoints here so their caps stay in lockstep.+NEWS_FEED_MAX_LIMIT = 100+def scheduler_control_required(f):"""Decorator that gates global scheduler control behind a setting.@@ -141,6 +148,7 @@ def get_news_feed() -> Any:settings_manager = get_settings_manager()default_limit = settings_manager.get_setting("news.feed.default_limit")limit = int(request.args.get("limit", default_limit))+ limit = max(1, min(limit, NEWS_FEED_MAX_LIMIT))use_cache = request.args.get("use_cache", "true").lower() == "true"strategy = request.args.get("strategy")focus = request.args.get("focus")@@ -668,6 +676,7 @@ def get_subscription_history(subscription_id: str) -> Any:settings_manager = get_settings_manager()default_limit = settings_manager.get_setting("news.feed.default_limit")limit = int(request.args.get("limit", default_limit))+ limit = max(1, min(limit, NEWS_FEED_MAX_LIMIT))result = api.get_subscription_history(subscription_id, limit)if "error" in result:logger.error(diff --git a/src/local_deep_research/research_library/routes/library_routes.py b/src/local_deep_research/research_library/routes/library_routes.pyindex 23df1edda1..a73c5c3993 100644--- a/src/local_deep_research/research_library/routes/library_routes.py+++ b/src/local_deep_research/research_library/routes/library_routes.py@@ -1266,7 +1266,6 @@ def check_downloads():download_status[resource.url] = {"downloaded": True,"document_id": document.id,- "file_path": document.file_path,"file_type": document.file_type,"title": document.title or resource.title,}diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.pyindex 95771c047f..61a287d330 100644--- a/src/local_deep_research/web/routes/research_routes.py+++ b/src/local_deep_research/web/routes/research_routes.py@@ -31,6 +31,7 @@ from ...security import ()from ...utilities.url_utils import is_safe_custom_llm_endpointfrom ...security.rate_limiter import (+ api_rate_limit,upload_rate_limit_ip,upload_rate_limit_user,)@@ -444,6 +445,7 @@ def _queue_research(@research_bp.route("/api/start_research", methods=["POST"])@login_required+@api_rate_limit@require_json_body(error_format="status")def start_research():data = request.jsondiff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex 40a1e3a4bb..7a752f1bc6 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -2423,6 +2423,15 @@ def run_research_process(research_id, query, mode, **kwargs):error_context = {"solution": "The provider rate-limited the request. Wait a moment and retry, or enable LLM Rate Limiting in Settings."}+ elif "LLM Configuration Error:" in user_friendly_error:+ # Surface the raw config detail to the operator (which model+ # path / .gguf / endpoint is misconfigured) rather than hiding+ # it behind a generic message: this is a self-hosted tool, so+ # the operator needs the specifics to fix their own setup.+ # Keep ``user_friendly_error`` as-is and just attach a hint.+ error_context = {+ "solution": "Review your LLM model settings and ensure they are correct."+ }# Generate enhanced error report for failed researchenhanced_report_content = Nonediff --git a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.pyindex 111d2360d7..ba8197d37e 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_ddg.py@@ -38,6 +38,7 @@ class DuckDuckGoSearchEngine(BaseSearchEngine):language: Language for content processinginclude_full_content: Whether to include full webpage content in results"""+ max_results = min(max_results, 50)# Initialize the BaseSearchEngine with LLM, max_filtered_results, and max_resultssuper().__init__(llm=llm,diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.pyindex c8dfe55d55..9c1547f4e6 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_pubmed.py@@ -621,7 +621,9 @@ The default assumption should be that medical and scientific queries want RECENT"db": "pubmed","term": query,"retmode": "json",- "retmax": self.max_results,+ # Cap PMIDs fetched per query so a large user-supplied+ # max_results can't trigger an unbounded esearch/efetch load.+ "retmax": min(self.max_results, 100),"usehistory": "y",}diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.pyindex 038a375e52..fc86bfd797 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_searxng.py@@ -151,7 +151,7 @@ class SearXNGSearchEngine(BaseSearchEngine):logger.error(f"Failed to access SearXNG instance at {self.instance_url}. Status code: {response.status_code}")- except requests.RequestException:+ except (requests.RequestException, ValueError):self.is_available = Falselogger.exception(f"Error while trying to access SearXNG instance at {self.instance_url}"diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.pyindex 476e8fd245..16917b2136 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serpapi.py@@ -88,7 +88,11 @@ class SerpAPISearchEngine(BaseSearchEngine):"gl": region,"safe": "active" if safe_search else "off","tbs": f"qdr:{time_period}",- "num": max_results,+ # Google's "num" tops out at 100 results per request; cap so a+ # large user-supplied max_results can't request an unbounded page.+ # Use the base-class-normalized self.max_results (positive int)+ # rather than the raw arg, which could be None/str.+ "num": min(self.max_results, 100),},)diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_serper.py b/src/local_deep_research/web_search_engines/engines/search_engine_serper.pyindex a145d66e06..8f079b9121 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_serper.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_serper.py@@ -110,7 +110,9 @@ class SerperSearchEngine(BaseSearchEngine):# Build request payloadpayload = {"q": query,- "num": self.max_results,+ # Google's "num" tops out at 100 results per request; cap so a+ # large user-supplied max_results can't request an unbounded page.+ "num": min(self.max_results, 100),"gl": self.region,"hl": self.search_language,}diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.py b/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.pyindex 27ec7fe85b..74acce1371 100644--- a/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.py+++ b/src/local_deep_research/web_search_engines/engines/search_engine_zenodo.py@@ -77,7 +77,7 @@ class ZenodoSearchEngine(BaseSearchEngine):"""Build query parameters for the API request."""params = {"q": query,- "size": self.max_results,+ "size": min(self.max_results, 100),"sort": self.sort,}diff --git a/tests/database/test_db_file_permissions.py b/tests/database/test_db_file_permissions.pynew file mode 100644index 0000000000..edd3835c34--- /dev/null+++ b/tests/database/test_db_file_permissions.py@@ -0,0 +1,106 @@+"""Regression tests for DB-file permission hardening (PR #3135).++``DatabaseManager.create_user_database`` tightens the on-disk database file to+owner-only (0o600). The encrypted (SQLCipher) branch chmods right after+creating the file; the unencrypted fallback — which writes PLAINTEXT data and+is therefore the higher-risk path — chmods after ``initialize_database``+materializes the file. This test pins the unencrypted behavior, mirroring the+salt-file permission test in ``test_encryption_constants.py``.+"""++import os+import stat+from unittest.mock import patch++from tests.test_utils import add_src_to_path++add_src_to_path()+++class TestDatabaseFilePermissions:+ def test_unencrypted_db_file_has_restrictive_permissions(+ self, tmp_path, monkeypatch+ ):+ """The unencrypted-fallback DB file must be created 0o600.++ It holds plaintext user data, so leaving it at umask-default perms+ (commonly 0o644) would expose it to other local accounts.+ """+ from local_deep_research.database.encrypted_db import DatabaseManager++ monkeypatch.setenv("LDR_BOOTSTRAP_ALLOW_UNENCRYPTED", "true")++ with patch(+ "local_deep_research.database.encrypted_db.get_sqlcipher_module"+ ) as mock_get_sqlcipher:+ mock_get_sqlcipher.side_effect = ImportError(+ "No module named 'sqlcipher3'"+ )+ with patch(+ "local_deep_research.database.encrypted_db.get_data_directory",+ return_value=tmp_path,+ ):+ manager = DatabaseManager()+ assert manager.has_encryption is False, (+ "Test requires the unencrypted fallback path"+ )++ engine = manager.create_user_database(+ "permuser", "test-password-123"+ )+ try:+ db_path = manager._get_user_db_path("permuser")+ assert db_path.exists(), "DB file was not created"++ mode = stat.S_IMODE(os.stat(db_path).st_mode)+ assert mode == 0o600, (+ f"Unencrypted DB file should be 0o600, got {oct(mode)}"+ )++ # The per-user DB directory is owner-only (0o700), so the+ # plaintext WAL/SHM sidecars and any temp files SQLite may+ # create alongside the DB are not sibling-readable either.+ dir_mode = stat.S_IMODE(os.stat(manager.data_dir).st_mode)+ assert dir_mode == 0o700, (+ f"DB directory should be 0o700, got {oct(dir_mode)}"+ )+ finally:+ engine.dispose()++ def test_db_creation_survives_chmod_failure(self, tmp_path, monkeypatch):+ """Permission hardening must never break DB creation.++ On filesystems that reject POSIX chmod (some Docker bind mounts,+ network/FUSE volumes — e.g. Docker Desktop on macOS/Windows),+ os.chmod can raise OSError. The chmods are best-effort, so+ create_user_database must still succeed and return a usable engine.+ """+ from sqlalchemy import text++ from local_deep_research.database.encrypted_db import DatabaseManager++ monkeypatch.setenv("LDR_BOOTSTRAP_ALLOW_UNENCRYPTED", "true")++ with patch(+ "local_deep_research.database.encrypted_db.get_sqlcipher_module",+ side_effect=ImportError("No module named 'sqlcipher3'"),+ ):+ with patch(+ "local_deep_research.database.encrypted_db.get_data_directory",+ return_value=tmp_path,+ ):+ # Simulate a volume that rejects chmod for every call.+ with patch(+ "local_deep_research.database.encrypted_db.os.chmod",+ side_effect=OSError("Operation not permitted"),+ ):+ manager = DatabaseManager()+ engine = manager.create_user_database(+ "chmoduser", "test-password-123"+ )+ try:+ # DB must be created and queryable despite chmod failing.+ with engine.connect() as conn:+ assert conn.execute(text("SELECT 1")).scalar() == 1+ finally:+ engine.dispose()diff --git a/tests/research_library/routes/test_library_routes_coverage.py b/tests/research_library/routes/test_library_routes_coverage.pyindex 056681162e..28b0e65e17 100644--- a/tests/research_library/routes/test_library_routes_coverage.py+++ b/tests/research_library/routes/test_library_routes_coverage.py@@ -1324,6 +1324,10 @@ class TestCheckDownloads:key = "https://arxiv.org/abs/2301.00001"assert status[key]["downloaded"] is Trueassert status[key]["document_id"] == "doc-1"+ # Server filesystem paths must not leak to the client (#3135).+ # mock_doc.file_path is set above, so its absence here proves+ # the route stopped including it in the response.+ assert "file_path" not in status[key]def test_not_downloaded_resource(self, app):mock_resource = Mock()diff --git a/tests/web/routes/test_start_research_rate_limit.py b/tests/web/routes/test_start_research_rate_limit.pynew file mode 100644index 0000000000..cb245d795e--- /dev/null+++ b/tests/web/routes/test_start_research_rate_limit.py@@ -0,0 +1,63 @@+"""Regression test: /api/start_research carries the @api_rate_limit decorator (#3135).++``start_research`` is the primary research-submission endpoint, so it must be+rate-limited (per-user, via ``@api_rate_limit``) — otherwise a single account+can flood the research queue.++This is a *static* check of the source: it parses research_routes.py and+asserts ``start_research`` is decorated with ``api_rate_limit``. Two earlier+approaches were abandoned as flaky in the full-suite CI run — both a+request-volume integration test and an introspection of+``limiter.limit_manager`` depend on the process-wide Flask-Limiter singleton,+whose enabled state and decorated-limit registry are mutated by other tests+(they pass in isolation but flake in the consolidated run). The AST check is+deterministic and guards exactly the regression we care about: someone dropping+``@api_rate_limit``. The limiter's runtime enforcement/exempt logic is covered+by ``tests/security/test_rate_limiter.py``.+"""++import ast+from pathlib import Path+++def _decorator_names(func_node):+ """Return the simple names of every decorator on a function node.++ Handles ``@name``, ``@obj.name`` and the call forms ``@name(...)`` /+ ``@obj.name(...)`` so e.g. ``@require_json_body(...)`` yields+ ``require_json_body``.+ """+ names = []+ for dec in func_node.decorator_list:+ target = dec.func if isinstance(dec, ast.Call) else dec+ if isinstance(target, ast.Name):+ names.append(target.id)+ elif isinstance(target, ast.Attribute):+ names.append(target.attr)+ return names+++def test_start_research_decorated_with_api_rate_limit():+ import local_deep_research.web.routes.research_routes as research_routes++ source = Path(research_routes.__file__).read_text()+ tree = ast.parse(source)++ func = next(+ (+ node+ for node in ast.walk(tree)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ and node.name == "start_research"+ ),+ None,+ )+ assert func is not None, (+ "start_research view not found in research_routes.py"+ )++ decorators = _decorator_names(func)+ assert "api_rate_limit" in decorators, (+ "start_research must be decorated with @api_rate_limit so research "+ f"submissions are rate limited; found decorators: {decorators}"+ )