~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
test: isolate security fixture data directories (#7957)
LearningCircuitde191c13943b
diff --git a/.github/workflows/security-tests.yml b/.github/workflows/security-tests.ymlindex f635c09be8..10b8412e6d 100644--- a/.github/workflows/security-tests.yml+++ b/.github/workflows/security-tests.yml@@ -69,6 +69,11 @@ jobs:# (osv-scanner.yml), which reads pdm.lock directly and doesn't# fight PDM's resolution overrides the way pip-audit did.+ - name: Verify security fixture isolation controls+ run: >-+ pdm run python -m unittest discover+ -s tests/ci/standalone -p test_security_data_dir_guard.py -v+- name: Run security test suiteenv:DATABASE_URL: postgresql://postgres:postgres@localhost:5432/test_security_dbdiff --git a/tests/ci/standalone/test_security_data_dir_guard.py b/tests/ci/standalone/test_security_data_dir_guard.pynew file mode 100644index 0000000000..cab2b4bbd1--- /dev/null+++ b/tests/ci/standalone/test_security_data_dir_guard.py@@ -0,0 +1,300 @@+"""Exercise the real security fixture in small, isolated pytest processes."""++import json+import os+from pathlib import Path+import subprocess+import sys+import tempfile+import textwrap+import unittest++import pytest+++ROOT = Path(__file__).resolve().parents[3]+# Only the interference probe starts two lightweight workers. Keep these+# subprocess checks out of the outer CI suite's parallel worker pool.+pytestmark = pytest.mark.serial+++class SecurityDataDirectoryGuardTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.project = Path(self.temporary.name)+ self.shared_default = self.project / "shared-default"+ self.project.joinpath("pytest.ini").write_text("[pytest]\n")+ support = (+ "from pathlib import Path\n"+ "import importlib.util\n"+ "import time\n"+ f"PROJECT = Path({str(self.project)!r})\n"+ f"SHARED_DEFAULT = Path({str(self.shared_default)!r})\n"+ f"PATHS_FILE = Path({str(ROOT / 'src/local_deep_research/config/paths.py')!r})\n"+ + textwrap.dedent(+ """+ PROVIDER_CALLS = []++ def controlled_user_data_dir(appname=None, *args, **kwargs):+ PROVIDER_CALLS.append((appname, args, kwargs))+ if appname == "local-deep-research":+ return str(SHARED_DEFAULT)+ return "other-provider-result"++ def paths():+ spec = importlib.util.spec_from_file_location(+ "guard_probe_paths", PATHS_FILE+ )+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module++ def wait_for(name):+ deadline = time.monotonic() + 15+ while not PROJECT.joinpath(name).exists():+ if time.monotonic() >= deadline:+ raise AssertionError("peer did not reach " + name)+ time.sleep(0.01)+ """+ )+ )+ self.project.joinpath("probe_support.py").write_text(support)+ self.project.joinpath("conftest.py").write_text(+ "import platformdirs\n"+ "from probe_support import controlled_user_data_dir\n"+ "platformdirs.user_data_dir = controlled_user_data_dir\n"+ 'pytest_plugins = ["tests.security.conftest"]\n'+ )++ def run_probe(self, guarded, *, peer=None):+ self.project.joinpath("test_raw_config_toml_smuggling.py").write_text(+ textwrap.dedent(guarded)+ )+ command = [+ sys.executable,+ "-m",+ "pytest",+ "-q",+ "--tb=short",+ "--color=no",+ "--confcutdir",+ str(self.project),+ "--basetemp",+ str(self.project / "pytest-temp"),+ "-o",+ "addopts=",+ ]+ if peer is not None:+ self.project.joinpath("test_peer.py").write_text(+ textwrap.dedent(peer)+ )+ command += ["-p", "xdist.plugin", "-n", "2", "--dist=loadfile"]+ environment = dict(os.environ)+ for name in (+ "LDR_DATA_DIR",+ "PYTEST_ADDOPTS",+ "PYTEST_PLUGINS",+ "PYTEST_CURRENT_TEST",+ "PYTEST_XDIST_WORKER",+ "PYTEST_XDIST_WORKER_COUNT",+ "PYTEST_XDIST_TESTRUNUID",+ ):+ environment.pop(name, None)+ environment.update(+ PYTHONPATH=os.pathsep.join((str(ROOT), str(ROOT / "src"))),+ PYTEST_DISABLE_PLUGIN_AUTOLOAD="1",+ OMP_NUM_THREADS="1",+ OPENBLAS_NUM_THREADS="1",+ MKL_NUM_THREADS="1",+ )+ return subprocess.run(+ command,+ cwd=self.project,+ env=environment,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ timeout=45,+ check=False,+ )++ def assert_guard_rejects(self, result):+ self.assertEqual(result.returncode, 1, result.stdout)+ self.assertIn("1 passed", result.stdout)+ self.assertIn("1 error", result.stdout)+ self.assertIn(+ "File-write-risk battery test leaked a write", result.stdout+ )++ def test_another_worker_default_write_is_not_attributed_to_guarded_test(+ self,+ ):+ result = self.run_probe(+ """+ from probe_support import PROJECT, wait_for++ def test_guarded():+ PROJECT.joinpath("ready").touch()+ wait_for("written")+ """,+ peer="""+ import json+ from probe_support import PROJECT, paths, wait_for++ def test_peer():+ wait_for("ready")+ directory = paths().get_library_directory()+ assert directory.is_dir()+ PROJECT.joinpath("peer-path.json").write_text(+ json.dumps(str(directory))+ )+ PROJECT.joinpath("written").touch()+ """,+ )+ self.assertEqual(result.returncode, 0, result.stdout)+ self.assertIn("2 passed", result.stdout)+ peer_path = Path(+ json.loads(self.project.joinpath("peer-path.json").read_text())+ )+ self.assertTrue(peer_path.is_dir())+ self.assertTrue(peer_path.is_relative_to(self.project / "pytest-temp"))+ self.assertFalse(self.shared_default.exists())++ def test_guard_still_rejects_own_default_directory_creation(self):+ result = self.run_probe(+ """+ from probe_support import paths++ def test_guarded():+ assert paths().get_library_directory().is_dir()+ """+ )+ self.assert_guard_rejects(result)++ def test_guard_still_rejects_own_default_file_creation(self):+ result = self.run_probe(+ """+ from probe_support import paths++ def test_guarded():+ directory = paths().get_data_directory()+ directory.mkdir(parents=True, exist_ok=True)+ directory.joinpath("example.txt").write_text("fixture data")+ """+ )+ self.assert_guard_rejects(result)++ def test_guard_still_rejects_native_sqlite_file_creation(self):+ result = self.run_probe(+ """+ import sqlite3+ from probe_support import paths++ def test_guarded():+ directory = paths().get_data_directory()+ directory.mkdir(parents=True, exist_ok=True)+ connection = sqlite3.connect(directory / "example.db")+ connection.close()+ """+ )+ self.assert_guard_rejects(result)++ def test_explicit_test_data_directory_remains_usable(self):+ result = self.run_probe(+ """+ from probe_support import paths++ def test_guarded(tmp_path, monkeypatch):+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ assert paths().get_library_directory() == tmp_path / "library"+ assert tmp_path.joinpath("library").is_dir()+ """+ )+ self.assertEqual(result.returncode, 0, result.stdout)+ self.assertFalse(self.shared_default.exists())++ def test_other_platformdirs_applications_keep_their_provider(self):+ result = self.run_probe(+ """+ import platformdirs+ from probe_support import PROVIDER_CALLS++ def test_guarded():+ value = platformdirs.user_data_dir(+ "other-tool", appauthor=False, version="v2", roaming=True+ )+ assert value == "other-provider-result"+ assert PROVIDER_CALLS[-1] == (+ "other-tool", (),+ {"appauthor": False, "version": "v2", "roaming": True},+ )+ """+ )+ self.assertEqual(result.returncode, 0, result.stdout)++ def test_default_path_is_private_to_the_guarded_test(self):+ result = self.run_probe(+ """+ import json+ from probe_support import PROJECT, paths++ def test_guarded():+ directory = paths().get_data_directory()+ PROJECT.joinpath("default.json").write_text(+ json.dumps(str(directory))+ )+ """+ )+ self.assertEqual(result.returncode, 0, result.stdout)+ directory = Path(+ json.loads(self.project.joinpath("default.json").read_text())+ )+ self.assertNotEqual(directory, self.shared_default)+ self.assertTrue(directory.is_relative_to(self.project / "pytest-temp"))+ self.assertFalse(self.shared_default.exists())++ def test_successive_tests_receive_distinct_default_paths(self):+ result = self.run_probe(+ """+ import json+ from probe_support import PROJECT, paths++ def test_first():+ PROJECT.joinpath("first.json").write_text(+ json.dumps(str(paths().get_data_directory()))+ )++ def test_second():+ PROJECT.joinpath("second.json").write_text(+ json.dumps(str(paths().get_data_directory()))+ )+ """+ )+ self.assertEqual(result.returncode, 0, result.stdout)+ first = json.loads(self.project.joinpath("first.json").read_text())+ second = json.loads(self.project.joinpath("second.json").read_text())+ self.assertNotEqual(first, second)+ self.assertFalse(self.shared_default.exists())++ def test_unaudited_tests_also_have_a_private_worker_default(self):+ self.project.joinpath("test_other.py").write_text(+ "import json\n"+ "from probe_support import PROJECT, paths\n"+ "def test_other():\n"+ " directory = paths().get_library_directory()\n"+ " PROJECT.joinpath('other.json').write_text(\n"+ " json.dumps(str(directory)))\n"+ )+ result = self.run_probe("def test_guarded(): pass\n")+ self.assertEqual(result.returncode, 0, result.stdout)+ directory = Path(+ json.loads(self.project.joinpath("other.json").read_text())+ )+ self.assertTrue(directory.is_dir())+ self.assertTrue(directory.is_relative_to(self.project / "pytest-temp"))+ self.assertFalse(self.shared_default.exists())+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/security/conftest.py b/tests/security/conftest.pyindex 83883cc650..a4c9c75b43 100644--- a/tests/security/conftest.py+++ b/tests/security/conftest.py@@ -16,7 +16,7 @@ from .auth_fixtures import AuthenticatedUser# ----------------------------------------------------------------------------# Guard against real-platformdirs-directory leaks+# Guard against unconfigured platform-default-directory writes## security/test-file-write-risk-battery (PR #5638) audited these files to# confirm every real filesystem write happens under tmp_path, pinning@@ -37,18 +37,19 @@ from .auth_fixtures import AuthenticatedUser# ``test_relative_storage_path_still_creates_a_library`` for the fixed# instances.#-# This fixture makes the class of leak fail loudly instead of silently-# polluting a developer's or CI runner's real data directory. It is scoped-# to exactly the audited battery below (by filename) rather than enabled-# for all of tests/security/: the rest of that tree has not been swept for-# this same hazard, and a blanket autouse assertion there could flag files-# nobody has vetted. As of this audit no test anywhere in tests/security/-# or tests/config/ intentionally exercises the real (non-tmp_path)-# platformdirs location -- every one either pins LDR_DATA_DIR or patches-# ``platformdirs.user_data_dir`` outright -- so nothing here is expected to-# need an opt-out; if a future test genuinely needs the real path, add it-# to the exclusion via a marker rather than removing this file from the-# guarded set.+# Security tests use a worker-private platform default. Guarded tests get a+# fresh default of their own, so writes still fail rather than disappearing+# into an already populated worker directory. Workers otherwise observe the+# same user directory and can attribute another worker's write to the wrong+# test. Only the application's default is redirected; LDR_DATA_DIR overrides+# and other applications' platformdirs calls retain their usual behavior.+# The write assertion covers exactly the audited battery below (by filename).+# The rest of tests/security/ has not been swept for this same hazard, so a+# blanket assertion there could flag files nobody has vetted. Guarded tests+# must pin LDR_DATA_DIR or patch the path+# provider they intend to exercise; a write through the unconfigured default+# still fails even though its destination is now safely under pytest's base+# temporary directory._GUARDED_BATTERY_FILES = {"test_benchmark_and_temp_lifecycle.py","test_disk_write_guards.py",@@ -77,40 +78,78 @@ def _is_guarded_battery_test(request: pytest.FixtureRequest) -> bool:return request.node.path.name in _GUARDED_BATTERY_FILES+def _isolated_user_data_dir(default_data_dir: Path, original_user_data_dir):+ def user_data_dir(appname=None, *args, **kwargs):+ if appname == "local-deep-research":+ return str(default_data_dir)+ return original_user_data_dir(appname, *args, **kwargs)++ return user_data_dir++[email protected](scope="session")+def _worker_platform_default_dir(tmp_path_factory):+ return (+ tmp_path_factory.mktemp("platform-default-worker")+ / "local-deep-research"+ )++@pytest.fixture(autouse=True)-def _guard_against_real_data_dir_writes(request):- """Fail loudly if a battery test leaks a write outside tmp_path into- the REAL platformdirs user data directory.-- Function-scoped (not session-scoped) so a failure pinpoints the exact- test that leaked, matching this file's other autouse fixtures. Compares- a before/after snapshot rather than asserting the directory is empty- or absent, since a developer's machine may already have one from real- (non-test) app use -- only NEW entries created during the test trip- this.-- Known limitation: under ``pytest-xdist -n auto`` a genuine leak in a- concurrently-running, unrelated test (outside this guarded set) could- in principle be misattributed to whichever guarded test happens to be- running at that moment. Nothing in this repo's test suite is known to- leak this way today (see the audit note above), so this is a- theoretical gap, not a live false-positive source.+def _isolate_default_data_dir(monkeypatch, _worker_platform_default_dir):+ """Keep security-test fallbacks off the machine's actual data directory.++ The path belongs to this worker; the provider patch is function-scoped+ so it cannot leak into tests outside this conftest's directory.+ """+ monkeypatch.setattr(+ platformdirs,+ "user_data_dir",+ _isolated_user_data_dir(+ _worker_platform_default_dir, platformdirs.user_data_dir+ ),+ )++[email protected](autouse=True)+def _guard_against_real_data_dir_writes(+ request, monkeypatch, tmp_path_factory, _isolate_default_data_dir+):+ """Reject default-data writes without sharing another worker's baseline.++ Use a separate temporary path for the platform default, outside the+ test's explicit data root. Application path helpers still resolve and+ create real directories, so the same before/after check catches an+ unintended fallback. A peer worker's activity cannot change this path."""if not _is_guarded_battery_test(request):yieldreturn- real_data_dir = Path(platformdirs.user_data_dir("local-deep-research"))- before = set(real_data_dir.iterdir()) if real_data_dir.is_dir() else set()+ default_data_dir = (+ tmp_path_factory.mktemp("platform-default-guard")+ / "local-deep-research"+ )+ monkeypatch.setattr(+ platformdirs,+ "user_data_dir",+ _isolated_user_data_dir(default_data_dir, platformdirs.user_data_dir),+ )+ before = (+ set(default_data_dir.iterdir()) if default_data_dir.is_dir() else set()+ )yield- after = set(real_data_dir.iterdir()) if real_data_dir.is_dir() else set()+ after = (+ set(default_data_dir.iterdir()) if default_data_dir.is_dir() else set()+ )leaked = after - beforeassert not leaked, (- "File-write-risk battery test leaked a write to the REAL "- f"platformdirs user data directory ({real_data_dir}), outside "- f"pytest's tmp_path sandbox: {sorted(p.name for p in leaked)}. "+ "File-write-risk battery test leaked a write to the unconfigured "+ f"platformdirs data directory ({default_data_dir}), instead of an "+ "explicit temporary data root: "+ f"{sorted(p.name for p in leaked)}. ""This almost always means a call chain resolved a ""settings-derived path (get_library_directory / ""get_absolute_path_from_settings / _ensure_dir / BackupService / "diff --git a/tests/security/test_cross_user_isolation_invariants.py b/tests/security/test_cross_user_isolation_invariants.pyindex e37e34d96c..a12e856014 100644--- a/tests/security/test_cross_user_isolation_invariants.py+++ b/tests/security/test_cross_user_isolation_invariants.py@@ -39,7 +39,6 @@ import asyncioimport threadingimport uuidfrom concurrent.futures import ThreadPoolExecutor-from unittest.mock import patchimport pytestfrom cachetools import LRUCache@@ -97,11 +96,11 @@ def real_db_manager(tmp_path_factory):mp.delenv("TESTING", raising=False)tmp_dir = tmp_path_factory.mktemp("cross_user_isolation_dbs")- with patch(- "local_deep_research.database.encrypted_db.get_data_directory",- return_value=tmp_dir,- ):- manager = DatabaseManager()+ manager = DatabaseManager()+ # The manager resolves its default directory on every access, so a+ # constructor-only path patch cannot keep module-scoped databases stable+ # across the function-scoped platform-default fixtures.+ manager.data_dir = tmp_dir / "encrypted_databases"manager.create_user_database(_ALICE, _ALICE_PW)manager.create_user_database(_BOB, _BOB_PW)