Skip to content

~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.

security: harden backup SQL injection guard and validate glob results (#3098)

LearningCircuit738b99355d88
diff --git a/src/local_deep_research/database/backup/backup_service.py b/src/local_deep_research/database/backup/backup_service.py
index ebf56a0cab..aa91b75aa0 100644
--- a/src/local_deep_research/database/backup/backup_service.py
+++ b/src/local_deep_research/database/backup/backup_service.py
@@ -36,6 +36,14 @@ 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")
+
def _get_user_lock(username: str) -> threading.Lock:
"""Get or create a lock for a specific user.
@@ -54,6 +62,32 @@ def _get_user_lock(username: str) -> threading.Lock:
return _user_locks[username]
+def _is_safe_glob_result(path: Path, base_dir: Path) -> bool:
+ """Validate that a glob result is safe to use.
+
+ Rejects symlinks and paths that resolve outside the expected
+ base directory, preventing path-traversal via crafted filenames
+ or symlink attacks.
+
+ This is a best-effort pre-check, not atomic with the subsequent
+ stat()/unlink()/open() on the path (a classic TOCTOU window). It is
+ acceptable here because the backup directory is per-user and
+ server-owned with 0o600 backups — an attacker who could swap a file
+ for a symlink already has write access to that directory.
+
+ Args:
+ path: The path returned by glob to validate.
+ base_dir: The directory the path must reside within.
+
+ Returns:
+ True if the path is a regular (non-symlink) file that resolves
+ to a location within base_dir.
+ """
+ return not path.is_symlink() and path.resolve().is_relative_to(
+ base_dir.resolve()
+ )
+
+
def pop_user_lock(username: str) -> None:
"""Remove the per-user backup lock for ``username`` from the registry.
@@ -137,9 +171,12 @@ class BackupService:
# Skip if a backup already exists for today (unless forced)
if not force:
today = datetime.now(UTC).strftime("%Y%m%d")
- existing_today = list(
- self.backup_dir.glob(f"ldr_backup_{today}_*.db")
- )
+ # After globbing, verify each result is a direct child of backup_dir
+ existing_today = [
+ f
+ for f in self.backup_dir.glob(f"ldr_backup_{today}_*.db")
+ if _is_safe_glob_result(f, self.backup_dir)
+ ]
if existing_today:
latest = max(existing_today, key=lambda p: p.name)
logger.debug(
@@ -219,10 +256,11 @@ class BackupService:
# 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).
temp_path_str = str(temp_path)
- if "'" in temp_path_str or '"' in temp_path_str:
+ if _UNSAFE_BACKUP_PATH_CHARS & set(temp_path_str):
raise ValueError(
- f"Invalid characters in backup path: {temp_path_str}"
+ f"Invalid characters in backup path: {temp_path_str!r}"
)
# Get the hex key for ATTACH (same key derivation as source)
@@ -393,7 +431,11 @@ class BackupService:
try:
# Clean up stale .tmp files from interrupted/crashed backups
- for tmp_file in self.backup_dir.glob("ldr_backup_*.db.tmp"):
+ for tmp_file in [
+ f
+ for f in self.backup_dir.glob("ldr_backup_*.db.tmp")
+ if _is_safe_glob_result(f, self.backup_dir)
+ ]:
try:
mtime = datetime.fromtimestamp(
tmp_file.stat().st_mtime, tz=UTC
@@ -413,6 +455,7 @@ class BackupService:
except FileNotFoundError:
return 0.0
+ # After globbing, verify each result is a direct child of backup_dir
backups = [
p
for p in sorted(
@@ -420,7 +463,7 @@ class BackupService:
key=_safe_mtime,
reverse=True,
)
- if p.exists()
+ if p.exists() and _is_safe_glob_result(p, self.backup_dir)
]
for i, backup in enumerate(backups):
@@ -477,8 +520,13 @@ class BackupService:
except FileNotFoundError:
return 0.0
+ # After globbing, verify each result is a direct child of backup_dir
for backup_file in sorted(
- self.backup_dir.glob("ldr_backup_*.db"),
+ [
+ f
+ for f in self.backup_dir.glob("ldr_backup_*.db")
+ if _is_safe_glob_result(f, self.backup_dir)
+ ],
key=_safe_mtime_list,
reverse=True,
):
@@ -489,7 +537,7 @@ class BackupService:
backups.append(
{
"filename": backup_file.name,
- "path": str(backup_file),
+ "path": backup_file.name, # Only expose filename, not full server path
"size_bytes": stat.st_size,
"created_at": datetime.fromtimestamp(
stat.st_mtime, tz=UTC
@@ -520,7 +568,7 @@ class BackupService:
# Delete all existing backup files
for info in self.list_backups():
try:
- Path(info["path"]).unlink()
+ (self.backup_dir / info["path"]).unlink()
logger.debug(f"Purged old-key backup: {info['filename']}")
except OSError:
logger.warning(
@@ -528,7 +576,11 @@ class BackupService:
)
# Also clean up any stale .tmp files
- for tmp_file in self.backup_dir.glob("ldr_backup_*.db.tmp"):
+ for tmp_file in [
+ f
+ for f in self.backup_dir.glob("ldr_backup_*.db.tmp")
+ if _is_safe_glob_result(f, self.backup_dir)
+ ]:
try:
tmp_file.unlink()
except OSError:
@@ -553,6 +605,7 @@ class BackupService:
except FileNotFoundError:
return 0.0
+ # After globbing, verify each result is a direct child of backup_dir
backups = [
p
for p in sorted(
@@ -560,7 +613,7 @@ class BackupService:
key=_safe_mtime_latest,
reverse=True,
)
- if p.exists()
+ if p.exists() and _is_safe_glob_result(p, self.backup_dir)
]
return backups[0] if backups else None
except Exception:
diff --git a/tests/database/backup/test_backup_service.py b/tests/database/backup/test_backup_service.py
index 7670948fa7..857148da53 100644
--- a/tests/database/backup/test_backup_service.py
+++ b/tests/database/backup/test_backup_service.py
@@ -5978,3 +5978,255 @@ class TestDailyBackupLimit:
# Proves it didn't skip — it tried to create a connection
mock_conn.assert_called()
+
+
+class TestIsSafeGlobResult:
+ """Unit tests for the ``_is_safe_glob_result`` glob-hardening helper.
+
+ This helper backs the symlink / path-traversal filtering that is applied
+ to every backup glob site. These tests exercise the helper directly,
+ rather than only asserting pathlib behavior on fixtures.
+ """
+
+ def test_accepts_regular_child_file(self, tmp_path):
+ """A regular (non-symlink) file inside base_dir is accepted."""
+ from local_deep_research.database.backup.backup_service import (
+ _is_safe_glob_result,
+ )
+
+ base_dir = tmp_path / "backups"
+ base_dir.mkdir()
+ backup = base_dir / "ldr_backup_20250101_120000.db"
+ backup.write_bytes(b"data")
+
+ assert _is_safe_glob_result(backup, base_dir) is True
+
+ def test_rejects_symlink_pointing_outside(self, tmp_path):
+ """A symlink that escapes base_dir is rejected."""
+ from local_deep_research.database.backup.backup_service import (
+ _is_safe_glob_result,
+ )
+
+ base_dir = tmp_path / "backups"
+ base_dir.mkdir()
+ outside = tmp_path / "outside.db"
+ outside.write_bytes(b"secret")
+
+ link = base_dir / "ldr_backup_evil.db"
+ link.symlink_to(outside)
+
+ assert _is_safe_glob_result(link, base_dir) is False
+
+ def test_rejects_symlink_even_when_target_inside(self, tmp_path):
+ """Symlinks are rejected outright, even pointing back inside base_dir.
+
+ ``is_symlink()`` is checked first, so the policy is "no symlinks at
+ all" — this documents that intentional behavior.
+ """
+ from local_deep_research.database.backup.backup_service import (
+ _is_safe_glob_result,
+ )
+
+ base_dir = tmp_path / "backups"
+ base_dir.mkdir()
+ real = base_dir / "ldr_backup_real.db"
+ real.write_bytes(b"data")
+
+ link = base_dir / "ldr_backup_link.db"
+ link.symlink_to(real)
+
+ assert _is_safe_glob_result(link, base_dir) is False
+
+ def test_rejects_path_resolving_outside_base(self, tmp_path):
+ """A non-symlink path that resolves outside base_dir is rejected."""
+ from local_deep_research.database.backup.backup_service import (
+ _is_safe_glob_result,
+ )
+
+ base_dir = tmp_path / "backups"
+ base_dir.mkdir()
+ other_dir = tmp_path / "elsewhere"
+ other_dir.mkdir()
+ stray = other_dir / "ldr_backup_20250101_120000.db"
+ stray.write_bytes(b"data")
+
+ assert _is_safe_glob_result(stray, base_dir) is False
+
+ def test_accepts_real_file_through_symlinked_base_dir(self, tmp_path):
+ """Real files are kept even when base_dir is reached via a symlink.
+
+ Regression guard: both sides are resolved, so a symlinked base
+ directory (e.g. macOS ``/tmp`` -> ``/private/tmp``, or a symlinked
+ ``$HOME``) must NOT cause legitimate backups to be silently dropped.
+ """
+ from local_deep_research.database.backup.backup_service import (
+ _is_safe_glob_result,
+ )
+
+ real_base = tmp_path / "real_backups"
+ real_base.mkdir()
+ backup = real_base / "ldr_backup_20250101_120000.db"
+ backup.write_bytes(b"data")
+
+ symlinked_base = tmp_path / "linked_backups"
+ symlinked_base.symlink_to(real_base)
+
+ # The file reached through the symlinked parent is itself a real file.
+ via_link = symlinked_base / "ldr_backup_20250101_120000.db"
+ assert not via_link.is_symlink()
+ assert _is_safe_glob_result(via_link, symlinked_base) is True
+
+
+class TestGlobHardeningIntegration:
+ """End-to-end checks that the glob hardening is wired into the service."""
+
+ @patch(
+ "local_deep_research.database.backup.backup_service.get_encrypted_database_path"
+ )
+ @patch(
+ "local_deep_research.database.backup.backup_service.get_user_backup_directory"
+ )
+ @patch(
+ "local_deep_research.database.backup.backup_service.get_user_database_filename"
+ )
+ def test_list_backups_excludes_symlinks(
+ self, mock_db_filename, mock_backup_dir, mock_db_path, tmp_path
+ ):
+ """list_backups() must skip symlinked entries even if names match."""
+ backup_dir = tmp_path / "backups"
+ backup_dir.mkdir()
+
+ # One legitimate backup.
+ real_backup = backup_dir / "ldr_backup_20250101_120000.db"
+ real_backup.write_bytes(b"backup-data")
+
+ # A malicious symlink whose name matches the glob but points outside.
+ outside = tmp_path / "outside_secret.db"
+ outside.write_bytes(b"secret")
+ evil_link = backup_dir / "ldr_backup_20250102_120000.db"
+ evil_link.symlink_to(outside)
+
+ mock_db_filename.return_value = "ldr_user_abc123.db"
+ mock_db_path.return_value = tmp_path
+ mock_backup_dir.return_value = backup_dir
+
+ service = BackupService(username="testuser", password="testpass")
+ backups = service.list_backups()
+
+ names = [b["filename"] for b in backups]
+ assert names == ["ldr_backup_20250101_120000.db"]
+ assert "ldr_backup_20250102_120000.db" not in names
+ # Listing must not have followed or removed the symlink.
+ assert evil_link.is_symlink()
+
+ @patch(
+ "local_deep_research.database.backup.backup_service.get_encrypted_database_path"
+ )
+ @patch(
+ "local_deep_research.database.backup.backup_service.get_user_backup_directory"
+ )
+ @patch(
+ "local_deep_research.database.backup.backup_service.get_user_database_filename"
+ )
+ def test_list_backups_path_field_is_filename_only(
+ self, mock_db_filename, mock_backup_dir, mock_db_path, tmp_path
+ ):
+ """The "path" field must be a bare filename, not the server path.
+
+ purge_and_refresh() reconstructs the absolute path via
+ ``self.backup_dir / info["path"]`` and relies on this invariant
+ (``Path(base) / absolute`` would silently discard ``base``).
+ """
+ backup_dir = tmp_path / "backups"
+ backup_dir.mkdir()
+ backup = backup_dir / "ldr_backup_20250101_120000.db"
+ backup.write_bytes(b"backup-data")
+
+ mock_db_filename.return_value = "ldr_user_abc123.db"
+ mock_db_path.return_value = tmp_path
+ mock_backup_dir.return_value = backup_dir
+
+ service = BackupService(username="testuser", password="testpass")
+ backups = service.list_backups()
+
+ assert len(backups) == 1
+ info = backups[0]
+ assert info["path"] == "ldr_backup_20250101_120000.db"
+ # It must NOT leak the absolute server path, and must round-trip.
+ assert os.sep not in info["path"]
+ assert (service.backup_dir / info["path"]) == backup
+
+
+class TestUnsafeBackupPathChars:
+ """Tests for the widened SQL-injection character guard on the ATTACH path."""
+
+ @pytest.mark.parametrize(
+ "bad_char, label",
+ [
+ ("\\", "backslash"),
+ ("\0", "null"),
+ ("\n", "newline"),
+ ("\r", "carriage_return"),
+ ("\t", "tab"),
+ ],
+ )
+ @patch(
+ "local_deep_research.database.backup.backup_service.get_encrypted_database_path"
+ )
+ @patch(
+ "local_deep_research.database.backup.backup_service.get_user_backup_directory"
+ )
+ @patch(
+ "local_deep_research.database.backup.backup_service.get_user_database_filename"
+ )
+ @patch(
+ "local_deep_research.database.backup.backup_service.create_sqlcipher_connection"
+ )
+ @patch("shutil.disk_usage")
+ def test_backup_path_with_unsafe_char_rejected(
+ self,
+ mock_disk_usage,
+ mock_create_conn,
+ mock_db_filename,
+ mock_backup_dir,
+ mock_db_path,
+ bad_char,
+ label,
+ tmp_path,
+ ):
+ """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.
+ """
+ db_dir = tmp_path / "encrypted_databases"
+ db_dir.mkdir()
+ db_file = db_dir / "ldr_user_abc123.db"
+ db_file.write_bytes(b"x" * 1000)
+
+ mock_db_filename.return_value = "ldr_user_abc123.db"
+ mock_db_path.return_value = db_dir
+ # Backup dir whose path string contains an unsafe character. It is
+ # never created on disk (disk_usage is mocked); only the string of the
+ # generated temp path matters to the guard.
+ mock_backup_dir.return_value = tmp_path / f"back{bad_char}ups"
+
+ mock_disk_usage.return_value = MagicMock(free=10_000_000)
+ mock_conn = MagicMock()
+ mock_conn.cursor.return_value = MagicMock()
+ mock_create_conn.return_value = mock_conn
+
+ service = BackupService(username="testuser", password="testpass")
+ # force=True skips the daily-glob check and goes straight to the guard.
+ result = service.create_backup(force=True)
+
+ assert result.success is False
+ assert "Invalid characters in backup path" 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)