~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(db): resolve encrypted data directory lazily (#5364)
Ziyang Guo505582c76897
diff --git a/changelog.d/+live-encrypted-db-data-dir.bugfix.md b/changelog.d/+live-encrypted-db-data-dir.bugfix.mdnew file mode 100644index 0000000000..297f5f0aa8--- /dev/null+++ b/changelog.d/+live-encrypted-db-data-dir.bugfix.md@@ -0,0 +1 @@+Per-user encrypted databases now follow a runtime `LDR_DATA_DIR` override even when the database manager was imported earlier, preventing files from leaking into the platform-default application-data directory.diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 66994f746f..ec8f5f73d9 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -159,15 +159,8 @@ class DatabaseManager:# the same database file at once. Created lazily under# _connections_lock; see open_user_database / _get_init_lock.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)+ self._data_dir_override: Optional[Path] = None+ self._initialized_data_dirs: set[Path] = set()# Check SQLCipher availabilityself.has_encryption = self._check_encryption_available()@@ -210,6 +203,41 @@ class DatabaseManager:self._use_static_pool = bool(os.environ.get("TESTING"))self._pool_class = StaticPool if self._use_static_pool else QueuePool+ def _ensure_data_dir(self, path: Path) -> None:+ """Create and harden one resolved encrypted-database directory."""+ path = Path(path)+ with self._connections_lock:+ if path in self._initialized_data_dirs:+ return+ path.mkdir(parents=True, exist_ok=True)+ # Restrict the per-user DB directory to the owner (0o700).+ # This covers SQLite WAL/SHM sidecars and plaintext fallback temp+ # files even when SQLite recreates them with umask permissions.+ _best_effort_chmod(path, 0o700)+ self._initialized_data_dirs.add(path)++ @property+ def data_dir(self) -> Path:+ """Return the encrypted-DB directory for the live data root.++ The default path is resolved on every access so a process that imports+ ``db_manager`` before ``LDR_DATA_DIR`` is set does not stay bound to+ the platform default. Explicit assignments use the setter below and+ remain stable for tests and programmatic callers.+ """+ path = self._data_dir_override+ if path is None:+ path = get_data_directory() / "encrypted_databases"+ self._ensure_data_dir(path)+ return path++ @data_dir.setter+ def data_dir(self, value: Path) -> None:+ """Set an explicit data-directory override for this manager."""+ path = Path(value)+ self._data_dir_override = path+ self._ensure_data_dir(path)+def _get_pool_kwargs(self) -> Dict[str, Any]:"""Get pool configuration kwargs based on pool type.diff --git a/tests/database/test_encrypted_db_live_data_dir.py b/tests/database/test_encrypted_db_live_data_dir.pynew file mode 100644index 0000000000..67bf32d4c1--- /dev/null+++ b/tests/database/test_encrypted_db_live_data_dir.py@@ -0,0 +1,102 @@+"""Regression tests for live encrypted-database directory resolution."""++import stat+from unittest.mock import call, patch+++MODULE = "local_deep_research.database.encrypted_db"+++def test_manager_init_does_not_resolve_data_dir():+ """Import-time singleton construction must not bind or create a data root."""+ from local_deep_research.database.encrypted_db import DatabaseManager++ with (+ patch(f"{MODULE}.get_data_directory") as mock_get_data_directory,+ patch.object(+ DatabaseManager, "_check_encryption_available", return_value=True+ ),+ ):+ DatabaseManager()++ mock_get_data_directory.assert_not_called()+++def test_data_dir_follows_runtime_data_root_override(tmp_path, monkeypatch):+ """A manager created before LDR_DATA_DIR changes follows the new root."""+ from local_deep_research.database.encrypted_db import DatabaseManager++ import_root = tmp_path / "import-root"+ runtime_root = tmp_path / "runtime-root"+ monkeypatch.delenv("LDR_DATA_DIR", raising=False)++ with (+ patch(f"{MODULE}.get_data_directory", return_value=import_root),+ patch.object(+ DatabaseManager, "_check_encryption_available", return_value=True+ ),+ ):+ manager = DatabaseManager()+ assert manager.data_dir == import_root / "encrypted_databases"++ monkeypatch.setenv("LDR_DATA_DIR", str(runtime_root))+ user_path = manager._get_user_db_path("runtime-user")++ assert user_path.parent == runtime_root / "encrypted_databases"+ assert stat.S_IMODE(user_path.parent.stat().st_mode) == 0o700+++def test_explicit_data_dir_assignment_remains_stable(tmp_path, monkeypatch):+ """Existing tests and callers can keep assigning a manager-local override."""+ from local_deep_research.database.encrypted_db import DatabaseManager++ initial_root = tmp_path / "initial-root"+ explicit_dir = tmp_path / "explicit-encrypted-databases"+ runtime_root = tmp_path / "runtime-root"++ with (+ patch(f"{MODULE}.get_data_directory", return_value=initial_root),+ patch.object(+ DatabaseManager, "_check_encryption_available", return_value=True+ ),+ ):+ manager = DatabaseManager()+ manager.data_dir = explicit_dir++ monkeypatch.setenv("LDR_DATA_DIR", str(runtime_root))++ assert manager.data_dir == explicit_dir+ assert manager._get_user_db_path("override-user").parent == explicit_dir+ assert stat.S_IMODE(explicit_dir.stat().st_mode) == 0o700+++def test_each_resolved_data_dir_is_initialized_once(tmp_path):+ """Permission hardening runs once for every distinct live data root."""+ from local_deep_research.database.encrypted_db import DatabaseManager++ roots = {"current": tmp_path / "first-root"}+ first_dir = roots["current"] / "encrypted_databases"+ second_dir = tmp_path / "second-root" / "encrypted_databases"++ with (+ patch(+ f"{MODULE}.get_data_directory",+ side_effect=lambda: roots["current"],+ ),+ patch.object(+ DatabaseManager, "_check_encryption_available", return_value=True+ ),+ patch(f"{MODULE}._best_effort_chmod") as mock_chmod,+ ):+ manager = DatabaseManager()+ assert manager.data_dir == first_dir+ assert manager.data_dir == first_dir++ roots["current"] = tmp_path / "second-root"+ assert manager.data_dir == second_dir+ assert manager.data_dir == second_dir++ assert mock_chmod.call_args_list == [+ call(first_dir, 0o700),+ call(second_dir, 0o700),+ ]