~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(database): refuse a symlinked database pathname at login (#6495)
Lukas Buckae7dd44e5868
diff --git a/changelog.d/6493.security.md b/changelog.d/6493.security.mdnew file mode 100644index 0000000000..fbe736a82a--- /dev/null+++ b/changelog.d/6493.security.md@@ -0,0 +1,19 @@+Opening a user database no longer follows a symlinked pathname. Replacing+`ldr_user_<hash>.db` with a link pointing outside the data directory made the+next open write a fresh multi-megabyte encrypted database at the link's target,+with the account opening normally and nothing reported — the same one-shot+primitive the create path refuses, with no race required (#6493).++The refusal is shared by every entry point that hands that pathname to+SQLCipher: the login, and the metrics session that opens it independently. A+password change is covered by composition, because it opens through the login+path. Only the leaf is checked, so a data directory that is itself a symlink+(a library on another volume) keeps working, and the log names the pathname and+the link target, which is the only actionable evidence an operator has.++The refusal reads the pathname rather than asking the database layer to+decline: neither `sqlcipher3` nor the standard library's `sqlite3` exposes+`SQLITE_OPEN_NOFOLLOW`, which is an open flag of SQLite's C API and not a URI+parameter. Same threat model as the create-path fix — a same-user or+compromised account with write access to the 0700 data directory — so this is+defence in depth rather than an advisory.diff --git a/src/local_deep_research/database/encrypted_db.py b/src/local_deep_research/database/encrypted_db.pyindex 2bc4e34e3d..0566eb4a6d 100644--- a/src/local_deep_research/database/encrypted_db.py+++ b/src/local_deep_research/database/encrypted_db.py@@ -100,6 +100,44 @@ def _best_effort_chmod(path, mode: int, *, warn: bool = False) -> None:)+def _db_path_is_symlinked(db_path: Path, username: str) -> bool:+ """True when a user-database pathname is a symlink, which is refused.++ SQLite and SQLCipher take a pathname and follow it, and neither+ ``sqlcipher3`` nor the standard library's ``sqlite3`` can ask for+ ``SQLITE_OPEN_NOFOLLOW`` -- it is an open flag of the C API, not a URI+ parameter, and a ``file:...?nofollow=1`` open still follows the link. So+ the link is refused here rather than declined at the open.++ Replacing ``ldr_user_<hash>.db`` with a link pointing outside the data+ directory otherwise makes the next open write a fresh multi-megabyte+ encrypted database at the link's target: the same one-shot primitive the+ create path refuses (#6354), on every path that opens an existing+ database (#6493).++ Called by each entry point that hands this pathname to SQLCipher, so a new+ one inherits the check by being written next to the others. Only the LEAF+ is checked: a data directory that is itself a symlink (another volume) is a+ legitimate deployment and must keep working.++ The log line carries the pathname and the link target because that is the+ only actionable evidence an operator has; the directory is 0700, so the+ disclosure is to someone who can already read it.+ """+ if not db_path.is_symlink():+ return False+ try:+ target = os.readlink(db_path)+ except OSError as exc:+ target = f"<unreadable: {exc.strerror}>"+ logger.error(+ f"Database path for user {username!r} is a symlink: {db_path} -> "+ f"{target}. Refusing to open it; replace it with the real database "+ "file."+ )+ return True++def _remove_partial_user_db_files(db_path: Path) -> None:"""Remove a half-created user database and all of its sidecar files.@@ -1096,6 +1134,14 @@ class DatabaseManager:# Pre-derive key before closures to avoid capturing plaintext passwordhex_key = get_key_from_password(password, db_path=db_path).hex()+ # After the key derivation, not before: the derivation is deliberately+ # unconditional so a non-existent user costs the same as an existing+ # one, and a check that returned early would time the difference.+ # Before the exists() check below, which follows the link and would+ # report a tampered pathname as a missing account.+ if _db_path_is_symlinked(db_path, username):+ return None+if not db_path.exists():logger.error(f"No database found for user {username}")return None@@ -1592,6 +1638,12 @@ class DatabaseManager:"""db_path = self._get_user_db_path(username)+ if _db_path_is_symlinked(db_path, username):+ raise ValueError(+ f"Database path for user {username!r} is a symlink; refusing "+ "to open it"+ )+if not db_path.exists():raise ValueError(f"No database found for user {username}")diff --git a/tests/security/test_open_user_database_symlink.py b/tests/security/test_open_user_database_symlink.pynew file mode 100644index 0000000000..c3059db626--- /dev/null+++ b/tests/security/test_open_user_database_symlink.py@@ -0,0 +1,267 @@+"""No path that opens a user database may follow a symlinked pathname.++#6354 / #6378 close this primitive on the **create** path. The same one-shot+primitive was live wherever an *existing* database is opened, and needed no+race at all: unlink ``ldr_user_<hash>.db``, point it at a path outside the data+directory, and the next open writes a fresh multi-megabyte encrypted database+wherever the link points, returns normally, and reports nothing (#6493).++Three entry points hand that pathname to SQLCipher — login, the password+re-key, and the metrics session — so the refusal lives in one helper they all+call rather than in the one this was first reported against.++Same threat model as #6354: a same-user or compromised account with write+access to the 0700 data directory. The reason the refusal belongs at the+pathname is that it cannot be asked for at the open: neither ``sqlcipher3`` nor+the standard library's ``sqlite3`` exposes ``SQLITE_OPEN_NOFOLLOW``, which is+an open flag of the C API rather than a URI parameter.+"""++import pytest++from local_deep_research.database.encrypted_db import DatabaseManager++PASSWORD = "TestPassword123!"+++def outside_dir(tmp_path_factory):+ """A directory this test owns, for link targets.++ Deliberately not pytest's shared basetemp: a leftover or concurrently+ created file there could satisfy an "the attacker's file was not written"+ assertion for the wrong reason, and xdist workers share it.+ """+ return tmp_path_factory.mktemp("outside")+++def db_manager(tmp_path, monkeypatch):+ monkeypatch.setattr(+ "local_deep_research.database.encrypted_db.get_data_directory",+ lambda: tmp_path,+ )+ manager = DatabaseManager()+ yield manager+ for username in list(manager.connections.keys()):+ manager.close_user_database(username)+++def _existing_user(manager, username):+ """Create a user database and drop the cached engine.++ The eviction is what makes the next call a cold open: a cached engine is+ returned before the pathname is consulted at all, so a test that skipped+ this would pass whatever the guard did.+ """+ manager.create_user_database(username, PASSWORD)+ manager.close_user_database(username)+ return manager._get_user_db_path(username)+++def _plant_link(db_path, target):+ db_path.unlink()+ db_path.symlink_to(target)+++class TestLoginRefusesASymlinkedDatabasePath:+ def test_login_through_a_symlink_writes_nothing_at_the_target(+ self, db_manager, outside_dir+ ):+ """The reported defect, in its reported shape: the link points at an+ **existing** empty file outside the data directory.++ That detail is what makes it an attack rather than a failed login.+ ``exists()`` follows the link, so a link to a *missing* target is+ already turned away by the pre-existing "no database found" branch; it+ is the link to a file that IS there which gets opened, written and+ adopted. The payload is the database that appears at the attacker's+ path, so that is what this asserts, not merely that the login failed.+ """+ db_path = _existing_user(db_manager, "victim")+ target = outside_dir / "outside-the-data-dir.db"+ target.touch()+ _plant_link(db_path, target)++ engine = db_manager.open_user_database("victim", PASSWORD)++ assert engine is None+ assert target.stat().st_size == 0+ # The link itself is left alone: refusing is not repairing, and an+ # operator has to be able to see what was there.+ assert db_path.is_symlink()++ def test_a_dangling_symlink_is_refused_before_it_can_be_materialized(+ self, db_manager, outside_dir+ ):+ """``exists()`` follows the link and answers False for a dangling one,+ so an existence check alone would report "no database for this user"+ and never notice the link.+ """+ db_path = _existing_user(db_manager, "dangling")+ target = outside_dir / "never-created.db"+ _plant_link(db_path, target)++ assert db_manager.open_user_database("dangling", PASSWORD) is None+ assert not target.exists()++ def test_a_symlink_to_a_real_database_is_refused_too(+ self, db_manager, outside_dir+ ):+ """It is the link that is refused, not a broken target. A guard that+ only rejected links it could not open would still follow the useful+ case: a link into another account's data, or onto a file the attacker+ can read afterwards.+ """+ db_path = _existing_user(db_manager, "linked")+ elsewhere = outside_dir / "relocated.db"+ db_path.rename(elsewhere)+ db_path.symlink_to(elsewhere)++ assert db_manager.open_user_database("linked", PASSWORD) is None+++class TestTheOtherPathsThatOpenTheSameFile:+ """Login is one of three entry points. A re-key or a metrics session fires+ the same one-shot write primitive at the same pathname, so a victim who+ changes their password instead of logging in must not be the way in.+ """++ def test_a_password_change_refuses_a_symlinked_path_and_says_why(+ self, db_manager, outside_dir, loguru_caplog+ ):+ """The re-key is covered by composition, and this pins that.++ ``change_password`` does not open the file itself: it calls+ ``open_user_database``, so the login guard already refuses it. A guard+ of its own was written first and then removed, because a mutant that+ deleted it left every assertion here green — the refusal was coming+ from the opener the whole time. What this cell locks in is that the+ re-key still refuses AND still says a symlink is why, so a future+ change that gives it a second, direct opener has to fail here.+ """+ db_path = _existing_user(db_manager, "rekey")+ target = outside_dir / "rekey-target.db"+ target.touch()+ _plant_link(db_path, target)++ with loguru_caplog.at_level("ERROR"):+ changed = db_manager.change_password(+ "rekey", PASSWORD, "NewPassword456!"+ )++ assert changed is False+ assert "is a symlink" in loguru_caplog.text+ assert target.stat().st_size == 0++ def test_a_metrics_session_refuses_a_symlinked_path(+ self, db_manager, outside_dir+ ):+ db_path = _existing_user(db_manager, "metrics")+ target = outside_dir / "metrics-target.db"+ target.touch()+ _plant_link(db_path, target)++ with pytest.raises(ValueError, match="symlink"):+ db_manager.create_thread_safe_session_for_metrics(+ "metrics", PASSWORD+ )+ assert target.stat().st_size == 0+++class TestWhatTheOperatorIsTold:+ def test_a_dangling_link_is_named_as_a_link_in_the_log(+ self, db_manager, outside_dir, loguru_caplog+ ):+ """Placement is only visible in the diagnostic. ``exists()`` follows+ the link, so a dangling one is refused either way; with the check after+ the existence branch an operator reads "No database found for user X"+ and concludes the account was never created, which is the wrong thing+ to conclude from a tampered pathname.+ """+ db_path = _existing_user(db_manager, "quiet")+ _plant_link(db_path, outside_dir / "never-created.db")++ with loguru_caplog.at_level("ERROR"):+ assert db_manager.open_user_database("quiet", PASSWORD) is None++ assert "is a symlink" in loguru_caplog.text+ assert "No database found" not in loguru_caplog.text++ def test_the_log_carries_the_pathname_and_the_link_target(+ self, db_manager, outside_dir, loguru_caplog+ ):+ """ "A symlink was refused" alone does not tell an operator which file+ under the data directory was tampered with, or where it pointed, which+ is the only actionable evidence there is.+ """+ db_path = _existing_user(db_manager, "evidence")+ target = outside_dir / "where-it-pointed.db"+ target.touch()+ _plant_link(db_path, target)++ with loguru_caplog.at_level("ERROR"):+ db_manager.open_user_database("evidence", PASSWORD)++ assert str(db_path) in loguru_caplog.text+ assert str(target) in loguru_caplog.text++ def test_an_unreadable_link_target_still_refuses_rather_than_raising(+ self, db_manager, outside_dir, monkeypatch+ ):+ """Reading the target is for the operator's benefit, so failing to read+ it must not turn a refusal into a crash. The window is real: the link+ can be removed between the check and the read.+ """+ import os as os_module++ db_path = _existing_user(db_manager, "unreadable")+ _plant_link(db_path, outside_dir / "target.db")+ monkeypatch.setattr(+ os_module,+ "readlink",+ lambda *_a, **_kw: (_ for _ in ()).throw(OSError(2, "gone")),+ )++ assert db_manager.open_user_database("unreadable", PASSWORD) is None+++class TestWhatMustKeepWorking:+ def test_a_real_database_file_still_opens(self, db_manager):+ """Accept control. The guard sits on the login path of every user, so+ a refusal that fired on an ordinary database would lock everyone out,+ and every assertion above would still pass.+ """+ _existing_user(db_manager, "ordinary")++ assert db_manager.open_user_database("ordinary", PASSWORD) is not None++ def test_a_symlinked_data_directory_still_opens(+ self, tmp_path, monkeypatch+ ):+ """Only the LEAF is checked, on purpose. A data directory that is+ itself a symlink — the library on another volume — is an ordinary+ deployment, and a ``resolve()``-based check would lock it out.+ """+ real = tmp_path / "real-data"+ real.mkdir()+ linked = tmp_path / "data"+ linked.symlink_to(real, target_is_directory=True)+ monkeypatch.setattr(+ "local_deep_research.database.encrypted_db.get_data_directory",+ lambda: linked,+ )+ manager = DatabaseManager()+ try:+ _existing_user(manager, "volume")++ assert manager.open_user_database("volume", PASSWORD) is not None+ finally:+ for username in list(manager.connections.keys()):+ manager.close_user_database(username)++ def test_a_missing_database_is_still_reported_as_missing(self, db_manager):+ """Second accept control: the new branch must not swallow the+ pre-existing "no database found" answer for a user who has none.+ """+ assert db_manager.open_user_database("nobody", PASSWORD) is None