~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): rework #3090 symlink + LDR_DATA_DIR hunks (500 on non-root, apostrophe crash) + add tests (#4808)
LearningCircuit6e1d1acf6dd5
diff --git a/changelog.d/4808.security.md b/changelog.d/4808.security.mdnew file mode 100644index 0000000000..a85a16a77d--- /dev/null+++ b/changelog.d/4808.security.md@@ -0,0 +1 @@+**Local file/RAG path validation no longer 500s or blocks legitimate paths.** Browsing to a restricted path on a non-root deployment returned a 500 (an uncaught permission error from a symlink pre-check) instead of a clean "invalid path" response, and legitimately symlinked index folders (Docker/Kubernetes bind mounts, macOS `/tmp`) were wrongly rejected; both are fixed, and the system-directory block now also holds on macOS (where `/etc` is itself a symlink to `/private/etc`). Separately, a `LDR_DATA_DIR` path containing an apostrophe (e.g. `/home/O'Brien/ldr`) is now fully supported: it no longer crashes startup, and encrypted-database backups handle it too (the apostrophe is safely escaped in the backup's `ATTACH DATABASE` statement).diff --git a/src/local_deep_research/config/paths.py b/src/local_deep_research/config/paths.pyindex c48a6c7555..ce9692c08c 100644--- a/src/local_deep_research/config/paths.py+++ b/src/local_deep_research/config/paths.py@@ -30,11 +30,18 @@ def get_data_directory() -> Path:if not Path(custom_path).is_absolute():raise ValueError("LDR_DATA_DIR must be an absolute path")data_dir = Path(custom_path).resolve()- # Block SQL-unsafe characters that could be exploited in ATTACH DATABASE statements+ # Reject only control characters that are never valid in a path and+ # could break a SQL/ATTACH statement (null byte, newline, carriage+ # return). Quotes are intentionally NOT rejected here: legitimate POSIX+ # home directories contain apostrophes (e.g. /home/O'Brien/ldr), and the+ # actual ATTACH-DATABASE sink (backup_service) already validates the+ # full interpolated path against a stricter denylist before use.+ # The offending path is not echoed, mirroring the redaction below.path_str = str(data_dir)- if any(c in path_str for c in ("'", '"', "\0", "\n", "\r")):+ if any(c in path_str for c in ("\0", "\n", "\r")):raise ValueError(- f"LDR_DATA_DIR contains unsafe characters: {path_str!r}"+ "LDR_DATA_DIR contains unsafe control characters "+ "(null byte, newline, or carriage return)")logger.debug(f"Using custom data directory from LDR_DATA_DIR: {data_dir}"diff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.pyindex e3b042d181..c6861df933 100644--- a/src/local_deep_research/database/backup/backup_service.py+++ b/src/local_deep_research/database/backup/backup_service.py@@ -36,13 +36,13 @@ from ..sqlcipher_utils import (_user_locks: dict[str, threading.Lock] = {}_user_locks_lock = threading.Lock()-# Characters that must never appear in a backup path. The path is-# server-generated (a timestamped filename under the per-user backup dir),-# so this denylist is defense-in-depth: ATTACH DATABASE takes a string-# literal and cannot be parameterized in SQLite/SQLCipher, so the path is-# interpolated into SQL — a stray quote, backslash, NUL or control char-# must be rejected before it reaches the statement.-_UNSAFE_BACKUP_PATH_CHARS = frozenset("'\"\\\0\n\r\t")+# Characters that must never appear in a backup path. ATTACH DATABASE takes a+# string literal and cannot be parameterized in SQLite/SQLCipher, so the path is+# interpolated into SQL. A single quote IS allowed — it is escaped by doubling+# (per the SQLite literal grammar) so an apostrophe in the data-dir path (a+# home dir named O'Brien, say) doesn't break backups. Backslash, double-quote,+# NUL and control chars are still rejected (never valid in a real backup path).+_UNSAFE_BACKUP_PATH_CHARS = frozenset('"\\\0\n\r\t')def _get_user_lock(username: str) -> threading.Lock:@@ -255,12 +255,17 @@ class BackupService:try:# Use sqlcipher_export() to create an encrypted backup# VACUUM INTO doesn't preserve encryption in SQLCipher- # Security: validate temp_path doesn't contain SQL injection chars- # (the ATTACH path below is interpolated, not parameterizable).+ # Security: the ATTACH path below is interpolated (not+ # parameterizable). Single quotes are escaped (see below); any+ # other unsafe char is rejected. Don't log the full path — it can+ # contain a username — only the offending characters.temp_path_str = str(temp_path)- if _UNSAFE_BACKUP_PATH_CHARS & set(temp_path_str):+ bad_chars = _UNSAFE_BACKUP_PATH_CHARS & set(temp_path_str)+ if bad_chars:raise ValueError(- f"Invalid characters in backup path: {temp_path_str!r}"+ "Backup path contains characters not allowed in a "+ "SQLCipher ATTACH statement: "+ + ", ".join(sorted(repr(c) for c in bad_chars)))# Get the hex key for ATTACH (same key derivation as source)@@ -274,11 +279,14 @@ class BackupService:):raise ValueError("Derived key is not valid hex")- # Attach backup database with encryption (using temp path)- # Note: ATTACH DATABASE does not support parameter binding- # in SQLite/SQLCipher — f-string is required here.+ # Attach backup database with encryption (using temp path).+ # ATTACH DATABASE can't be parameterized in SQLite/SQLCipher, so+ # the path is interpolated as a string literal — escape any+ # single quote by doubling it per the SQLite literal grammar+ # (all other unsafe chars were rejected above).+ attach_path = temp_path_str.replace("'", "''")cursor.execute(- f"ATTACH DATABASE '{temp_path_str}' AS backup KEY \"x'{hex_key}'\""+ f"ATTACH DATABASE '{attach_path}' AS backup KEY \"x'{hex_key}'\"")try:diff --git a/src/local_deep_research/security/path_validator.py b/src/local_deep_research/security/path_validator.pyindex 3aed6ba744..1e0821959a 100644--- a/src/local_deep_research/security/path_validator.py+++ b/src/local_deep_research/security/path_validator.py@@ -225,12 +225,6 @@ class PathValidator:if ".." in user_path:raise ValueError("Path traversal patterns not allowed")- # Check for symlinks BEFORE resolve(), since resolve() follows symlinks- # making a post-resolve is_symlink() check ineffective (always False)- raw_path = Path(user_path)- if raw_path.is_symlink():- raise ValueError("Symlinks are not permitted for security reasons")-# Use safe_join to sanitize the path - this is recognized by static analyzers# For absolute paths, we validate against the root directoryif user_path.startswith("/"):@@ -279,9 +273,18 @@ class PathValidator:])- # Check against restricted directories+ # Check against restricted directories. Resolve each restricted dir so+ # the containment check holds on platforms where these are symlinks+ # (e.g. macOS /etc -> /private/etc, /var -> /private/var) — validated_path+ # is already resolved, so an unresolved "/etc" would never match+ # "/private/etc/...". resolve(strict=False) does not raise for a missing+ # or unreadable dir; fall back to the literal path if it ever does.for restricted in restricted_dirs:- if validated_path.is_relative_to(restricted):+ try:+ restricted_resolved = restricted.resolve()+ except OSError:+ restricted_resolved = restricted+ if validated_path.is_relative_to(restricted_resolved):logger.error(f"Security: Blocked access to restricted directory: {validated_path}")diff --git a/tests/config/test_paths.py b/tests/config/test_paths.pyindex 8a2e927a4b..60bd7dcac2 100644--- a/tests/config/test_paths.py+++ b/tests/config/test_paths.py@@ -4,6 +4,8 @@ import hashlibfrom pathlib import Pathfrom unittest.mock import patch+import pytest+from local_deep_research.config.paths import (get_data_directory,get_research_outputs_directory,@@ -36,6 +38,30 @@ class TestGetDataDirectory:result = get_data_directory()assert isinstance(result, Path)+ def test_apostrophe_in_path_is_allowed(self, tmp_path, monkeypatch):+ """Regression for #3090: a legitimate POSIX path containing an+ apostrophe (e.g. /home/O'Brien/ldr) must NOT crash startup. The+ over-broad quote rejection was removed; the actual ATTACH-DATABASE+ sink validates the interpolated path separately."""+ data_dir = tmp_path / "O'Brien" / "ldr"+ monkeypatch.setenv("LDR_DATA_DIR", str(data_dir))+ result = get_data_directory()+ assert result == data_dir.resolve()++ def test_relative_path_rejected(self, monkeypatch):+ """A relative LDR_DATA_DIR is rejected (must be absolute)."""+ monkeypatch.setenv("LDR_DATA_DIR", "relative/dir")+ with pytest.raises(ValueError, match="absolute"):+ get_data_directory()++ def test_control_characters_rejected(self, tmp_path, monkeypatch):+ """A newline in LDR_DATA_DIR is still rejected (could break a SQL/+ ATTACH statement), and the offending value is not echoed."""+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path) + "\nDROP")+ with pytest.raises(ValueError, match="control character") as exc_info:+ get_data_directory()+ assert "DROP" not in str(exc_info.value)+class TestGetResearchOutputsDirectory:"""Tests for get_research_outputs_directory function."""diff --git a/tests/database/backup/test_backup_crash_recovery_ci.py b/tests/database/backup/test_backup_crash_recovery_ci.pyindex 61f915401c..d590de8a0f 100644--- a/tests/database/backup/test_backup_crash_recovery_ci.py+++ b/tests/database/backup/test_backup_crash_recovery_ci.py@@ -523,3 +523,55 @@ class TestBackupDataIntegrity:assert cursor.fetchone()[0] == 21cursor.close()conn.close()+++class TestBackupPathWithApostrophe:+ """Regression for #4808: a backup/data-dir path containing an apostrophe+ (e.g. /home/O'Brien) must back up successfully. ATTACH DATABASE can't be+ parameterized, so the path literal escapes the single quote (doubling it)+ instead of the denylist rejecting the path."""++ def test_backup_succeeds_with_apostrophe_in_path(self, tmp_path):+ _get_sqlcipher() # skip early if SQLCipher is unavailable++ db_dir = tmp_path / "encrypted_databases"+ db_dir.mkdir()+ db_path = db_dir / "ldr_user_apos.db"+ # The offending component: a directory whose name has a single quote.+ backup_dir = tmp_path / "O'Brien" / "backups"+ backup_dir.mkdir(parents=True)+ password = "apostrophe_password_123"++ _create_test_database(db_path, password)++ with (+ patch(+ "local_deep_research.database.backup.backup_service"+ ".get_encrypted_database_path",+ return_value=db_dir,+ ),+ patch(+ "local_deep_research.database.backup.backup_service"+ ".get_user_database_filename",+ return_value=db_path.name,+ ),+ patch(+ "local_deep_research.database.backup.backup_service"+ ".get_user_backup_directory",+ return_value=backup_dir,+ ),+ ):+ svc = BackupService(+ username="apostuser",+ password=password,+ max_backups=3,+ max_age_days=7,+ )+ result = svc.create_backup()++ assert result.success, f"Backup failed: {result.error}"+ assert "'" in str(result.backup_path) # the apostrophe path was used+ assert result.backup_path.exists()+ assert result.backup_path.stat().st_size > 0+ # Encrypted, not a plaintext SQLite file+ assert result.backup_path.read_bytes()[:16] != b"SQLite format 3\x00"diff --git a/tests/database/backup/test_backup_service.py b/tests/database/backup/test_backup_service.pyindex 2ff0df74b2..ca2eb172db 100644--- a/tests/database/backup/test_backup_service.py+++ b/tests/database/backup/test_backup_service.py@@ -8,6 +8,7 @@ from unittest.mock import MagicMock, patchimport pytestfrom local_deep_research.database.backup.backup_service import (+ _UNSAFE_BACKUP_PATH_CHARS,BackupResult,BackupService,)@@ -2178,7 +2179,7 @@ class TestSecurityFixes:"local_deep_research.database.backup.backup_service.create_sqlcipher_connection")@patch("shutil.disk_usage")- def test_backup_path_with_quotes_rejected(+ def test_backup_path_with_single_quote_is_escaped_not_rejected(self,mock_disk_usage,mock_create_conn,@@ -2187,7 +2188,8 @@ class TestSecurityFixes:mock_db_path,tmp_path,):- """Should reject backup paths containing SQL injection characters."""+ """A single quote in the backup path is escaped ('') in the ATTACH+ literal, not rejected — apostrophe data dirs are supported (#4808)."""# Create a fake database filedb_dir = tmp_path / "encrypted_databases"db_dir.mkdir()@@ -2196,10 +2198,10 @@ class TestSecurityFixes:mock_db_filename.return_value = "ldr_user_abc123.db"mock_db_path.return_value = db_dir- # Create a backup directory with a quote in the path- malicious_dir = tmp_path / "back'ups"- malicious_dir.mkdir()- mock_backup_dir.return_value = malicious_dir+ # A backup directory whose path contains a single quote.+ apostrophe_dir = tmp_path / "back'ups"+ apostrophe_dir.mkdir()+ mock_backup_dir.return_value = apostrophe_dirmock_disk_usage.return_value = MagicMock(free=10000000)@@ -2212,8 +2214,19 @@ class TestSecurityFixes:service = BackupService(username="testuser", password="testpass")result = service.create_backup()- assert result.success is False- assert "Invalid characters in backup path" in result.error+ # The path-character guard did NOT reject it (the backup may still fail+ # later for unrelated mocked reasons, but never with that guard error).+ if result.error:+ assert "not allowed in a SQLCipher ATTACH" not in result.error+ # ATTACH ran with the single quote doubled (escaped). Read the actual+ # SQL argument, not str(call) (whose repr re-escapes the quotes).+ attach_sql = [+ c.args[0]+ for c in mock_cursor.execute.call_args_list+ if c.args and "ATTACH DATABASE" in c.args[0]+ ]+ assert attach_sql, "ATTACH should run — the apostrophe path is accepted"+ assert "back''ups" in attach_sql[0]def test_user_backup_directory_has_restrictive_permissions(self, tmp_path):"""Should create user backup directory with mode 0o700."""@@ -2303,7 +2316,7 @@ class TestSecurityFixes:result = service.create_backup()assert result.success is False- assert "Invalid characters in backup path" in result.error+ assert "not allowed in a SQLCipher ATTACH" in result.errorclass TestBackupEdgeCases:@@ -6196,10 +6209,10 @@ class TestUnsafeBackupPathChars:):"""Reject backslash, NUL, CR, LF and tab in the backup path.- These were NOT blocked before this hardening (only ``'`` and ``"``- were). ``temp_path`` is server-generated, so the only way these reach- the ``ATTACH DATABASE`` literal is via the backup directory, which is- simulated here.+ ``'`` is intentionally NOT rejected — it is escaped (doubled) in the+ ATTACH literal so apostrophe data dirs work (#4808). ``temp_path`` is+ server-generated, so the only way these reach the ``ATTACH DATABASE``+ literal is via the backup directory, which is simulated here."""db_dir = tmp_path / "encrypted_databases"db_dir.mkdir()@@ -6223,10 +6236,18 @@ class TestUnsafeBackupPathChars:result = service.create_backup(force=True)assert result.success is False- assert "Invalid characters in backup path" in result.error+ assert "not allowed in a SQLCipher ATTACH" in result.error# The ATTACH statement must never execute for an unsafe path.executed = [str(call)for call in mock_conn.cursor.return_value.execute.call_args_list]assert not any("ATTACH DATABASE" in c for c in executed)++ def test_single_quote_no_longer_in_denylist(self):+ """#4808: the apostrophe is escaped (doubled) in the ATTACH literal,+ not rejected, so /home/O'Brien/... can be backed up. The genuinely+ dangerous characters stay denied. (Runs without SQLCipher.)"""+ assert "'" not in _UNSAFE_BACKUP_PATH_CHARS+ for ch in ('"', "\\", "\0", "\n", "\r", "\t"):+ assert ch in _UNSAFE_BACKUP_PATH_CHARSdiff --git a/tests/security/test_path_validator.py b/tests/security/test_path_validator.pyindex e427ac7850..48f6874d2e 100644--- a/tests/security/test_path_validator.py+++ b/tests/security/test_path_validator.py@@ -168,11 +168,52 @@ class TestValidateLocalFilesystemPath:@pytest.mark.skipif(sys.platform == "win32", reason="Unix-specific test")def test_root_blocked(self):- """Blocks access to /root directory."""+ """Blocks access to /root directory.++ Also a regression guard for #3090: this must surface as a clean+ ValueError. The removed pre-resolve is_symlink() lstat() raised an+ uncaught PermissionError for /root/.bashrc on non-root hosts (where it+ escaped to a Flask 500); pytest.raises(ValueError) here would not catch+ that, so this test fails loudly if the EACCES leak ever returns.+ """with pytest.raises(ValueError) as exc_info:PathValidator.validate_local_filesystem_path("/root/.bashrc")assert "system" in str(exc_info.value).lower()+ @pytest.mark.skipif(+ sys.platform == "win32",+ reason="symlink creation needs privileges on Windows",+ )+ def test_symlinked_directory_is_permitted(self, temp_safe_dir):+ """Regression for #3090: a symlinked directory is accepted.++ The removed pre-resolve symlink check rejected ALL symlinks, breaking+ legitimate setups (Docker/k8s bind mounts, macOS /tmp -> /private/tmp).+ Containment is still enforced by resolve()+restricted_dirs.+ """+ real = temp_safe_dir / "real"+ real.mkdir()+ link = temp_safe_dir / "link"+ link.symlink_to(real, target_is_directory=True)++ result = PathValidator.validate_local_filesystem_path(+ str(link), restricted_dirs=[]+ )+ assert result is not None++ @pytest.mark.skipif(sys.platform == "win32", reason="Unix-specific test")+ def test_symlink_escaping_to_system_dir_still_blocked(self, temp_safe_dir):+ """A symlink that resolves into a restricted system dir is still blocked:+ resolve() follows it and the restricted-dir check catches the target.+ This is the real symlink control (vs. the removed leaf-only lstat).+ """+ link = temp_safe_dir / "escape"+ link.symlink_to("/etc", target_is_directory=True)++ with pytest.raises(ValueError) as exc_info:+ PathValidator.validate_local_filesystem_path(str(link / "passwd"))+ assert "system" in str(exc_info.value).lower()+def test_custom_restricted_dirs(self, temp_safe_dir):"""Respects custom restricted directories."""restricted = [temp_safe_dir]diff --git a/tests/storage/test_file_storage.py b/tests/storage/test_file_storage.pyindex 2788103f88..a55365786a 100644--- a/tests/storage/test_file_storage.py+++ b/tests/storage/test_file_storage.py@@ -4,6 +4,7 @@ import jsonfrom pathlib import Pathfrom unittest.mock import patch+import pytestfrom local_deep_research.storage.file import FileReportStorage@@ -59,6 +60,34 @@ class TestGetMetadataPath:assert path == tmp_path / "test-uuid_metadata.json"+class TestPathTraversalContainment:+ """Regression tests for the #3090 traversal guard: a research_id that+ escapes base_dir must be rejected, not resolved to an arbitrary on-disk+ path. (research_ids are normally server-generated UUIDs; this is+ defense-in-depth.)"""++ def test_report_path_rejects_parent_traversal(self, tmp_path):+ storage = FileReportStorage(base_dir=tmp_path)+ with pytest.raises(ValueError, match="Path traversal attempt"):+ storage._get_report_path("../../etc/passwd")++ def test_metadata_path_rejects_parent_traversal(self, tmp_path):+ storage = FileReportStorage(base_dir=tmp_path)+ with pytest.raises(ValueError, match="Path traversal attempt"):+ storage._get_metadata_path("../../etc/passwd")++ def test_report_path_rejects_single_level_escape(self, tmp_path):+ storage = FileReportStorage(base_dir=tmp_path / "reports")+ with pytest.raises(ValueError, match="Path traversal attempt"):+ storage._get_report_path("../escapee")++ def test_normal_id_stays_within_base_dir(self, tmp_path):+ storage = FileReportStorage(base_dir=tmp_path)+ path = storage._get_report_path("9f8e-uuid-1234")+ assert path.is_relative_to(tmp_path.resolve())+ assert path.name == "9f8e-uuid-1234.md"++class TestSaveReport:"""Tests for save_report method."""