~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(security): cover filesystem boundaries and cleanup (#5638)
LearningCircuitc0373cc115db
diff --git a/changelog.d/+security-file-write-test-battery.misc.md b/changelog.d/+security-file-write-test-battery.misc.mdnew file mode 100644index 0000000000..41b8397309--- /dev/null+++ b/changelog.d/+security-file-write-test-battery.misc.md@@ -0,0 +1 @@+Add a file-write / disk / host-effect security test battery; related hardening is tracked privately.diff --git a/tests/security/conftest.py b/tests/security/conftest.pyindex 4e16da8cd6..83883cc650 100644--- a/tests/security/conftest.py+++ b/tests/security/conftest.py@@ -5,13 +5,173 @@ Fixtures for security module tests.from __future__ import annotationsimport uuid+from pathlib import Path+import platformdirsimport pytestfrom fastapi.testclient import TestClient+from loguru import loggerfrom .auth_fixtures import AuthenticatedUser+# ---------------------------------------------------------------------------+# Guard against real-platformdirs-directory leaks+#+# security/test-file-write-risk-battery (PR #5638) audited these files to+# confirm every real filesystem write happens under tmp_path, pinning+# LDR_DATA_DIR (via monkeypatch.setenv) wherever a call chain resolves a+# settings-derived path. The audit found several holes caused by an+# EAGERLY-EVALUATED DEFAULT ARGUMENT: e.g.+# ``settings.get_setting("research_library.storage_path",+# str(get_library_directory()))`` in ``research_library/utils/__init__.py``+# -- Python evaluates ``str(get_library_directory())`` (which+# ``mkdir(parents=True)``s ``<data_dir>/library`` via ``config.paths.+# _ensure_dir``) BEFORE ``get_setting`` even runs, regardless of whether a+# stub/mock settings manager ever looks at that default. A test that forgot+# to pin ``LDR_DATA_DIR`` therefore created a real directory under+# ``platformdirs.user_data_dir("local-deep-research")`` on the machine+# running the suite -- exactly what this battery exists to prove doesn't+# happen. See ``test_document_path_deletion.py``'s ``_settings_root`` and+# ``test_settings_path_escape.py``'s+# ``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.+_GUARDED_BATTERY_FILES = {+ "test_benchmark_and_temp_lifecycle.py",+ "test_disk_write_guards.py",+ "test_disk_write_guards_extended.py",+ "test_document_path_deletion.py",+ "test_downloader_filename_pipeline.py",+ "test_identity_and_index_pins.py",+ "test_identity_paths_and_host_effects.py",+ "test_journal_dataset_writes.py",+ "test_mcp_and_secure_logging.py",+ "test_notes_and_upload_paths.py",+ "test_path_property_fuzz.py",+ "test_poisoned_path_reads.py",+ "test_queue_processor_writes.py",+ "test_raw_config_toml_smuggling.py",+ "test_remote_filename_writes.py",+ "test_report_path_deletion.py",+ "test_secure_logging_writes.py",+ "test_settings_bulk_import.py",+ "test_settings_path_escape.py",+ "test_zotero_ingest_writes.py",+}+++def _is_guarded_battery_test(request: pytest.FixtureRequest) -> bool:+ return request.node.path.name in _GUARDED_BATTERY_FILES++[email protected](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.+ """+ if not _is_guarded_battery_test(request):+ yield+ return++ 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()++ yield++ after = set(real_data_dir.iterdir()) if real_data_dir.is_dir() else set()+ leaked = after - before+ assert 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)}. "+ "This almost always means a call chain resolved a "+ "settings-derived path (get_library_directory / "+ "get_absolute_path_from_settings / _ensure_dir / BackupService / "+ "DownloadService / get_library_storage_path / etc.) without the "+ "test pinning LDR_DATA_DIR via monkeypatch.setenv -- see this "+ "fixture's module docstring for the eager-default-argument "+ "mechanism."+ )+++def _loguru_global_state() -> dict[str, object]:+ """Snapshot the process-wide loguru configuration a test can leak.++ ``config_logger()`` and ``configure_mcp_logging()`` (which+ ``run_server()`` calls) replace the handler table, install the+ credential-redaction patcher and enable the ``local_deep_research``+ namespace. Loguru's per-module ``enabled`` cache is left out on purpose:+ loguru fills it lazily for every module that logs, so it also grows in+ tests that never touch the configuration.+ """+ core = logger._core+ return {+ "patcher": core.patcher,+ "activation_list": list(core.activation_list),+ "activation_none": core.activation_none,+ "handlers": dict(core.handlers),+ "min_level": core.min_level,+ }++[email protected](autouse=True)+def _guard_against_loguru_state_leaks(request):+ """Fail the battery test that leaves loguru's global configuration changed.++ Loguru keeps one handler table and one patcher per process, and+ monkeypatch restores neither. A leaked redaction patcher rewrites every+ later record in the same worker, so the failure surfaces in an unrelated+ file instead of the test that caused it: the ``***REDACTED***`` marker+ asserted by ``test_settings_logger_non_dict_redaction.py`` arrives as+ ``[REDACTED]``. Run in-process logging configuration inside+ ``tests.test_utils.restored_loguru_state()``.+ """+ if not _is_guarded_battery_test(request):+ yield+ return++ before = _loguru_global_state()++ yield++ after = _loguru_global_state()+ changed = sorted(+ name for name, value in before.items() if after[name] != value+ )+ assert not changed, (+ "File-write-risk battery test leaked process-wide loguru state "+ f"({', '.join(changed)}). Run in-process config_logger() and "+ "run_server() calls inside tests.test_utils.restored_loguru_state()."+ )++@pytest.fixturedef mock_pdf_content():"""Create minimal valid PDF content for testing."""@@ -76,6 +236,128 @@ def sample_urls():}+# ---------------------------------------------------------------------------+# Shared library-PDF fixtures.+#+# Hoisted out of the four security batteries that each carried a verbatim+# copy (test_remote_filename_writes, test_zotero_ingest_writes,+# test_downloader_filename_pipeline, test_path_property_fuzz) so the set is+# defined once. ``test_poisoned_path_reads`` keeps its own file-local+# ``library_session`` on purpose: it yields ``(session, source_type)`` rather+# than a bare session, and a file-local fixture shadows this one.+#+# The heavy imports stay inside the fixture bodies so importing this conftest+# does not drag the library stack into every unrelated security test module.+# ---------------------------------------------------------------------------+++def library_session():+ """In-memory SQLite session with the library models loaded.++ ``StaticPool`` + ``check_same_thread=False``: some callers (e.g.+ ``test_path_property_fuzz.py``'s ``TestPositiveControls``) patch this+ session into a real FastAPI ``TestClient`` request for a sync route,+ which Starlette dispatches through ``run_in_threadpool`` — a+ different OS thread than the one that created/seeded this session.+ Without a shared, thread-agnostic connection, SQLAlchemy either hands+ that worker thread a fresh, empty ``:memory:`` database or reuses the+ literal ``sqlite3.Connection`` object across threads and trips+ Python's ``check_same_thread`` guard (``sqlite3.ProgrammingError:+ SQLite objects created in a thread can only be used in that same+ thread``) on close/rollback. Same fix as+ ``test_socket_ownership_edges_fastapi.py`` and+ ``test_pagination_bounds.py``.+ """+ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker+ from sqlalchemy.pool import StaticPool++ from local_deep_research.database.models import Base++ engine = create_engine(+ "sqlite:///:memory:",+ poolclass=StaticPool,+ connect_args={"check_same_thread": False},+ )+ Base.metadata.create_all(engine)+ with sessionmaker(bind=engine)() as session:+ yield session+ engine.dispose()+++def fresh_document(library_session):+ """A new completed Document per test, so file_path/storage_mode reset.++ The ``SourceType`` row is created inline rather than in its own+ ``source_type`` fixture: no test in this directory requests it+ directly, and ``source_type`` is already used as a parametrize+ argname in test_journal_dataset_writes.py.+ """+ import hashlib+ import uuid++ from local_deep_research.database.models.library import (+ Document,+ DocumentStatus,+ SourceType,+ )++ source_type = SourceType(+ id=str(uuid.uuid4()),+ name="research_download",+ display_name="Research Download",+ description="x",+ )+ library_session.add(source_type)+ library_session.commit()++ value = Document(+ id=str(uuid.uuid4()),+ source_type_id=source_type.id,+ document_hash=hashlib.sha256(b"placeholder").hexdigest(),+ file_size=0,+ file_type="pdf",+ status=DocumentStatus.COMPLETED,+ title="t",+ )+ library_session.add(value)+ library_session.commit()+ return value+++def fs_storage(tmp_path):+ """Real PDFStorageManager in filesystem mode rooted under tmp_path."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ library_root = tmp_path / "library"+ (library_root / "pdfs").mkdir(parents=True)+ return PDFStorageManager(+ library_root=library_root,+ storage_mode="filesystem",+ username="testuser",+ )+++def canary_paths(tmp_path):+ """Files planted OUTSIDE library_root that must remain untouched."""+ outside = tmp_path / "outside_canary_zone"+ outside.mkdir()+ canaries = {+ "outer_passwd": outside / "passwd.txt",+ "outer_home": outside / "home.txt",+ "outer_etc": outside / "etc_marker.txt",+ }+ for path in canaries.values():+ path.write_text("UNTOUCHED-CANARY\n", encoding="utf-8")+ return canaries++# =============================================================================# Cross-user (two-principal) fixtures# =============================================================================diff --git a/tests/security/test_benchmark_and_temp_lifecycle.py b/tests/security/test_benchmark_and_temp_lifecycle.pynew file mode 100644index 0000000000..0f03ce8952--- /dev/null+++ b/tests/security/test_benchmark_and_temp_lifecycle.py@@ -0,0 +1,384 @@+import json+import os+import shutil+import tempfile+import time+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import MagicMock++import pytest+++def _result_line() -> str:+ return (+ json.dumps(+ {+ "id": "1",+ "problem": "question",+ "correct_answer": "answer",+ "response": "answer",+ }+ )+ + "\n"+ )+++def _allow_benchmark_writes(monkeypatch) -> None:+ monkeypatch.setattr(+ "local_deep_research.config.search_config.get_setting_from_snapshot",+ lambda *_args, **_kwargs: True,+ )+++def _grader() -> MagicMock:+ grader = MagicMock()+ grader.invoke.return_value = SimpleNamespace(+ content="Extracted Answer: answer\nReasoning: ok\nCorrect: yes"+ )+ return grader+++def test_automated_grader_replaces_only_its_output_file(tmp_path):+ from local_deep_research.benchmarks.graders import _grade_results_inner++ results = tmp_path / "results.jsonl"+ output = tmp_path / "results.json"+ sibling = tmp_path / "results-backup.json"+ nested = tmp_path / "nested" / "results.json"+ results.write_text(_result_line())+ output.write_text("stale")+ sibling.write_text("canary")+ nested.parent.mkdir()+ nested.write_text("nested canary")++ graded = _grade_results_inner(+ _grader(), str(results), str(output), "simpleqa", None+ )++ assert len(graded) == 1+ assert [+ json.loads(line) for line in output.read_text().splitlines()+ ] == graded+ assert graded[0]["is_correct"] is True+ assert sibling.read_text() == "canary"+ assert nested.read_text() == "nested canary"+++def test_automated_grader_unlinks_symlink_without_deleting_target(tmp_path):+ from local_deep_research.benchmarks.graders import _grade_results_inner++ results = tmp_path / "results.jsonl"+ output = tmp_path / "results.json"+ outside = tmp_path / "outside.json"+ results.write_text(_result_line())+ outside.write_text("outside canary")+ try:+ output.symlink_to(outside)+ except (OSError, NotImplementedError):+ pytest.skip("Cannot create symlinks in this environment")++ _grade_results_inner(_grader(), str(results), str(output), "simpleqa", None)++ assert outside.read_text() == "outside canary"+ assert output.is_file() and not output.is_symlink()+++def test_human_grader_replaces_only_its_output_file(tmp_path):+ from local_deep_research.benchmarks.graders import human_evaluation++ results = tmp_path / "results.jsonl"+ output = tmp_path / "results.json"+ sibling = tmp_path / "results-backup.json"+ results.write_text(_result_line())+ output.write_text("stale")+ sibling.write_text("canary")++ graded = human_evaluation(str(results), str(output), interactive=False)++ assert len(graded) == 1+ assert [+ json.loads(line) for line in output.read_text().splitlines()+ ] == graded+ assert graded[0]["human_evaluation"] is True+ assert sibling.read_text() == "canary"+++def test_runner_cleanup_only_unlinks_its_timestamped_outputs(+ tmp_path, monkeypatch+):+ from local_deep_research.benchmarks import runners++ timestamp = "20000101_000000"+ monkeypatch.setattr(+ runners,+ "time",+ SimpleNamespace(strftime=lambda _format: timestamp),+ )+ dataset = MagicMock()+ dataset.load.return_value = []+ monkeypatch.setattr(+ runners.DatasetRegistry, "create_dataset", lambda **_kwargs: dataset+ )+ for suffix in ("results.jsonl", "evaluation.jsonl", "report.md"):+ (tmp_path / f"simpleqa_{timestamp}_{suffix}").write_text("stale")+ sibling = tmp_path / f"simpleqa_{timestamp}_results-backup.jsonl"+ nested = tmp_path / "nested" / f"simpleqa_{timestamp}_results.jsonl"+ sibling.write_text("canary")+ nested.parent.mkdir()+ nested.write_text("nested canary")++ runners.run_benchmark(+ "simpleqa", output_dir=str(tmp_path), run_evaluation=False+ )++ for suffix in ("results.jsonl", "evaluation.jsonl", "report.md"):+ assert not (tmp_path / f"simpleqa_{timestamp}_{suffix}").exists()+ assert sibling.read_text() == "canary"+ assert nested.read_text() == "nested canary"+++def test_simpleqa_writer_keeps_adjacent_canary(tmp_path, monkeypatch):+ from local_deep_research.benchmarks.evaluators import simpleqa++ timestamp = "20000101_000000"+ monkeypatch.setattr(+ simpleqa,+ "time",+ SimpleNamespace(strftime=lambda _format: timestamp, time=time.time),+ )+ dataset = MagicMock()+ dataset.load.return_value = [{"id": "1"}]+ dataset.get_question.return_value = "question"+ dataset.get_answer.return_value = "answer"+ monkeypatch.setattr(+ simpleqa.DatasetRegistry, "create_dataset", lambda **_kwargs: dataset+ )+ monkeypatch.setattr(+ "local_deep_research.api.quick_summary",+ lambda **_kwargs: {"summary": "answer", "sources": []},+ )+ monkeypatch.setattr(+ "local_deep_research.benchmarks.graders.grade_results",+ lambda **_kwargs: [],+ )+ monkeypatch.setattr(simpleqa, "calculate_metrics", lambda _path: {})+ monkeypatch.setattr(simpleqa, "generate_report", lambda **_kwargs: "report")+ canary = tmp_path / f"simpleqa_{timestamp}_results-backup.jsonl"+ canary.write_text("canary")++ result = simpleqa.SimpleQAEvaluator()._run_with_dataset_class(+ {}, 1, str(tmp_path)+ )++ assert Path(result["results_path"]).is_file()+ assert canary.read_text() == "canary"+++def test_optimizer_writes_only_named_result_files(tmp_path, monkeypatch):+ from local_deep_research.benchmarks.optimization.optuna_optimizer import (+ OptunaOptimizer,+ )++ _allow_benchmark_writes(monkeypatch)+ optimizer = OptunaOptimizer(+ "query", output_dir=str(tmp_path), study_name="study"+ )+ optimizer.trials_history = [{"score": 0.5}]+ optimizer.study = SimpleNamespace(+ best_params={"iterations": 1}, best_value=0.5, trials=[1]+ )+ canary = tmp_path / "study_history-backup.json"+ canary.write_text("canary")++ optimizer._save_results()++ assert (tmp_path / "study_history.json").is_file()+ assert (tmp_path / "study_best_params.json").is_file()+ assert (tmp_path / "study_study.pkl").is_file()+ assert canary.read_text() == "canary"+++def test_comparison_results_writer_keeps_adjacent_canary(tmp_path, monkeypatch):+ from local_deep_research.benchmarks.comparison.results import (+ Benchmark_results,+ )++ _allow_benchmark_writes(monkeypatch)+ output = tmp_path / "results.json"+ canary = tmp_path / "results-backup.json"+ canary.write_text("canary")++ results = Benchmark_results(str(output))+ results.add_result("model", "hardware", 1, 1, 1, 1, 0, "v", "today")++ assert json.loads(output.read_text())[0]["model"] == "model"+ assert canary.read_text() == "canary"+++def test_reporting_writer_keeps_adjacent_canary(tmp_path, monkeypatch):+ from local_deep_research.benchmarks.metrics.reporting import generate_report++ _allow_benchmark_writes(monkeypatch)+ results = tmp_path / "results.jsonl"+ output = tmp_path / "report.md"+ canary = tmp_path / "report-backup.md"+ results.write_text(_result_line())+ canary.write_text("canary")++ generate_report({}, str(results), str(output))++ assert output.is_file()+ assert canary.read_text() == "canary"+++def test_comparison_api_writer_keeps_adjacent_canary(tmp_path, monkeypatch):+ from local_deep_research.api import benchmark_functions++ _allow_benchmark_writes(monkeypatch)+ monkeypatch.setattr(+ benchmark_functions,+ "run_benchmark",+ lambda **_kwargs: {"metrics": {}, "total_examples": 0},+ )+ canary = tmp_path / "comparison_simpleqa_backup.md"+ nested = tmp_path / "nested" / "comparison_simpleqa.md"+ canary.write_text("canary")+ nested.parent.mkdir()+ nested.write_text("nested canary")++ result = benchmark_functions.compare_configurations(+ configurations=[{"name": "only"}], output_dir=str(tmp_path)+ )++ assert Path(result["report_path"]).is_file()+ assert canary.read_text() == "canary"+ assert nested.read_text() == "nested canary"+++def test_quality_evaluation_removes_real_mkdtemp_directory(+ tmp_path, monkeypatch+):+ from local_deep_research.benchmarks.metrics import calculation++ temp_dir = tmp_path / "ldr_benchmark_created"+ temp_dir.mkdir()+ monkeypatch.setattr(+ calculation,+ "tempfile",+ SimpleNamespace(mkdtemp=lambda prefix: str(temp_dir)),+ )+ monkeypatch.setattr(+ "local_deep_research.benchmarks.runners.run_simpleqa_benchmark",+ lambda **_kwargs: {"metrics": {"accuracy": 1.0}},+ )++ assert calculation.evaluate_benchmark_quality({})["accuracy"] == 1.0+ assert not temp_dir.exists()+++def test_quality_evaluation_rmtree_targets_only_mkdtemp_dir_on_error(+ tmp_path, monkeypatch+):+ from local_deep_research.benchmarks.metrics import calculation++ temp_dir = tmp_path / "ldr_benchmark_created"+ temp_dir.mkdir()+ captured = []+ monkeypatch.setattr(+ calculation,+ "tempfile",+ SimpleNamespace(mkdtemp=lambda prefix: str(temp_dir)),+ )+ monkeypatch.setattr(+ "local_deep_research.benchmarks.runners.run_simpleqa_benchmark",+ lambda **_kwargs: (_ for _ in ()).throw(+ RuntimeError("benchmark failure")+ ),+ )+ monkeypatch.setattr(shutil, "rmtree", lambda path: captured.append(path))++ assert calculation.evaluate_benchmark_quality({})["accuracy"] == 0.0+ assert captured == [str(temp_dir)]+++def test_sqlcipher_probe_removes_real_temp_file_on_success(+ monkeypatch, tmp_path+):+ from local_deep_research.database import encrypted_db++ # The probe spools through tempfile.NamedTemporaryFile+ # (encrypted_db.py:302-305); point tempfile at tmp_path so the test+ # never creates a file in the real system temp directory.+ monkeypatch.setattr(tempfile, "tempdir", str(tmp_path))+ paths = []+ original_unlink = os.unlink+ monkeypatch.setattr(+ encrypted_db, "apply_cipher_defaults_before_key", lambda _: None+ )+ monkeypatch.setattr(encrypted_db, "set_sqlcipher_key", lambda *_: None)+ monkeypatch.setattr(+ encrypted_db, "apply_sqlcipher_pragmas", lambda *_args, **_kwargs: None+ )+ monkeypatch.setattr(+ encrypted_db, "apply_performance_pragmas", lambda _: None+ )+ monkeypatch.setattr(encrypted_db, "get_sqlcipher_version", lambda _: "4.0")+ cursor = SimpleNamespace(close=lambda: None)+ connection = SimpleNamespace(+ cursor=lambda: cursor,+ execute=lambda _sql: SimpleNamespace(fetchone=lambda: (1,)),+ close=lambda: None,+ )+ monkeypatch.setattr(+ encrypted_db,+ "get_sqlcipher_module",+ lambda: SimpleNamespace(+ dbapi2=SimpleNamespace(connect=lambda _path: connection)+ ),+ )++ def observe_unlink(path):+ paths.append(Path(path))+ original_unlink(path)++ monkeypatch.setattr(os, "unlink", observe_unlink)++ manager = encrypted_db.DatabaseManager.__new__(encrypted_db.DatabaseManager)+ assert manager._check_encryption_available()+ assert len(paths) == 1+ assert paths[0].parent == tmp_path+ assert not paths[0].exists()+++def test_sqlcipher_probe_removes_temp_file_when_probe_fails(+ monkeypatch, tmp_path+):+ from local_deep_research.database import encrypted_db++ # The probe spools through tempfile.NamedTemporaryFile+ # (encrypted_db.py:302-305); point tempfile at tmp_path so the test+ # never creates a file in the real system temp directory.+ monkeypatch.setattr(tempfile, "tempdir", str(tmp_path))+ paths = []+ original_unlink = os.unlink+ monkeypatch.setattr(+ encrypted_db,+ "get_sqlcipher_module",+ lambda: (_ for _ in ()).throw(RuntimeError("probe failed")),+ )+ monkeypatch.setattr(encrypted_db, "get_env_setting", lambda *_args: False)++ def observe_unlink(path):+ paths.append(Path(path))+ original_unlink(path)++ monkeypatch.setattr(os, "unlink", observe_unlink)++ manager = encrypted_db.DatabaseManager.__new__(encrypted_db.DatabaseManager)+ with pytest.raises(RuntimeError, match="SQLCipher not available"):+ manager._check_encryption_available()++ assert len(paths) == 1+ assert paths[0].parent == tmp_path+ assert not paths[0].exists()diff --git a/tests/security/test_disk_write_guards.py b/tests/security/test_disk_write_guards.pynew file mode 100644index 0000000000..a58a0dc280--- /dev/null+++ b/tests/security/test_disk_write_guards.py@@ -0,0 +1,362 @@+"""GREEN disk-write guardrail battery: pins CURRENT secure write/delete+behavior so any regression turns the suite red.++Surfaces covered (complements tests/vector_stores/*, tests/security/+test_file_write_verifier.py, and tests/web/routes/test_research_routes_config.py+— those drive mocked settings or the full client; this file uses real+tmp_path filesystems and unmocked write paths wherever possible):++1. FAISS atomic persist (tempfile.mkstemp + os.replace, 0700 dir, stale-.tmp sweep)+2. Legacy docstore migration symlink/hostile-path guards+3. Verified JSON writes scrubbing sensitive keys (unmocked happy path)+4. /api/save_raw_config: blocked-key refusal + verified-write gate composition+5. FileReportStorage research_id containment + delete scoping+6. Backup prune deleting only direct-child ldr_backup_*.db(.tmp) matches++Offline, tmp_path-only, no LLM/network. If symlinks cannot be created the+affected tests skip rather than pass vacuously.+"""++import json+import os+import sys+import tempfile+import time+from pathlib import Path++import numpy as np+import pytest+++# --------------------------------------------------------------------------+# Surface 1: FAISS atomic persist+# (src/local_deep_research/vector_stores/implementations/faiss_store.py)+# --------------------------------------------------------------------------+def _make_store():+ from local_deep_research.vector_stores.implementations.faiss_store import (+ FaissVectorStore,+ )++ store = FaissVectorStore.create(+ dimension=2,+ index_type="flat",+ metric="l2",+ normalize=False,+ )+ store.add([1], np.array([[1.0, 2.0]], dtype="float32"))+ return store+++ sys.platform == "win32", reason="chmod is not supported on Windows"+)+def test_faiss_persist_stays_in_cache_root_and_leaves_no_tmp(tmp_path):+ target = tmp_path / "cache" / "index.faiss"++ _make_store().persist(target)++ assert target.is_file()+ assert target.resolve().is_relative_to((tmp_path / "cache").resolve())+ assert (target.parent.stat().st_mode & 0o777) == 0o700+ # The index is the ONLY file anywhere under the cache root — persist+ # must not scatter bytes to any other location.+ assert [p for p in tmp_path.rglob("*") if p.is_file()] == [target]+ assert list(target.parent.glob(f"{target.name}.*.tmp")) == []+++def test_faiss_persist_sweeps_stale_tmp_but_spares_fresh_tmp(tmp_path):+ from local_deep_research.vector_stores.implementations.faiss_store import (+ _STALE_TMP_AGE_SECONDS,+ )++ target = tmp_path / "cache" / "index.faiss"+ target.parent.mkdir()+ # Sibling temps with the REAL mkstemp prefix/suffix the write itself+ # uses, so this fails if the sweep glob and the write ever drift apart.+ stale_fd, stale_name = tempfile.mkstemp(+ dir=target.parent, prefix=f"{target.name}.", suffix=".tmp"+ )+ fresh_fd, fresh_name = tempfile.mkstemp(+ dir=target.parent, prefix=f"{target.name}.", suffix=".tmp"+ )+ os.close(stale_fd)+ os.close(fresh_fd)+ stale = Path(stale_name)+ fresh = Path(fresh_name)+ old_time = time.time() - _STALE_TMP_AGE_SECONDS - 1+ os.utime(stale, (old_time, old_time))++ _make_store().persist(target)++ assert not stale.exists() # orphaned by a hard-killed prior write -> swept+ assert fresh.exists() # concurrent worker's in-flight temp -> spared+++def test_faiss_persist_replace_failure_keeps_original_index(+ tmp_path, monkeypatch+):+ import local_deep_research.vector_stores.implementations.faiss_store as module++ target = tmp_path / "cache" / "index.faiss"+ original = _make_store()+ original.persist(target)+ original_bytes = target.read_bytes()++ def fail_replace(_source, _destination):+ raise OSError("simulated rename failure")++ monkeypatch.setattr(module.os, "replace", fail_replace)++ with pytest.raises(OSError, match="simulated rename failure"):+ _make_store().persist(target)++ # os.replace-only persistence: the durable file is either the old bytes+ # or the new bytes, never a partial write, and no temp litter remains.+ assert target.read_bytes() == original_bytes+ assert list(target.parent.glob(f"{target.name}.*.tmp")) == []+++# --------------------------------------------------------------------------+# Surface 2: legacy cleanup symlink / hostile-path guards+# (src/local_deep_research/vector_stores/legacy_cleanup.py)+# --------------------------------------------------------------------------+def test_legacy_cleanup_refuses_symlinked_root(tmp_path, monkeypatch):+ import local_deep_research.vector_stores.legacy_cleanup as cleanup++ outside = tmp_path / "outside"+ outside.mkdir()+ foreign = outside / "foreign.pkl"+ foreign.write_bytes(b"outside plaintext")+ root = tmp_path / "rag_indices"+ try:+ root.symlink_to(outside, target_is_directory=True)+ except (OSError, NotImplementedError):+ pytest.skip("Cannot create symlinks in this environment")+ monkeypatch.setattr(cleanup, "_rag_cache_root", lambda: root)++ result = cleanup.migrate_legacy_docstores()++ assert result["scan_errors"] == 1+ assert result["deleted"] == 0+ assert foreign.exists() # nothing outside the intended tree was touched+++def test_legacy_cleanup_flags_symlinked_pkl_without_touching_target(+ tmp_path, monkeypatch+):+ import local_deep_research.vector_stores.legacy_cleanup as cleanup++ root = tmp_path / "rag_indices"+ root.mkdir()+ outside = tmp_path / "outside.pkl"+ outside.write_bytes(b"outside plaintext")+ linked_pkl = root / "linked.pkl"+ try:+ linked_pkl.symlink_to(outside)+ except (OSError, NotImplementedError):+ pytest.skip("Cannot create symlinks in this environment")+ monkeypatch.setattr(cleanup, "_rag_cache_root", lambda: root)++ result = cleanup.migrate_legacy_docstores()++ # A symlinked .pkl must be flagged (incomplete migration), never+ # unlinked-and-declared-clean while the real plaintext target survives.+ assert result["scan_errors"] == 1+ assert result["deleted"] == 0+ assert linked_pkl.is_symlink()+ assert outside.read_bytes() == b"outside plaintext"+++def test_legacy_cleanup_deletes_real_pkl_inside_cache_root(+ tmp_path, monkeypatch+):+ import local_deep_research.vector_stores.legacy_cleanup as cleanup++ root = tmp_path / "rag_indices"+ root.mkdir()+ real_pkl = root / "legacy.pkl"+ real_pkl.write_bytes(b"invalid legacy pickle")+ monkeypatch.setattr(cleanup, "_rag_cache_root", lambda: root)++ result = cleanup.migrate_legacy_docstores()++ # Only REAL in-root .pkl files are migrated/deleted (unreadable ones+ # still deleted for plaintext removal, falling back to reindex).+ assert result["found"] == 1+ assert result["deleted"] == 1+ assert result["reindex_fallback"] == 1+ assert not real_pkl.exists()+++# --------------------------------------------------------------------------+# Surface 3: verified JSON writes scrub sensitive keys (unmocked happy path)+# (src/local_deep_research/security/file_write_verifier.py)+# --------------------------------------------------------------------------+def test_write_json_verified_scrubs_nested_secrets_to_real_file(tmp_path):+ from local_deep_research.security.file_write_verifier import (+ write_json_verified,+ )++ target = tmp_path / "verified.json"+ secret = "nested-secret-value"+ # No mocks: a real settings snapshot gates a real file write.+ write_json_verified(+ target,+ {+ "name": "safe",+ "nested": {"api_key": secret},+ "items": [{"password": secret}],+ },+ "system.allow_config_write",+ settings_snapshot={"system.allow_config_write": True},+ )++ written_text = target.read_text()+ assert secret not in written_text+ assert json.loads(written_text) == {+ "name": "safe",+ "nested": {"api_key": "[REDACTED]"},+ "items": [{"password": "[REDACTED]"}],+ }+++# --------------------------------------------------------------------------+# Surface 4: /api/save_raw_config verified-write composition+# (src/local_deep_research/web/routers/research.py)+#+# This surface used to be exercised here by calling the Flask route handler+# directly through a bare ``app.test_request_context()`` — the FastAPI+# migration (#3299) deleted ``web.routes.research_routes`` entirely, so+# that harness no longer imports. Rather than re-invent a second harness+# in this file, the coverage lives in+# ``tests/security/test_save_raw_config_blocked_keys_fastapi.py``, which+# drives the real FastAPI route end to end (auth + CSRF + the real+# ``TestClient``) and is a strict superset of what stood here: every+# blocked-key pattern, the open/closed write gate, and the real verified+# write landing on disk unmocked.+# --------------------------------------------------------------------------+++# --------------------------------------------------------------------------+# Surface 5: report path containment + delete scoping+# (src/local_deep_research/storage/file.py)+# --------------------------------------------------------------------------+ "research_id", ["../escape", "/tmp/escape", "bad\x00id"]+)+def test_report_path_rejects_hostile_research_ids(tmp_path, research_id):+ from local_deep_research.storage.file import FileReportStorage++ storage = FileReportStorage(tmp_path / "outputs")++ with pytest.raises(ValueError):+ storage._get_report_path(research_id)+++def test_delete_report_cannot_unlink_outside_outputs_root(tmp_path):+ from local_deep_research.storage.file import FileReportStorage++ outputs = tmp_path / "outputs"+ outside = tmp_path / "escape.md"+ outside.write_text("canary")+ storage = FileReportStorage(outputs)++ assert storage.delete_report("../escape") is False+ assert outside.read_text() == "canary"+++def test_delete_report_only_removes_files_under_outputs_root(tmp_path):+ from local_deep_research.storage.file import FileReportStorage++ outputs = tmp_path / "outputs"+ storage = FileReportStorage(outputs)+ report = outputs / "report.md"+ metadata = outputs / "report_metadata.json"+ canary = tmp_path / "canary.md"+ report.write_text("report")+ metadata.write_text("{}")+ canary.write_text("outside")++ assert storage.delete_report("report") is True+ assert not report.exists()+ assert not metadata.exists()+ assert canary.read_text() == "outside"+++# --------------------------------------------------------------------------+# Surface 6: backup prune safety+# (src/local_deep_research/database/backup/backup_service.py)+# --------------------------------------------------------------------------+def backup_service(tmp_path, monkeypatch):+ # Resolve every BackupService path inside tmp_path via the real+ # path config (no attribute overrides, nothing outside tmp_path).+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ from local_deep_research.database.backup.backup_service import BackupService++ return BackupService("test-user", "test-password", max_backups=1)+++def test_backup_prune_only_removes_matching_direct_child_backups(+ backup_service,+):+ backup_dir = backup_service.backup_dir+ newest = backup_dir / "ldr_backup_new.db"+ old = backup_dir / "ldr_backup_old.db"+ keep = backup_dir / "keep.txt"+ odd_name = backup_dir / "ldr_backup_old.db.bak"+ nested = backup_dir / "nested" / "ldr_backup_nested.db"+ newest.write_bytes(b"new")+ old.write_bytes(b"old")+ keep.write_text("keep")+ odd_name.write_text("keep")+ nested.parent.mkdir()+ nested.write_bytes(b"nested")+ old_time = time.time() - 10+ os.utime(old, (old_time, old_time))++ assert backup_service._cleanup_old_backups() == 1+ assert newest.exists() # within max count -> kept+ assert not old.exists() # exceeds max count -> pruned+ assert keep.exists() # non-matching name -> untouched+ assert odd_name.exists() # weird name not matching the glob -> untouched+ assert nested.exists() # nested dir (glob does not recurse) -> untouched+++def test_backup_prune_only_removes_stale_matching_tmp_files(backup_service):+ backup_dir = backup_service.backup_dir+ stale_tmp = backup_dir / "ldr_backup_old.db.tmp"+ fresh_tmp = backup_dir / "ldr_backup_fresh.db.tmp"+ nonmatching_tmp = backup_dir / "keep.db.tmp"+ nested_tmp = backup_dir / "nested" / "ldr_backup_nested.db.tmp"+ for path in (stale_tmp, fresh_tmp, nonmatching_tmp):+ path.write_bytes(b"tmp")+ nested_tmp.parent.mkdir()+ nested_tmp.write_bytes(b"tmp")+ old_time = time.time() - 3601+ os.utime(stale_tmp, (old_time, old_time))++ # Stale .tmp sweeps are not counted as backup deletions.+ assert backup_service._cleanup_old_backups() == 0+ assert not stale_tmp.exists() # older than the 1h cutoff -> swept+ assert fresh_tmp.exists() # in-flight temp -> spared+ assert nonmatching_tmp.exists() # wrong prefix -> spared+ assert nested_tmp.exists() # nested (non-child) -> spared+++def test_backup_prune_spares_matching_symlink(backup_service, tmp_path):+ backup_dir = backup_service.backup_dir+ real = backup_dir / "ldr_backup_keep.db"+ real.write_bytes(b"real")+ outside = tmp_path / "outside.db"+ outside.write_bytes(b"canary")+ link = backup_dir / "ldr_backup_link.db"+ try:+ link.symlink_to(outside)+ except (OSError, NotImplementedError):+ pytest.skip("Cannot create symlinks in this environment")++ assert backup_service._cleanup_old_backups() == 0+ assert link.is_symlink() # a symlink match is never unlinked+ assert outside.read_bytes() == b"canary"+ assert real.exists()diff --git a/tests/security/test_disk_write_guards_extended.py b/tests/security/test_disk_write_guards_extended.pynew file mode 100644index 0000000000..fde2872fb2--- /dev/null+++ b/tests/security/test_disk_write_guards_extended.py@@ -0,0 +1,404 @@+"""Extended GREEN disk-write guardrail battery.++Complements ``test_disk_write_guards.py`` without duplicating its first-pin+coverage. Every test uses only ``tmp_path`` and asserts current secure+behavior: a failure is a regression, not a reason to weaken the assertion.++Surfaces covered:+1. legacy_rekey cleanup/quarantine mutations stay scoped to their cache paths.+2. FAISS stale-temp sweeping stays scoped to the target index directory/name.+3. Server-mode open-file-location routes refuse before any subprocess spawn.+4. Failed/crashed backup creation leaves no partial or outside-root artifacts.+"""++import os+import re+import sys+import threading+import time+from contextlib import contextmanager+from pathlib import Path+from unittest.mock import MagicMock++import numpy as np+import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker+++# --------------------------------------------------------------------------+# Surface 1: login-time legacy re-key cleanup containment+# (src/local_deep_research/vector_stores/legacy_rekey.py)+# --------------------------------------------------------------------------+def test_purge_redundant_pkl_only_unlinks_its_own_companion(tmp_path):+ from local_deep_research.vector_stores.legacy_rekey import (+ _purge_redundant_pkl,+ )++ cache_root = tmp_path / "rag_indices"+ cache_root.mkdir()+ faiss_path = cache_root / "index.faiss"+ pkl_path = cache_root / "index.pkl"+ faiss_path.write_bytes(b"index")+ pkl_path.write_bytes(b"legacy plaintext")++ outside = tmp_path / "outside"+ outside.mkdir()+ outside_canary = outside / "index.pkl"+ outside_canary.write_bytes(b"outside plaintext")+ in_root_canary = cache_root / "keep.txt"+ in_root_canary.write_text("keep")++ assert _purge_redundant_pkl(faiss_path, "password") is True++ assert faiss_path.exists()+ assert not pkl_path.exists()+ assert outside_canary.read_bytes() == b"outside plaintext"+ assert in_root_canary.read_text() == "keep"+++@contextmanager+def _session_context(session):+ yield session+++def rekey_session(monkeypatch):+ from local_deep_research.database.models import Base+ import local_deep_research.vector_stores.legacy_rekey as rekey_module++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ monkeypatch.setattr(+ rekey_module,+ "get_user_db_session",+ lambda *args, **kwargs: _session_context(session),+ )+ monkeypatch.setattr(rekey_module, "FileIntegrityManager", MagicMock())+ yield session+ session.close()+ engine.dispose()+++def _add_rag_index(session, faiss_path):+ from local_deep_research.database.models.library import (+ EmbeddingProvider,+ RAGIndex,+ )++ row = RAGIndex(+ collection_name="collection_scoped",+ embedding_model="test-model",+ embedding_model_type=EmbeddingProvider.SENTENCE_TRANSFORMERS,+ embedding_dimension=2,+ index_path=str(faiss_path),+ index_hash="scoped-index-hash",+ chunk_size=500,+ chunk_overlap=50,+ index_type="flat",+ distance_metric="cosine",+ normalize_vectors=False,+ is_current=True,+ )+ session.add(row)+ session.commit()+++def test_orphaned_sidecar_cleanup_stays_inside_cache_root(+ tmp_path, rekey_session+):+ from local_deep_research.vector_stores.legacy_rekey import (+ rekey_user_indexes,+ )++ cache_root = tmp_path / "rag_indices"+ index_dir = cache_root / "user_indexes"+ index_dir.mkdir(parents=True)+ faiss_path = index_dir / "index.faiss"+ sidecar_path = index_dir / "index.idmap.json"+ pkl_path = index_dir / "index.pkl"+ sidecar_path.write_text("{}")+ pkl_path.write_bytes(b"legacy plaintext")++ outside = tmp_path / "outside"+ outside.mkdir()+ outside_canary = outside / "index.pkl"+ outside_canary.write_bytes(b"outside plaintext")+ in_root_canary = index_dir / "unrelated.txt"+ in_root_canary.write_text("keep")+ _add_rag_index(rekey_session, faiss_path)++ stats = rekey_user_indexes("scoped-user", "password")++ assert stats["checked"] == 1+ assert stats["skipped_no_faiss"] == 1+ assert not sidecar_path.exists()+ assert not pkl_path.exists()+ assert outside_canary.read_bytes() == b"outside plaintext"+ assert in_root_canary.read_text() == "keep"+++def test_quarantine_file_effects_stay_inside_cache_root(tmp_path, monkeypatch):+ from local_deep_research.database.models.library import (+ DocumentCollection,+ RAGIndex,+ RagDocumentStatus,+ )+ import local_deep_research.vector_stores.legacy_rekey as rekey_module++ cache_root = tmp_path / "rag_indices"+ index_dir = cache_root / "user_indexes"+ index_dir.mkdir(parents=True)+ faiss_path = index_dir / "index.faiss"+ sidecar_path = index_dir / "index.idmap.json"+ pkl_path = index_dir / "index.pkl"+ faiss_path.write_bytes(b"broken index")+ sidecar_path.write_text("{}")+ pkl_path.write_bytes(b"legacy plaintext")++ outside = tmp_path / "outside"+ outside.mkdir()+ outside_canary = outside / "index.pkl"+ outside_canary.write_bytes(b"outside plaintext")+ in_root_canary = index_dir / "unrelated.txt"+ in_root_canary.write_text("keep")++ rag_index = MagicMock(id=7, collection_name="collection_scoped")+ idx = MagicMock(id=7, is_current=True)+ q_ragindex = MagicMock()+ q_ragindex.filter_by.return_value.first.return_value = idx+ q_status = MagicMock()+ q_collection = MagicMock()+ session = MagicMock()+ session.query.side_effect = lambda model: {+ RAGIndex: q_ragindex,+ RagDocumentStatus: q_status,+ DocumentCollection: q_collection,+ }[model]+ monkeypatch.setattr(+ rekey_module,+ "get_user_db_session",+ lambda *args, **kwargs: _session_context(session),+ )++ rekey_module._quarantine_and_reset(+ "scoped-user",+ "password",+ rag_index,+ faiss_path,+ sidecar_path,+ threading.Lock(),+ )++ assert not faiss_path.exists()+ assert not sidecar_path.exists()+ assert not pkl_path.exists()+ assert list(index_dir.glob("index.faiss.corrupt-*"))+ assert list(index_dir.glob("index.idmap.json.corrupt-*"))+ assert outside_canary.read_bytes() == b"outside plaintext"+ assert in_root_canary.read_text() == "keep"+++# --------------------------------------------------------------------------+# Surface 2: FAISS stale-temp sweep containment+# (src/local_deep_research/vector_stores/implementations/faiss_store.py)+# --------------------------------------------------------------------------+def _make_store():+ from local_deep_research.vector_stores.implementations.faiss_store import (+ FaissVectorStore,+ )++ store = FaissVectorStore.create(+ dimension=2,+ index_type="flat",+ metric="l2",+ normalize=False,+ )+ store.add([1], np.array([[1.0, 2.0]], dtype="float32"))+ return store+++def test_faiss_stale_tmp_sweep_is_confined_to_index_directory(tmp_path):+ from local_deep_research.vector_stores.implementations.faiss_store import (+ _STALE_TMP_AGE_SECONDS,+ )++ index_dir = tmp_path / "index_dir"+ sibling_dir = tmp_path / "sibling_dir"+ nested_dir = index_dir / "nested"+ for directory in (index_dir, sibling_dir, nested_dir):+ directory.mkdir(parents=True, exist_ok=True)+ sibling_canary = sibling_dir / "index.faiss.orphan.tmp"+ nested_canary = nested_dir / "index.faiss.orphan.tmp"+ for canary in (sibling_canary, nested_canary):+ canary.write_bytes(b"stale elsewhere")+ old_time = time.time() - _STALE_TMP_AGE_SECONDS - 1+ os.utime(canary, (old_time, old_time))++ _make_store().persist(index_dir / "index.faiss")++ assert (index_dir / "index.faiss").is_file()+ assert sibling_canary.read_bytes() == b"stale elsewhere"+ assert nested_canary.read_bytes() == b"stale elsewhere"+++def test_faiss_sweep_spares_stale_foreign_prefix_tmp_in_index_dir(tmp_path):+ from local_deep_research.vector_stores.implementations.faiss_store import (+ _STALE_TMP_AGE_SECONDS,+ )++ index_dir = tmp_path / "index_dir"+ index_dir.mkdir()+ foreign_canary = index_dir / "other-index.orphan.tmp"+ foreign_canary.write_bytes(b"not this index")+ old_time = time.time() - _STALE_TMP_AGE_SECONDS - 1+ os.utime(foreign_canary, (old_time, old_time))++ _make_store().persist(index_dir / "index.faiss")++ assert foreign_canary.read_bytes() == b"not this index"+++# --------------------------------------------------------------------------+# Surface 3: server-mode file-manager routes and utility subprocess guard+# (web/routers/research.py, web/routers/settings.py,+# research_library/utils/__init__.py)+#+# The two route-level refusal tests that used to live here called the+# Flask handlers directly through a bare ``app.test_request_context()``.+# The FastAPI migration (#3299) deleted ``web.routes.research_routes`` and+# ``web.routes.settings_routes`` entirely, and both replacement routers+# (``web/routers/research.py`` / ``web/routers/settings.py``) now refuse+# ``POST /open_file_location`` and ``POST /settings/open_file_location``+# unconditionally with a 403 and never touch ``subprocess`` at all — so+# there is no "unwrap the handler and call it directly" shape left to+# port here. That refusal is already pinned end to end (auth + the real+# FastAPI route) by+# ``tests/web/routers/test_research_route_error_envelopes.py::test_open_file_location_is_always_refused``,+# which is a strict superset of what stood here. The utility-level guard+# below is independent of the route layer and is unaffected.+# --------------------------------------------------------------------------+++ "hostile_path", ["/etc/passwd", "/etc/shadow", "../../etc/passwd"]+)+def test_open_file_location_utility_never_spawns_for_hostile_path(+ hostile_path, monkeypatch+):+ import subprocess+ from local_deep_research.research_library.utils import open_file_location++ calls = []++ def record_run(*args, **kwargs):+ calls.append((args, kwargs))+ return MagicMock(returncode=0)++ monkeypatch.setattr(subprocess, "run", record_run)++ assert open_file_location(hostile_path) is False+ assert calls == []+++# --------------------------------------------------------------------------+# Surface 4: failed backup crash cleanup+# (src/local_deep_research/database/backup/backup_service.py)+# --------------------------------------------------------------------------+def backup_service(tmp_path, monkeypatch):+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ from local_deep_research.database.backup.backup_service import BackupService++ service = BackupService("crash-guard-user", "password", max_backups=3)+ service.db_path.parent.mkdir(parents=True, exist_ok=True)+ service.db_path.write_bytes(b"source database bytes")+ service.db_path.chmod(0o600)+ return service+++def _patch_backup_export(monkeypatch, service, *, crash_during_export):+ import local_deep_research.database.backup.backup_service as backup_module++ temp_paths = []+ cursor = MagicMock()++ def execute(sql, *args, **kwargs):+ if sql.startswith("ATTACH DATABASE"):+ match = re.search(r"ATTACH DATABASE '([^']+)'", sql)+ assert match is not None+ temp_path = Path(match.group(1).replace("''", "'"))+ temp_path.write_bytes(b"partial encrypted backup")+ temp_paths.append(temp_path)+ if "sqlcipher_export" in sql and crash_during_export:+ raise RuntimeError("simulated crash during backup export")++ cursor.execute.side_effect = execute+ connection = MagicMock()+ connection.cursor.return_value = cursor+ monkeypatch.setattr(+ backup_module,+ "create_sqlcipher_connection",+ lambda *args, **kwargs: connection,+ )+ monkeypatch.setattr(+ backup_module,+ "get_key_from_password",+ lambda *args, **kwargs: b"\xab" * 32,+ )+ return temp_paths+++def _assert_no_crash_artifacts(service, tmp_path, outside_canary):+ assert list(service.backup_dir.glob("ldr_backup_*.db.tmp")) == []+ assert list(service.backup_dir.glob("ldr_backup_*.db")) == []+ assert outside_canary.read_bytes() == b"outside canary"+ assert not [+ path+ for path in tmp_path.rglob("*")+ if path.is_file() and path.stat().st_mode & 0o022+ ]+++ sys.platform == "win32", reason="POSIX permission bits required"+)+def test_crashed_backup_export_leaves_no_partial_or_outside_artifacts(+ backup_service, tmp_path, monkeypatch+):+ outside_canary = tmp_path / "outside-canary.bin"+ outside_canary.write_bytes(b"outside canary")+ outside_canary.chmod(0o600)+ temp_paths = _patch_backup_export(+ monkeypatch, backup_service, crash_during_export=True+ )++ result = backup_service.create_backup(force=True)++ assert result.success is False+ assert temp_paths+ _assert_no_crash_artifacts(backup_service, tmp_path, outside_canary)+++ sys.platform == "win32", reason="POSIX permission bits required"+)+def test_failed_backup_verification_deletes_partial_tmp(+ backup_service, tmp_path, monkeypatch+):+ outside_canary = tmp_path / "outside-canary.bin"+ outside_canary.write_bytes(b"outside canary")+ outside_canary.chmod(0o600)+ temp_paths = _patch_backup_export(+ monkeypatch, backup_service, crash_during_export=False+ )+ monkeypatch.setattr(+ type(backup_service), "_verify_backup", lambda self, path: False+ )++ result = backup_service.create_backup(force=True)++ assert result.success is False+ assert temp_paths+ _assert_no_crash_artifacts(backup_service, tmp_path, outside_canary)diff --git a/tests/security/test_document_path_deletion.py b/tests/security/test_document_path_deletion.pynew file mode 100644index 0000000000..6bf6fd2e6d--- /dev/null+++ b/tests/security/test_document_path_deletion.py@@ -0,0 +1,732 @@+# allow: no-sut-import — security tests for the document-library+# deletion cascade; drives the REAL LibraryService / DocumentDeletionService+# / PDFStorageManager / CascadeHelper code against an in-memory library DB+# whose DB-stored path columns point at canary files under tmp_path.+"""Security tripwire tests for DB-stored-path -> unlink in the library+deletion cascade.++Surfaces verified on this branch (security/test-file-write-risk-battery):++(1) Document file deletion cascade — every unlink is guarded today:++* ``src/local_deep_research/research_library/services/library_service.py``+ lines 1041-1052 (``LibraryService.delete_document``): resolves+ ``DownloadTracker.file_path`` through+ ``get_absolute_path_from_settings(..., allow_legacy_fallback=False)``+ -> ``_resolve_within_root`` -> ``PathValidator.validate_safe_path``+ (werkzeug ``safe_join``: absolute / ``..`` / encoded / unicode+ traversal all rejected) + a leaf ``is_symlink()`` refusal, and only+ then ``.unlink()``.+* ``src/local_deep_research/research_library/deletion/services/document_deletion.py``+ lines 239-266 (``DocumentDeletionService._delete_document_locked``,+ the service behind the routed DELETE handler in+ ``deletion/routes/delete_routes.py:80``): same validated resolution,+ then ``CascadeHelper.delete_filesystem_file`` with+ ``allowed_root=<per-user library root>``. The twin sites at ~484+ (``delete_blob_only``) and ~737 (unlink-only path) share the guard.+* ``src/local_deep_research/research_library/services/pdf_storage_manager.py``+ lines 538-542 (``PDFStorageManager.delete_pdf``): validates+ ``Document.file_path`` via ``_get_safe_file_path(...,+ allow_legacy_fallback=False)`` -> ``_safe_path_in_root`` ->+ ``PathValidator`` + leaf-symlink refusal, and fails closed without a+ username.+* ``src/local_deep_research/research_library/deletion/utils/cascade_helper.py``+ lines 176-226 (``delete_filesystem_file``): unconditional leaf-symlink+ refusal + ``_resolved_containment_ok`` against ``allowed_root``.+ Lines 229-353 (``delete_faiss_index_files``): containment on the+ ``RAGIndex.index_path``-derived ``.faiss``/``.pkl``/``.idmap.json``+ family + per-file symlink refusals; all production callers+ (``collection_deletion.py:267,387``, ``rag_routes.py:2446``) pass+ ``allowed_root=<cache>/rag_indices``.++(2) Stale-research cleanup in ``research_routes.py``: VERIFIED NOT TO+EXIST as a distinct surface. ``grep -n "unlink" research_routes.py``+finds exactly two sites — line 1500 (``DELETE /api/delete/<id>``) and+line 1580 (``POST /api/clear_history`` loop) — both already covered by+the sibling battery ``tests/security/test_report_path_deletion.py``.+The ~1045-1088 range is research-*creation* code with no unlink, and+``web/queue/lifecycle_cleanup.py`` contains no file deletion. This+battery therefore does not duplicate the sibling's coverage.++The DB columns themselves remain plain unvalidated ``Text``+(``DownloadTracker.file_path``, ``Document.file_path``,+``RAGIndex.index_path``) — poisonable via DB restore / direct SQL — so+these tests plant hostile values directly in the columns and assert the+SECURE delete-side behaviour: canaries outside the caller's library root+must SURVIVE. They are GREEN regression tripwires today; if a refactor+ever swaps the validated resolution for a raw ``Path(...).unlink()``+they turn RED. Positive controls confirm legitimate in-root files still+delete, guarding against over-blocking fixes.++Run with: .venv/bin/python -m pytest tests/security/test_document_path_deletion.py -v --no-header --timeout=120+"""++import hashlib+import uuid+from contextlib import contextmanager+from pathlib import Path+from unittest.mock import patch++import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from tests.test_utils import add_src_to_path++add_src_to_path()++from local_deep_research.database.models import Base # noqa: E402+from local_deep_research.database.models.download_tracker import ( # noqa: E402+ DownloadTracker,+)+from local_deep_research.database.models.library import ( # noqa: E402+ Document,+ DocumentStatus,+ SourceType,+)+from local_deep_research.research_library.deletion.services.document_deletion import ( # noqa: E402+ DocumentDeletionService,+)+from local_deep_research.research_library.deletion.utils.cascade_helper import ( # noqa: E402+ CascadeHelper,+)+from local_deep_research.research_library.services.library_service import ( # noqa: E402+ LibraryService,+)+from local_deep_research.research_library.services.pdf_storage_manager import ( # noqa: E402+ PDFStorageManager,+)+from local_deep_research.research_library.utils import get_url_hash # noqa: E402++_TEST_USER = "path-canary-user"++# get_absolute_path_from_settings looks the settings manager up at call+# time (``from ...utilities.db_utils import get_settings_manager`` inside+# the function body), so patching the SOURCE module covers every caller.+_SETTINGS_MGR = "local_deep_research.utilities.db_utils.get_settings_manager"++# Modules that import get_user_db_session at module load — the DB/session+# plumbing mock targets for the services under test. LibraryService's+# post-commit purge delegates to DocumentDeletionService, so its tests+# patch both.+_LS_SESSION = (+ "local_deep_research.research_library.services.library_service"+ ".get_user_db_session"+)+_DD_SESSION = (+ "local_deep_research.research_library.deletion.services"+ ".document_deletion.get_user_db_session"+)+++class _StubSettingsManager:+ """Minimal settings manager: per-user library root under tmp_path."""++ def __init__(self, storage_base: Path):+ self._storage_base = str(storage_base)++ def get_setting(self, key, default=None):+ if key == "research_library.storage_path":+ return self._storage_base+ if key == "research_library.shared_library":+ return False+ return default+++@contextmanager+def _settings_root(tmp_path, monkeypatch):+ """Point ``research_library.storage_path`` at ``<tmp>/app_data/storage``.++ The resulting per-user library root (``apply_user_subdir`` joins the+ username) is ``<tmp>/app_data/storage/<_TEST_USER>``.++ Also pins ``LDR_DATA_DIR`` under ``tmp_path``. ``get_absolute_path_+ from_settings`` calls ``settings.get_setting("research_library.+ storage_path", str(get_library_directory()))`` -- the default is a+ normal function argument, so Python evaluates+ ``str(get_library_directory())`` (which ``mkdir``s+ ``<data_dir>/library``) *before* ``get_setting`` even runs, regardless+ of whether the stub below ignores that default. Without this,+ "default" is the real ``platformdirs.user_data_dir`` on the machine+ running the suite. Pinning ``LDR_DATA_DIR`` keeps that unconditional+ side effect inside ``tmp_path``.+ """+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "app_data"))+ base = tmp_path / "app_data" / "storage"+ per_user_root = base / _TEST_USER+ per_user_root.mkdir(parents=True, exist_ok=True)+ with patch(_SETTINGS_MGR, return_value=_StubSettingsManager(base)):+ yield base, per_user_root+++@contextmanager+def _patched_user_session(targets, session):+ """Replace ``get_user_db_session`` in each target module namespace.++ The replacement yields a fresh context manager per call, so services+ that open several sessions (delete + post-commit purge) all operate+ on the same real in-memory session.+ """++ @contextmanager+ def _factory(username=None):+ yield session++ patchers = [patch(t, new=_factory) for t in targets]+ for p in patchers:+ p.start()+ try:+ yield+ finally:+ for p in reversed(patchers):+ p.stop()+++def _seed_library_db():+ """In-memory SQLite session with the library models loaded."""+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ return session, engine+++def _make_document(session, *, file_path=None, original_url=None):+ """Commit one filesystem-mode Document and return it."""+ st = SourceType(+ id=str(uuid.uuid4()),+ name="research_download",+ display_name="Research Download",+ description="x",+ )+ session.add(st)+ session.commit()+ doc = Document(+ id=str(uuid.uuid4()),+ source_type_id=st.id,+ document_hash=hashlib.sha256(b"placeholder").hexdigest(),+ file_size=0,+ file_type="pdf",+ status=DocumentStatus.COMPLETED,+ title="canary doc",+ storage_mode="filesystem",+ file_path=file_path,+ original_url=original_url,+ )+ session.add(doc)+ session.commit()+ return doc+++def _make_tracker(session, url, file_path):+ """Commit one DownloadTracker row whose file_path is the payload.++ ``first_resource_id`` is nullable=False but SQLite FK enforcement is+ off by default in a fresh SQLAlchemy engine, so a synthetic id+ commits cleanly without seeding a ResearchResource row.+ """+ tracker = DownloadTracker(+ url=url,+ url_hash=get_url_hash(url),+ first_resource_id=1,+ file_path=file_path,+ is_downloaded=True,+ )+ session.add(tracker)+ session.commit()+ return tracker+++def _relative_escape(root: Path, canary: Path) -> str:+ """A ``..``-laden relative path from ``root`` to the canary."""+ root_parts = root.resolve().parts+ canary_parts = canary.resolve().parts+ common = 0+ for a, b in zip(root_parts, canary_parts):+ if a != b:+ break+ common += 1+ ups = [".."] * (len(root_parts) - common)+ downs = list(canary_parts[common:])+ return "/".join(ups + downs)+++# ---------------------------------------------------------------------------+# LibraryService.delete_document — DownloadTracker.file_path -> unlink+# (library_service.py:1041-1052)+# ---------------------------------------------------------------------------+++class TestLibraryServiceDeleteDocumentTrackerFile:+ """The tracker-file unlink in ``LibraryService.delete_document`` must+ never reach outside the caller's per-user library root."""++ def _run_delete(self, session, document_id):+ with _patched_user_session([_LS_SESSION, _DD_SESSION], session):+ return LibraryService(_TEST_USER).delete_document(document_id)++ def test_absolute_tracker_path_outside_root_is_preserved(+ self, tmp_path, monkeypatch+ ):+ with _settings_root(tmp_path, monkeypatch) as (_base, per_user_root):+ outside = tmp_path / "outside_storage"+ outside.mkdir()+ canary = outside / "canary.txt"+ canary.write_text("DO NOT DELETE")++ session, engine = _seed_library_db()+ try:+ doc = _make_document(+ session, original_url="https://example.com/abs.pdf"+ )+ _make_tracker(session, doc.original_url, str(canary))+ deleted = self._run_delete(session, doc.id)+ finally:+ session.close()+ engine.dispose()++ assert deleted is True+ assert canary.exists(), (+ "LibraryService.delete_document unlinked an absolute "+ "DownloadTracker.file_path outside the library root — no path "+ "validation present"+ )+ assert canary.read_text() == "DO NOT DELETE"++ def test_traversal_tracker_path_is_preserved(self, tmp_path, monkeypatch):+ with _settings_root(tmp_path, monkeypatch) as (_base, per_user_root):+ outside = tmp_path / "outside_sibling"+ outside.mkdir()+ canary = outside / "victim.txt"+ canary.write_text("DO NOT DELETE")+ traversal = _relative_escape(per_user_root, canary)+ assert traversal.startswith(".."), "payload must traverse"++ session, engine = _seed_library_db()+ try:+ doc = _make_document(+ session, original_url="https://example.com/trav.pdf"+ )+ _make_tracker(session, doc.original_url, traversal)+ deleted = self._run_delete(session, doc.id)+ finally:+ session.close()+ engine.dispose()++ assert deleted is True+ assert canary.exists(), (+ "LibraryService.delete_document followed a ``..``-laden "+ "DownloadTracker.file_path outside the library root — no "+ "containment check present"+ )+ assert canary.read_text() == "DO NOT DELETE"++ def test_symlink_tracker_path_is_refused(self, tmp_path, monkeypatch):+ with _settings_root(tmp_path, monkeypatch) as (_base, per_user_root):+ outside = tmp_path / "outside_target"+ outside.mkdir()+ canary = outside / "symlink_target.txt"+ canary.write_text("DO NOT DELETE")+ link = per_user_root / "evil_link"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ assert link.is_symlink()++ session, engine = _seed_library_db()+ try:+ doc = _make_document(+ session, original_url="https://example.com/link.pdf"+ )+ _make_tracker(session, doc.original_url, "evil_link")+ deleted = self._run_delete(session, doc.id)+ finally:+ session.close()+ engine.dispose()++ assert deleted is True+ assert canary.exists(), (+ "LibraryService.delete_document dereferenced a symlinked "+ "DownloadTracker.file_path — no link-target containment "+ "present"+ )+ assert canary.read_text() == "DO NOT DELETE"+ assert link.is_symlink() or link.exists(), (+ "LibraryService.delete_document removed a symlink planted in "+ "the library root — no leaf-symlink refusal present"+ )++ def test_legitimate_tracker_file_is_deleted(self, tmp_path, monkeypatch):+ """POSITIVE CONTROL: a real file inside the per-user root is+ still unlinked by delete_document."""+ with _settings_root(tmp_path, monkeypatch) as (_base, per_user_root):+ (per_user_root / "pdfs").mkdir(exist_ok=True)+ legit = per_user_root / "pdfs" / "legit.pdf"+ legit.write_bytes(b"%PDF-1.4 legit")++ session, engine = _seed_library_db()+ try:+ doc = _make_document(+ session, original_url="https://example.com/legit.pdf"+ )+ _make_tracker(session, doc.original_url, "pdfs/legit.pdf")+ deleted = self._run_delete(session, doc.id)+ finally:+ session.close()+ engine.dispose()++ assert deleted is True+ assert not legit.exists(), (+ "POSITIVE CONTROL FAILED: a legitimate in-root tracker file "+ "was not deleted. If a containment fix was just added, it is "+ "overly restrictive."+ )+++# ---------------------------------------------------------------------------+# DocumentDeletionService — Document.file_path -> unlink+# (document_deletion.py:239-266; routed via delete_routes.py:80)+# ---------------------------------------------------------------------------+++class TestDocumentDeletionServiceDocumentFile:+ """The routed document-delete service must keep the+ ``Document.file_path`` unlink inside the per-user library root."""++ def _run_delete(self, session, document_id):+ with _patched_user_session([_DD_SESSION], session):+ return DocumentDeletionService(_TEST_USER).delete_document(+ document_id+ )++ def test_absolute_document_file_path_outside_root_is_preserved(+ self, tmp_path, monkeypatch+ ):+ with _settings_root(tmp_path, monkeypatch) as (_base, per_user_root):+ outside = tmp_path / "dd_outside"+ outside.mkdir()+ canary = outside / "canary.txt"+ canary.write_text("DO NOT DELETE")++ session, engine = _seed_library_db()+ try:+ doc = _make_document(session, file_path=str(canary))+ result = self._run_delete(session, doc.id)+ finally:+ session.close()+ engine.dispose()++ assert result.get("deleted") is True+ assert result.get("file_deleted") is False+ assert canary.exists(), (+ "DocumentDeletionService unlinked an absolute "+ "Document.file_path outside the library root — no path "+ "validation present"+ )+ assert canary.read_text() == "DO NOT DELETE"++ def test_symlink_document_file_path_is_refused(self, tmp_path, monkeypatch):+ with _settings_root(tmp_path, monkeypatch) as (_base, per_user_root):+ outside = tmp_path / "dd_symlink_target"+ outside.mkdir()+ canary = outside / "target.txt"+ canary.write_text("DO NOT DELETE")+ link = per_user_root / "evil_doc_link"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ assert link.is_symlink()++ session, engine = _seed_library_db()+ try:+ doc = _make_document(session, file_path="evil_doc_link")+ result = self._run_delete(session, doc.id)+ finally:+ session.close()+ engine.dispose()++ assert result.get("deleted") is True+ assert result.get("file_deleted") is False+ assert canary.exists(), (+ "DocumentDeletionService dereferenced a symlinked "+ "Document.file_path — no link-target containment present"+ )+ assert link.is_symlink() or link.exists(), (+ "DocumentDeletionService removed a symlink planted in the "+ "library root — no leaf-symlink refusal present"+ )++ def test_legitimate_document_file_is_deleted(self, tmp_path, monkeypatch):+ """POSITIVE CONTROL: a real in-root file is unlinked by the+ routed deletion service."""+ with _settings_root(tmp_path, monkeypatch) as (_base, per_user_root):+ (per_user_root / "pdfs").mkdir(exist_ok=True)+ legit = per_user_root / "pdfs" / "legit_doc.pdf"+ legit.write_bytes(b"%PDF-1.4 legit")++ session, engine = _seed_library_db()+ try:+ doc = _make_document(session, file_path="pdfs/legit_doc.pdf")+ result = self._run_delete(session, doc.id)+ finally:+ session.close()+ engine.dispose()++ assert result.get("deleted") is True, result+ assert result.get("file_deleted") is True, result+ assert not legit.exists(), (+ "POSITIVE CONTROL FAILED: a legitimate in-root document file "+ "was not deleted by DocumentDeletionService. If a containment "+ "fix was just added, it is overly restrictive."+ )+++# ---------------------------------------------------------------------------+# PDFStorageManager.delete_pdf — Document.file_path -> unlink+# (pdf_storage_manager.py:538-542)+# ---------------------------------------------------------------------------+++class TestPdfStorageManagerDeletePdf:+ """``delete_pdf`` must keep the unlink inside the manager's own+ library root (constructor-supplied, mirroring the real per-user+ root)."""++ @pytest.fixture+ def psm_case(self, tmp_path):+ """(manager, session) — real manager rooted under tmp_path plus+ an in-memory library DB."""+ library_root = tmp_path / "library"+ (library_root / "pdfs").mkdir(parents=True)+ manager = PDFStorageManager(+ library_root=library_root,+ storage_mode="filesystem",+ username=_TEST_USER,+ )+ session, engine = _seed_library_db()+ try:+ yield manager, session+ finally:+ session.close()+ engine.dispose()++ def test_absolute_file_path_outside_root_is_preserved(+ self, tmp_path, psm_case+ ):+ manager, session = psm_case+ outside = tmp_path / "psm_outside"+ outside.mkdir()+ canary = outside / "canary.txt"+ canary.write_text("DO NOT DELETE")+ doc = _make_document(session, file_path=str(canary))++ ok = manager.delete_pdf(doc, session)++ assert ok is True+ assert canary.exists(), (+ "PDFStorageManager.delete_pdf unlinked an absolute "+ "Document.file_path outside the library root — no path "+ "validation present"+ )++ def test_traversal_file_path_outside_root_is_preserved(+ self, tmp_path, psm_case+ ):+ manager, session = psm_case+ outside = tmp_path / "psm_outside_sibling"+ outside.mkdir()+ canary = outside / "victim.txt"+ canary.write_text("DO NOT DELETE")+ traversal = _relative_escape(manager.library_root, canary)+ assert traversal.startswith(".."), "payload must traverse"+ doc = _make_document(session, file_path=traversal)++ ok = manager.delete_pdf(doc, session)++ assert ok is True+ assert canary.exists(), (+ "PDFStorageManager.delete_pdf followed a ``..``-laden "+ "Document.file_path outside the library root — no containment "+ "check present"+ )++ def test_legitimate_pdf_inside_root_is_deleted(self, tmp_path, psm_case):+ """POSITIVE CONTROL: an in-root pdfs/... file is unlinked."""+ manager, session = psm_case+ legit = manager.library_root / "pdfs" / "legit.pdf"+ legit.write_bytes(b"%PDF-1.4 legit")+ doc = _make_document(session, file_path="pdfs/legit.pdf")++ ok = manager.delete_pdf(doc, session)++ assert ok is True+ assert not legit.exists(), (+ "POSITIVE CONTROL FAILED: a legitimate in-root PDF was not "+ "deleted by delete_pdf. If a containment fix was just added, "+ "it is overly restrictive."+ )+++# ---------------------------------------------------------------------------+# CascadeHelper.delete_filesystem_file (cascade_helper.py:176-226)+# ---------------------------------------------------------------------------+++class TestCascadeHelperFilesystemFileUnlink:+ """The narrowest unlink primitive — used directly by+ DocumentDeletionService with ``allowed_root=<per-user root>``."""++ def test_absolute_path_outside_allowed_root_is_refused(self, tmp_path):+ root = tmp_path / "allowed_root"+ root.mkdir()+ outside = tmp_path / "fs_outside"+ outside.mkdir()+ canary = outside / "canary.txt"+ canary.write_text("DO NOT DELETE")++ deleted = CascadeHelper.delete_filesystem_file(+ str(canary), allowed_root=root+ )++ assert deleted is False+ assert canary.exists(), (+ "CascadeHelper.delete_filesystem_file unlinked an absolute "+ "path outside allowed_root — containment check missing"+ )++ def test_traversal_path_outside_allowed_root_is_refused(self, tmp_path):+ root = tmp_path / "allowed_root"+ (root / "sub").mkdir(parents=True)+ outside = tmp_path / "fs_outside_sibling"+ outside.mkdir()+ canary = outside / "victim.txt"+ canary.write_text("DO NOT DELETE")+ traversal = (+ root / "sub" / ".." / ".." / "fs_outside_sibling" / "victim.txt"+ )+ assert traversal.exists(), "traversal payload must be stat-able"+ assert traversal.resolve() == canary.resolve()++ deleted = CascadeHelper.delete_filesystem_file(+ str(traversal), allowed_root=root+ )++ assert deleted is False+ assert canary.exists(), (+ "CascadeHelper.delete_filesystem_file followed a ``..``-laden "+ "path outside allowed_root — containment check missing"+ )++ def test_legitimate_file_inside_allowed_root_is_deleted(self, tmp_path):+ """POSITIVE CONTROL: an in-root file is unlinked."""+ root = tmp_path / "allowed_root"+ root.mkdir()+ legit = root / "doc.pdf"+ legit.write_bytes(b"%PDF-1.4 legit")++ deleted = CascadeHelper.delete_filesystem_file(+ str(legit), allowed_root=root+ )++ assert deleted is True+ assert not legit.exists(), (+ "POSITIVE CONTROL FAILED: delete_filesystem_file refused a "+ "legitimate in-root file — containment is overly restrictive."+ )+++# ---------------------------------------------------------------------------+# CascadeHelper.delete_faiss_index_files (cascade_helper.py:229-353)+# RAGIndex.index_path is a plain Text column — the poisonable DB input.+# ---------------------------------------------------------------------------+++def _make_index_family(base_dir: Path, name: str = "index"):+ """Create a real .faiss/.pkl/.idmap.json family under ``base_dir``."""+ base_dir.mkdir(parents=True, exist_ok=True)+ stem = base_dir / name+ files = {+ "faiss": stem.with_suffix(".faiss"),+ "pkl": stem.with_suffix(".pkl"),+ "idmap": stem.with_suffix(".idmap.json"),+ }+ for f in files.values():+ f.write_bytes(b"payload")+ return str(stem), files+++class TestCascadeHelperFaissIndexFamilyUnlink:+ """The FAISS family unlink must stay inside the rag_indices root the+ production callers pass (collection_deletion.py:267,387;+ rag_routes.py:2446)."""++ def test_absolute_index_path_outside_rag_root_is_refused(self, tmp_path):+ rag_root = tmp_path / "cache" / "rag_indices"+ rag_root.mkdir(parents=True)+ outside_dir = tmp_path / "outside_rag"+ stem, files = _make_index_family(outside_dir)++ deleted = CascadeHelper.delete_faiss_index_files(+ stem, allowed_root=rag_root+ )++ assert deleted is False+ for label, f in files.items():+ assert f.exists(), (+ f"CascadeHelper.delete_faiss_index_files unlinked the "+ f"{label} canary outside rag_indices/ — containment check "+ "missing"+ )++ def test_symlinked_index_family_files_are_refused(self, tmp_path):+ rag_root = tmp_path / "cache" / "rag_indices"+ coll_dir = rag_root / "coll"+ coll_dir.mkdir(parents=True)+ outside_dir = tmp_path / "outside_rag_links"+ outside_dir.mkdir()+ canaries = {}+ links = {}+ for ext in ("faiss", "pkl", "idmap.json"):+ canary = outside_dir / f"target.{ext}"+ canary.write_bytes(b"DO NOT DELETE")+ link = coll_dir / f"index.{ext}"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ canaries[ext] = canary+ links[ext] = link++ deleted = CascadeHelper.delete_faiss_index_files(+ str(coll_dir / "index"), allowed_root=rag_root+ )++ assert deleted is False+ for ext, canary in canaries.items():+ assert canary.exists(), (+ f"delete_faiss_index_files dereferenced the .{ext} "+ "symlink to an outside canary — leaf-symlink refusal "+ "missing"+ )+ assert links[ext].is_symlink(), (+ f"delete_faiss_index_files removed the .{ext} symlink "+ "itself — leaf-symlink refusal missing"+ )++ def test_legitimate_index_family_inside_rag_root_is_deleted(self, tmp_path):+ """POSITIVE CONTROL: a real in-root index family is unlinked."""+ rag_root = tmp_path / "cache" / "rag_indices"+ stem, files = _make_index_family(rag_root / "coll")++ deleted = CascadeHelper.delete_faiss_index_files(+ stem, allowed_root=rag_root+ )++ assert deleted is True+ for label, f in files.items():+ assert not f.exists(), (+ f"POSITIVE CONTROL FAILED: the legitimate in-root "+ f"{label} file was not deleted. If a containment fix was "+ "just added, it is overly restrictive."+ )diff --git a/tests/security/test_downloader_filename_pipeline.py b/tests/security/test_downloader_filename_pipeline.pynew file mode 100644index 0000000000..a940d12ae2--- /dev/null+++ b/tests/security/test_downloader_filename_pipeline.py@@ -0,0 +1,533 @@+"""Offline security battery for per-engine downloader filename pipelines.++HTML and Playwright downloaders have no filename derivation: HTML titles feed+extracted text only, and Playwright's parsed domains feed rate-limit keys. The+generic fallback row below covers their URL-to-storage boundary.+"""++from __future__ import annotations++import hashlib+import re+from pathlib import Path+from typing import Optional+from unittest.mock import patch++import pytest++from local_deep_research.database.models.library import (+ Document,+)+from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+)+from local_deep_research.research_library.downloaders.base import BaseDownloader+from local_deep_research.research_library.downloaders.biorxiv import (+ BioRxivDownloader,+)+from local_deep_research.research_library.downloaders.openalex import (+ OpenAlexDownloader,+)+from local_deep_research.research_library.downloaders.pubmed import (+ PubMedDownloader,+)+from local_deep_research.research_library.downloaders.semantic_scholar import (+ SemanticScholarDownloader,+)+from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+)++_MINIMAL_PDF = b"%PDF-1.4\n1 0 obj <<>>endobj\ntrailer<<>>\n%%EOF\n"+_S2_HASH = "abcdef0123456789abcdef0123456789abcdef01"+++# ``library_session``, ``fresh_document``, ``fs_storage`` and+# ``canary_paths`` now live in tests/security/conftest.py -- they were+# duplicated verbatim across four batteries in this directory.+++def _assert_files_inside(+ library_root: Path, relative: Optional[str], canaries: dict[str, Path]+) -> None:+ root = library_root.resolve()+ if relative is not None:+ written = (root / relative).resolve()+ assert written.is_relative_to(root), (+ f"VULNERABILITY: save_pdf wrote outside library root: {written}"+ )+ assert written.read_bytes() == _MINIMAL_PDF+ for name, canary in canaries.items():+ assert canary.exists(), f"VULNERABILITY: deleted outside canary {name}"+ assert canary.read_text(encoding="utf-8") == "UNTOUCHED-CANARY\n", (+ f"VULNERABILITY: modified outside canary {name}"+ )+++def _assert_safe_filename(value: str) -> None:+ assert value.endswith(".pdf")+ assert "/" not in value+ assert "\\" not in value+ assert ".." not in value+ assert "\x00" not in value+ assert "%2e" not in value.lower()+++def _save_and_assert_contained(+ storage: PDFStorageManager,+ document: Document,+ session,+ canaries: dict[str, Path],+ url: str,+ fallback: str,+) -> Optional[str]:+ try:+ relative, _ = storage.save_pdf(+ pdf_content=_MINIMAL_PDF,+ document=document,+ session=session,+ filename=fallback,+ url=url,+ resource_id=1,+ )+ except (ValueError, FileNotFoundError, OSError):+ _assert_files_inside(storage.library_root, None, canaries)+ return None+ _assert_files_inside(storage.library_root, relative, canaries)+ assert relative.startswith("pdfs/")+ return relative+++class TestGenerateFilenameArxiv:+ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ pytest.param(+ "http://arxiv.org/abs/2301.12345/../../../etc/passwd.pdf",+ "fallback.pdf",+ id="dotdot-path",+ ),+ pytest.param(+ "http://arxiv.org/pdf/%2e%2e/%2e%2e/2301.12345v2.pdf",+ "fallback.pdf",+ id="encoded-traversal",+ ),+ pytest.param(+ "http://export.arxiv.org/abs/2301.12345/../../x",+ "fallback.pdf",+ id="subdomain-path",+ ),+ pytest.param(+ "http://arxiv.org/abs/2301.12345?download=../../etc/passwd",+ "arxiv_2301.12345.pdf",+ id="query-traversal",+ ),+ ],+ )+ def test_hostile_url_uses_safe_fallback_unless_it_names_a_valid_paper(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ expected,+ ):+ derived = fs_storage._generate_filename(url, 1, "fallback.pdf")+ assert derived == expected+ _assert_safe_filename(derived)+ _save_and_assert_contained(+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ "fallback.pdf",+ )++ @pytest.mark.parametrize(+ "url",+ [+ pytest.param(+ "http://arxiv.org/abs/../../../etc/passwd", id="no-id"+ ),+ pytest.param(+ "http://arxiv.org/abs/2301\x00.12345/../../x", id="null-id"+ ),+ pytest.param(+ "http://arxiv.org/abs/cond-mat/0501234/../../x",+ id="old-format-id",+ ),+ ],+ )+ def test_unextractable_id_uses_supplied_safe_fallback(+ self, fs_storage, fresh_document, library_session, canary_paths, url+ ):+ derived = fs_storage._generate_filename(url, 1, "fallback.pdf")+ assert derived == "fallback.pdf"+ _assert_safe_filename(derived)+ _save_and_assert_contained(+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ "fallback.pdf",+ )+++class TestGenerateFilenamePmc:+ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ pytest.param(+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC4149827/../../../../etc/passwd",+ "pmc_PMC4149827.pdf",+ id="dotdot-path",+ ),+ pytest.param(+ "https://ncbi.nlm.nih.gov/pmc/../../PMC9999.pdf",+ "pmc_PMC9999.pdf",+ id="traversal-before-id",+ ),+ ],+ )+ def test_hostile_url_extracts_only_pmc_id(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ expected,+ ):+ derived = fs_storage._generate_filename(url, 1, "fallback.pdf")+ assert derived == expected+ _assert_safe_filename(derived)+ _save_and_assert_contained(+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ "fallback.pdf",+ )++ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ pytest.param(+ "https://ncbi.nlm.nih.gov/pmc/%2e%2e/%2e%2e/etc/passwd",+ r"pubmed_\d{8}_1\.pdf",+ id="encoded-traversal-no-id",+ ),+ pytest.param(+ "https://ncbi.nlm.nih.gov/labs/../../etc/passwd",+ "fallback.pdf",+ id="ncbi-without-pmc-path",+ ),+ ],+ )+ def test_unextractable_pmc_id_uses_safe_fallback(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ expected,+ ):+ derived = fs_storage._generate_filename(url, 1, "fallback.pdf")+ if expected == "fallback.pdf":+ assert derived == expected+ else:+ assert re.fullmatch(expected, derived)+ _assert_safe_filename(derived)+ _save_and_assert_contained(+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ "fallback.pdf",+ )+++class TestArxivDownloader:+ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ pytest.param(+ "http://arxiv.org/abs/2301.12345/../../../etc/passwd",+ None,+ id="new-format-traversal",+ ),+ pytest.param(+ "http://arxiv.org/abs/cond-mat/0501234/../../x",+ None,+ id="old-format-traversal",+ ),+ pytest.param(+ "https://evil.example/fake/arxiv.org/abs/2301.12345/../../x",+ None,+ id="spoofed-path",+ ),+ pytest.param(+ "https://pubmed.ncbi.nlm.nih.gov/12345/", None, id="foreign-url"+ ),+ pytest.param(+ "https://arxiv.org/abs/2301.12345",+ "2301.12345",+ id="valid-new-format",+ ),+ pytest.param(+ "https://arxiv.org/pdf/cond-mat/0501234.pdf",+ "cond-mat/0501234",+ id="valid-old-format",+ ),+ ],+ )+ def test_extract_arxiv_id_returns_strict_identifier_or_none(+ self, url, expected+ ):+ extracted = ArxivDownloader()._extract_arxiv_id(url)+ assert extracted == expected+ if extracted is not None:+ assert re.fullmatch(r"\d+\.\d+|[a-z-]+/\d+", extracted)+ assert (+ ".." not in extracted+ and "\\" not in extracted+ and "\x00" not in extracted+ )++ @pytest.mark.parametrize(+ "url",+ [+ pytest.param(+ "http://arxiv.org/abs/2301.12345/../../../etc/passwd.pdf",+ id="new-format",+ ),+ pytest.param(+ "http://arxiv.org/abs/cond-mat/0501234/../../x",+ id="old-format",+ ),+ ],+ )+ def test_hostile_url_is_rejected_before_downloading(self, url):+ with patch.object(BaseDownloader, "_download_pdf") as download:+ result = ArxivDownloader().download_with_result(url)++ assert not result.is_success+ assert result.content is None+ assert result.skip_reason.startswith("Invalid arXiv URL")+ download.assert_not_called()++ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ (+ "http://arxiv.org/abs/2301.12345",+ "https://arxiv.org/pdf/2301.12345.pdf",+ ),+ (+ "http://arxiv.org/abs/cond-mat/0501234",+ "https://arxiv.org/pdf/cond-mat/0501234.pdf",+ ),+ ],+ )+ def test_valid_paper_url_is_reconstructed_for_download(self, url, expected):+ captured = []++ def fake_download(self, fetch_url, headers=None):+ captured.append(fetch_url)+ return _MINIMAL_PDF++ with patch.object(BaseDownloader, "_download_pdf", fake_download):+ result = ArxivDownloader().download_with_result(url)++ assert result.is_success and result.content == _MINIMAL_PDF+ assert captured == [expected]+++class TestPubmedDownloader:+ def test_pmc_fetch_url_is_reconstructed_without_traversal(self):+ captured = []++ def fake_download(self, fetch_url, headers=None):+ captured.append(fetch_url)+ return _MINIMAL_PDF++ url = "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4149827/../../../../etc/passwd"+ with patch.object(BaseDownloader, "_download_pdf", fake_download):+ result = PubMedDownloader(+ rate_limit_delay=0.0+ ).download_with_result(url)++ assert result.is_success and result.content == _MINIMAL_PDF+ assert captured == [+ "https://europepmc.org/backend/ptpmcrender.fcgi?accid=PMC4149827&blobtype=pdf"+ ]+++class TestSemanticScholarExtractor:+ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ pytest.param(+ f"https://www.semanticscholar.org/paper/Title/{_S2_HASH}/../../../etc/passwd",+ _S2_HASH,+ id="traversal-after-hash",+ ),+ pytest.param(+ f"https://www.semanticscholar.org/../../../../../etc/passwd/{_S2_HASH}",+ None,+ id="traversal-before-hash",+ ),+ pytest.param(+ "https://www.semanticscholar.org/paper/abc\x00def0123456789abcdef0123456789abcdef01",+ None,+ id="null-byte",+ ),+ pytest.param(+ "http://arxiv.org/abs/2301.12345/../../../etc/passwd",+ None,+ id="foreign-url",+ ),+ ],+ )+ def test_extract_paper_id_returns_hex_identifier_or_none(+ self, url, expected+ ):+ extracted = SemanticScholarDownloader()._extract_paper_id(url)+ assert extracted == expected+ if extracted is not None:+ assert re.fullmatch(r"[a-f0-9]{40}", extracted)+ assert ".." not in extracted and "/" not in extracted+++class TestOpenAlexExtractor:+ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ pytest.param(+ "https://openalex.org/works/W123456789/../../../etc/passwd",+ "W123456789",+ id="traversal-after-id",+ ),+ pytest.param(+ "https://openalex.org/../../../W1",+ "W1",+ id="traversal-before-id",+ ),+ pytest.param(+ "https://evil.example/works/W999/../../etc/passwd",+ None,+ id="wrong-host",+ ),+ pytest.param(+ "http://arxiv.org/abs/2301.12345/../../../etc/passwd",+ None,+ id="foreign-url",+ ),+ ],+ )+ def test_extract_work_id_returns_w_identifier_or_none(self, url, expected):+ extracted = OpenAlexDownloader()._extract_work_id(url)+ assert extracted == expected+ if extracted is not None:+ assert re.fullmatch(r"W\d+", extracted)+ assert ".." not in extracted and "/" not in extracted+++class TestBioRxivPipeline:+ def test_biorxiv_url_cannot_supply_saved_filename(+ self, fs_storage, fresh_document, library_session, canary_paths+ ):+ url = "https://www.biorxiv.org/content/10.1101/2024.01.01.123456/../../../etc"+ assert (+ BioRxivDownloader()._convert_to_pdf_url(url).startswith("https://")+ )+ derived = fs_storage._generate_filename(url, 1, "biorxiv_paper.pdf")+ assert derived == "biorxiv_paper.pdf"+ _assert_safe_filename(derived)+ relative = _save_and_assert_contained(+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ derived,+ )+ content_hash = hashlib.sha256(_MINIMAL_PDF).hexdigest()+ assert relative == f"pdfs/biorxiv_paper_{content_hash}.pdf"+++class TestCrossEngineHostileUrlMatrix:+ def test_same_hostile_arxiv_url_across_all_extractors(self):+ url = "http://arxiv.org/abs/2301.12345/../../../etc/passwd.pdf"+ assert ArxivDownloader()._extract_arxiv_id(url) is None+ assert SemanticScholarDownloader()._extract_paper_id(url) is None+ assert OpenAlexDownloader()._extract_work_id(url) is None++ @pytest.mark.parametrize(+ ("url", "fallback", "expected"),+ [+ pytest.param(+ "http://arxiv.org/abs/2301.12345/../../../etc/passwd.pdf",+ "fallback.pdf",+ "fallback.pdf",+ id="arxiv",+ ),+ pytest.param(+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC4149827/../../../../etc/passwd",+ "fallback.pdf",+ "pmc_PMC4149827.pdf",+ id="pubmed-pmc",+ ),+ pytest.param(+ "https://openalex.org/works/W123456789/../../../etc/passwd",+ "openalex_paper.pdf",+ "openalex_paper.pdf",+ id="openalex",+ ),+ pytest.param(+ "https://www.biorxiv.org/content/10.1101/2024.01.01.123456/../../../etc",+ "biorxiv_paper.pdf",+ "biorxiv_paper.pdf",+ id="biorxiv",+ ),+ pytest.param(+ f"https://www.semanticscholar.org/paper/{_S2_HASH}/../../../etc",+ "s2_paper.pdf",+ "s2_paper.pdf",+ id="semantic-scholar",+ ),+ pytest.param(+ "https://attacker.example/page/../../../etc/passwd.html",+ "webpage_capture.pdf",+ "webpage_capture.pdf",+ id="html-playwright-generic",+ ),+ ],+ )+ def test_hostile_url_never_reaches_saved_filename(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ fallback,+ expected,+ ):+ derived = fs_storage._generate_filename(url, 1, fallback)+ assert derived == expected+ _assert_safe_filename(derived)+ _save_and_assert_contained(+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ fallback,+ )diff --git a/tests/security/test_identity_and_index_pins.py b/tests/security/test_identity_and_index_pins.pynew file mode 100644index 0000000000..345a8fc98d--- /dev/null+++ b/tests/security/test_identity_and_index_pins.py@@ -0,0 +1,332 @@+"""GREEN identity and index filesystem guardrail battery.++Pins secure path derivation and write scopes with real ``tmp_path`` roots.+Failures indicate regressions and must not weaken these assertions.++Surfaces covered (third green-pin battery; complements+``test_disk_write_guards.py`` and ``test_disk_write_guards_extended.py``):++1. Collection-name -> FAISS index path hashing in+ ``research_library/services/library_rag_service.py::_get_index_path``.+2. Per-user backup directory containment in+ ``config/paths.py::get_user_backup_directory``.+3. Installation secret-key file permissions in+ ``web/fastapi_app.py::_load_secret_key`` (the FastAPI migration, #3299,+ replaced Flask's ``web/app_factory.py::create_app`` with a module-level+ secret-key load; see that surface's test for why it drives+ ``_load_secret_key`` directly rather than the whole app).+4. Uploaded filename sanitization before spool/target composition in+ ``security/filename_sanitizer.py`` + the ``PDFStorageManager`` spool+ layer the upload route (``web/routers/rag.py``) drives.+5. Report metadata sidecar containment and deletion scoping in+ ``storage/file.py::FileReportStorage``.+6. Plaintext filesystem PDF storage remains default-denied at+ ``research_library/services/pdf_storage_manager.py``.++Offline, tmp_path-only, no LLM/network.+"""++import re+import sys+from unittest.mock import MagicMock++import pytest+++# --------------------------------------------------------------------------+# Surface 1: collection identity -> hashed, per-user FAISS path+# (research_library/services/library_rag_service.py)+# --------------------------------------------------------------------------+def _bare_rag_service(username: str):+ from local_deep_research.research_library.services.library_rag_service import (+ LibraryRAGService,+ )++ service = object.__new__(LibraryRAGService)+ service.username = username+ service.chunk_overlap = 200+ service.chunk_size = 1000+ service.distance_metric = "cosine"+ service.index_type = "flat"+ service.normalize_vectors = True+ service.splitter_type = "recursive"+ service.text_separators = ["\n\n", "\n", ". ", " ", ""]+ return service+++ "collection_name",+ ["../../etc", "unicode/秘密", "nul\x00name", "x" * 4096],+)+def test_hostile_collection_identity_hashes_to_in_cache_faiss_path(+ tmp_path, monkeypatch, collection_name+):+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ service = _bare_rag_service("index-owner")++ index_hash = service._get_index_hash(+ collection_name, "model/name", "sentence_transformers"+ )+ index_path = service._get_index_path(index_hash)++ assert re.fullmatch(r"[0-9a-f]{64}", index_hash)+ assert index_path.resolve().is_relative_to((tmp_path / "cache").resolve())+ assert index_path.name == f"{index_hash}.faiss"+ # No raw collection-name fragment leaks into the resolved path: even a+ # 4KiB name cannot push bytes into the directory tree.+ assert collection_name not in str(index_path.resolve())+++def test_collection_names_differing_only_by_case_get_distinct_index_paths(+ tmp_path, monkeypatch+):+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ service = _bare_rag_service("index-owner")++ upper = service._get_index_path(+ service._get_index_hash("Collection", "model", "sentence_transformers")+ )+ lower = service._get_index_path(+ service._get_index_hash("collection", "model", "sentence_transformers")+ )++ assert upper.resolve().is_relative_to((tmp_path / "cache").resolve())+ assert lower.resolve().is_relative_to((tmp_path / "cache").resolve())+ assert upper != lower+++# --------------------------------------------------------------------------+# Surface 2: per-user backup directory containment+# (config/paths.py)+# --------------------------------------------------------------------------+ "username", ["../escape", "/absolute/path", "user/../../etc"]+)+def test_hostile_backup_username_is_hashed_inside_data_directory(+ tmp_path, monkeypatch, username+):+ from local_deep_research.config.paths import get_user_backup_directory++ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ backup_dir = get_user_backup_directory(username)+ backup_root = tmp_path / "encrypted_databases" / "backups"++ assert backup_dir.resolve().is_relative_to(backup_root.resolve())+ assert backup_dir.parent == backup_root+ assert re.fullmatch(r"[0-9a-f]{16}", backup_dir.name)+ if sys.platform != "win32":+ # Windows ignores mkdir/chmod modes and reports 0o777; the+ # containment assertions above are the portable half.+ assert backup_dir.stat().st_mode & 0o777 == 0o700+++# --------------------------------------------------------------------------+# Surface 3: installation secret-key file permissions+# (web/fastapi_app.py)+#+# Flask's ``app_factory.create_app()`` ran ``_load_secret_key()``-equivalent+# logic every time an app was built. The FastAPI migration (#3299) moved+# the SECRET_KEY load to ``web/fastapi_app.py::_load_secret_key`` and calls+# it exactly once, at MODULE IMPORT time (``SECRET_KEY =+# _load_secret_key()``) -- so calling ``create_app()``-equivalent a second+# time in a test process would not re-run it, and reloading the whole+# ``fastapi_app`` module to force a re-run risks corrupting every other+# test's view of the app singleton. Driving ``_load_secret_key()`` directly+# instead exercises the exact same file-permission logic without either+# hazard; ``config.paths.get_data_directory()`` reads ``LDR_DATA_DIR`` live+# (no caching), so the ``monkeypatch.setenv`` below is still honoured.+# --------------------------------------------------------------------------+def test_generated_secret_key_is_private_and_under_configured_data_dir(+ tmp_path, monkeypatch+):+ from local_deep_research.web import fastapi_app++ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))+ fastapi_app._load_secret_key()++ secret_key_file = tmp_path / ".secret_key"+ assert secret_key_file.is_file()+ assert secret_key_file.resolve().is_relative_to(tmp_path.resolve())+ if sys.platform != "win32":+ # Windows ignores the 0o600 chmod and reports 0o666.+ assert secret_key_file.stat().st_mode & 0o077 == 0+++# --------------------------------------------------------------------------+# Surface 4: uploaded filename sanitization before spool/target composition+# (web/routers/rag.py's upload route + security/filename_sanitizer.py)+# --------------------------------------------------------------------------+def test_hostile_upload_filenames_cannot_escape_spool_target(tmp_path):+ from local_deep_research.security.filename_sanitizer import (+ sanitize_filename,+ )++ spool_root = tmp_path / "data" / "upload_spool"+ spool_root.mkdir(parents=True)+ for raw_filename in (+ "../escape.pdf",+ "/absolute/escape.pdf",+ "nul\x00name.pdf",+ r"..\escape.pdf",+ ):+ safe_filename = sanitize_filename(raw_filename)+ target = (spool_root / safe_filename).resolve()++ assert target.is_relative_to(spool_root.resolve())+ assert not {"/", "\\", "\x00"}.intersection(safe_filename)+++def test_upload_pdf_storage_layer_keeps_spool_inside_library_root(+ tmp_path,+):+ # Depth pin on the storage layer the upload route drives+ # (rag_routes.upload_to_collection only ever constructs+ # PDFStorageManager with storage_mode="database", passing filenames+ # that already went through sanitize_filename). Database mode must+ # leave NO plaintext file under the library root, and even the+ # operator-gated filesystem mode must refuse traversal joins before+ # any write (PathValidator raises, nothing lands outside the root).+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ library_root = tmp_path / "library"+ library_root.mkdir()+ document = MagicMock(id=1)+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = None++ database_manager = PDFStorageManager(+ library_root=library_root, storage_mode="database"+ )+ result = database_manager.save_pdf(+ b"%PDF-1.4 bytes", document, session, "paper.pdf"+ )++ assert result[0] == "database"+ assert document.file_path is None+ assert not [path for path in tmp_path.rglob("*") if path.is_file()]++ outside_canary = tmp_path / "escape.pdf"+ outside_canary.write_bytes(b"canary")+ filesystem_manager = PDFStorageManager(+ library_root=library_root, storage_mode="filesystem"+ )+ with pytest.raises(ValueError):+ filesystem_manager.save_pdf(+ b"%PDF-1.4 bytes", document, session, "../../escape.pdf"+ )++ assert outside_canary.read_bytes() == b"canary"+ assert not [path for path in library_root.rglob("*") if path.is_file()]+++# --------------------------------------------------------------------------+# Surface 5: report metadata sidecar containment and deletion scope+# (storage/file.py)+# --------------------------------------------------------------------------+def test_hostile_research_id_cannot_escape_metadata_sidecar_root(tmp_path):+ from local_deep_research.storage.file import FileReportStorage++ outputs = tmp_path / "outputs"+ storage = FileReportStorage(outputs)+ for research_id in ("../escape", "/tmp/escape", "bad\x00id"):+ with pytest.raises(ValueError):+ storage._get_metadata_path(research_id)++ assert list(outputs.iterdir()) == []+++def test_save_report_rejects_hostile_id_before_report_or_sidecar_write(+ tmp_path,+):+ from local_deep_research.storage.file import FileReportStorage++ outputs = tmp_path / "outputs"+ canary = outputs / "unrelated.txt"+ storage = FileReportStorage(outputs)+ canary.write_text("keep")++ assert storage.save_report("../escape", "report", {"query": "q"}) is False+ assert canary.read_text() == "keep"+ assert list(outputs.iterdir()) == [canary]+++def test_delete_report_removes_own_sidecar_but_spares_outputs_sibling(+ tmp_path,+):+ from local_deep_research.storage.file import FileReportStorage++ outputs = tmp_path / "outputs"+ storage = FileReportStorage(outputs)+ report = outputs / "report.md"+ sidecar = outputs / "report_metadata.json"+ canary = outputs / "unrelated.txt"+ report.write_text("report")+ sidecar.write_text("{}")+ canary.write_text("keep")++ assert storage.delete_report("report") is True+ assert not report.exists()+ assert not sidecar.exists()+ assert canary.read_text() == "keep"+++# --------------------------------------------------------------------------+# Surface 6: plaintext filesystem PDF storage remains default-denied+# (research_library/services/pdf_storage_manager.py)+# --------------------------------------------------------------------------+def test_pdf_filesystem_storage_env_var_completely_unset(monkeypatch):+ """The env var MUST be absent (not just falsy) for the gate to+ default-deny; this guards against any future change that interprets a+ present-but-empty value as an opt-in."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ filesystem_pdf_storage_allowed,+ resolve_pdf_storage_mode,+ )++ monkeypatch.delenv(+ "LDR_RESEARCH_LIBRARY_ALLOW_FILESYSTEM_PDF_STORAGE", raising=False+ )++ assert filesystem_pdf_storage_allowed() is False+ assert resolve_pdf_storage_mode("filesystem") == "database"+++def test_pdf_filesystem_storage_explicit_truthy_opt_in_honors_filesystem(+ monkeypatch,+):+ """Positive control: an explicit truthy opt-in is honored (filesystem+ is NOT coerced). If a future regression tightens the gate past the env+ var, this turns red."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ filesystem_pdf_storage_allowed,+ resolve_pdf_storage_mode,+ )++ monkeypatch.setenv(+ "LDR_RESEARCH_LIBRARY_ALLOW_FILESYSTEM_PDF_STORAGE", "true"+ )++ assert filesystem_pdf_storage_allowed() is True+ assert resolve_pdf_storage_mode("filesystem") == "filesystem"++[email protected]("value", ["", "not-an-opt-in"])+def test_pdf_filesystem_storage_falsy_env_values_default_deny(+ monkeypatch, value+):+ """A present-but-falsy env var still reads as off; the gate must not+ be confused by empty strings or non-truthy literals into honoring+ filesystem."""+ from local_deep_research.research_library.services.pdf_storage_manager import (+ filesystem_pdf_storage_allowed,+ resolve_pdf_storage_mode,+ )++ monkeypatch.setenv(+ "LDR_RESEARCH_LIBRARY_ALLOW_FILESYSTEM_PDF_STORAGE", value+ )++ assert filesystem_pdf_storage_allowed() is False+ assert resolve_pdf_storage_mode("filesystem") == "database"diff --git a/tests/security/test_identity_paths_and_host_effects.py b/tests/security/test_identity_paths_and_host_effects.pynew file mode 100644index 0000000000..4b208b9786--- /dev/null+++ b/tests/security/test_identity_paths_and_host_effects.py@@ -0,0 +1,331 @@+import itertools+from pathlib import Path+from types import SimpleNamespace++import pytest+from fastapi.testclient import TestClient++from local_deep_research.database.backup import backup_service+from local_deep_research.database.backup.backup_service import (+ BackupResult,+ BackupService,+)+from local_deep_research.document_loaders import bytes_loader+from local_deep_research.exporters.base import ExportOptions+from local_deep_research.exporters import odt_exporter+from local_deep_research.research_library.utils import apply_user_subdir+++ "username",+ [+ "../outside",+ "/absolute/path",+ r"C:\\outside",+ "name\u2215..\u2215outside",+ ],+)+def test_user_library_path_rejects_hostile_username_components(+ tmp_path, username+):+ library_root = tmp_path / "library"+ library_root.mkdir()+ outside_canary = tmp_path / "outside"++ with pytest.raises(ValueError, match="Unsafe username"):+ apply_user_subdir(library_root, username)++ assert not outside_canary.exists()+ assert list(library_root.iterdir()) == []+++# Monotonic, never random \u2014 see test_save_raw_config_blocked_keys_fastapi.py+# for why: random /8 addresses collide across a session with many clients.+_FORWARDED_IP_SEQ = itertools.count(1)++[email protected](autouse=True)+def _slowapi_off():+ """Take the per-IP HTTP rate limiter out of the picture.++ Each parametrized case below registers a fresh user; nothing here is+ about rate limiting.+ """+ from local_deep_research.web.dependencies.rate_limit import limiter++ original = limiter.enabled+ limiter.enabled = False+ try:+ yield+ finally:+ limiter.enabled = original+++def _csrf(client: TestClient) -> str:+ """Stamp the session with a CSRF token, then fetch it as a string."""+ client.get("/auth/login")+ resp = client.get("/auth/csrf-token")+ return resp.json().get("csrf_token", "") if resp.status_code == 200 else ""+++def registration_client(app) -> TestClient:+ """A TestClient over the real FastAPI app for driving ``/auth/register``.++ Flask's ``web.app_factory.create_app()`` + a bare ``.test_client()``+ used to build this; the FastAPI migration (#3299) deleted that+ factory. The ``app`` fixture (``tests/conftest.py``) already points+ ``LDR_DATA_DIR`` at a throwaway ``temp_data_dir`` and initializes the+ auth database before ``fastapi_app`` is imported, so this just wraps+ it in a ``TestClient`` with its own forwarded IP.+ """+ n = next(_FORWARDED_IP_SEQ)+ client = TestClient(app, raise_server_exceptions=False)+ client.headers.update(+ {"X-Forwarded-For": f"10.{(n // 250) % 250 + 1}.{n % 250 + 1}.29"}+ )+ return client+++ "username", ["../outside", "/absolute/path", "user\u202e.."]+)+def test_registration_rejects_path_like_usernames(+ registration_client, username+):+ response = registration_client.post(+ "/auth/register",+ data={+ "username": username,+ "password": "TestPass123",+ "confirm_password": "TestPass123",+ "acknowledge": "true",+ "csrf_token": _csrf(registration_client),+ },+ )++ assert response.status_code == 400+ assert b"Username can only contain" in response.data+++ "title,author,date",+ [+ ("--output=/tmp/owned", "Author", "2026-01-01"),+ ("title\n--metadata=author:attacker", "Author\x00", "2026-01-01"),+ ("\u2010output=/tmp/owned", "Author", "2026-01-01"),+ ("x" * 20_000, "y" * 20_000, "z" * 20_000),+ ],+)+def test_odt_metadata_cannot_add_pandoc_arguments(+ monkeypatch, title, author, date+):+ captured = []++ def fake_run(command, **kwargs):+ captured.append((command, kwargs))+ return SimpleNamespace(stdout=b"odt")++ monkeypatch.setattr(odt_exporter, "PYPANDOC_AVAILABLE", True)+ monkeypatch.setattr(+ odt_exporter,+ "pypandoc",+ SimpleNamespace(get_pandoc_path=lambda: "pandoc"),+ )+ monkeypatch.setattr(odt_exporter.subprocess, "run", fake_run)+ monkeypatch.setattr(+ odt_exporter.ODTExporter,+ "_pandoc_supports_sandbox",+ staticmethod(lambda: True),+ )++ odt_exporter.ODTExporter(max_heap_mb=128).export(+ "body",+ ExportOptions(title=title, metadata={"author": author, "date": date}),+ )++ command, kwargs = captured[0]+ assert isinstance(command, list)+ assert command[:11] == [+ "pandoc",+ "+RTS",+ "-M128m",+ "-RTS",+ "--sandbox",+ "-f",+ "markdown",+ "-t",+ "odt",+ "-o",+ "-",+ ]+ assert all(token.startswith("--metadata=") for token in command[11:])+ assert kwargs["check"] is True+ assert "shell" not in kwargs+ for token in command[11:]:+ _key, separator, value = token.partition(":")+ # Fail with the offending token rather than an opaque IndexError if+ # a --metadata= argument ever loses its ``key:value`` shape.+ assert separator, f"metadata token is not key:value form: {token!r}"+ # argv-list invocation (asserted above: list command, no shell=)+ # is the complete mitigation -- a value can never split into a+ # separate pandoc argument whatever bytes it contains. These two+ # assertions only pin the belt-and-braces scrubbing that+ # _sanitize_metadata (odt_exporter.py:187-188) already performs.+ assert "--" not in value+ assert "\n" not in value+++def _configure_temp_loader(monkeypatch, tmp_path, loader_class):+ monkeypatch.setattr(bytes_loader.tempfile, "tempdir", str(tmp_path))+ monkeypatch.setattr(+ bytes_loader, "is_extension_supported", lambda _ext: True+ )+ monkeypatch.setattr(+ bytes_loader,+ "get_loader_class_for_extension",+ lambda _ext: (loader_class, {}),+ )+++def test_generic_upload_spool_stays_in_configured_tempdir_and_is_removed(+ tmp_path, monkeypatch+):+ observed_paths = []++ class Loader:+ def __init__(self, path):+ observed_paths.append(Path(path))++ def load(self):+ return []++ _configure_temp_loader(monkeypatch, tmp_path, Loader)+ # PDFs now use the bounded in-memory extractor; text exercises the+ # generic loader's temporary-file lifecycle.+ bytes_loader.load_from_bytes(b"content", ".txt")++ assert len(observed_paths) == 1+ assert observed_paths[0].parent == tmp_path+ assert observed_paths[0].name.startswith("ldr_upload_")+ assert observed_paths[0].suffix == ".txt"+ assert not observed_paths[0].exists()+++def test_generic_upload_spool_is_removed_when_parser_raises(+ tmp_path, monkeypatch+):+ observed_paths = []++ class ExplodingLoader:+ def __init__(self, path):+ observed_paths.append(Path(path))++ def load(self):+ raise RuntimeError("parser failed")++ _configure_temp_loader(monkeypatch, tmp_path, ExplodingLoader)++ with pytest.raises(RuntimeError, match="parser failed"):+ bytes_loader.load_from_bytes(b"content", ".txt")++ assert observed_paths[0].parent == tmp_path+ assert not observed_paths[0].exists()+++ "extension", [".pdf/../../x", "\u2010.pdf", "", "." + "x" * 20_000]+)+def test_upload_rejects_hostile_extensions_before_spooling(+ tmp_path, monkeypatch, extension+):+ monkeypatch.setattr(bytes_loader.tempfile, "tempdir", str(tmp_path))+ monkeypatch.setattr(+ bytes_loader, "is_extension_supported", lambda _ext: False+ )++ with pytest.raises(ValueError, match="Unsupported file extension"):+ bytes_loader.load_from_bytes(b"content", extension)++ assert list(tmp_path.iterdir()) == []+++def backup_service_in_tmpdir(tmp_path, monkeypatch):+ backup_dir = tmp_path / "backups"+ backup_dir.mkdir()+ monkeypatch.setattr(+ backup_service, "get_user_database_filename", lambda _u: "user.db"+ )+ monkeypatch.setattr(+ backup_service, "get_encrypted_database_path", lambda: tmp_path+ )+ monkeypatch.setattr(+ backup_service, "get_user_backup_directory", lambda _u: backup_dir+ )+ service = BackupService("testuser", "password")+ monkeypatch.setattr(+ service, "_create_backup_impl", lambda: BackupResult(success=True)+ )+ return service+++ strict=True,+ reason=(+ "DEFENCE IN DEPTH: purge_and_refresh deletes every entry returned "+ "by list_backups without resolving it and checking containment in "+ "self.backup_dir (backup_service.py purge_and_refresh). The value "+ "is server-derived today -- list_backups enumerates backup_dir -- "+ "so this is NOT a reachable attack, only a missing guard that a "+ "future caller or a poisoned directory listing could turn into an "+ "out-of-root unlink. This test monkeypatches list_backups to "+ "inject the hostile path. Fix: resolve each entry against "+ "backup_dir and skip anything outside it. Flip the marker when "+ "the containment check lands. The sibling symlink test below "+ "passes already -- bare names are resolved against backup_dir."+ ),+)[email protected]("forged_path", ["../outside.db", "/tmp/not-used"])+def test_purge_does_not_delete_backup_entries_outside_root(+ tmp_path, monkeypatch, backup_service_in_tmpdir, forged_path+):+ service = backup_service_in_tmpdir+ outside_canary = tmp_path / "outside.db"+ outside_canary.write_bytes(b"do not delete")+ if forged_path.startswith("/"):+ forged_path = str(outside_canary)+ monkeypatch.setattr(+ service,+ "list_backups",+ lambda: [{"filename": "forged.db", "path": forged_path}],+ )++ service.purge_and_refresh()++ assert outside_canary.exists()+++ __import__("sys").platform == "win32", reason="Unix-specific test"+)+def test_purge_does_not_follow_forged_backup_symlink(+ tmp_path, monkeypatch, backup_service_in_tmpdir+):+ service = backup_service_in_tmpdir+ outside_canary = tmp_path / "outside.db"+ outside_canary.write_bytes(b"do not delete")+ symlink = service.backup_dir / "forged.db"+ try:+ symlink.symlink_to(outside_canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ monkeypatch.setattr(+ service,+ "list_backups",+ lambda: [{"filename": "forged.db", "path": symlink.name}],+ )++ service.purge_and_refresh()++ assert outside_canary.exists()diff --git a/tests/security/test_journal_dataset_writes.py b/tests/security/test_journal_dataset_writes.pynew file mode 100644index 0000000000..056d746dc6--- /dev/null+++ b/tests/security/test_journal_dataset_writes.py@@ -0,0 +1,390 @@+from __future__ import annotations++import gzip+import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from local_deep_research.config.paths import get_journal_data_directory+from local_deep_research.journal_quality import downloader+from local_deep_research.journal_quality.data_sources import _openalex_common+from local_deep_research.journal_quality.data_sources.doaj import DOAJSource+from local_deep_research.journal_quality.data_sources.institutions import (+ InstitutionSource,+)+from local_deep_research.journal_quality.data_sources.jabref import JabRefSource+from local_deep_research.journal_quality.data_sources.openalex import (+ OpenAlexSource,+)+from local_deep_research.journal_quality.data_sources.predatory import (+ PredatorySource,+)+from local_deep_research.journal_quality.db import (+ DB_FILENAME,+ JournalQualityDB,+ build_db,+)+++CANARY = b"OUTSIDE-CANARY-MUST-SURVIVE"+++class _Response:+ def __init__(+ self, content: bytes, payload: dict[str, object] | None = None+ ):+ self.content = content+ self.text = content.decode("utf-8", errors="replace")+ self._payload = payload++ def raise_for_status(self) -> None:+ return None++ def json(self) -> dict[str, object]:+ assert self._payload is not None+ return self._payload+++def journal_dir(tmp_path, monkeypatch) -> Path:+ root = tmp_path / "ldr-root"+ monkeypatch.setenv("LDR_DATA_DIR", str(root))+ return get_journal_data_directory()+++def outside_canary(tmp_path) -> Path:+ path = tmp_path / "outside-canary"+ path.write_bytes(CANARY)+ return path+++def _assert_contained(data_dir: Path, outside_canary: Path) -> None:+ root = data_dir.resolve()+ for path in data_dir.rglob("*"):+ assert path.resolve().is_relative_to(root), (+ f"VULNERABILITY: escaped write {path}"+ )+ assert outside_canary.read_bytes() == CANARY, (+ "VULNERABILITY: outside canary changed"+ )+++def test_ldr_data_dir_resolves_journal_writes_under_override(+ journal_dir, outside_canary+):+ assert journal_dir == journal_dir.parent / "journal_data"+ assert journal_dir.resolve().is_relative_to(journal_dir.parent.resolve())+ _assert_contained(journal_dir, outside_canary)+++def test_openalex_partition_tmp_is_contained_and_cleaned(+ journal_dir, outside_canary+):+ compressed = gzip.compress(b'{"id":"https://openalex.org/S1"}\n')++ parts = _openalex_common.iter_partitions(+ [{"url": "s3://openalex/data/part.gz"}],+ journal_dir,+ file_prefix="openalex_sources",+ label="test",+ safe_get=lambda *_args, **_kwargs: _Response(compressed),+ max_retries=0,+ backoff_times=(),+ )+ _, _, records = next(parts)+ assert list(records) == [{"id": "https://openalex.org/S1"}]+ with pytest.raises(StopIteration):+ next(parts)++ assert not list(journal_dir.glob(".openalex_sources_part_*.gz"))+ _assert_contained(journal_dir, outside_canary)+++def test_openalex_partition_failure_preserves_existing_dataset_and_cleans_tmp(+ journal_dir, outside_canary, monkeypatch+):+ final = journal_dir / "openalex_sources.json.gz"+ final.write_bytes(b"OLD-DATASET")++ original_write_bytes = Path.write_bytes++ def partial_write_then_fail(path: Path, data: bytes) -> int:+ if path.name == ".openalex_sources_part_0.gz":+ original_write_bytes(path, data)+ raise OSError("mid-download write failure")+ return original_write_bytes(path, data)++ monkeypatch.setattr(Path, "write_bytes", partial_write_then_fail)++ parts = _openalex_common.iter_partitions(+ [{"url": "s3://openalex/data/part.gz"}],+ journal_dir,+ file_prefix="openalex_sources",+ label="test",+ safe_get=lambda *_args, **_kwargs: _Response(+ gzip.compress(b'{"id":"https://openalex.org/S1"}\n')+ ),+ max_retries=0,+ backoff_times=(),+ )+ with pytest.raises(OSError, match="mid-download write failure"):+ next(parts)++ assert final.read_bytes() == b"OLD-DATASET"+ assert not list(journal_dir.glob(".openalex_sources_part_*.gz"))+ _assert_contained(journal_dir, outside_canary)+++def test_db_atomic_build_replaces_only_the_contained_target(+ journal_dir, outside_canary+):+ (journal_dir / "openalex_sources.json.gz").write_bytes(+ gzip.compress(b'{"s": {}}')+ )+ target = journal_dir / DB_FILENAME+ target.write_bytes(b"OLD-DB")++ build_db(data_dir=journal_dir, output_path=target)++ assert target.read_bytes().startswith(b"SQLite format 3")+ assert not list(journal_dir.glob(f"{DB_FILENAME}.tmp-*"))+ _assert_contained(journal_dir, outside_canary)+++def test_doaj_atomic_replace_stays_contained(+ journal_dir, outside_canary, monkeypatch+):+ source = DOAJSource()+ target = journal_dir / source.filename+ target.write_bytes(b"OLD-DOAJ")+ monkeypatch.setattr(+ "local_deep_research.journal_quality.data_sources.doaj._MIN_DOAJ_JOURNALS",+ 1,+ )+ csv_bytes = b"Journal title,Journal ISSN (print version),Journal EISSN (online version),Publisher\nJ,1234-5678,,P\n"+ monkeypatch.setattr(+ "local_deep_research.security.safe_requests.safe_get_with_retries",+ lambda *_args, **_kwargs: _Response(csv_bytes),+ )++ assert source.fetch(journal_dir) == 1+ assert (+ json.loads(target.read_text(encoding="utf-8"))["journals"]["12345678"][+ "name"+ ]+ == "J"+ )+ assert not (journal_dir / f"{source.filename}.tmp").exists()+ _assert_contained(journal_dir, outside_canary)+++def test_predatory_atomic_replace_stays_contained(+ journal_dir, outside_canary, monkeypatch+):+ source = PredatorySource()+ target = journal_dir / source.filename+ target.write_bytes(b"OLD-PREDATORY")+ monkeypatch.setattr(+ "local_deep_research.journal_quality.data_sources.predatory._MIN_PREDATORY_TOTAL",+ 1,+ )+ payloads = iter(+ (+ b"name,url\nPublisher,https://p\n",+ b"name,url\nJournal,https://j\n",+ b"hijacked,authentic,hijackedurl,authenticurl\n",+ )+ )+ monkeypatch.setattr(+ "local_deep_research.security.safe_requests.safe_get_with_retries",+ lambda *_args, **_kwargs: _Response(next(payloads)),+ )++ assert source.fetch(journal_dir) == 2+ assert (+ json.loads(target.read_text(encoding="utf-8"))["publishers"][0]["name"]+ == "Publisher"+ )+ assert not (journal_dir / f"{source.filename}.tmp").exists()+ _assert_contained(journal_dir, outside_canary)+++def test_jabref_atomic_replace_stays_contained(+ journal_dir, outside_canary, monkeypatch+):+ source = JabRefSource()+ target = journal_dir / source.filename+ target.write_bytes(b"OLD-JABREF")+ monkeypatch.setattr(+ "local_deep_research.journal_quality.data_sources.jabref._JABREF_FILES",+ ["fixture.csv"],+ )+ monkeypatch.setattr(+ "local_deep_research.security.safe_requests.safe_get_with_retries",+ lambda *_args, **_kwargs: _Response(+ b"\n".join(+ f"Journal {index},J{index}".encode() for index in range(100)+ )+ + b"\n"+ ),+ )++ assert source.fetch(journal_dir) == 100+ with gzip.open(target, "rt", encoding="utf-8") as handle:+ assert handle.read()+ assert not (journal_dir / f"{source.filename}.tmp").exists()+ _assert_contained(journal_dir, outside_canary)+++ ("source_type", "module_path", "filename"),+ [+ (OpenAlexSource, "openalex", "openalex_sources.json.gz"),+ (InstitutionSource, "institutions", "openalex_institutions.json.gz"),+ ],+)+def test_openalex_final_dataset_atomic_replace_stays_contained(+ journal_dir,+ outside_canary,+ monkeypatch,+ source_type,+ module_path,+ filename,+):+ target = journal_dir / filename+ target.write_bytes(b"OLD-OPENALEX")+ module = __import__(+ f"local_deep_research.journal_quality.data_sources.{module_path}",+ fromlist=["x"],+ )+ records = (+ iter(+ {+ "id": f"https://openalex.org/S{index}",+ "display_name": f"Source {index}",+ }+ for index in range(10_000)+ )+ if source_type is OpenAlexSource+ else iter(+ [{"id": "https://openalex.org/I1", "display_name": "Institution"}]+ )+ )+ if source_type is InstitutionSource:+ monkeypatch.setattr(module, "_MIN_INSTITUTIONS", 1)+ monkeypatch.setattr(+ module,+ "iter_partitions",+ lambda *_args, **_kwargs: iter([(0, 1, records)]),+ )+ monkeypatch.setattr(+ "local_deep_research.security.safe_requests.safe_get_with_retries",+ lambda *_args, **_kwargs: _Response(b"{}", {"files": []}),+ )++ assert source_type().fetch(journal_dir) == (+ 10_000 if source_type is OpenAlexSource else 1+ )+ assert target.read_bytes() != b"OLD-OPENALEX"+ assert not (journal_dir / f"{filename}.tmp").exists()+ _assert_contained(journal_dir, outside_canary)+++def test_sentinel_uses_exclusive_creation_and_is_removed_on_success(+ journal_dir, outside_canary, monkeypatch+):+ calls: list[tuple[Path, str]] = []+ original_open = Path.open++ def tracking_open(path: Path, mode="r", *args, **kwargs):+ calls.append((path, mode))+ return original_open(path, mode, *args, **kwargs)++ monkeypatch.setattr(Path, "open", tracking_open)+ monkeypatch.setattr(downloader, "ALL_SOURCES", [])+ monkeypatch.setattr(+ "shutil.disk_usage", lambda _path: SimpleNamespace(free=10**15)+ )+ monkeypatch.setattr(+ "local_deep_research.journal_quality.db.build_db",+ lambda **_kwargs: None,+ )++ success, _ = downloader.download_journal_data(force=True)+ assert success+ assert (journal_dir / "version.json").is_file()+ assert (journal_dir / ".downloading", "x") in calls+ assert not (journal_dir / ".downloading").exists()+ _assert_contained(journal_dir, outside_canary)+++def test_sentinel_is_removed_after_required_source_failure(+ journal_dir, outside_canary, monkeypatch+):+ class FailingSource:+ key = "required"+ name = "required"+ count_label = "items"+ required = True++ def fetch(self, _data_dir, progress_cb=None):+ raise RuntimeError("offline canary failure")++ monkeypatch.setattr(downloader, "ALL_SOURCES", [FailingSource()])+ monkeypatch.setattr(+ "shutil.disk_usage", lambda _path: SimpleNamespace(free=10**15)+ )+ success, message = downloader.download_journal_data(force=True)++ assert not success+ assert "Failed to fetch required" in message+ assert not (journal_dir / ".downloading").exists()+ _assert_contained(journal_dir, outside_canary)+++def test_stale_sentinel_contents_cannot_redirect_download_writes(+ journal_dir, outside_canary, monkeypatch+):+ (journal_dir / ".downloading").write_text(+ str(outside_canary), encoding="utf-8"+ )++ class WritingSource:+ key = "required"+ name = "required"+ count_label = "items"+ required = True++ def fetch(self, data_dir, progress_cb=None):+ (data_dir / "fixed_dataset.json").write_bytes(b"INSIDE")+ return 1++ monkeypatch.setattr(downloader, "ALL_SOURCES", [WritingSource()])+ monkeypatch.setattr(+ "shutil.disk_usage", lambda _path: SimpleNamespace(free=10**15)+ )+ monkeypatch.setattr(+ "local_deep_research.journal_quality.db.build_db",+ lambda **_kwargs: None,+ )++ success, _ = downloader.download_journal_data(force=True)+ assert success+ assert (journal_dir / "fixed_dataset.json").read_bytes() == b"INSIDE"+ assert not (journal_dir / ".downloading").exists()+ _assert_contained(journal_dir, outside_canary)+++def test_unusable_db_cleanup_does_not_unlink_outside_canary(+ journal_dir, outside_canary+):+ corrupt_db = journal_dir / "journal_quality.db"+ corrupt_db.write_bytes(b"NOT-A-DB")++ JournalQualityDB._unlink_unusable_db(corrupt_db)++ assert not corrupt_db.exists()+ _assert_contained(journal_dir, outside_canary)diff --git a/tests/security/test_mcp_and_secure_logging.py b/tests/security/test_mcp_and_secure_logging.pynew file mode 100644index 0000000000..cdbb6422f2--- /dev/null+++ b/tests/security/test_mcp_and_secure_logging.py@@ -0,0 +1,407 @@+from __future__ import annotations++import importlib+import os+import subprocess+from pathlib import Path+from unittest.mock import patch++import pytest+from loguru import logger++from tests.test_utils import restored_loguru_state+++HOSTILE_QUERY = "../../etc/passwd; $(rm -rf /); `cat /etc/shadow` \u202eevil"+++def _outside_canaries(tmp_path: Path) -> tuple[Path, Path]:+ outside = tmp_path / "outside"+ outside.mkdir()+ file_canary = outside / "canary.txt"+ pkl_canary = outside / "canary.pkl"+ file_canary.write_text("outside data")+ pkl_canary.write_bytes(b"outside legacy plaintext")+ return file_canary, pkl_canary+++def _outside_files(tmp_path: Path, data_dir: Path) -> set[Path]:+ data_root = data_dir.resolve()+ return {+ path.relative_to(tmp_path)+ for path in tmp_path.rglob("*")+ if path.is_file() and not path.resolve().is_relative_to(data_root)+ }+++def _forbid_subprocess(+ monkeypatch: pytest.MonkeyPatch,+) -> list[tuple[str, tuple[object, ...], dict[str, object]]]:+ calls: list[tuple[str, tuple[object, ...], dict[str, object]]] = []++ def forbidden(name: str):+ def _record(*args, **kwargs):+ calls.append((name, args, kwargs))+ raise AssertionError(f"subprocess invocation reached {name}")++ return _record++ for name in ("Popen", "run", "call", "check_call", "check_output"):+ monkeypatch.setattr(subprocess, name, forbidden(name))+ monkeypatch.setattr(os, "system", forbidden("os.system"))+ return calls+++def _configure_file_sink(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+ name: str,+ *,+ debug: bool = False,+) -> tuple[Path, object]:+ import local_deep_research.utilities.log_utils as log_utils++ log_dir = tmp_path / "data" / "logs"+ monkeypatch.setattr(log_utils, "_LOG_DIR", log_dir)+ monkeypatch.setenv("LDR_ENABLE_FILE_LOGGING", "true")+ log_utils.config_logger(name, debug=debug)+ return log_dir / f"{name}.log", log_utils++[email protected](autouse=True)+def _isolated_loguru_state():+ """Keep each test's logging configuration out of the rest of the session.++ ``config_logger()`` and ``run_server()`` (through+ ``configure_mcp_logging()``) replace loguru's process-wide handler table,+ install the credential-redaction patcher and enable the+ ``local_deep_research`` namespace, and monkeypatch undoes none of it. A+ leaked patcher rewrote the ``***REDACTED***`` marker that+ ``test_settings_logger_non_dict_redaction.py`` asserts. Autouse, so tests+ that reach those calls cannot forget to opt in.+ ``restored_loguru_state()`` detaches the session's handlers for the test,+ then removes the sinks the test added and puts the original patcher,+ activation and handlers back.+ """+ with restored_loguru_state():+ yield+++ ("tool_name", "backend_name"),+ [+ ("quick_research", "ldr_quick_summary"),+ ("detailed_research", "ldr_detailed_research"),+ ("generate_report", "ldr_generate_report"),+ ],+)+def test_mcp_research_tools_keep_hostile_query_outside_data_dir(+ tmp_path, monkeypatch, tool_name, backend_name+):+ import local_deep_research.mcp.server as server++ data_dir = tmp_path / "data"+ monkeypatch.setenv("LDR_DATA_DIR", str(data_dir))+ file_canary, pkl_canary = _outside_canaries(tmp_path)+ before = _outside_files(tmp_path, data_dir)+ calls = _forbid_subprocess(monkeypatch)++ with patch.object(server, backend_name, return_value={}) as backend:+ result = getattr(server, tool_name)(HOSTILE_QUERY)++ assert result["status"] == "success"+ assert backend.call_args.args[0] == HOSTILE_QUERY+ assert calls == []+ assert _outside_files(tmp_path, data_dir) == before+ assert file_canary.read_text() == "outside data"+ assert pkl_canary.read_bytes() == b"outside legacy plaintext"+++def test_mcp_analyze_documents_rejects_hostile_collection_before_backend(+ tmp_path, monkeypatch+):+ import local_deep_research.mcp.server as server++ data_dir = tmp_path / "data"+ monkeypatch.setenv("LDR_DATA_DIR", str(data_dir))+ file_canary, pkl_canary = _outside_canaries(tmp_path)+ before = _outside_files(tmp_path, data_dir)+ calls = _forbid_subprocess(monkeypatch)++ with patch.object(server, "ldr_analyze_documents") as backend:+ result = server.analyze_documents(HOSTILE_QUERY, "../../outside")++ assert result["status"] == "error"+ assert result["error_type"] == "validation_error"+ backend.assert_not_called()+ assert calls == []+ assert _outside_files(tmp_path, data_dir) == before+ assert file_canary.read_text() == "outside data"+ assert pkl_canary.read_bytes() == b"outside legacy plaintext"+++def test_mcp_search_rejects_hostile_engine_without_subprocess_or_engine_creation(+ tmp_path, monkeypatch+):+ import local_deep_research.mcp.server as server+ import local_deep_research.web_search_engines.search_engine_factory as factory++ data_dir = tmp_path / "data"+ monkeypatch.setenv("LDR_DATA_DIR", str(data_dir))+ file_canary, pkl_canary = _outside_canaries(tmp_path)+ before = _outside_files(tmp_path, data_dir)+ calls = _forbid_subprocess(monkeypatch)+ engine_calls: list[tuple[tuple[object, ...], dict[str, object]]] = []++ def no_engine(*args, **kwargs):+ engine_calls.append((args, kwargs))+ raise AssertionError("hostile engine reached engine construction")++ monkeypatch.setattr(factory, "create_search_engine", no_engine)++ result = server.search(HOSTILE_QUERY, "wikipedia; $(id)")++ assert result["status"] == "error"+ assert result["error_type"] == "validation_error"+ assert engine_calls == []+ assert calls == []+ assert _outside_files(tmp_path, data_dir) == before+ assert file_canary.read_text() == "outside data"+ assert pkl_canary.read_bytes() == b"outside legacy plaintext"+++ ("tool_name", "kwargs"),+ [+ ("quick_research", {"iterations": "1; touch outside"}),+ ("detailed_research", {"questions_per_iteration": "$(id)"}),+ ("generate_report", {"searches_per_section": "2 && id"}),+ (+ "analyze_documents",+ {"collection_name": "safe", "max_results": "1; id"},+ ),+ ],+)+def test_mcp_hostile_numeric_metadata_is_rejected_before_settings_snapshot(+ tmp_path, monkeypatch, tool_name, kwargs+):+ import local_deep_research.mcp.server as server++ data_dir = tmp_path / "data"+ monkeypatch.setenv("LDR_DATA_DIR", str(data_dir))+ file_canary, pkl_canary = _outside_canaries(tmp_path)+ before = _outside_files(tmp_path, data_dir)+ calls = _forbid_subprocess(monkeypatch)++ with patch.object(server, "create_settings_snapshot") as snapshot:+ result = getattr(server, tool_name)("safe query", **kwargs)++ assert result["status"] == "error"+ assert result["error_type"] == "validation_error"+ snapshot.assert_not_called()+ assert calls == []+ assert _outside_files(tmp_path, data_dir) == before+ assert file_canary.read_text() == "outside data"+ assert pkl_canary.read_bytes() == b"outside legacy plaintext"+++def test_mcp_run_server_migrates_only_its_data_dir_cache(tmp_path, monkeypatch):+ import local_deep_research.mcp.server as server++ data_dir = tmp_path / "data"+ monkeypatch.setenv("LDR_DATA_DIR", str(data_dir))+ cache_root = data_dir / "cache" / "rag_indices"+ cache_root.mkdir(parents=True)+ legacy_pkl = cache_root / "legacy.pkl"+ legacy_pkl.write_bytes(b"unreadable legacy pickle")+ _, outside_pkl = _outside_canaries(tmp_path)+ transports: list[str] = []+ monkeypatch.setattr(+ server.mcp, "run", lambda *, transport: transports.append(transport)+ )++ server.run_server()++ assert not legacy_pkl.exists()+ assert outside_pkl.read_bytes() == b"outside legacy plaintext"+ assert transports == ["stdio"]+++def test_mcp_run_server_refuses_symlinked_cache_root(tmp_path, monkeypatch):+ import local_deep_research.mcp.server as server++ data_dir = tmp_path / "data"+ cache_parent = data_dir / "cache"+ cache_parent.mkdir(parents=True)+ outside = tmp_path / "outside"+ outside.mkdir()+ foreign_pkl = outside / "foreign.pkl"+ foreign_pkl.write_bytes(b"outside legacy plaintext")+ rag_root = cache_parent / "rag_indices"+ try:+ rag_root.symlink_to(outside, target_is_directory=True)+ except (OSError, NotImplementedError):+ pytest.skip("Cannot create symlinks in this environment")+ monkeypatch.setenv("LDR_DATA_DIR", str(data_dir))+ transports: list[str] = []+ monkeypatch.setattr(+ server.mcp, "run", lambda *, transport: transports.append(transport)+ )++ server.run_server()++ assert rag_root.is_symlink()+ assert foreign_pkl.read_bytes() == b"outside legacy plaintext"+ assert transports == ["stdio"]++[email protected]("value", [None, "", "false", "0"])+def test_file_logging_gate_off_creates_no_log_file(+ tmp_path, monkeypatch, value+):+ import local_deep_research.utilities.log_utils as log_utils++ monkeypatch.setattr(log_utils, "_LOG_DIR", tmp_path / "data" / "logs")+ if value is None:+ monkeypatch.delenv("LDR_ENABLE_FILE_LOGGING", raising=False)+ else:+ monkeypatch.setenv("LDR_ENABLE_FILE_LOGGING", value)++ log_utils.config_logger("gate-off")+ logger.info("file sink must remain disabled")+ logger.complete()++ assert list(tmp_path.rglob("*.log")) == []+++def test_file_logging_gate_on_writes_only_under_configured_log_dir(+ tmp_path, monkeypatch+):+ canary, _ = _outside_canaries(tmp_path)+ log_file, _ = _configure_file_sink(monkeypatch, tmp_path, "contained")++ logger.info("persistent logging enabled")+ logger.complete()++ assert log_file.is_file()+ assert log_file.resolve().is_relative_to(+ (tmp_path / "data" / "logs").resolve()+ )+ assert list(tmp_path.rglob("*.log")) == [log_file]+ assert canary.read_text() == "outside data"+++def test_file_sink_strips_unsafe_control_characters_before_disk(+ tmp_path, monkeypatch+):+ log_file, _ = _configure_file_sink(monkeypatch, tmp_path, "sanitized")+ unsafe = "\x00\x1b[31m\u202e\u200b"++ logger.info(f"before{unsafe}visible-payload")+ logger.complete()++ written = log_file.read_text()+ assert "visible-payload" in written+ assert "\x00" not in written+ assert "\x1b" not in written+ assert "\u202e" not in written+ assert "\u200b" not in written++[email protected]("diagnose", ["", "true"])+def test_file_sink_never_dumps_frame_local_secret_even_with_diagnose_optin(+ tmp_path, monkeypatch, diagnose+):+ monkeypatch.setenv("LDR_LOGURU_DIAGNOSE", diagnose)+ log_file, _ = _configure_file_sink(+ monkeypatch, tmp_path, "no-frame-locals", debug=True+ )++ def emit_exception():+ frame_local_secret = "frame-local-secret-value-9876543210"+ try:+ # Loguru diagnoses variables referenced on the failing line.+ # The exception value contains only the length, so a plaintext+ # secret on disk would come from frame-local rendering.+ raise RuntimeError("engine failure", len(frame_local_secret))+ except RuntimeError:+ logger.opt(exception=True).error("request failed (scrubbed)")++ emit_exception()+ logger.complete()++ written = log_file.read_text()+ assert "request failed (scrubbed)" in written+ assert "frame-local-secret-value-9876543210" not in written+++def test_secure_logger_exception_keeps_traceback_cause_off_disk(+ tmp_path, monkeypatch+):+ from local_deep_research.security.secure_logging import (+ logger as secure_logger,+ )++ log_file, _ = _configure_file_sink(monkeypatch, tmp_path, "secure-wrapper")+ monkeypatch.delenv("LDR_APP_DEBUG", raising=False)+ monkeypatch.delenv("LDR_LOGURU_DIAGNOSE", raising=False)++ try:+ try:+ raise ValueError("cause-chain-secret-13579")+ except ValueError as inner:+ raise RuntimeError("wrapped failure") from inner+ except RuntimeError:+ secure_logger.exception("provider call failed (scrubbed)")+ logger.complete()++ written = log_file.read_text()+ assert "provider call failed (scrubbed)" in written+ assert "cause-chain-secret-13579" not in written+ assert "Traceback" not in written+++def test_log_utils_import_mkdir_stays_under_data_dir_despite_redirect_env(+ tmp_path, monkeypatch+):+ import local_deep_research.utilities.log_utils as log_utils+ from local_deep_research.config.paths import get_logs_directory++ data_dir = tmp_path / "data"+ outside = tmp_path / "outside"+ monkeypatch.setenv("LDR_DATA_DIR", str(data_dir))+ for variable in ("LDR_LOG_DIR", "LDR_LOGS_DIR", "LOG_DIR", "LOGDIR"):+ monkeypatch.setenv(variable, str(outside))++ try:+ importlib.reload(log_utils)+ log_dir = get_logs_directory()++ assert log_utils._LOG_DIR.resolve() == (data_dir / "logs").resolve()+ assert log_dir.resolve().is_relative_to(data_dir.resolve())+ assert not outside.exists()+ assert {path.relative_to(tmp_path) for path in tmp_path.rglob("*")} <= {+ Path("data"),+ Path("data/logs"),+ }+ finally:+ # ``importlib.reload`` mutates the shared module globals in place, so+ # ``log_utils._LOG_DIR`` would keep pointing at this test's+ # soon-deleted ``tmp_path`` for the remainder of the session and make+ # every later ``log_utils`` consumer order-dependent. Drop the+ # redirect env first, then reload once more so the module ends up+ # with the same state it had on first import.+ monkeypatch.undo()+ importlib.reload(log_utils)+++ "hostile_data_dir", ["relative/ldr", "/tmp/ldr\npath", "/tmp/ldr\rpath"]+)+def test_hostile_data_dir_values_are_rejected(hostile_data_dir, monkeypatch):+ from local_deep_research.config.paths import get_data_directory++ monkeypatch.setenv("LDR_DATA_DIR", hostile_data_dir)++ with pytest.raises(ValueError):+ get_data_directory()diff --git a/tests/security/test_notes_and_upload_paths.py b/tests/security/test_notes_and_upload_paths.pynew file mode 100644index 0000000000..764d03c9f6--- /dev/null+++ b/tests/security/test_notes_and_upload_paths.py@@ -0,0 +1,253 @@+from __future__ import annotations++from io import BytesIO+from pathlib import Path++import pytest++from local_deep_research.research_library.downloaders.arxiv import (+ ArxivDownloader,+)+from local_deep_research.research_library.downloaders.biorxiv import (+ BioRxivDownloader,+)+from local_deep_research.research_library.downloaders.direct_pdf import (+ DirectPDFDownloader,+)+from local_deep_research.research_library.downloaders.generic import (+ GenericDownloader,+)+from local_deep_research.research_library.downloaders.html import HTMLDownloader+from local_deep_research.research_library.downloaders.openalex import (+ OpenAlexDownloader,+)+from local_deep_research.research_library.downloaders.playwright_html import (+ PlaywrightHTMLDownloader,+)+from local_deep_research.research_library.downloaders.pubmed import (+ PubMedDownloader,+)+from local_deep_research.research_library.downloaders.semantic_scholar import (+ SemanticScholarDownloader,+)+from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+)+from local_deep_research.security.filename_sanitizer import sanitize_filename+from local_deep_research.security.path_validator import PathValidator+++_PDF_BYTES = b"%PDF-1.4\n1 0 obj <<>>endobj\n%%EOF\n"+_HOSTILE_CONTENT_DISPOSITION = 'attachment; filename="../../outside.pdf"'+++class _OfflineResponse:+ def __init__(self, *, content=_PDF_BYTES, payload=None, text=""):+ self.status_code = 200+ self.content = content+ self.text = text+ self.headers = {+ "content-type": "application/pdf",+ "content-disposition": _HOSTILE_CONTENT_DISPOSITION,+ }+ self._payload = payload or {}++ def json(self):+ return self._payload+++class _OfflineSession:+ def __init__(self):+ self.headers = {}++ def get(self, url, **_kwargs):+ if "api.semanticscholar.org" in url:+ return _OfflineResponse(+ payload={+ "openAccessPdf": {"url": "https://files.test/paper.pdf"}+ }+ )+ if "api.openalex.org" in url:+ return _OfflineResponse(+ payload={+ "open_access": {"is_oa": True},+ "best_oa_location": {+ "pdf_url": "https://files.test/paper.pdf"+ },+ }+ )+ return _OfflineResponse()++ def close(self):+ pass+++def _snapshot(root: Path) -> set[Path]:+ return {path.relative_to(root) for path in root.rglob("*")}+++def test_notes_create_with_hostile_title_creates_no_attachment_file(+ authenticated_client, temp_data_dir, tmp_path+):+ outside_canary = tmp_path / "notes-attachment-canary.pdf"+ outside_canary.write_bytes(b"unchanged")++ response = authenticated_client.post(+ "/notes/api/notes",+ json={+ "title": "../../notes-attachment-canary.pdf",+ "content": "note body",+ },+ )++ assert response.status_code == 201+ assert response.get_json()["success"] is True+ assert outside_canary.read_bytes() == b"unchanged"+ assert not list(temp_data_dir.rglob("*.pdf"))+++def test_authenticated_pdf_upload_sanitizes_filename_before_extraction(+ authenticated_client, monkeypatch, tmp_path+):+ # ``research_routes`` (Flask) was deleted by the FastAPI migration+ # (#3299); ``/api/upload/pdf`` and both symbols patched below now live+ # in ``web.routers.research``.+ from local_deep_research.web.routers import research as research_routes++ captured_filenames = []++ class _ExtractionService:+ def extract_text_and_metadata(self, content, filename):+ captured_filenames.append(filename)+ assert content == _PDF_BYTES+ return {+ "success": True,+ "filename": filename,+ "text": "offline text",+ "size": len(content),+ "pages": 1,+ }++ outside_canary = tmp_path / "upload-canary.pdf"+ outside_canary.write_bytes(b"unchanged")+ monkeypatch.setattr(+ research_routes,+ "get_pdf_extraction_service",+ lambda: _ExtractionService(),+ )+ monkeypatch.setattr(+ research_routes.FileUploadValidator,+ "validate_upload",+ lambda **_kwargs: (True, ""),+ )++ response = authenticated_client.post(+ "/api/upload/pdf",+ data={"files": (BytesIO(_PDF_BYTES), "../../upload-canary.pdf")},+ content_type="multipart/form-data",+ )++ assert response.status_code == 200+ assert captured_filenames == ["upload-canary.pdf"]+ assert outside_canary.read_bytes() == b"unchanged"+++ ("url", "expected_filename"),+ [+ (+ "https://arxiv.org/abs/2401.12345/../../outside",+ "42.pdf",+ ),+ (+ "https://ncbi.nlm.nih.gov/pmc/articles/PMC12345/../../outside",+ "pmc_PMC12345.pdf",+ ),+ ("https://hostile.example/../../outside.pdf", "42.pdf"),+ ],+)+def test_download_service_filename_resolution_stays_validated_under_library_root(+ tmp_path, url, expected_filename+):+ manager = PDFStorageManager(tmp_path / "library", storage_mode="filesystem")++ filename = manager._generate_filename(+ url, resource_id=42, fallback_filename="42.pdf"+ )+ validated = PathValidator.validate_safe_path(+ f"pdfs/{filename}",+ base_dir=str(manager.library_root),+ required_extensions=(".pdf",),+ )++ assert filename == expected_filename+ assert sanitize_filename(filename, allowed_extensions={".pdf"}) == filename+ assert (+ Path(validated).resolve().is_relative_to(manager.library_root.resolve())+ )+++ ("downloader_class", "url"),+ [+ (ArxivDownloader, "https://arxiv.org/abs/2401.12345"),+ (PubMedDownloader, "https://pubmed.ncbi.nlm.nih.gov/12345/"),+ (+ BioRxivDownloader,+ "https://www.biorxiv.org/content/10.1101/2024.01.01",+ ),+ (+ SemanticScholarDownloader,+ "https://www.semanticscholar.org/paper/"+ "0123456789abcdef0123456789abcdef01234567",+ ),+ (OpenAlexDownloader, "https://openalex.org/W123456789"),+ (DirectPDFDownloader, "https://files.test/../../outside.pdf"),+ (GenericDownloader, "https://files.test/../../outside.pdf"),+ ],+)+def test_pdf_downloaders_return_bytes_without_writing_remote_filename(+ tmp_path, monkeypatch, downloader_class, url+):+ monkeypatch.chdir(tmp_path)+ downloader = downloader_class()+ downloader.session = _OfflineSession()+ if downloader_class is PubMedDownloader:+ monkeypatch.setattr(+ downloader, "_download_pdf_content", lambda _url: _PDF_BYTES+ )+ before = _snapshot(tmp_path)++ result = downloader.download(url)++ assert result == _PDF_BYTES+ assert _snapshot(tmp_path) == before+ downloader.close()+++ "downloader_class", [HTMLDownloader, PlaywrightHTMLDownloader]+)+def test_html_downloaders_extract_in_memory_without_file_writes(+ tmp_path, monkeypatch, downloader_class+):+ monkeypatch.chdir(tmp_path)+ downloader = downloader_class()+ monkeypatch.setattr(downloader, "_fetch_html", lambda _url: "<html></html>")+ monkeypatch.setattr(+ downloader,+ "_extract_content",+ lambda _html, url: {+ "title": "t",+ "description": None,+ "content": "body",+ "url": url,+ },+ )+ before = _snapshot(tmp_path)++ result = downloader.download("https://hostile.example/../../outside.html")++ assert result is not None+ assert _snapshot(tmp_path) == before+ downloader.close()diff --git a/tests/security/test_path_property_fuzz.py b/tests/security/test_path_property_fuzz.pynew file mode 100644index 0000000000..d32586a124--- /dev/null+++ b/tests/security/test_path_property_fuzz.py@@ -0,0 +1,497 @@+"""Hypothesis properties for library PDF filesystem confinement.++Complements the fixed-payload batteries in ``test_remote_filename_writes``+and ``test_poisoned_path_reads``. A failure that creates/modifies an+outside-root path or serves the canary marker is a vulnerability;+setup/liveness failures are a broken test.++Fixtures: ``fs_storage``, ``fresh_document``, ``library_session`` and+``canary_paths`` come from+``tests/security/conftest.py`` (they were duplicated verbatim across four+batteries in this directory and are now defined once); ``library_client``+is built here from ``test_poisoned_path_reads``'s+``_authenticated_fastapi_client`` helper because it is specific to the+library router. The registered username is exposed as+``library_client.username`` (random per test — the Flask-era+``_make_bare_flask_client`` this used to build on could fake a fixed+session username, a real FastAPI login cannot). All of them use+``tmp_path`` only.++Run with:+``.venv/bin/python -m pytest tests/security/test_path_property_fuzz.py -v --no-header --timeout=120``+"""++from __future__ import annotations++from pathlib import Path+from unittest.mock import patch++import pytest+from hypothesis import HealthCheck, given, settings, strategies as st++from tests.test_utils import add_src_to_path++add_src_to_path()++from tests.security.test_poisoned_path_reads import ( # noqa: E402+ _LR,+ _PDF_POISON,+ _PDF_SAFE,+ _authenticated_fastapi_client,+ _library_settings_mock,+ _make_canary,+ _patched_user_db_session,+ _slowapi_off, # noqa: F401 -- registers the autouse rate-limiter fixture+)+from tests.security.test_remote_filename_writes import ( # noqa: E402+ _MINIMAL_PDF,+ _assert_files_inside,+)+++_ANY_NON_SURROGATE = st.characters(blacklist_categories=("Cs",))+_HOSTILE_ATOMS = st.sampled_from(+ [+ "..",+ ".",+ "...",+ "....",+ "/",+ "\\",+ "../",+ "..\\",+ "..//",+ "....//",+ "..;/",+ "%2e%2e%2f",+ "%2e%2e/",+ "..%2f",+ "..%252f",+ "..%c0%af",+ "\x00",+ "evil\x00.pdf",+ "\uff0e\uff0e\uff0f",+ "cafe\u0301",+ "cafe\u00e9",+ "a b",+ "-rf",+ "tmp",+ "etc",+ "root",+ "escape.pdf",+ ]+)+++def _hostile_paths():+ """Random 1..2000-character names, biased toward hostile path atoms."""+ return st.one_of(+ st.text(alphabet=_ANY_NON_SURROGATE, min_size=1, max_size=2000),+ st.builds(+ "".join,+ st.lists(+ st.one_of(+ _HOSTILE_ATOMS,+ st.text(alphabet=_ANY_NON_SURROGATE, max_size=25),+ ),+ min_size=1,+ max_size=8,+ ),+ ),+ )+++def _depth_neutral_segments():+ """Fuzzed single path segments that preserve a fixed escape depth."""+ return st.text(+ alphabet=st.characters(blacklist_categories=("Cs", "Cc")),+ min_size=1,+ max_size=60,+ ).filter(lambda value: "/" not in value and value not in (".", ".."))+++def _outside_state(+ base: Path, library_root: Path+) -> dict[str, tuple[str, bytes | str | None]]:+ root = library_root.resolve()+ state: dict[str, tuple[str, bytes | str | None]] = {}+ for path in sorted(base.rglob("*")):+ resolved = path.resolve()+ if resolved == root or root in resolved.parents:+ continue+ if path.is_symlink():+ state[str(path)] = ("symlink", str(path.readlink()))+ elif path.is_file():+ state[str(path)] = ("file", path.read_bytes())+ else:+ state[str(path)] = ("directory", None)+ return state+++def _assert_outside_tree_unchanged(+ before: dict[str, tuple[str, bytes | str | None]],+ tmp_path: Path,+ library_root: Path,+) -> None:+ after = _outside_state(tmp_path, library_root)+ assert after == before, (+ "VULNERABILITY: save_pdf created, deleted, or modified an entry "+ f"outside library_root {library_root}"+ )+++def library_client(app):+ """Authenticated client for the REAL FastAPI library router.++ Same helper as ``test_poisoned_path_reads.library_client``. The real+ registered username is exposed as ``.username`` — tests below use it+ to compute the per-user storage root the same way the route does+ (``apply_user_subdir``), rather than a hardcoded constant.+ """+ return _authenticated_fastapi_client(app, "library-pdf-user")+++class TestSavePdfProperty:+ @given(filename=_hostile_paths())+ @settings(+ max_examples=50,+ deadline=None,+ suppress_health_check=[HealthCheck.function_scoped_fixture],+ )+ def test_random_filename_is_rejected_or_confined(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ tmp_path,+ filename,+ ):+ before = _outside_state(tmp_path, fs_storage.library_root)+ fresh_document.storage_mode = None+ fresh_document.file_path = None++ try:+ relative_path, _ = fs_storage.save_pdf(+ _MINIMAL_PDF,+ fresh_document,+ library_session,+ filename,+ )+ except (ValueError, OSError):+ _assert_files_inside(fs_storage.library_root, None, canary_paths)+ _assert_outside_tree_unchanged(+ before, tmp_path, fs_storage.library_root+ )+ return++ _assert_files_inside(+ fs_storage.library_root, relative_path, canary_paths+ )+ written = (fs_storage.library_root / relative_path).resolve()+ assert written.is_file(), f"save_pdf returned missing path: {written}"+ assert written.read_bytes() == _MINIMAL_PDF+ _assert_outside_tree_unchanged(+ before, tmp_path, fs_storage.library_root+ )++ @given(segment=_depth_neutral_segments())+ @settings(+ max_examples=40,+ deadline=None,+ suppress_health_check=[HealthCheck.function_scoped_fixture],+ )+ def test_live_traversal_filename_cannot_create_outside_file(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ tmp_path,+ segment,+ ):+ filename = f"pdfs/{segment}/../../../outside_canary_zone/escape.pdf"+ expected = tmp_path / "outside_canary_zone" / "escape.pdf"+ assert (+ fs_storage.library_root / filename+ ).resolve() == expected.resolve()++ before = _outside_state(tmp_path, fs_storage.library_root)+ fresh_document.storage_mode = None+ fresh_document.file_path = None+ try:+ relative_path, _ = fs_storage.save_pdf(+ _MINIMAL_PDF,+ fresh_document,+ library_session,+ filename,+ )+ except (ValueError, OSError):+ _assert_files_inside(fs_storage.library_root, None, canary_paths)+ _assert_outside_tree_unchanged(+ before, tmp_path, fs_storage.library_root+ )+ return++ _assert_files_inside(+ fs_storage.library_root, relative_path, canary_paths+ )+ _assert_outside_tree_unchanged(+ before, tmp_path, fs_storage.library_root+ )+++class TestLibraryResolverProperty:+ USERNAME = "fuzz-resolver-user"++ @staticmethod+ def _root(tmp_path: Path) -> tuple[Path, Path]:+ base_root = tmp_path / "library"+ root = base_root / TestLibraryResolverProperty.USERNAME+ root.mkdir(parents=True, exist_ok=True)+ return base_root, root++ @given(relative_path=_hostile_paths())+ @settings(+ max_examples=50,+ deadline=None,+ suppress_health_check=[HealthCheck.function_scoped_fixture],+ )+ def test_random_path_resolves_inside_root_or_none(+ self, tmp_path, relative_path, monkeypatch+ ):+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ # get_absolute_path_from_settings's storage_path lookup carries an+ # eagerly-evaluated str(get_library_directory()) default -- Python+ # evaluates it before get_setting() runs, regardless of the+ # explicit settings_manager passed below, so it unconditionally+ # mkdirs <data_dir>/library. Pin LDR_DATA_DIR so that lands under+ # tmp_path instead of the real platformdirs user data dir.+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "app_data"))+ base_root, root = self._root(tmp_path)+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)+ resolved = get_absolute_path_from_settings(+ relative_path,+ self.USERNAME,+ settings_manager=_library_settings_mock(base_root),+ )++ if resolved is not None:+ assert resolved.resolve().is_relative_to(root.resolve()), (+ "VULNERABILITY: get_absolute_path_from_settings returned "+ f"outside-root path {resolved} for {relative_path!r}"+ )+ assert canary.read_bytes() == _PDF_POISON++ @given(segment=_depth_neutral_segments())+ @settings(+ max_examples=40,+ deadline=None,+ suppress_health_check=[HealthCheck.function_scoped_fixture],+ )+ def test_live_traversal_resolver_returns_none(+ self, tmp_path, segment, monkeypatch+ ):+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ # Same eager-default-argument hazard as+ # test_random_path_resolves_inside_root_or_none above.+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "app_data"))+ base_root, root = self._root(tmp_path)+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)+ relative_path = f"pdfs/{segment}/../../../../secrets/canary.pdf"+ assert (root / relative_path).resolve() == canary.resolve()++ resolved = get_absolute_path_from_settings(+ relative_path,+ self.USERNAME,+ settings_manager=_library_settings_mock(base_root),+ )+ assert resolved is None, (+ "VULNERABILITY: resolver returned a path for a live traversal "+ f"payload: {resolved}"+ )+ assert canary.read_bytes() == _PDF_POISON+++class TestPdfStorageReadProperty:+ @given(file_path=_hostile_paths())+ @settings(+ max_examples=40,+ deadline=None,+ suppress_health_check=[HealthCheck.function_scoped_fixture],+ )+ def test_random_file_path_never_returns_bytes(+ self, fs_storage, fresh_document, library_session, tmp_path, file_path+ ):+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)+ fresh_document.file_path = file_path+ fresh_document.storage_mode = "filesystem"++ result = fs_storage.load_pdf(fresh_document, library_session)+ assert result is None, (+ "VULNERABILITY: load_pdf returned bytes although the only PDF is "+ f"the outside canary for {file_path!r}"+ )+ assert canary.read_bytes() == _PDF_POISON++ @given(segment=_depth_neutral_segments())+ @settings(+ max_examples=40,+ deadline=None,+ suppress_health_check=[HealthCheck.function_scoped_fixture],+ )+ def test_live_traversal_file_path_never_returns_canary(+ self, fs_storage, fresh_document, library_session, tmp_path, segment+ ):+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)+ file_path = f"pdfs/{segment}/../../../secrets/canary.pdf"+ assert (+ fs_storage.library_root / file_path+ ).resolve() == canary.resolve()+ fresh_document.file_path = file_path+ fresh_document.storage_mode = "filesystem"++ assert fs_storage.load_pdf(fresh_document, library_session) is None, (+ "VULNERABILITY: load_pdf served the outside-root canary"+ )+ assert canary.read_bytes() == _PDF_POISON++ @given(+ payload=st.one_of(+ _hostile_paths().map(lambda value: (value, None)),+ _depth_neutral_segments().map(+ lambda segment: (+ f"pdfs/{segment}/../../../secrets/canary.pdf",+ segment,+ )+ ),+ )+ )+ @settings(+ max_examples=40,+ deadline=None,+ suppress_health_check=[HealthCheck.function_scoped_fixture],+ )+ def test_has_pdf_is_false_without_an_in_root_file(+ self, fs_storage, fresh_document, library_session, tmp_path, payload+ ):+ file_path, live_segment = payload+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)+ if live_segment is not None:+ assert (+ fs_storage.library_root / file_path+ ).resolve() == canary.resolve()+ fresh_document.file_path = file_path+ fresh_document.storage_mode = "filesystem"++ assert fs_storage.has_pdf(fresh_document, library_session) is False, (+ "VULNERABILITY: has_pdf accepted a path despite no in-root PDF "+ f"existing for {file_path!r}"+ )+ assert canary.read_bytes() == _PDF_POISON+++class TestViewPdfRouteProperty:+ @given(+ payload=st.one_of(+ _hostile_paths().map(lambda value: (value, None)),+ _depth_neutral_segments().map(+ lambda segment: (+ f"pdfs/{segment}/../../../../secrets/canary.pdf",+ segment,+ )+ ),+ )+ )+ @settings(+ max_examples=25,+ deadline=None,+ suppress_health_check=[HealthCheck.function_scoped_fixture],+ )+ def test_route_never_serves_outside_canary(+ self,+ library_client,+ fresh_document,+ library_session,+ tmp_path,+ payload,+ ):+ file_path, live_segment = payload+ base_root = tmp_path / "library"+ root = base_root / library_client.username+ (root / "pdfs").mkdir(parents=True, exist_ok=True)+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)+ if live_segment is not None:+ assert (root / file_path).resolve() == canary.resolve()++ fresh_document.file_path = file_path+ fresh_document.storage_mode = "filesystem"+ library_session.commit()+ with patch(+ f"{_LR}.get_settings_manager",+ return_value=_library_settings_mock(base_root),+ ):+ with _patched_user_db_session(_LR, library_session):+ response = library_client.get(+ f"/library/document/{fresh_document.id}/pdf"+ )++ assert response.status_code in (200, 404, 500)+ assert _PDF_POISON not in response.data, (+ "VULNERABILITY: view_pdf route served outside-root canary bytes"+ )+ assert canary.read_bytes() == _PDF_POISON+++class TestPositiveControls:+ def test_clean_filename_round_trips_inside_root(+ self, fs_storage, fresh_document, library_session, canary_paths+ ):+ relative_path, _ = fs_storage.save_pdf(+ _MINIMAL_PDF,+ fresh_document,+ library_session,+ "clean.pdf",+ )+ written = (fs_storage.library_root / relative_path).resolve()+ assert written.is_relative_to(+ (fs_storage.library_root / "pdfs").resolve()+ )+ assert (+ fs_storage.load_pdf(fresh_document, library_session) == _MINIMAL_PDF+ )+ assert fs_storage.has_pdf(fresh_document, library_session) is True+ _assert_files_inside(+ fs_storage.library_root, relative_path, canary_paths+ )++ def test_view_pdf_route_serves_legitimate_in_root_pdf(+ self, library_client, fresh_document, library_session, tmp_path+ ):+ base_root = tmp_path / "library"+ root = base_root / library_client.username+ legitimate = root / "pdfs" / "legitimate.pdf"+ legitimate.parent.mkdir(parents=True)+ legitimate.write_bytes(_PDF_SAFE)+ fresh_document.file_path = "pdfs/legitimate.pdf"+ fresh_document.storage_mode = "filesystem"+ library_session.commit()++ with patch(+ f"{_LR}.get_settings_manager",+ return_value=_library_settings_mock(base_root),+ ):+ with _patched_user_db_session(_LR, library_session):+ response = library_client.get(+ f"/library/document/{fresh_document.id}/pdf"+ )++ assert response.status_code == 200+ assert response.data == _PDF_SAFEdiff --git a/tests/security/test_poisoned_path_reads.py b/tests/security/test_poisoned_path_reads.pynew file mode 100644index 0000000000..65b96bb494--- /dev/null+++ b/tests/security/test_poisoned_path_reads.py@@ -0,0 +1,926 @@+# allow: no-sut-import — security battery for read-side poisoning of+# DB-stored paths (research report_path, library Document.file_path, backup+# metadata). Drives the real FastAPI routes through a real authenticated+# TestClient while stubbing the DB session so we can plant rows whose path+# columns point at a canary file under tmp_path, then asserts the canary+# marker NEVER appears in the response bytes/content.+"""Security battery: poisoned DB-stored paths on the READ side.++Complements+ * ``tests/security/test_report_path_deletion.py`` — pins the+ DELETE / clear_history unlink surface for ``ResearchHistory.report_path``+ (write/delete side: the unlink trusts the column verbatim).+ * ``tests/security/test_pdf_path_traversal.py`` — pins+ ``PDFStorageManager._get_safe_file_path`` as a unit; this file drives+ the same manager end-to-end via the real FastAPI route and ``load_pdf``.+ * ``tests/security/test_remote_filename_writes.py`` — pins the+ write-side of ``Document.file_path`` (``save_pdf``); this file pins+ the matching read-side (``load_pdf`` -> ``view_pdf_page``).++SURFACE VERIFICATION (re-verified against the FastAPI routers after+#3299 deleted the Flask blueprints this file used to drive):++1. Research export/report — GREEN PIN (report_path is never opened).+ * ``POST /api/v1/research/<id>/export/<format>``+ (``export_research_report`` in ``web/routers/research.py``) builds+ content via ``assemble_full_report``, which reads+ ``ResearchHistory.report_content`` from the DB+ (``web/services/report_assembly_service.py``:+ ``body = research.report_content or ""``) and streams the assembled+ bytes back — never opens a file on disk.+ * ``GET /api/report/<id>`` (``get_research_report`` in+ ``web/routers/research.py``) uses the same DB-content path.+ * ``report_path`` is only ever echoed back in JSON metadata elsewhere in+ the same router — never opened as a file.+ => Poisoning vector does not exist; the tests below pin that and turn+ red if a future change serves the file at ``report_path``.++2. Library PDF serving — GREEN PIN (validator-routed).+ * ``view_pdf_page`` / ``serve_pdf_api`` (``web/routers/library.py``,+ both delegating to the shared ``_serve_pdf``) call+ ``PDFStorageManager.load_pdf`` (pdf_storage_manager.py) ->+ ``_load_from_filesystem`` -> ``_get_safe_file_path`` ->+ ``_safe_path_in_root`` -> ``PathValidator.validate_safe_path``+ (path_validator.py; werkzeug's ``safe_join`` — retained deliberately+ as a security utility, not Flask residue — rejects absolute paths+ and ``..`` segments, plus encoded/unicode traversal) followed by an+ explicit ``is_symlink()`` block.+ * The other read consumer ``get_absolute_path_from_settings``+ (research_library/utils/__init__.py; used by+ download_service.py's ``_try_existing_pdf_extraction`` and+ library_service.py reads) routes through ``_resolve_within_root`` —+ the same validator + symlink check. The legacy shared-root read+ fallback is operator-gated OFF by default+ (``research_library.allow_legacy_read_fallback``).++3. Backup metadata — GREEN PIN (no restore exists; metadata is validated).+ * backup_service.py has NO restore function and no HTTP route accepts+ a user-supplied backup name (the only backup route,+ ``GET /api/backup-status`` in ``web/routers/settings.py``, globs).+ * ``list_backups`` globs ``ldr_backup_*.db`` filtered by+ ``is_safe_glob_result`` (rejects symlinks and entries whose+ ``resolve()`` leaves backup_dir) and exposes only the bare filename.+ * The single ``info["path"]`` consumer, ``purge_and_refresh``,+ iterates that validated list.++FAILURE CLASSIFICATION: red = canary marker appeared in served content,+a canary/symlink was deleted, or backup metadata described a foreign path+(vulnerability tripped). Broken-test = import/setup/expectation bugs.++Run with:+.venv/bin/python -m pytest tests/security/test_poisoned_path_reads.py -v --no-header --timeout=120+"""++from __future__ import annotations++import hashlib+import itertools+import uuid+from contextlib import contextmanager+from datetime import datetime, timezone+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+from fastapi.testclient import TestClient+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker+from sqlalchemy.pool import StaticPool++from tests.test_utils import add_src_to_path++add_src_to_path()++from local_deep_research.database.models import Base, ResearchHistory # noqa: E402+from local_deep_research.database.models.library import ( # noqa: E402+ Document,+ DocumentStatus,+ SourceType,+)++# The FastAPI migration (#3299) deleted the Flask blueprints this file used+# to drive (``web.routes.research_routes``, ``research_library.routes.+# library_routes``); both route bodies now live in FastAPI routers that+# import ``get_user_db_session`` / ``get_settings_manager`` at module level,+# so the same "patch it at its source" technique below still works.+_RR = "local_deep_research.web.routers.research"+_LR = "local_deep_research.web.routers.library"++# Unique ASCII markers — survive LaTeX templating unchanged and cannot be+# confused with framework noise.+_REPORT_POISON = "LDR_POISONED_REPORT_READ_7f3a9c"+_REPORT_SAFE = "SAFEDBCONTENT42"+_PDF_POISON = b"LDR_POISONED_PDF_READ_7f3a9c"+_PDF_SAFE = b"%PDF-1.4 SAFELIBPDF42\n%%EOF\n"++TEST_PASSWORD = "PoisonReadsPass123" # noqa: S105++# Monotonic, never random: several clients register per test session and+# random /8 addresses can collide, producing a 429 from a bucket some+# earlier test filled (see test_save_raw_config_blocked_keys_fastapi.py+# for the same reasoning).+_FORWARDED_IP_SEQ = itertools.count(1)+++# ---------------------------------------------------------------------------+# Fixtures / helpers+# ---------------------------------------------------------------------------++[email protected](autouse=True)+def _slowapi_off():+ """Take the per-IP HTTP rate limiter out of the picture.++ Every client below registers a fresh user (``/auth/register`` caps at+ 3/hour per IP); nothing here is about rate limiting.+ """+ from local_deep_research.web.dependencies.rate_limit import limiter++ original = limiter.enabled+ limiter.enabled = False+ try:+ yield+ finally:+ limiter.enabled = original+++def _csrf(client: TestClient) -> str:+ """Stamp the session with a CSRF token, then fetch it as a string."""+ client.get("/auth/login")+ resp = client.get("/auth/csrf-token")+ return resp.json().get("csrf_token", "") if resp.status_code == 200 else ""+++def _authenticated_fastapi_client(app, username_prefix: str) -> TestClient:+ """Register a fresh real user and return their logged-in TestClient.++ Real registration/login (not a faked session) is what lets these+ requests past the FastAPI routers' ``require_auth`` dependency; the DB+ session itself is separately patched per-test (see+ ``_patched_user_db_session``) so the real per-user database is never+ touched. The registered username is attached to the client as+ ``.username`` for tests that need to compute the per-user storage root.+ """+ n = next(_FORWARDED_IP_SEQ)+ client = TestClient(app, raise_server_exceptions=False)+ client.headers.update(+ {"X-Forwarded-For": f"10.{(n // 250) % 250 + 1}.{n % 250 + 1}.17"}+ )+ username = f"{username_prefix}_{uuid.uuid4().hex[:8]}"+ resp = client.post(+ "/auth/register",+ data={+ "username": username,+ "password": TEST_PASSWORD,+ "confirm_password": TEST_PASSWORD,+ "acknowledge": "true",+ "csrf_token": _csrf(client),+ },+ follow_redirects=False,+ )+ assert resp.status_code == 302, (+ "harness broken — could not register a user to drive the endpoint "+ f"with: {resp.status_code} {resp.text[:300]}"+ )+ client.username = username+ # Every state-changing request below needs a CSRF header (ASGI+ # middleware, no off switch); set a default so POSTs don't each have+ # to fetch their own.+ token = _csrf(client)+ if token:+ client.headers.update({"X-CSRFToken": token})+ return client+++def research_client(app):+ """Authenticated client for the REAL FastAPI research router."""+ return _authenticated_fastapi_client(app, "poison-reads-research")+++def library_client(app):+ """Authenticated client for the REAL FastAPI library router.++ ``client.username`` is the real registered username — ``TestViewPdfRoute``+ needs it to compute the per-user storage root the same way the route+ does (``apply_user_subdir``).+ """+ return _authenticated_fastapi_client(app, "library-pdf-user")+++def _seed_research_db(rid, report_path_value, report_content=_REPORT_SAFE):+ """In-memory SQLite session with one ResearchHistory row.++ The row carries BOTH a poisoned ``report_path`` and legitimate+ ``report_content`` — an implementation that trusts the DB serves the+ safe marker; one that opens ``report_path`` leaks the poison marker.+ Returns ``(session, engine)``; caller must ``_close``.++ ``StaticPool`` + ``check_same_thread=False``: this session is patched+ into a real ``TestClient`` request for a sync route, dispatched+ through ``run_in_threadpool`` on a different thread than the one that+ seeded it here — without a shared, thread-agnostic connection,+ closing/rolling back this session later trips ``sqlite3.+ ProgrammingError: SQLite objects created in a thread can only be used+ in that same thread``. Same fix as+ ``test_socket_ownership_edges_fastapi.py``.+ """+ engine = create_engine(+ "sqlite:///:memory:",+ poolclass=StaticPool,+ connect_args={"check_same_thread": False},+ )+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ session.add(+ ResearchHistory(+ id=rid,+ query="q",+ mode="quick",+ status="completed",+ created_at=datetime.now(timezone.utc).isoformat(),+ report_path=report_path_value,+ report_content=report_content,+ )+ )+ session.commit()+ return session, engine+++def _close(session, engine):+ session.close()+ engine.dispose()+++@contextmanager+def _patched_user_db_session(module_target, session):+ """Patch ``get_user_db_session`` in ``module_target`` to yield+ ``session`` (used as a context manager by the route handlers)."""+ with patch(f"{module_target}.get_user_db_session") as get_sess:+ get_sess.return_value.__enter__ = lambda _s: session+ get_sess.return_value.__exit__ = MagicMock(return_value=False)+ yield+++def library_session():+ """In-memory SQLite session with the library models + a SourceType.++ Pattern from tests/security/test_remote_filename_writes.py. The+ fixture tears the session down, so tests need no manual cleanup.++ ``StaticPool`` + ``check_same_thread=False`` — see ``_seed_research_db``+ above: ``TestViewPdfRoute`` patches this session into a real+ ``TestClient`` request for a sync route, run in a threadpool worker+ thread.+ """+ engine = create_engine(+ "sqlite:///:memory:",+ poolclass=StaticPool,+ connect_args={"check_same_thread": False},+ )+ Base.metadata.create_all(engine)+ with sessionmaker(bind=engine)() as session:+ source_type = SourceType(+ id=str(uuid.uuid4()),+ name="research_download",+ display_name="Research Download",+ description="x",+ )+ session.add(source_type)+ session.commit()+ yield session, source_type+ engine.dispose()+++def _seed_document(session, source_type, file_path_value) -> Document:+ """Add a completed filesystem-mode Document with the given (possibly+ poisoned) ``file_path`` and return it."""+ doc = Document(+ id=str(uuid.uuid4()),+ source_type_id=source_type.id,+ document_hash=hashlib.sha256(b"placeholder").hexdigest(),+ file_size=100,+ file_type="pdf",+ status=DocumentStatus.COMPLETED,+ title="t",+ filename="t.pdf",+ storage_mode="filesystem",+ file_path=file_path_value,+ )+ session.add(doc)+ session.commit()+ return doc+++def _make_canary(directory, name, marker):+ """Plant a canary file with the marker content; returns its path."""+ directory.mkdir(parents=True, exist_ok=True)+ canary = directory / name+ if isinstance(marker, bytes):+ canary.write_bytes(marker)+ else:+ canary.write_text(marker)+ return canary+++def _library_settings_mock(base_root: Path):+ """MagicMock settings manager pinning the library root for+ ``view_pdf_page`` (which calls ``get_settings_manager(db_session)``).++ ``apply_user_subdir`` (real code, utils/__init__.py) then resolves the+ effective per-user root to ``<base_root>/<session username>`` — the+ tests must plant payloads relative to THAT root.+ """+ settings_mgr = MagicMock()++ def _get(key, default=None):+ if key == "research_library.storage_path":+ return str(base_root)+ if key == "research_library.pdf_storage_mode":+ return "filesystem"+ if key == "research_library.shared_library":+ return False+ return default++ settings_mgr.get_setting.side_effect = _get+ return settings_mgr+++# ---------------------------------------------------------------------------+# SURFACE 1 — POST /api/v1/research/<id>/export/<format>+# ---------------------------------------------------------------------------+++class TestResearchExportReads:+ """Export must assemble from DB ``report_content`` and must never open+ the file at ``report_path`` (verified research_routes.py:2170-2254)."""++ def test_absolute_report_path_content_not_served(+ self, research_client, tmp_path+ ):+ canary = _make_canary(+ tmp_path / "export_outside_abs", "canary.txt", _REPORT_POISON+ )+ rid = "rid-export-abs"+ session, engine = _seed_research_db(rid, str(canary))+ try:+ with _patched_user_db_session(_RR, session):+ resp = research_client.post(+ f"/api/v1/research/{rid}/export/latex"+ )+ assert resp.status_code in (200, 400, 500)+ assert _REPORT_POISON.encode() not in resp.data, (+ "POST /api/v1/research/<id>/export served the file at an "+ "absolute report_path outside the storage root — "+ "arbitrary file read"+ )+ finally:+ _close(session, engine)+ assert canary.read_text() == _REPORT_POISON++ def test_parent_traversal_report_path_content_not_served(+ self, research_client, tmp_path+ ):+ canary = _make_canary(+ tmp_path / "export_outside_traversal", "victim.txt", _REPORT_POISON+ )+ fake_storage = tmp_path / "research_outputs"+ (fake_storage / "sub").mkdir(parents=True)+ traversal = (+ fake_storage+ / "sub"+ / ".."+ / ".."+ / "export_outside_traversal"+ / "victim.txt"+ )+ # The payload must be stat-able, or a reader's .exists() guard+ # would skip the file and produce a false green.+ assert traversal.exists()+ assert traversal.resolve() == canary.resolve()++ rid = "rid-export-traversal"+ session, engine = _seed_research_db(rid, str(traversal))+ try:+ with _patched_user_db_session(_RR, session):+ resp = research_client.post(+ f"/api/v1/research/{rid}/export/latex"+ )+ assert resp.status_code in (200, 400, 500)+ assert _REPORT_POISON.encode() not in resp.data, (+ "POST /api/v1/research/<id>/export followed a ..-laden "+ "report_path outside the storage root — arbitrary file read"+ )+ finally:+ _close(session, engine)+ assert canary.read_text() == _REPORT_POISON++ def test_symlink_report_path_content_not_served(+ self, research_client, tmp_path+ ):+ canary = _make_canary(+ tmp_path / "export_outside_target",+ "symlink_target.txt",+ _REPORT_POISON,+ )+ fake_storage = tmp_path / "research_outputs"+ fake_storage.mkdir()+ link = fake_storage / "evil_link"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ assert link.is_symlink()++ rid = "rid-export-symlink"+ session, engine = _seed_research_db(rid, str(link))+ try:+ with _patched_user_db_session(_RR, session):+ resp = research_client.post(+ f"/api/v1/research/{rid}/export/latex"+ )+ assert resp.status_code in (200, 400, 500)+ assert _REPORT_POISON.encode() not in resp.data, (+ "POST /api/v1/research/<id>/export followed a symlink "+ "report_path outside the storage root — arbitrary file read"+ )+ finally:+ _close(session, engine)+ assert canary.read_text() == _REPORT_POISON+ assert link.is_symlink() or link.exists()++ def test_positive_control_db_content_is_served(self, research_client):+ """The export feature must keep working: report_content from+ the DB is exported. The row deliberately has no report_path, so+ a regression that starts reading from disk would find nothing+ to serve and these assertions would fail loudly."""+ rid = "rid-export-legit"+ session, engine = _seed_research_db(rid, None)+ try:+ with _patched_user_db_session(_RR, session):+ resp = research_client.post(+ f"/api/v1/research/{rid}/export/latex"+ )+ finally:+ _close(session, engine)+ assert resp.status_code == 200, (+ f"POSITIVE CONTROL FAILED: legit export returned "+ f"{resp.status_code}; if a path-validation fix was just added "+ "it is over-restrictive."+ )+ assert _REPORT_SAFE.encode() in resp.data+ assert _REPORT_POISON.encode() not in resp.data+++# ---------------------------------------------------------------------------+# SURFACE 1b — GET /api/report/<id>+# ---------------------------------------------------------------------------+++class TestResearchReportEndpointReads:+ """/api/report must assemble from the DB, never open report_path+ (verified research_routes.py:2093-2163)."""++ def test_absolute_report_path_content_not_served(+ self, research_client, tmp_path+ ):+ canary = _make_canary(+ tmp_path / "report_outside_abs", "canary.txt", _REPORT_POISON+ )+ rid = "rid-report-abs"+ session, engine = _seed_research_db(rid, str(canary))+ try:+ with _patched_user_db_session(_RR, session):+ resp = research_client.get(f"/api/report/{rid}")+ assert resp.status_code in (200, 400, 500)+ assert _REPORT_POISON.encode() not in resp.data, (+ "GET /api/report/<id> served the file at an absolute "+ "report_path outside the storage root — arbitrary file read"+ )+ finally:+ _close(session, engine)+ assert canary.read_text() == _REPORT_POISON++ def test_positive_control_db_content_is_served(self, research_client):+ rid = "rid-report-legit"+ session, engine = _seed_research_db(rid, None)+ try:+ with _patched_user_db_session(_RR, session):+ resp = research_client.get(f"/api/report/{rid}")+ finally:+ _close(session, engine)+ assert resp.status_code == 200, resp.status_code+ assert _REPORT_SAFE.encode() in resp.data+++# ---------------------------------------------------------------------------+# SURFACE 2 — PDFStorageManager.load_pdf (service level)+# ---------------------------------------------------------------------------+++class TestPdfStorageLoadPdf:+ """``load_pdf`` must route filesystem reads through+ ``_get_safe_file_path`` (PathValidator + symlink check). Pinned+ unit-level by test_pdf_path_traversal.py; pinned here at the serving+ level with an in-memory library DB."""++ @pytest.fixture+ def fs_storage(self, tmp_path):+ from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+ )++ library_root = tmp_path / "library"+ (library_root / "pdfs").mkdir(parents=True)+ return PDFStorageManager(+ library_root=library_root,+ storage_mode="filesystem",+ username="testuser",+ )++ def test_absolute_file_path_not_served(self, fs_storage, library_session):+ session, source_type = library_session+ canary = _make_canary(+ fs_storage.library_root.parent / "outside_zone",+ "victim.pdf",+ _PDF_POISON,+ )+ doc = _seed_document(session, source_type, str(canary))+ result = fs_storage.load_pdf(doc, session)+ assert result is None or _PDF_POISON not in result, (+ "PDFStorageManager.load_pdf served bytes from an absolute "+ "Document.file_path outside the library root — arbitrary "+ "file read"+ )+ assert canary.read_bytes() == _PDF_POISON++ def test_parent_traversal_file_path_not_served(+ self, fs_storage, library_session+ ):+ session, source_type = library_session+ canary = _make_canary(+ fs_storage.library_root.parent / "outside_zone",+ "victim.pdf",+ _PDF_POISON,+ )+ # library_root/pdfs/../../outside_zone/victim.pdf -> the canary.+ traversal = "pdfs/../../outside_zone/victim.pdf"+ assert (fs_storage.library_root / traversal).resolve() == (+ canary.resolve()+ )+ doc = _seed_document(session, source_type, traversal)+ result = fs_storage.load_pdf(doc, session)+ assert result is None or _PDF_POISON not in result, (+ "PDFStorageManager.load_pdf followed a ..-laden "+ "Document.file_path outside the library root — arbitrary "+ "file read"+ )+ assert canary.read_bytes() == _PDF_POISON++ def test_symlink_file_path_not_served(self, fs_storage, library_session):+ session, source_type = library_session+ canary = _make_canary(+ fs_storage.library_root.parent / "outside_target",+ "victim.pdf",+ _PDF_POISON,+ )+ link = fs_storage.library_root / "pdfs" / "evil_link.pdf"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ assert link.is_symlink()+ doc = _seed_document(session, source_type, "pdfs/evil_link.pdf")+ result = fs_storage.load_pdf(doc, session)+ assert result is None or _PDF_POISON not in result, (+ "PDFStorageManager.load_pdf followed a symlink "+ "Document.file_path outside the library root — arbitrary "+ "file read"+ )+ assert canary.read_bytes() == _PDF_POISON+ assert link.is_symlink() or link.exists()++ def test_positive_control_legit_file_is_served(+ self, fs_storage, library_session+ ):+ session, source_type = library_session+ legit = fs_storage.library_root / "pdfs" / "legit.pdf"+ legit.write_bytes(_PDF_SAFE)+ doc = _seed_document(session, source_type, "pdfs/legit.pdf")+ result = fs_storage.load_pdf(doc, session)+ assert result == _PDF_SAFE, (+ "POSITIVE CONTROL FAILED: a legitimate in-root PDF was not "+ "served by load_pdf — containment is overly restrictive"+ )+++# ---------------------------------------------------------------------------+# SURFACE 2b — GET /library/document/<id>/pdf (real route)+# ---------------------------------------------------------------------------+++class TestViewPdfRoute:+ """The real serving route must never leak canary bytes for a poisoned+ ``Document.file_path``.++ The route computes its root as+ ``apply_user_subdir(base_root, session_username, shared_library=False)``+ = ``<base_root>/<the registered username>`` — all relative payloads are+ planted LIVE against that exact root so a validator regression actually+ trips. The username comes from ``library_client.username`` (the real+ user ``_authenticated_fastapi_client`` registered), not a hardcoded+ constant.+ """++ def _root(self, base_root: Path, library_client) -> Path:+ return base_root / library_client.username++ def _get_pdf(self, library_client, session, doc, base_root):+ with patch(+ f"{_LR}.get_settings_manager",+ return_value=_library_settings_mock(base_root),+ ):+ with _patched_user_db_session(_LR, session):+ return library_client.get(f"/library/document/{doc.id}/pdf")++ def test_absolute_file_path_not_served(+ self, library_client, library_session, tmp_path+ ):+ session, source_type = library_session+ base_root = tmp_path / "library"+ (self._root(base_root, library_client) / "pdfs").mkdir(parents=True)+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)+ doc = _seed_document(session, source_type, str(canary))+ resp = self._get_pdf(library_client, session, doc, base_root)+ assert resp.status_code in (200, 404, 500)+ assert _PDF_POISON not in resp.data, (+ "GET /library/document/<id>/pdf served bytes from an absolute "+ "Document.file_path outside the library root — arbitrary "+ "file read"+ )+ assert canary.read_bytes() == _PDF_POISON++ def test_parent_traversal_file_path_not_served(+ self, library_client, library_session, tmp_path+ ):+ session, source_type = library_session+ base_root = tmp_path / "library"+ root = self._root(base_root, library_client)+ (root / "pdfs").mkdir(parents=True)+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)+ # root/pdfs/../../../secrets/canary.pdf -> tmp_path/secrets/...+ traversal = "pdfs/../../../secrets/canary.pdf"+ assert (root / traversal).resolve() == canary.resolve()+ doc = _seed_document(session, source_type, traversal)+ resp = self._get_pdf(library_client, session, doc, base_root)+ assert resp.status_code in (200, 404, 500)+ assert _PDF_POISON not in resp.data, (+ "GET /library/document/<id>/pdf followed a ..-laden "+ "Document.file_path outside the library root — arbitrary "+ "file read"+ )+ assert canary.read_bytes() == _PDF_POISON++ def test_symlink_file_path_not_served(+ self, library_client, library_session, tmp_path+ ):+ session, source_type = library_session+ base_root = tmp_path / "library"+ root = self._root(base_root, library_client)+ (root / "pdfs").mkdir(parents=True)+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)+ link = root / "pdfs" / "evil_link.pdf"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ assert link.is_symlink()+ doc = _seed_document(session, source_type, "pdfs/evil_link.pdf")+ resp = self._get_pdf(library_client, session, doc, base_root)+ assert resp.status_code in (200, 404, 500)+ assert _PDF_POISON not in resp.data, (+ "GET /library/document/<id>/pdf followed a symlink "+ "Document.file_path outside the library root — arbitrary "+ "file read"+ )+ assert canary.read_bytes() == _PDF_POISON+ assert link.is_symlink() or link.exists()++ def test_positive_control_legit_file_is_served(+ self, library_client, library_session, tmp_path+ ):+ session, source_type = library_session+ base_root = tmp_path / "library"+ root = self._root(base_root, library_client)+ (root / "pdfs").mkdir(parents=True)+ legit = root / "pdfs" / "legit.pdf"+ legit.write_bytes(_PDF_SAFE)+ doc = _seed_document(session, source_type, "pdfs/legit.pdf")+ resp = self._get_pdf(library_client, session, doc, base_root)+ assert resp.status_code == 200, (+ f"POSITIVE CONTROL FAILED: legit PDF view returned "+ f"{resp.status_code}; if a containment fix was just added it "+ "is over-restrictive."+ )+ assert resp.data == _PDF_SAFE+++# ---------------------------------------------------------------------------+# SURFACE 2c — get_absolute_path_from_settings (the resolver used by+# download_service._try_existing_pdf_extraction and library_service reads)+# ---------------------------------------------------------------------------+++def _relative_escape(root: Path, canary: Path) -> str:+ """A ``..``-laden relative path from ``root`` to ``canary`` (pure pathlib)."""+ root_parts = root.resolve().parts+ canary_parts = canary.resolve().parts+ common = 0+ for a, b in zip(root_parts, canary_parts):+ if a != b:+ break+ common += 1+ ups = [".."] * (len(root_parts) - common)+ downs = list(canary_parts[common:])+ return "/".join(ups + downs)+++class TestLibraryPathResolver:+ def test_poisoned_relative_paths_resolve_to_none(+ self, tmp_path, monkeypatch+ ):+ """absolute / ..-traversal / symlink inputs must all fail closed+ to ``None`` — the contract every filesystem read in the library+ services depends on.++ The explicit ``settings_manager`` argument is the exact+ mechanism ``DownloadService`` uses in production (it passes its+ captured per-user manager); the ambient manager would resolve+ the operator's real defaults-file storage_path, which is not+ writable test territory."""+ from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ )++ # get_absolute_path_from_settings's storage_path lookup carries an+ # eagerly-evaluated str(get_library_directory()) default -- Python+ # evaluates it before get_setting() runs, regardless of the+ # explicit settings_manager passed below, so it unconditionally+ # mkdirs <data_dir>/library. Pin LDR_DATA_DIR so that lands under+ # tmp_path instead of the real platformdirs user data dir.+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "app_data"))+ base_root = tmp_path / "library"+ username = "poison-resolver-user"+ root = base_root / username # apply_user_subdir, shared off+ root.mkdir(parents=True)+ settings = _library_settings_mock(base_root)+ canary = _make_canary(tmp_path / "secrets", "canary.pdf", _PDF_POISON)++ # Absolute input -> rejected by safe_join (isabs).+ assert (+ get_absolute_path_from_settings(+ str(canary), username, settings_manager=settings+ )+ is None+ ), "resolver returned a path for an ABSOLUTE input — traversal hole"++ # ..-laden relative input, derived from the ACTUAL root so the+ # payload is live (resolves onto the canary).+ traversal = _relative_escape(root, canary)+ assert traversal.startswith(".."), traversal+ assert (root / traversal).resolve() == canary.resolve()+ assert (+ get_absolute_path_from_settings(+ traversal, username, settings_manager=settings+ )+ is None+ ), "resolver returned a path for a ..-laden input — traversal hole"++ # Symlink inside the per-user root pointing outside.+ link = root / "evil_link.pdf"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ resolved = get_absolute_path_from_settings(+ "evil_link.pdf", username, settings_manager=settings+ )+ assert resolved is None, (+ f"resolver returned {resolved} for a symlink input — symlink "+ "escape hole"+ )+ assert canary.read_bytes() == _PDF_POISON+++# ---------------------------------------------------------------------------+# SURFACE 3 — backup metadata (list_backups / purge_and_refresh)+# ---------------------------------------------------------------------------+++class TestBackupMetadata:+ """No restore function exists and no HTTP route takes a backup name;+ the only ``info["path"]`` consumer is purge_and_refresh. Pin that+ backup metadata never describes anything outside the per-user backup+ dir — the invariant any future restore would have to trust."""++ USERNAME = "poison-backup-user"++ def _service(self, tmp_path, monkeypatch):+ from local_deep_research.database.backup.backup_service import (+ BackupService,+ )++ # LDR_DATA_DIR routes get_data_directory() (and therefore+ # get_user_backup_directory) under tmp_path.+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "app_data"))+ service = BackupService(self.USERNAME, "pw-not-used")+ service.backup_dir.mkdir(parents=True, exist_ok=True)+ return service++ def test_list_backups_excludes_symlinks_and_reports_only_in_root(+ self, tmp_path, monkeypatch+ ):+ service = self._service(tmp_path, monkeypatch)+ legit = service.backup_dir / "ldr_backup_20260101_000000.db"+ legit.write_bytes(b"fake-encrypted-backup")+ canary = _make_canary(+ tmp_path / "outside_backups", "victim.db", _PDF_POISON+ )+ link = service.backup_dir / "ldr_backup_evil.db"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")++ backups = service.list_backups()+ names = {info["path"] for info in backups}++ # The symlink entry must never be reported — a consumer (purge,+ # or any future restore) would follow it outside the backup dir.+ assert "ldr_backup_evil.db" not in names, (+ "list_backups reported a symlink backup entry pointing "+ "outside backup_dir"+ )+ assert "ldr_backup_20260101_000000.db" in names, (+ "POSITIVE CONTROL FAILED: a legitimate in-root backup was "+ "not listed"+ )+ # Every reported path is a bare, in-root, non-symlink filename.+ for info in backups:+ p = info["path"]+ assert p == Path(p).name, (+ f"backup metadata path {p!r} is not a bare filename"+ )+ full = (service.backup_dir / p).resolve()+ assert full.is_relative_to(service.backup_dir.resolve()), (+ f"backup metadata path {p!r} resolves outside backup_dir"+ )+ assert not (service.backup_dir / p).is_symlink()+ assert canary.read_bytes() == _PDF_POISON+ assert link.is_symlink() or link.exists()++ def test_purge_and_refresh_unlinks_only_validated_backups(+ self, tmp_path, monkeypatch+ ):+ from local_deep_research.database.backup.backup_service import (+ BackupResult,+ )++ service = self._service(tmp_path, monkeypatch)+ legit = service.backup_dir / "ldr_backup_20260101_000000.db"+ legit.write_bytes(b"fake-encrypted-backup")+ canary = _make_canary(+ tmp_path / "outside_backups", "victim.db", _PDF_POISON+ )+ link = service.backup_dir / "ldr_backup_evil.db"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")++ # Stub the fresh-backup creation (needs real SQLCipher); the+ # list_backups-driven unlink loop runs for real.+ with patch.object(+ service,+ "_create_backup_impl",+ return_value=BackupResult(success=True),+ ):+ result = service.purge_and_refresh()++ assert result.success+ # Positive control: the validated legit backup IS purged.+ assert not legit.exists(), (+ "POSITIVE CONTROL FAILED: purge_and_refresh did not remove a "+ "validated in-root backup"+ )+ # The symlink entry must survive untouched (never followed).+ assert link.is_symlink(), (+ "purge_and_refresh removed a symlink entry from the backup "+ "dir — the is_safe_glob_result filter regressed"+ )+ assert canary.read_bytes() == _PDF_POISON, (+ "purge_and_refresh followed a symlink backup entry and "+ "deleted/modified a file outside the backup dir"+ )diff --git a/tests/security/test_queue_processor_writes.py b/tests/security/test_queue_processor_writes.pynew file mode 100644index 0000000000..b2860bee3c--- /dev/null+++ b/tests/security/test_queue_processor_writes.py@@ -0,0 +1,183 @@+from contextlib import contextmanager+from pathlib import Path+from unittest.mock import MagicMock++import pytest+++@contextmanager+def _session_context(session):+ yield session+++def _forbid_filesystem_mutations(monkeypatch):+ calls = []++ def forbidden(*args, **kwargs):+ calls.append((args, kwargs))+ raise AssertionError("queue lifecycle attempted a filesystem mutation")++ monkeypatch.setattr(Path, "write_text", forbidden)+ monkeypatch.setattr(Path, "write_bytes", forbidden)+ monkeypatch.setattr(Path, "unlink", forbidden)+ return calls++[email protected]("task_id", ["../escape", "/tmp/escape", "bad\\x00id"])+def test_cancellation_status_persists_only_to_database(task_id, monkeypatch):+ # ``_do_update_task_status`` moved from the deleted Flask+ # ``research_library.routes.rag_routes`` to ``web.routers.rag`` in the+ # FastAPI migration (#3299); the retry-wrapped body is unchanged.+ import local_deep_research.web.routers.rag as routes++ task = MagicMock(status="processing", metadata_json={})+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = task+ monkeypatch.setattr(+ "local_deep_research.database.session_context.get_user_db_session",+ lambda *args, **kwargs: _session_context(session),+ )+ fs_calls = _forbid_filesystem_mutations(monkeypatch)++ routes._do_update_task_status(+ "alice", "password", task_id, status="cancelled"+ )++ assert task.status == "cancelled"+ assert task.completed_at is not None+ session.commit.assert_called_once()+ assert fs_calls == []+++def test_cancellation_commit_failure_surfaces_without_filesystem_fallback(+ monkeypatch,+):+ # ``_do_update_task_status`` moved from the deleted Flask+ # ``research_library.routes.rag_routes`` to ``web.routers.rag`` in the+ # FastAPI migration (#3299); the retry-wrapped body is unchanged.+ import local_deep_research.web.routers.rag as routes++ task = MagicMock(status="processing", metadata_json={})+ session = MagicMock()+ session.query.return_value.filter_by.return_value.first.return_value = task+ session.commit.side_effect = RuntimeError("database unavailable")+ monkeypatch.setattr(+ "local_deep_research.database.session_context.get_user_db_session",+ lambda *args, **kwargs: _session_context(session),+ )+ fs_calls = _forbid_filesystem_mutations(monkeypatch)++ with pytest.raises(RuntimeError, match="database unavailable"):+ routes._do_update_task_status(+ "alice", "password", "cancel-me", status="cancelled"+ )++ assert fs_calls == []++[email protected]("username", ["../escape", "/tmp/escape"])+def test_queue_sweep_state_is_database_only_for_hostile_usernames(+ username, monkeypatch+):+ import local_deep_research.web.queue.processor_v2 as processor_module++ processor = processor_module.QueueProcessorV2(check_interval=1)+ session = MagicMock()+ session.query.return_value.outerjoin.return_value.filter.return_value.all.return_value = []+ monkeypatch.setattr(+ processor_module,+ "reconcile_research_queue_status",+ lambda _session: False,+ )+ fs_calls = _forbid_filesystem_mutations(monkeypatch)++ result = processor._sweep_missing_parent_queue_rows(session, username)++ assert result.can_dispatch is True+ assert result.cleaned_ids == frozenset()+ session.commit.assert_not_called()+ assert fs_calls == []+++def test_queue_sweep_cleanup_commits_database_rows_without_filesystem_state(+ monkeypatch,+):+ import local_deep_research.web.queue.processor_v2 as processor_module++ processor = processor_module.QueueProcessorV2(check_interval=1)+ session = MagicMock()+ query_results = iter([[("../queued",)], [("/tmp/metadata",)]])+ session.query.return_value.outerjoin.return_value.filter.return_value.all.side_effect = (+ lambda: next(query_results)+ )+ cleaned = MagicMock(cleaned_ids=frozenset({"../queued", "/tmp/metadata"}))+ cleanup = MagicMock(return_value=cleaned)+ monkeypatch.setattr(+ processor_module, "cleanup_queued_research_state", cleanup+ )+ fs_calls = _forbid_filesystem_mutations(monkeypatch)++ result = processor._sweep_missing_parent_queue_rows(session, "alice")++ cleanup.assert_called_once_with(+ session, {"../queued", "/tmp/metadata"}, include_claimed=True+ )+ session.commit.assert_called_once()+ assert result.cleaned_ids == cleaned.cleaned_ids+ assert fs_calls == []+++ "report_path", ["../escape.md", "/tmp/escape.md", "nested/../../escape.md"]+)+def test_queue_error_operation_retains_report_path_in_memory_without_writing(+ report_path, monkeypatch+):+ from local_deep_research.web.queue.processor_v2 import QueueProcessorV2++ processor = QueueProcessorV2(check_interval=1)+ fs_calls = _forbid_filesystem_mutations(monkeypatch)++ processor.queue_error_update(+ "alice",+ "research-1",+ "failed",+ "error",+ {},+ "2026-01-01T00:00:00",+ report_path=report_path,+ )++ operation = next(iter(processor.pending_operations.values()))+ assert operation["research_id"] == "research-1"+ assert operation["report_path"] == report_path+ assert fs_calls == []+++def test_pending_error_flush_assigns_report_path_to_database_column_only(+ monkeypatch,+):+ from local_deep_research.web.queue.processor_v2 import QueueProcessorV2++ processor = QueueProcessorV2(check_interval=1)+ hostile_path = "../../outside/report.md"+ processor.queue_error_update(+ "alice",+ "research-2",+ "failed",+ "error",+ {"source": "test"},+ "2026-01-01T00:00:00",+ report_path=hostile_path,+ )+ research = MagicMock(id="research-2")+ session = MagicMock()+ session.query.return_value.filter.return_value.all.return_value = [research]+ fs_calls = _forbid_filesystem_mutations(monkeypatch)++ assert processor.process_pending_operations_for_user("alice", session) == 1++ assert research.report_path == hostile_path+ session.commit.assert_called_once()+ assert processor.pending_operations == {}+ assert fs_calls == []diff --git a/tests/security/test_raw_config_toml_smuggling.py b/tests/security/test_raw_config_toml_smuggling.pynew file mode 100644index 0000000000..17576b9dc3--- /dev/null+++ b/tests/security/test_raw_config_toml_smuggling.py@@ -0,0 +1,339 @@+"""Security tripwire battery: TOML parse -> scan -> raw-write roundtrip+smuggling against /api/save_raw_config.++Route semantics (src/local_deep_research/web/routers/research.py, around+line 1757 ``save_raw_config``): the raw TOML text is parsed with+``tomllib.loads``, the parsed tree is walked by ``find_blocked_keys``+rejecting any key whose lowercased name contains+``module_path``/``class_name``/``module``/``class`` (BLOCKED_KEY_PATTERNS),+and then the RAW string is written verbatim to+``<config_dir>/config.toml`` via ``write_file_verified``+(security/file_write_verifier.py).++Loader semantics: config.toml has NO dedicated reader in src/ — the only+occurrence of the filename is the write itself. Every TOML consumer in the+app parses with tomllib (the route itself, ``web/themes/loader.py``), and+the real dynamic-import sink for module_path/class_name reads from the+settings DB, never this file+(``web_search_engines/search_engines_config.py``,+``web/routers/settings.py``), gated by the ``get_safe_module_class``+whitelist (``security/module_whitelist.py``). The route's blocked-key+guard is therefore defense-in-depth, and the invariant this battery pins+is:++ any payload the route ACCEPTS must, when the written bytes are re-parsed+ with tomllib (the loader interpretation the app actually performs),+ contain no key whose lowercased name matches a blocked pattern.++Because the scanner and any re-parse share one parser, a smuggle requires a+scanner-vs-disk divergence. The payloads below cover every fold/encoding+trick that could make the parsed view look clean while the raw bytes carry+a dangerous key: dotted and quoted keys, ``\\u`` escapes in quoted keys,+whitespace/case variants, bare and nested table headers (including arrays+of tables), inline tables (bare and inside arrays), TOML-looking decoy text+inside multi-line string values, homoglyph key names, a UTF-8 BOM prefix,+CRLF line endings, and duplicate keys. A payload that lands verbatim AND+re-parses to a blocked key == RED tripwire (smuggle worked).++The regular settings API is out of scope: it persists to the settings DB and+never writes config.toml (verified: no other reference to config.toml+anywhere in src/).++Harness: the real FastAPI route through ``TestClient(app)`` — an+authenticated, CSRF-carrying request, with ``system.allow_config_write``+patched open — mirroring+``tests/security/test_save_raw_config_blocked_keys_fastapi.py``. The+Flask ``app.test_request_context()`` + unwrapped-handler harness this file+used before the FastAPI migration (#3299) deleted+``web.routes.research_routes`` no longer applies. Offline, tmp_path-only,+no LLM/network.+"""++import itertools+import sys+import tomllib+import uuid+from pathlib import Path++import pytest+from fastapi.testclient import TestClient++# Mirror of BLOCKED_KEY_PATTERNS in the route+# (src/local_deep_research/web/routers/research.py, ``save_raw_config``).+# If the route's list ever changes, this mirror — and the whole battery —+# must change with it.+BLOCKED_KEY_PATTERNS = ["module_path", "class_name", "module", "class"]++TEST_PASSWORD = "TomlSmugglePass123" # noqa: S105++# Monotonic, never random: many clients register in one session and random+# /8 addresses can collide, producing a 429 from a bucket some earlier test+# filled (see the sibling FastAPI file for the same reasoning).+_FORWARDED_IP_SEQ = itertools.count(1)+++def _blocked_keys_in_parsed(obj, path=""):+ """Walk a parsed TOML tree exactly like the route's find_blocked_keys:+ substring match on lowercased key names, recursing into nested dicts+ and lists. Applied to the RE-PARSED file bytes, this is the+ loader-side view of "did a dangerous key survive".+ """+ blocked = []+ if isinstance(obj, dict):+ for key, value in obj.items():+ current_path = f"{path}.{key}" if path else key+ key_lower = key.lower()+ for pattern in BLOCKED_KEY_PATTERNS:+ if pattern in key_lower:+ blocked.append(current_path)+ break+ blocked.extend(_blocked_keys_in_parsed(value, current_path))+ elif isinstance(obj, list):+ for i, item in enumerate(obj):+ blocked.extend(_blocked_keys_in_parsed(item, f"{path}[{i}]"))+ return blocked+++# ---------------------------------------------------------------------------+# Harness+# ---------------------------------------------------------------------------++[email protected](autouse=True)+def _slowapi_off():+ """Take the per-IP HTTP rate limiter out of the picture.++ Every payload in this battery registers a fresh user to get a CSRF'd,+ authenticated client, and ``/auth/register`` caps at 3/hour per IP. A+ 429 leaking in would mask the status code each test asserts.+ """+ from local_deep_research.web.dependencies.rate_limit import limiter++ original = limiter.enabled+ limiter.enabled = False+ try:+ yield+ finally:+ limiter.enabled = original+++def allow_config_write(monkeypatch):+ """Open the ``system.allow_config_write`` gate for this test.++ Without this, ``write_file_verified`` default-denies (the setting is+ undefined anywhere in this repo) and every payload would 500 before+ the scanner is even relevant — see+ ``test_save_raw_config_blocked_keys_fastapi.py::test_pinned_write_gate_default_denies_with_a_500``.+ """+ import local_deep_research.config.search_config as search_config++ real = search_config.get_setting_from_snapshot++ def _resolve(key, default=None, *args, **kwargs):+ if key == "system.allow_config_write":+ return True+ return real(key, default, *args, **kwargs)++ monkeypatch.setattr(search_config, "get_setting_from_snapshot", _resolve)+++def saved_config_path(allow_config_write, temp_data_dir) -> Path:+ """Where a successful save lands (``LDR_DATA_DIR/config/config.toml``).++ ``get_config_directory()`` resolves against ``LDR_DATA_DIR``, which the+ ``app`` fixture points at ``temp_data_dir`` before ``fastapi_app`` is+ imported.+ """+ return temp_data_dir / "config" / "config.toml"+++def _client(app) -> TestClient:+ client = TestClient(app, raise_server_exceptions=False)+ n = next(_FORWARDED_IP_SEQ)+ client.headers.update(+ {"X-Forwarded-For": f"10.{(n // 250) % 250 + 1}.{n % 250 + 1}.9"}+ )+ return client+++def _csrf(client: TestClient) -> str:+ """Stamp the session with a CSRF token, then fetch it as a string."""+ client.get("/auth/login")+ resp = client.get("/auth/csrf-token")+ return resp.json().get("csrf_token", "") if resp.status_code == 200 else ""+++def _authenticated_client(app) -> TestClient:+ """Register a fresh user and return their logged-in client."""+ client = _client(app)+ username = f"tomlsmg_{uuid.uuid4().hex[:10]}"+ resp = client.post(+ "/auth/register",+ data={+ "username": username,+ "password": TEST_PASSWORD,+ "confirm_password": TEST_PASSWORD,+ "acknowledge": "true",+ "csrf_token": _csrf(client),+ },+ follow_redirects=False,+ )+ assert resp.status_code == 302, (+ "harness broken — could not register a user to drive the endpoint "+ f"with: {resp.status_code} {resp.text[:300]}"+ )+ return client+++def _call_save_raw_config(app, raw_config):+ """POST the raw TOML through the real FastAPI route with a live CSRF+ token, mirroring ``tests/security/test_save_raw_config_blocked_keys_fastapi.py``.+ """+ client = _authenticated_client(app)+ resp = client.post(+ "/api/save_raw_config",+ json={"raw_config": raw_config},+ headers={"X-CSRFToken": _csrf(client)},+ )+ return resp.json(), resp.status_code+++# Each payload is a smuggle attempt. Dispositions verified against this+# venv's tomllib:+# - fold/table/inline/case/escape variants -> the scanner sees the blocked+# key in the PARSED tree -> 403, nothing written;+# - multiline-decoy / quoted-homoglyph / CRLF-clean -> accepted (200); the+# written bytes must re-parse to a tree with NO blocked key;+# - bare Cyrillic homoglyph (invalid bare key), BOM prefix, and duplicate+# keys -> tomllib itself rejects -> 400.+SMUGGLE_PAYLOADS = [+ # --- tomllib folds these key syntaxes to a blocked name: scanner must 403+ pytest.param('search.module_path = "evil.module"', id="dotted_key"),+ pytest.param('"\\u006dodule_path" = "evil"', id="quoted_unicode_escape"),+ pytest.param(+ 'custom."\\u006dodule" = "evil"',+ id="dotted_quoted_unicode_escape",+ ),+ pytest.param('"module_path " = "evil"', id="quoted_trailing_space"),+ pytest.param('ClAsS_nAmE = "Evil"', id="bare_mixed_case"),+ # --- blocked names via table syntax (bare header, nested header, array+ # of tables — plain and with a dotted module header)+ pytest.param('[module]\nname = "evil"', id="bare_table_header"),+ pytest.param('[custom.module]\nname = "evil"', id="nested_table_header"),+ pytest.param(+ '[[engines]]\nname = "safe"\nclass_name = "Evil"',+ id="array_of_tables",+ ),+ pytest.param(+ '[[custom.module]]\nname = "evil"',+ id="array_of_tables_module_header",+ ),+ pytest.param('engine = { module_path = "evil" }', id="inline_table"),+ pytest.param(+ 'engines = [{ class_name = "Evil" }]', id="inline_table_in_array"+ ),+ # --- designed to be ACCEPTED: dangerous text may only ever live in a+ # string VALUE or a non-ASCII key, never as a real key on disk+ pytest.param(+ "[search]\n"+ 'tool = "google"\n'+ 'note = """\n'+ "[custom]\n"+ 'module_path = "evil.module"\n'+ 'class_name = "Evil"\n'+ '"""\n',+ id="multiline_string_decoy_value",+ ),+ # Greek omicron (U+03BF) in a QUOTED key: tomllib performs no NFKC+ # normalization, so the on-disk key is NOT the ASCII "module_path" the+ # dynamic-import sink looks for. If the app ever adds a+ # unicode-normalizing config loader, this case is the divergence surface.+ pytest.param(+ '[custom]\n"mοdule_path" = "evil"',+ id="homoglyph_quoted_omicron",+ ),+ # Cyrillic o (U+043E) in a BARE key: invalid TOML bare-key charset ->+ # parser rejection before the scanner ever runs.+ pytest.param(+ 'mоdule_path = "evil.module"',+ id="homoglyph_bare_cyrillic",+ ),+ # --- encoding / parser-divergence edges+ pytest.param(+ '[custom]\nmodule_path = "evil"',+ id="utf8_bom_prefix",+ ),+ pytest.param(+ '[search]\r\ntool = "searxng"\r\niterations = 3\r\n',+ id="crlf_clean_accepted",+ ),+ pytest.param(+ '[custom]\r\nmodule_path = "evil"\r\n',+ id="crlf_blocked",+ ),+ pytest.param(+ '[custom]\nmodule_path = "a"\nmodule_path = "b"',+ id="duplicate_blocked_key",+ ),+]+++def _assert_rejected_or_semantically_safe(app, raw_config, config_file):+ """Universal invariant per payload:++ - accepted (2xx) -> config.toml exists, holds the payload verbatim, and+ re-parses (tomllib — the app's loader interpretation) to a tree with+ NO blocked key. Any violation == smuggle worked == RED;+ - rejected (400 invalid TOML / 403 blocked key) -> clean pass, provided+ nothing landed on disk.+ """+ data, status = _call_save_raw_config(app, raw_config)++ if 200 <= status < 300:+ assert data["success"] is True+ assert config_file.is_file()+ written = config_file.read_bytes()+ # The route's threat model is the verbatim raw write; pin that the+ # scanned text is exactly what landed (POSIX text-mode writes are+ # byte-exact; Windows translates newlines).+ if sys.platform != "win32":+ assert written == raw_config.encode("utf-8")+ # The loader interpretation: any consumer of config.toml in this app+ # parses it with tomllib. A parse failure here would mean the bytes+ # on disk diverged from what the route scanned.+ parsed = tomllib.loads(written.decode("utf-8"))+ assert _blocked_keys_in_parsed(parsed) == []+ else:+ assert status in (400, 403)+ assert data["success"] is False+ assert not config_file.exists()++[email protected]("raw_config", SMUGGLE_PAYLOADS)+def test_raw_config_smuggling_never_lands_dangerous_key(+ app, raw_config, saved_config_path+):+ _assert_rejected_or_semantically_safe(app, raw_config, saved_config_path)+++def test_positive_control_clean_config_accepted(app, saved_config_path):+ """A clean config must be accepted and retain its text on every platform."""+ raw = '[search]\ntool = "google"\niterations = 5\n'++ _assert_rejected_or_semantically_safe(app, raw, saved_config_path)++ assert saved_config_path.read_text(encoding="utf-8") == raw+++def test_positive_control_blocked_config_rejected(app, saved_config_path):+ """An obviously blocked config must be refused BEFORE any write."""+ data, status = _call_save_raw_config(+ app, '[custom]\nmodule_path = "evil.module"\n'+ )++ assert status == 403+ assert data["success"] is False+ assert "custom.module_path" in data["blocked_keys"]+ assert not saved_config_path.exists()diff --git a/tests/security/test_remote_filename_writes.py b/tests/security/test_remote_filename_writes.pynew file mode 100644index 0000000000..905e5ade59--- /dev/null+++ b/tests/security/test_remote_filename_writes.py@@ -0,0 +1,375 @@+"""End-to-end security battery: hostile remote-derived filenames -> disk writes.++Complements:+ * tests/security/test_pdf_path_traversal.py (covers only the+ _get_safe_file_path READ-path validator method, no actual writes)+ * tests/security/test_filename_sanitizer.py (covers only the bare+ sanitize_filename unit)++This file exercises the FULL save pipeline the way the production download+service feeds it: PDFStorageManager.save_pdf(pdf_content, document, session,+filename=...) in filesystem mode, with filenames derived the way+DownloadService._generate_filename derives them from a URL.++For each hostile input the test asserts:+ * The written file lands STRICTLY inside the configured library root+ (a tmp_path subdirectory; canary files planted OUTSIDE the root must+ remain untouched and unmodified).+ * No symlink escape: a pre-planted symlink inside the root pointing+ outside must NOT be followed by the write path.+ * Either the write is rejected cleanly (rejection is a GOOD security+ outcome) OR it succeeds with the file strictly inside the root.++FAILURE CLASSIFICATION:+ * Red because of vulnerability: any file lands outside library_root, any+ canary outside library_root is touched, or a symlink is followed.+ * Broken-test: setup/import/expectation bugs.++Run with: .venv/bin/python -m pytest tests/security/test_remote_filename_writes.py -v --no-header+"""++from __future__ import annotations++import os+from pathlib import Path+from typing import Optional++import pytest++from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+)+from local_deep_research.security.filename_sanitizer import (+ UnsafeFilenameError,+ sanitize_filename,+)+++# Minimal bytes that pass "%PDF" sniffers — content is irrelevant, the+# write path is what we care about.+_MINIMAL_PDF = b"%PDF-1.4\n1 0 obj <<>>endobj\ntrailer<<>>\n%%EOF\n"+++# ---------------------------------------------------------------------------+# Fixtures and helpers+# ---------------------------------------------------------------------------+++# ``library_session``, ``fresh_document``, ``fs_storage`` and+# ``canary_paths`` now live in tests/security/conftest.py -- they were+# duplicated verbatim across four batteries in this directory.+++def _assert_files_inside(+ library_root: Path,+ written_relative: Optional[str],+ canaries: dict,+):+ """Strict safety assertion: any file written MUST be inside library_root+ AND must not have modified any canary outside it."""+ library_root = library_root.resolve()++ if written_relative is not None:+ written = (library_root / written_relative).resolve()+ try:+ written.relative_to(library_root)+ except ValueError as exc:+ pytest.fail(+ f"VULNERABILITY: save_pdf wrote {written} OUTSIDE library_root "+ f"{library_root} (relative_to raised: {exc})"+ )++ for name, canary in canaries.items():+ assert canary.exists(), (+ f"VULNERABILITY: canary {name} at {canary} was DELETED"+ )+ assert canary.read_text(encoding="utf-8") == "UNTOUCHED-CANARY\n", (+ f"VULNERABILITY: canary {name} at {canary} was MODIFIED "+ f"(content: {canary.read_text(encoding='utf-8')!r})"+ )+++# ---------------------------------------------------------------------------+# Hostile filename battery — full save_pdf() end-to-end+# ---------------------------------------------------------------------------+++# (id, filename, url, resource_id). url=None means the filename is passed+# straight through to _save_to_filesystem (mirrors how DownloadService hands+# a derived filename in). url=<str> means _generate_filename will run first.+# Covers every hostile shape specified in the task brief (13 in the brief + 1 nested variant).+HOSTILE_FILENAMES = [+ pytest.param("../escape.pdf", None, 1, id="dotdot-traversal-single"),+ pytest.param("a/../../b.pdf", None, 1, id="nested-traversal"),+ pytest.param("..%2Fescape.pdf", None, 1, id="encoded-slash-single"),+ pytest.param("%2e%2e%2fescape.pdf", None, 1, id="encoded-dotdot-slash"),+ pytest.param("evil\x00.pdf", None, 1, id="null-byte"),+ pytest.param("/tmp/x.pdf", None, 1, id="absolute-path-as-filename"),+ pytest.param("..\\escape.pdf", None, 1, id="backslash-traversal"),+ pytest.param("....//escape.pdf", None, 1, id="quad-dot-double-slash"),+ pytest.param(+ "\uff0e\uff0e\uff0fescape.pdf", # fullwidth ../escape.pdf+ None,+ 1,+ id="fullwidth-unicode-traversal",+ ),+ pytest.param("-rf.pdf", None, 1, id="leading-dash"),+ pytest.param("a" * 5000 + ".pdf", None, 1, id="extremely-long-name"),+ pytest.param(".pdf", None, 1, id="extension-only-hidden"),+ pytest.param("x.pdf.exe", None, 1, id="double-extension"),+]+++class TestHostileFilenameEndToEnd:+ """Drive the REAL PDFStorageManager.save_pdf() with hostile filenames.++ Failure mode this guards against: any file landing OUTSIDE+ library_root, or any canary outside the root being touched.++ Exceptions raised by PathValidator / write_file_verified are ACCEPTABLE+ rejections; the test passes when the rejection occurs cleanly. The+ test only FAILS when a file actually lands in the wrong place.+ """++ @pytest.mark.parametrize("filename,url,resource_id", HOSTILE_FILENAMES)+ def test_hostile_filename_does_not_escape_library_root(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ filename,+ url,+ resource_id,+ ):+ # Reset document between parametrize iterations.+ fresh_document.storage_mode = None+ fresh_document.file_path = None++ try:+ relative, _size = fs_storage.save_pdf(+ pdf_content=_MINIMAL_PDF,+ document=fresh_document,+ session=library_session,+ filename=filename,+ url=url,+ resource_id=resource_id,+ )+ except (ValueError, FileNotFoundError, OSError):+ # PathValidator rejecting traversal, OS rejecting a non-existent+ # intermediate dir, etc. — all valid "rejection" outcomes.+ _assert_files_inside(fs_storage.library_root, None, canary_paths)+ return++ # save_pdf accepted the filename — assert it stayed strictly inside.+ _assert_files_inside(fs_storage.library_root, relative, canary_paths)+++# ---------------------------------------------------------------------------+# URL-derivation fidelity — feed _generate_filename then save_pdf+# ---------------------------------------------------------------------------+++class TestURLDerivedFilename:+ """Calls DownloadService._generate_filename with hostile URLs and feeds+ its OUTPUT into the real save_pdf. For non-arxiv/non-pmc URLs+ _generate_filename returns the supplied fallback_filename unchanged+ (no URL-path traversal can sneak through the regex extractor) — so+ the hostile bit really is what _save_to_filesystem sees.+ """++ URL_CASES = [+ pytest.param(+ "http://arxiv.org/abs/2301.12345/../../../etc/passwd.pdf",+ "fallback.pdf",+ id="arxiv-url-with-traversal-in-path",+ ),+ pytest.param(+ "http://attacker.example/%2e%2e/escape.pdf",+ "hostile-fallback.pdf",+ id="attacker-url-with-encoded-traversal",+ ),+ ]++ @pytest.mark.parametrize("url,fallback", URL_CASES)+ def test_url_derived_filename_does_not_escape(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ url,+ fallback,+ ):+ fresh_document.storage_mode = None+ fresh_document.file_path = None++ derived = PDFStorageManager._generate_filename(+ fs_storage, url, 1, fallback+ )++ try:+ relative, _size = fs_storage.save_pdf(+ pdf_content=_MINIMAL_PDF,+ document=fresh_document,+ session=library_session,+ filename=derived,+ url=url,+ resource_id=1,+ )+ except (ValueError, FileNotFoundError, OSError):+ _assert_files_inside(fs_storage.library_root, None, canary_paths)+ return++ _assert_files_inside(fs_storage.library_root, relative, canary_paths)+++# ---------------------------------------------------------------------------+# Symlink-write escape — pre-plant symlink at the EXACT write path+# ---------------------------------------------------------------------------+++class TestSymlinkWriteEscape:+ """A symlink planted at the intended PDF filename must not redirect writes.++ The verified writer refuses the link where O_NOFOLLOW is available.+ The outside canary must survive, and legitimate in-root saves remain+ covered by the positive controls."""++ @pytest.mark.xfail(+ not getattr(os, "O_NOFOLLOW", 0),+ strict=True,+ reason="The verified writer cannot refuse leaf symlinks without O_NOFOLLOW",+ )+ def test_symlink_inside_pdf_subdir_does_not_let_write_escape(+ self,+ fs_storage,+ fresh_document,+ library_session,+ tmp_path,+ canary_paths,+ ):+ library_root = fs_storage.library_root+ target_name = "evil_link_target.pdf"++ # Real canary file outside the library root.+ outside_target = tmp_path / "outside_canary_zone" / target_name+ outside_target.write_text("UNTOUCHED-CANARY\n", encoding="utf-8")+ canary_paths["symlink_target"] = outside_target++ # Discover the real destination with a successful save. New writes+ # append a content hash, so planting the unhashed display name would+ # leave the canary untouched without exercising the symlink guard.+ saved_relative, _ = fs_storage.save_pdf(+ _MINIMAL_PDF, fresh_document, library_session, target_name+ )+ link = library_root / saved_relative+ assert link.read_bytes() == _MINIMAL_PDF+ link.unlink()+ try:+ link.symlink_to(outside_target)+ except (OSError, NotImplementedError):+ pytest.skip("Cannot create symlinks in this environment")+ assert link.resolve() == outside_target.resolve()++ fresh_document.storage_mode = None+ fresh_document.file_path = None++ try:+ relative, _size = fs_storage.save_pdf(+ pdf_content=_MINIMAL_PDF,+ document=fresh_document,+ session=library_session,+ filename=target_name,+ )+ except (ValueError, OSError):+ _assert_files_inside(library_root, None, canary_paths)+ return++ assert relative == saved_relative+ assert (+ outside_target.read_text(encoding="utf-8") == "UNTOUCHED-CANARY\n"+ ), (+ f"VULNERABILITY: save_pdf wrote through symlink and overwrote "+ f"outside-root canary at {outside_target}; relative returned "+ f"was {relative!r}"+ )+ _assert_files_inside(library_root, relative, canary_paths)+++# ---------------------------------------------------------------------------+# Happy path — clean name saves inside pdfs/ — guards against over-blocking+# ---------------------------------------------------------------------------+++class TestHappyPath:+ def test_clean_name_saves_inside_pdfs(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ ):+ relative, _size = fs_storage.save_pdf(+ pdf_content=_MINIMAL_PDF,+ document=fresh_document,+ session=library_session,+ filename="clean_paper.pdf",+ url="http://example.com/clean_paper.pdf",+ resource_id=1,+ )++ written = fs_storage.library_root / relative+ assert written.is_file()+ # Must be inside library_root/pdfs/ — the intended location.+ assert written.resolve().is_relative_to(+ (fs_storage.library_root / "pdfs").resolve()+ ), f"clean file landed at unexpected path: {written}"+ assert written.read_bytes() == _MINIMAL_PDF+ assert fresh_document.file_path == relative+ assert fresh_document.storage_mode == "filesystem"+ _assert_files_inside(fs_storage.library_root, relative, canary_paths)+++# ---------------------------------------------------------------------------+# Zotero sanitize_filename battery — remote-controlled hostile names+# ---------------------------------------------------------------------------+++class TestZoteroFilenameSanitizer:+ """The Zotero sync_service (_filename_for in sync_service.py) builds a+ candidate display filename from the remote item's title and feeds it+ through sanitize_filename before storing on Document.filename. Drives+ sanitize_filename with the same shapes of remote payloads an+ attacker-controlled Zotero response could carry, and asserts the+ sanitized output:+ * never contains a path separator+ * never begins with '..'+ * raises UnsafeFilenameError when nothing safe survives+ """++ CASES = [+ pytest.param("../../etc/passwd", None, id="dotdot-passes"),+ pytest.param("evil\x00name", None, id="null-byte"),+ pytest.param("", None, id="empty-raises"),+ ]++ @pytest.mark.parametrize("raw,exts", CASES)+ def test_sanitize_blocks_traversal_in_zotero_titles(self, raw, exts):+ try:+ safe = sanitize_filename(raw, allowed_extensions=exts)+ except UnsafeFilenameError:+ return++ assert "/" not in safe, (+ f"sanitize_filename returned a path-containing value: {safe!r}"+ )+ assert "\\" not in safe, (+ f"sanitize_filename returned a backslash-containing value: {safe!r}"+ )+ assert not safe.startswith(".."), (+ f"sanitize_filename returned a traversal-leading value: {safe!r}"+ )+ assert "\x00" not in safe, (+ f"sanitize_filename did not strip null bytes: {safe!r}"+ )diff --git a/tests/security/test_report_path_deletion.py b/tests/security/test_report_path_deletion.pynew file mode 100644index 0000000000..05cb3858e6--- /dev/null+++ b/tests/security/test_report_path_deletion.py@@ -0,0 +1,605 @@+# allow: no-sut-import — security tests for the delete/clear_history+# endpoints; drives the real FastAPI routes through an authenticated+# TestClient while stubbing the DB session so we can plant a ResearchHistory+# row whose ``report_path`` points at a canary file under tmp_path.+"""Regression tests for database-stored report paths used during deletion.++Both single-research deletion and clear-history apply the shared report-path+containment checks. These tests plant absolute, traversing and symlink paths+in isolated database rows and require outside canaries to survive. Positive+controls require legitimate in-root reports to be deleted.++The write-surface checks also record whether production creates report_path+values, independently of the delete-side containment contract."""++import itertools+import uuid+from contextlib import contextmanager+from datetime import datetime, timezone+from unittest.mock import MagicMock, patch++import pytest+from fastapi.testclient import TestClient+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker+from sqlalchemy.pool import StaticPool++from tests.test_utils import add_src_to_path++add_src_to_path()++from local_deep_research.database.models import Base, ResearchHistory # noqa: E402++# Patching targets — ``web.routers.research`` imports ``get_user_db_session``+# and ``get_active_research_ids`` at module load, but does a local+# ``from ..queue.lifecycle_cleanup import cleanup_queued_research_state``+# inside the route bodies (unchanged by the FastAPI migration). The+# lifecycle symbol has to be patched at its SOURCE so the local re-import+# resolves to the mock.+_RR = "local_deep_research.web.routers.research"+_LIFECYCLE = "local_deep_research.web.queue.lifecycle_cleanup"++TEST_PASSWORD = "ReportPathCanaryPass123" # noqa: S105++# Monotonic, never random — see test_save_raw_config_blocked_keys_fastapi.py+# for why: random /8 addresses collide across a session with many clients.+_FORWARDED_IP_SEQ = itertools.count(1)++[email protected](autouse=True)+def _slowapi_off():+ """Take the per-IP HTTP rate limiter out of the picture.++ Every test below registers a fresh user to get an authenticated,+ CSRF-carrying client; nothing here is about rate limiting.+ """+ from local_deep_research.web.dependencies.rate_limit import limiter++ original = limiter.enabled+ limiter.enabled = False+ try:+ yield+ finally:+ limiter.enabled = original+++def _csrf(client: TestClient) -> str:+ client.get("/auth/login")+ resp = client.get("/auth/csrf-token")+ return resp.json().get("csrf_token", "") if resp.status_code == 200 else ""+++def route_client(app):+ """Authenticated TestClient over the REAL FastAPI research router.++ A real registered/logged-in user (not a faked session) is what gets+ past ``require_auth``; the DB session itself is separately patched per+ test (``_route_db_patches``) so the real per-user database is never+ touched.+ """+ n = next(_FORWARDED_IP_SEQ)+ client = TestClient(app, raise_server_exceptions=False)+ client.headers.update(+ {"X-Forwarded-For": f"10.{(n // 250) % 250 + 1}.{n % 250 + 1}.23"}+ )+ username = f"report_path_canary_{uuid.uuid4().hex[:8]}"+ resp = client.post(+ "/auth/register",+ data={+ "username": username,+ "password": TEST_PASSWORD,+ "confirm_password": TEST_PASSWORD,+ "acknowledge": "true",+ "csrf_token": _csrf(client),+ },+ follow_redirects=False,+ )+ assert resp.status_code == 302, (+ "harness broken — could not register a user to drive the endpoint "+ f"with: {resp.status_code} {resp.text[:300]}"+ )+ # DELETE and POST both need a live CSRF header (ASGI middleware, no+ # off switch).+ token = _csrf(client)+ if token:+ client.headers.update({"X-CSRFToken": token})+ return client+++def _seed_db(rid, report_path_value, status="completed"):+ """Build an in-memory SQLite session with one ResearchHistory row.++ Returns ``(session, engine)``. Caller is responsible for closing /+ disposing.++ ``StaticPool`` + ``check_same_thread=False``: this session is patched+ into a real ``TestClient`` request for a sync route, dispatched+ through ``run_in_threadpool`` on a different thread than the one that+ seeded it here — without a shared, thread-agnostic connection,+ closing/rolling back this session later trips ``sqlite3.+ ProgrammingError: SQLite objects created in a thread can only be used+ in that same thread``. Same fix as+ ``test_socket_ownership_edges_fastapi.py``.+ """+ engine = create_engine(+ "sqlite:///:memory:",+ poolclass=StaticPool,+ connect_args={"check_same_thread": False},+ )+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ session.add(+ ResearchHistory(+ id=rid,+ query="q",+ mode="quick",+ status=status,+ created_at=datetime.now(timezone.utc).isoformat(),+ report_path=report_path_value,+ )+ )+ session.commit()+ return session, engine+++def _close(session, engine):+ session.close()+ engine.dispose()+++@contextmanager+def _route_db_patches(session):+ """Patch the symbols ``research_routes`` looks up at request time.++ Yields nothing — the patchers remain active inside the ``with`` block.+ Use as::++ with _route_db_patches(session):+ resp = route_client.delete(...)+ """+ patchers = [+ patch(f"{_RR}.get_user_db_session"),+ patch(f"{_RR}.get_active_research_ids", return_value=[]),+ patch(f"{_LIFECYCLE}.cleanup_queued_research_state"),+ ]+ mocks = [p.start() for p in patchers]+ try:+ # get_user_db_session is used as a context manager by the routes:+ # ``with get_user_db_session(username) as db_session``.+ mocks[0].return_value.__enter__ = lambda _s: session+ mocks[0].return_value.__exit__ = MagicMock(return_value=False)+ mocks[2].return_value = MagicMock()+ yield+ finally:+ for p in reversed(patchers):+ p.stop()+++# ---------------------------------------------------------------------------+# DELETE /api/delete/<research_id>+# ---------------------------------------------------------------------------+++class TestDeleteEndpointCanaryProtection:+ """``DELETE /api/delete/<research_id>`` must not unlink paths outside+ the configured research outputs directory.++ FIXED during the FastAPI port (see module docstring): the handler now+ resolves ``report_path`` and requires+ ``is_relative_to(research_outputs_root)`` before unlinking. These three+ tests used to be ``xfail(strict=True)`` documenting the missing check;+ they are now plain regression pins on the containment behaviour.+ """++ def test_absolute_path_outside_root_is_preserved(+ self, route_client, tmp_path+ ):+ """An absolute path stored in ``report_path`` that lives outside+ any plausible research-outputs root must not be unlinked."""+ outside_dir = tmp_path / "outside_storage"+ outside_dir.mkdir()+ canary = outside_dir / "canary.txt"+ canary.write_text("DO NOT DELETE")+ assert canary.exists()++ rid = "rid-delete-abs"+ session, engine = _seed_db(rid, str(canary))+ try:+ with _route_db_patches(session):+ resp = route_client.delete(f"/api/delete/{rid}")+ # The endpoint may succeed (200) or fail for unrelated reasons+ # (400 if it bails out before the unlink); the security+ # assertion is that the canary file is never touched either way.+ assert resp.status_code == 200, resp.text+ assert session.query(ResearchHistory).count() == 0+ finally:+ _close(session, engine)++ assert canary.exists(), (+ "DELETE /api/delete/<id> unlinked an absolute report_path "+ "outside the storage root — no path validation present"+ )+ assert canary.read_text() == "DO NOT DELETE"++ def test_parent_traversal_path_is_preserved(self, route_client, tmp_path):+ """A ``report_path`` containing ``..`` segments that resolves+ outside the storage root must not be unlinked."""+ outside_dir = tmp_path / "outside_sibling"+ outside_dir.mkdir()+ canary = outside_dir / "victim.txt"+ canary.write_text("DO NOT DELETE")++ # Pretend the "storage root" is tmp_path / "research_outputs".+ # Construct a path that uses ``..`` to escape it and reach the canary.+ fake_storage_root = tmp_path / "research_outputs"+ traversal_path = (+ fake_storage_root+ / "sub"+ / ".."+ / ".."+ / "outside_sibling"+ / "victim.txt"+ )+ # NOTE: the intermediate "sub" dir must exist or the OS cannot+ # stat the ``..``-laden path at all (ENOENT on the first hop) and+ # the route's ``.exists()`` guard would skip the unlink — a false+ # green rather than a security pass.+ (fake_storage_root / "sub").mkdir(parents=True)+ # Sanity-check the traversal is live: stat-able AND pointing at+ # the canary.+ assert traversal_path.exists(), "traversal payload must be stat-able"+ assert traversal_path.resolve() == canary.resolve()++ rid = "rid-delete-traversal"+ session, engine = _seed_db(rid, str(traversal_path))+ try:+ with _route_db_patches(session):+ resp = route_client.delete(f"/api/delete/{rid}")+ assert resp.status_code == 200, resp.text+ assert session.query(ResearchHistory).count() == 0+ finally:+ _close(session, engine)++ assert canary.exists(), (+ "DELETE /api/delete/<id> followed a ``..``-laden report_path "+ "outside the storage root — no containment check present"+ )+ assert canary.read_text() == "DO NOT DELETE"++ def test_symlink_pointing_outside_root_is_preserved(+ self, route_client, tmp_path+ ):+ """A ``report_path`` that is a symlink whose target lives outside+ the storage root must not be unlinked (whether the unlink follows+ the link or not — either is unsafe)."""+ outside_dir = tmp_path / "outside_target"+ outside_dir.mkdir()+ canary = outside_dir / "symlink_target.txt"+ canary.write_text("DO NOT DELETE")++ # Place the symlink inside the (hypothetical) storage root.+ fake_storage_root = tmp_path / "research_outputs"+ fake_storage_root.mkdir()+ link = fake_storage_root / "evil_link"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ assert link.is_symlink()++ rid = "rid-delete-symlink"+ # Use the symlink path (not the target). The route does+ # ``Path(report_path).unlink()`` which deletes the symlink itself —+ # also outside the storage semantics, so it must be blocked.+ session, engine = _seed_db(rid, str(link))+ try:+ with _route_db_patches(session):+ resp = route_client.delete(f"/api/delete/{rid}")+ assert resp.status_code == 200, resp.text+ assert session.query(ResearchHistory).count() == 0+ finally:+ _close(session, engine)++ # Canary target must STILL exist (tripwire against dereferencing).+ assert canary.exists(), (+ "DELETE /api/delete/<id> followed a symlink target outside the "+ "storage root — no link-target containment check present"+ )+ assert canary.read_text() == "DO NOT DELETE"+ # The symlink in the storage area must also still exist.+ assert link.is_symlink() or link.exists(), (+ "DELETE /api/delete/<id> removed a symlink whose report_path "+ "was trusted verbatim — no path validation present"+ )++ def test_legitimate_path_inside_storage_root_can_be_deleted(+ self, route_client, tmp_path, monkeypatch+ ):+ """POSITIVE CONTROL: a ``report_path`` that lives inside the+ configured research outputs directory must still be unlinked so+ that the documented delete behaviour is preserved.++ This test should stay GREEN. If a future fix accidentally blocks+ legitimate deletes, this test breaks and flags the regression.+ """+ # Point LDR_DATA_DIR at a tmp_path subdir so+ # ``get_research_outputs_directory()`` returns+ # tmp_path/app_data/research_outputs.+ ldr_data = tmp_path / "app_data"+ monkeypatch.setenv("LDR_DATA_DIR", str(ldr_data))+ outputs_root = ldr_data / "research_outputs"+ outputs_root.mkdir(parents=True)++ legit_report = outputs_root / "legit_report.md"+ legit_report.write_text("# legit report")+ assert legit_report.exists()++ rid = "rid-delete-legit"+ session, engine = _seed_db(rid, str(legit_report))+ try:+ with _route_db_patches(session):+ resp = route_client.delete(f"/api/delete/{rid}")+ assert resp.status_code == 200, resp.status_code+ finally:+ _close(session, engine)++ assert not legit_report.exists(), (+ "POSITIVE CONTROL FAILED: a legitimate report inside the "+ "research outputs root was not deleted. If a containment fix "+ "was just added, it is overly restrictive."+ )+++# ---------------------------------------------------------------------------+# POST /api/clear_history+# ---------------------------------------------------------------------------+++class TestClearHistoryEndpointCanaryProtection:+ """``POST /api/clear_history`` must not unlink paths outside the+ configured research outputs directory — for ANY row in the user's+ history."""++ def test_absolute_path_outside_root_is_preserved(+ self, route_client, tmp_path+ ):+ """An absolute canary path outside the storage root survives a+ bulk clear_history."""+ outside_dir = tmp_path / "clear_outside"+ outside_dir.mkdir()+ canary = outside_dir / "canary.txt"+ canary.write_text("DO NOT DELETE")++ rid = "rid-clear-abs"+ session, engine = _seed_db(rid, str(canary))+ try:+ with _route_db_patches(session):+ resp = route_client.post("/api/clear_history")+ assert resp.status_code == 200, resp.text+ assert session.query(ResearchHistory).count() == 0+ finally:+ _close(session, engine)++ assert canary.exists(), (+ "POST /api/clear_history unlinked an absolute report_path "+ "outside the storage root — no path validation present"+ )+ assert canary.read_text() == "DO NOT DELETE"++ def test_parent_traversal_path_is_preserved(self, route_client, tmp_path):+ """A ``..``-laden ``report_path`` that resolves outside the+ storage root survives clear_history."""+ outside_dir = tmp_path / "clear_outside_sibling"+ outside_dir.mkdir()+ canary = outside_dir / "victim.txt"+ canary.write_text("DO NOT DELETE")++ fake_storage_root = tmp_path / "research_outputs"+ traversal_path = (+ fake_storage_root+ / "sub"+ / ".."+ / ".."+ / "clear_outside_sibling"+ / "victim.txt"+ )+ # Intermediate dir must exist for the OS to resolve the ``..`` hops+ # (see the delete-endpoint twin for the false-green explanation).+ (fake_storage_root / "sub").mkdir(parents=True)+ assert traversal_path.exists(), "traversal payload must be stat-able"+ assert traversal_path.resolve() == canary.resolve()++ rid = "rid-clear-traversal"+ session, engine = _seed_db(rid, str(traversal_path))+ try:+ with _route_db_patches(session):+ resp = route_client.post("/api/clear_history")+ assert resp.status_code == 200, resp.text+ assert session.query(ResearchHistory).count() == 0+ finally:+ _close(session, engine)++ assert canary.exists(), (+ "POST /api/clear_history followed a ``..``-laden report_path "+ "outside the storage root — no containment check present"+ )+ assert canary.read_text() == "DO NOT DELETE"++ def test_symlink_pointing_outside_root_is_preserved(+ self, route_client, tmp_path+ ):+ """A ``report_path`` that is a symlink to a file outside the+ storage root survives clear_history."""+ outside_dir = tmp_path / "clear_symlink_target"+ outside_dir.mkdir()+ canary = outside_dir / "symlink_target.txt"+ canary.write_text("DO NOT DELETE")++ fake_storage_root = tmp_path / "research_outputs"+ fake_storage_root.mkdir()+ link = fake_storage_root / "evil_link"+ try:+ link.symlink_to(canary)+ except OSError:+ pytest.skip("Cannot create symlinks in this environment")+ assert link.is_symlink()++ rid = "rid-clear-symlink"+ session, engine = _seed_db(rid, str(link))+ try:+ with _route_db_patches(session):+ resp = route_client.post("/api/clear_history")+ assert resp.status_code == 200, resp.text+ assert session.query(ResearchHistory).count() == 0+ finally:+ _close(session, engine)++ assert canary.exists(), (+ "POST /api/clear_history followed a symlink target outside the "+ "storage root — no link-target containment check present"+ )+ assert canary.read_text() == "DO NOT DELETE"+ assert link.is_symlink() or link.exists(), (+ "POST /api/clear_history removed a symlink whose report_path "+ "was trusted verbatim — no path validation present"+ )++ def test_multiple_malicious_paths_all_preserved(+ self, route_client, tmp_path+ ):+ """When several rows hold canary paths, clear_history must not+ touch ANY of them."""+ outside_dir = tmp_path / "bulk_outside"+ outside_dir.mkdir()+ canaries = []+ for i in range(3):+ c = outside_dir / f"canary_{i}.txt"+ c.write_text(f"DO NOT DELETE {i}")+ canaries.append(c)++ session, engine = _seed_db("rid-clear-bulk-0", str(canaries[0]))+ for i in range(1, len(canaries)):+ session.add(+ ResearchHistory(+ id=f"rid-clear-bulk-{i}",+ query="q",+ mode="quick",+ status="completed",+ created_at=datetime.now(timezone.utc).isoformat(),+ report_path=str(canaries[i]),+ )+ )+ session.commit()+ try:+ with _route_db_patches(session):+ resp = route_client.post("/api/clear_history")+ assert resp.status_code == 200, resp.text+ assert session.query(ResearchHistory).count() == 0+ finally:+ _close(session, engine)++ for i, c in enumerate(canaries):+ assert c.exists(), (+ f"POST /api/clear_history unlinked bulk canary #{i} "+ f"({c}) — no path validation present"+ )+ assert c.read_text() == f"DO NOT DELETE {i}"++ def test_legitimate_path_inside_storage_root_can_be_deleted(+ self, route_client, tmp_path, monkeypatch+ ):+ """POSITIVE CONTROL: legitimate reports inside the storage root+ still get cleaned up by clear_history."""+ ldr_data = tmp_path / "app_data"+ monkeypatch.setenv("LDR_DATA_DIR", str(ldr_data))+ outputs_root = ldr_data / "research_outputs"+ outputs_root.mkdir(parents=True)++ legit = outputs_root / "clear_legit.md"+ legit.write_text("# legit")++ rid = "rid-clear-legit"+ session, engine = _seed_db(rid, str(legit))+ try:+ with _route_db_patches(session):+ resp = route_client.post("/api/clear_history")+ assert resp.status_code == 200, resp.status_code+ finally:+ _close(session, engine)++ assert not legit.exists(), (+ "POSITIVE CONTROL FAILED: a legitimate report inside the "+ "research outputs root was not cleared. If a containment fix "+ "was just added, it is overly restrictive."+ )+++# ---------------------------------------------------------------------------+# Write-side tripwires: the column itself has no validator, and processor_v2+# faithfully copies op_data["report_path"] into the column. Together these+# close the loop on the vulnerability even though we don't exercise the+# HTTP write path here.+# ---------------------------------------------------------------------------+++class TestReportPathWriteSurface:+ """Document the write-side surface that makes the unlink-trust bug+ reachable in practice."""++ def test_research_history_report_path_is_unvalidated_text(self):+ """``ResearchHistory.report_path`` is a plain ``Column(Text)`` —+ no SQLAlchemy ``CheckConstraint``, no custom ``TypeDecorator``,+ no validator. Tripwire against future hardening regressions: a+ later change that adds a validator here is what would make the+ delete-time trust assumption safe."""+ col = ResearchHistory.__table__.columns["report_path"]+ assert col.type.__class__.__name__ == "Text", (+ f"Expected Text column type, got {col.type.__class__.__name__} "+ f"— write-side validator added? Audit delete-side unlinks."+ )+ check_constraints = [+ c+ for c in ResearchHistory.__table__.constraints+ if c.__class__.__name__ == "CheckConstraint"+ ]+ offending = [+ c+ for c in check_constraints+ if "report_path"+ in (c.sqltext.text if hasattr(c, "sqltext") else str(c))+ ]+ assert not offending, (+ "ResearchHistory has a CHECK constraint on report_path; "+ "review whether it actually constrains the value space."+ )++ def test_processor_v2_copies_arbitrary_op_data_report_path(self):+ """``QueueProcessorV2.process_pending_operations_for_user`` assigns+ ``op_data["report_path"]`` directly to ``ResearchHistory.report_path``+ without normalisation. Tripwire: if a future revision adds+ sanitisation here, the delete-time trust assumption is partly+ defused and this assertion flags it for re-review."""+ import inspect as _inspect++ from local_deep_research.web.queue import processor_v2++ source = _inspect.getsource(+ processor_v2.QueueProcessorV2.process_pending_operations_for_user+ )+ assert 'report_path = op_data.get("report_path")' in source+ # No Path.resolve, no is_relative_to, no PathValidator on the same+ # source fragment. If a future fix adds one, this assertion flags+ # it for re-evaluation of the delete-time unlink trust.+ forbidden_helpers = (+ "Path(report_path).resolve()",+ 'op_data["report_path"]).resolve()',+ "is_relative_to",+ "PathValidator",+ )+ for fragment in forbidden_helpers:+ assert fragment not in source, (+ f"processor_v2 source now contains {fragment!r} — "+ f"report-path sanitisation added? Re-evaluate the "+ f"delete-time unlink trust."+ )diff --git a/tests/security/test_secure_logging_writes.py b/tests/security/test_secure_logging_writes.pynew file mode 100644index 0000000000..2bc2faa4d7--- /dev/null+++ b/tests/security/test_secure_logging_writes.py@@ -0,0 +1,359 @@+# allow: no-sut-import — drives real log_utils config_logger() file sinks inside isolated subprocesses (LDR_TEST_LOG_PAYLOAD); production code runs in the child, not imported at module level here.+"""Security battery for the secure-logging FILE write path.++Complements ``test_secure_logging.py`` (record-level wrapper gates verified+via caplog) and ``tests/utilities/test_log_utils*.py`` (mocked sink wiring):+this battery drives REAL ``config_logger()`` file-sink writes in isolated+subprocesses and inspects what actually lands on disk.++Surfaces pinned:++* ``utilities/log_utils.py`` — the ``LDR_ENABLE_FILE_LOGGING`` gate (~:761),+ import-time ``logs`` dir creation (~:27-28), the control-char patcher+ (~:689-692), and the file sink's ``diagnose=False`` (~:781).+* ``config/paths.py`` — ``get_logs_directory()`` derives strictly from+ ``LDR_DATA_DIR``. Neither a hostile ``LDR_LOG_DIR`` env var nor the+ registered-but-unread ``bootstrap.log_dir`` setting+ (``LDR_BOOTSTRAP_LOG_DIR``, ``settings/env_definitions/bootstrap.py``)+ can move the sink: the same containment contract as+ ``test_settings_path_escape.py`` (battery B).+* ``security/log_sanitizer.py`` — the sanctioned dual-scrub keeps known+ secrets off disk. The file sink also redacts raw credential fields;+ ``test_raw_sensitive_fields_are_redacted_before_disk_write`` pins that+ protection independently of explicit caller-side scrubbing.++Each test spawns a fresh interpreter so ``log_utils`` resolves ``_LOG_DIR``+under the controlled environment (the real import-time path) and no global+loguru state leaks into the pytest session.+"""++import json+import os+import subprocess+import sys+from pathlib import Path+++import pytest+++_REPO_ROOT = Path(__file__).resolve().parents[2]++# Env vars that must never leak from the outer session into the child.+_SCRUBBED_ENV_VARS = (+ "LDR_APP_DEBUG",+ "LDR_LOGURU_DIAGNOSE",+ "LDR_LOG_DIR",+ "LDR_BOOTSTRAP_LOG_DIR",+ "LDR_ENABLE_FILE_LOGGING",+)++# The child: configure logging exactly as the application does, emit one+# record selected by LDR_TEST_EMIT_MODE, then report every *.log file that+# exists under LDR_DATA_DIR.+_EMIT_SCRIPT = """+import json+import os+from pathlib import Path++from local_deep_research.utilities.log_utils import config_logger+from local_deep_research.security.secure_logging import logger++config_logger("write-battery")++mode = os.environ.get("LDR_TEST_EMIT_MODE", "info")+if mode == "info":+ logger.info(os.environ["LDR_TEST_LOG_PAYLOAD"])+elif mode == "error":+ logger.error(os.environ["LDR_TEST_LOG_PAYLOAD"])+elif mode == "scrubbed":+ from local_deep_research.security.log_sanitizer import scrub_error++ logger.error(+ scrub_error(+ os.environ["LDR_TEST_LOG_PAYLOAD"],+ os.environ["LDR_TEST_LOG_SECRET"],+ )+ )+elif mode == "control-chars":+ logger.error("ctrl-marker\\x00\\x1b[31m\\u202efin")+elif mode == "exception":+ try:+ raise ValueError(os.environ["LDR_TEST_LOG_PAYLOAD"])+ except ValueError:+ logger.exception("emit exception marker")++data_dir = Path(os.environ["LDR_DATA_DIR"])+print(json.dumps(+ {"logs": [str(path.resolve()) for path in data_dir.rglob("*.log")]},+))+"""+++def _files_below(directory: Path) -> dict[Path, bytes]:+ """Capture files beneath a controlled test directory, including canaries."""+ return {+ path.relative_to(directory): path.read_bytes()+ for path in directory.rglob("*")+ if path.is_file()+ }+++def _run_emit(+ tmp_path: Path,+ data_dir: str | None = None,+ expect_success: bool = True,+ **environment: str | None,+) -> tuple[subprocess.CompletedProcess[str], Path]:+ """Run the emit script in a fresh interpreter under a controlled env.++ The child runs with its own workspace directory as cwd (so a relative+ ``../escape`` resolves inside ``tmp_path``) and its own ``$HOME`` (so+ ``$HOME``-based escape attempts stay observable). Returns the completed+ process and the effective data directory.+ """+ env = os.environ.copy()+ for var in _SCRUBBED_ENV_VARS:+ _ = env.pop(var, None)+ env["LDR_DATA_DIR"] = data_dir or str(tmp_path / "data")+ env["LDR_TEST_LOG_PAYLOAD"] = "write-battery marker"+ for name, value in environment.items():+ if value is None:+ _ = env.pop(name, None)+ else:+ env[name] = value++ workspace = tmp_path / "workspace"+ workspace.mkdir(exist_ok=True)+ home = tmp_path / "home"+ home.mkdir(exist_ok=True)+ env["HOME"] = str(home)++ result = subprocess.run(+ [sys.executable, "-c", _EMIT_SCRIPT],+ cwd=workspace,+ env=env,+ capture_output=True,+ text=True,+ # A fresh interpreter pays the full LDR import cost (see the+ # module docstring); 20s is tight on a loaded CI runner.+ timeout=60,+ check=False,+ )+ if expect_success:+ assert result.returncode == 0, result.stderr+ return result, Path(env["LDR_DATA_DIR"])+++def _log_paths(result: subprocess.CompletedProcess[str]) -> list[Path]:+ """Parse the child's JSON report of *.log files under its data dir."""+ payload: dict[str, list[str]] = json.loads(result.stdout)+ return [Path(entry) for entry in payload["logs"]]+++def _log_contents(result: subprocess.CompletedProcess[str]) -> str:+ return "\n".join(path.read_text() for path in _log_paths(result))+++class TestFileLoggingGate:+ """LDR_ENABLE_FILE_LOGGING must gate every file write."""++ @pytest.mark.parametrize("enabled", [None, "false"])+ def test_gate_off_creates_no_log_file(self, tmp_path, enabled):+ """Unset or explicitly false: no *.log anywhere under the data root."""+ result, _ = _run_emit(tmp_path, LDR_ENABLE_FILE_LOGGING=enabled)++ assert not _log_paths(result)+ assert not list(tmp_path.rglob("*.log"))++ @pytest.mark.parametrize("enabled", ["true", "TRUE"])+ def test_gate_on_writes_inside_data_logs(self, tmp_path, enabled):+ """Enabled: exactly <LDR_DATA_DIR>/logs/write-battery.log, with content."""+ result, data_dir = _run_emit(tmp_path, LDR_ENABLE_FILE_LOGGING=enabled)+ logs = _log_paths(result)++ assert logs, "file logging was enabled but no log file exists"+ assert all(path.parent == data_dir / "logs" for path in logs), logs+ assert "write-battery marker" in _log_contents(result)+++class TestLogDirContainment:+ """The log file must stay inside LDR_DATA_DIR under hostile inputs."""++ @pytest.mark.parametrize(+ "attack",+ ["relative", "expandvars", "absolute"],+ )+ def test_hostile_log_dir_env_cannot_move_log_file(self, tmp_path, attack):+ """LDR_LOG_DIR / LDR_BOOTSTRAP_LOG_DIR cannot relocate the sink.++ ``bootstrap.log_dir`` is registered in+ ``settings/env_definitions/bootstrap.py`` but nothing in the write+ path consumes it, and no code reads ``LDR_LOG_DIR`` — the sink+ location is derived only from ``LDR_DATA_DIR``+ (``config/paths.py::get_logs_directory``).+ """+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "CANARY").write_text("do not alter")+ hostile_values = {+ "relative": "../escape",+ "expandvars": "$HOME/escape",+ "absolute": str(outside / "absolute-logs"),+ }+ before = _files_below(tmp_path)++ result, data_dir = _run_emit(+ tmp_path,+ LDR_ENABLE_FILE_LOGGING="true",+ LDR_LOG_DIR=hostile_values[attack],+ LDR_BOOTSTRAP_LOG_DIR=hostile_values[attack],+ )++ logs = _log_paths(result)+ data_dir = data_dir.resolve()+ assert logs, "file logging was enabled but no log file exists"+ assert all(path.is_relative_to(data_dir) for path in logs), logs++ new_files = set(_files_below(tmp_path)) - set(before)+ assert new_files, "the child wrote nothing at all"+ assert all(+ (tmp_path / rel).is_relative_to(data_dir) for rel in new_files+ ), sorted(new_files)+ assert not (tmp_path / "escape").exists()+ assert not (tmp_path / "home" / "escape").exists()+ assert _files_below(outside) == {Path("CANARY"): b"do not alter"}++ def test_relative_data_dir_fails_closed_without_writing(self, tmp_path):+ """A relative LDR_DATA_DIR must abort loudly, never write logs."""+ result, _ = _run_emit(+ tmp_path,+ data_dir="relative/ldr-data",+ expect_success=False,+ )++ assert result.returncode != 0+ assert "absolute" in result.stderr+ assert not list(tmp_path.rglob("*.log"))++ def test_import_creates_logs_dir_under_data_dir_when_gate_off(+ self, tmp_path+ ):+ """Import-time mkdir (log_utils.py:27-28) stays inside LDR_DATA_DIR.++ The gate suppresses the FILE, not the directory: ``logs/`` is+ created eagerly, which is safe only because it is clamped under the+ (validated) data directory.+ """+ result, data_dir = _run_emit(tmp_path) # gate unset++ assert (data_dir / "logs").is_dir()+ assert not _log_paths(result)+++class TestDiskScrubbing:+ """What reaches the persistent, unencrypted log file."""++ def test_scrubbed_secret_never_reaches_disk(self, tmp_path):+ """Dual-scrub output survives the write path without the secrets.++ The sanctioned catch-site pattern is+ ``logger.error(scrub_error(msg, known_literal))`` — credential+ shapes (URL userinfo, query params, key prefixes) plus the caller's+ literal secret must all be absent from the file.+ """+ message = (+ "scrubbed-marker provider failed "+ "https://user:[email protected]/v1"+ "?api_key=AKIAABCDEFGHIJKLMNOP&token=tok-abcdefghijklmnop1234 "+ "sk-live-abcdefghijklmnopqrst and known SuperSecretLiteral99"+ )+ result, _ = _run_emit(+ tmp_path,+ LDR_ENABLE_FILE_LOGGING="true",+ LDR_TEST_EMIT_MODE="scrubbed",+ LDR_TEST_LOG_PAYLOAD=message,+ LDR_TEST_LOG_SECRET="SuperSecretLiteral99",+ )+ contents = _log_contents(result)++ assert "scrubbed-marker" in contents+ assert "[REDACTED" in contents+ for leak in (+ "hunter2secret",+ "AKIAABCDEFGHIJKLMNOP",+ "tok-abcdefghijklmnop1234",+ "sk-live-abcdefghijklmnopqrst",+ "SuperSecretLiteral99",+ ):+ assert leak not in contents, leak++ def test_control_characters_stripped_before_disk_write(self, tmp_path):+ """The config_logger patcher strips control/format chars on disk."""+ result, _ = _run_emit(+ tmp_path,+ LDR_ENABLE_FILE_LOGGING="true",+ LDR_TEST_EMIT_MODE="control-chars",+ )+ contents = _log_contents(result)++ assert "ctrl-marker" in contents+ assert "\x00" not in contents+ assert "\x1b" not in contents+ assert "\u202e" not in contents++ def test_secure_logger_exception_writes_error_without_traceback(+ self, tmp_path+ ):+ """SecureLogger.exception() on disk: ERROR line, no traceback text.++ The on-disk counterpart of ``test_secure_logging.py``'s caplog+ assertions: with both diagnose flags unset, the record carries no+ exception, so the unencrypted file cannot capture the+ secret-bearing traceback.+ """+ result, _ = _run_emit(+ tmp_path,+ LDR_ENABLE_FILE_LOGGING="true",+ LDR_TEST_EMIT_MODE="exception",+ LDR_TEST_LOG_PAYLOAD="api_key=sk-LEAK-0123456789abcdef",+ )+ contents = _log_contents(result)++ assert "emit exception marker" in contents+ assert "ERROR" in contents+ assert "Traceback" not in contents+ assert "sk-LEAK" not in contents++ def test_raw_sensitive_fields_are_redacted_before_disk_write(+ self, tmp_path+ ):+ """Raw ``field=value`` secrets must not reach the persistent file.++ All four field shapes ride one log line so this pays for a single+ interpreter spawn instead of four -- each ``_run_emit`` starts a+ fresh ``sys.executable`` and pays the full LDR import cost.+ """+ fields = {+ "api_key": "api-key-plaintext-12345678",+ "password": "password-plaintext-12345678",+ "secret": "secret-plaintext-12345678",+ "token": "token-plaintext-12345678",+ }+ payload = "write-battery raw " + " ".join(+ f"{field}={secret}" for field, secret in fields.items()+ )+ result, _ = _run_emit(+ tmp_path,+ LDR_ENABLE_FILE_LOGGING="true",+ LDR_TEST_EMIT_MODE="error",+ LDR_TEST_LOG_PAYLOAD=payload,+ )+ contents = _log_contents(result)++ assert "write-battery raw " in contents # the line itself arrived+ for field, secret in fields.items():+ assert f"{field}=" in contents # the field survived to disk+ assert secret not in contents, (+ f"plaintext {field} value reached the unencrypted log file"+ )diff --git a/tests/security/test_settings_bulk_import.py b/tests/security/test_settings_bulk_import.pynew file mode 100644index 0000000000..a4f92da6c4--- /dev/null+++ b/tests/security/test_settings_bulk_import.py@@ -0,0 +1,244 @@+# allow: no-sut-import — drives the REAL settings import surface+# (``SettingsManager.import_settings``) against a real SQLite session.+"""Regression tests for settings import policy and value validation.++Library storage paths are operator-only after #7152/#7224: existing saved+locations and environment overrides remain supported, including locations+outside LDR_DATA_DIR, but user imports cannot redirect them. These checks+exercise the real manager and download-service path with isolated roots.++The separate benchmark-output containment gap remains a strict xfail.+Select validation and valid user-editable imports are ordinary controls.+"""++from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest+from sqlalchemy import create_engine+from sqlalchemy.orm import sessionmaker++from local_deep_research.database.models import Base, Setting, SettingType+from local_deep_research.settings.manager import SettingsManager+++_STORAGE_KEY = "research_library.storage_path"+_OUTPUT_KEY = "benchmark.output_dir"+++def _metadata(key: str, value: str, **extra) -> dict[str, object]:+ data: dict[str, object] = {+ "value": value,+ "type": "APP",+ "name": key,+ "description": "security test setting",+ "ui_element": "text",+ }+ data.update(extra)+ return data+++def settings_manager(tmp_path, monkeypatch):+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "ldr-data"))+ monkeypatch.delenv("LDR_RESEARCH_LIBRARY_STORAGE_PATH", raising=False)+ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ db_session = sessionmaker(bind=engine)()+ for key, value in (+ (_STORAGE_KEY, str(tmp_path / "saved-library")),+ (_OUTPUT_KEY, "./benchmarks"),+ ):+ db_session.add(+ Setting(+ key=key,+ value=value,+ type=SettingType.APP,+ name=key,+ ui_element="text",+ )+ )+ db_session.commit()+ manager = SettingsManager(db_session=db_session)+ yield manager+ manager.close()+ db_session.close()+ engine.dispose()+++def _import(manager: SettingsManager, key: str, value: str) -> None:+ manager.import_settings({key: _metadata(key, value)})++[email protected]("value", ["$HOME/victim", "../victim", "collections"])+def test_import_cannot_redirect_saved_library_root(settings_manager, value):+ """Even a benign-looking user import must preserve the operator-only root."""+ before = settings_manager.get_setting(_STORAGE_KEY, check_env=False)++ _import(settings_manager, _STORAGE_KEY, value)++ assert settings_manager.get_setting(_STORAGE_KEY, check_env=False) == before+++ strict=True,+ reason=(+ "OPEN EXPOSURE: benchmark.output_dir still accepts paths outside "+ "LDR_DATA_DIR; the library's operator-only policy does not cover "+ "benchmark output. Remove this marker when that policy is fixed."+ ),+)+def test_import_rejects_benchmark_path_escape(settings_manager):+ before = settings_manager.get_setting(_OUTPUT_KEY, check_env=False)++ _import(settings_manager, _OUTPUT_KEY, "$HOME/victim")++ assert settings_manager.get_setting(_OUTPUT_KEY, check_env=False) == before++[email protected]("value", ["./benchmarks", "./other-benchmarks"])+def test_import_accepts_editable_relative_path_controls(+ settings_manager, value+):+ """A valid user-editable setting must still be imported, including changes."""+ _import(settings_manager, _OUTPUT_KEY, value)++ assert settings_manager.get_setting(_OUTPUT_KEY, check_env=False) == value+++def test_import_enforces_same_value_validation_as_save_routes(+ settings_manager,+):+ """GUARANTEE: the import applies the same value validation as the save routes.++ ``import_settings`` (settings/manager.py) runs+ ``validate_imported_setting_value`` over every value that comes from+ the imported file and skips the row when the value is invalid under+ the CURRENT defaults schema. That closes what used to be a genuine+ import-specific bypass: the import validated only the KEY shape and+ persisted the VALUE verbatim, so a select-typed setting could be+ driven out of its allowed options -- something ``validate_setting``+ (web/services/settings_service.py) refuses on every per-key save+ route.++ ``app.timezone`` is used because select is one of the classes the+ validator can actually judge. Library paths have a separate operator-only+ write policy; benchmark path containment remains a separate expected failure.++ Note the two validators read their constraints from different places:+ the save route judges the stored ``Setting`` row, while the import+ judges the shipped defaults metadata for the key. Both reject+ ``Mars/Phobos`` for ``app.timezone``, and the assertions below pin+ both halves so neither can regress unnoticed.+ """+ from local_deep_research.web.services.settings_service import (+ validate_setting,+ )++ options = ["UTC", "America/New_York"]+ row = Setting(+ key="app.timezone",+ value="UTC",+ type=SettingType.APP,+ name="app.timezone",+ ui_element="select",+ )+ row.options = list(options)+ settings_manager.db_session.add(row)+ settings_manager.db_session.commit()++ is_valid, _error = validate_setting(row, "Mars/Phobos")+ assert not is_valid # control: the save-route validator refuses it++ settings_manager.import_settings(+ {+ "app.timezone": _metadata(+ "app.timezone", "Mars/Phobos", ui_element="select"+ )+ }+ )++ assert (+ settings_manager.get_setting("app.timezone", check_env=False) == "UTC"+ ), (+ "import_settings persisted a value that validate_setting rejects "+ "on every save route \u2014 the import path skips the save-path "+ "validators entirely"+ )+++def test_import_still_accepts_in_options_select_values(settings_manager):+ """POSITIVE CONTROL for the test above: a legal select value still imports.++ Without this, an ``import_settings`` that rejected *everything* (or+ that never reached the persist step at all) would satisfy the+ regression assertion vacuously.+ """+ row = Setting(+ key="app.timezone",+ value="UTC",+ type=SettingType.APP,+ name="app.timezone",+ ui_element="select",+ )+ row.options = ["UTC", "America/New_York"]+ settings_manager.db_session.add(row)+ settings_manager.db_session.commit()++ settings_manager.import_settings(+ {+ "app.timezone": _metadata(+ "app.timezone", "America/New_York", ui_element="select"+ )+ }+ )++ assert (+ settings_manager.get_setting("app.timezone", check_env=False)+ == "America/New_York"+ )++[email protected]("operator_override", [False, True])+def test_imported_storage_escape_cannot_redirect_download_service(+ settings_manager, tmp_path, monkeypatch, operator_override+):+ """A refused import preserves saved/operator roots and still creates a library."""+ from local_deep_research.research_library.services.download_service import (+ DownloadService,+ )++ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HOME", str(home))+ saved_root = settings_manager.get_setting(_STORAGE_KEY, check_env=False)+ expected_root = Path(saved_root)+ if operator_override:+ expected_root = tmp_path / "operator-library"+ monkeypatch.setenv(+ "LDR_RESEARCH_LIBRARY_STORAGE_PATH", str(expected_root)+ )+ _import(settings_manager, _STORAGE_KEY, "$HOME/victim")++ with (+ patch(+ "local_deep_research.research_library.services.download_service.get_settings_manager",+ return_value=settings_manager,+ ),+ patch(+ "local_deep_research.research_library.services.download_service.RetryManager",+ return_value=MagicMock(),+ ),+ ):+ service = DownloadService("alice")+ try:+ assert Path(service.library_root) == expected_root / "alice"+ assert (expected_root / "alice" / "pdfs").is_dir()+ assert (+ settings_manager.get_setting(_STORAGE_KEY, check_env=False)+ == saved_root+ )+ finally:+ service.close()++ assert not (home / "victim").exists()diff --git a/tests/security/test_settings_path_escape.py b/tests/security/test_settings_path_escape.pynew file mode 100644index 0000000000..1f705acc9d--- /dev/null+++ b/tests/security/test_settings_path_escape.py@@ -0,0 +1,223 @@+"""Configured library-root compatibility and benchmark containment tripwires.++The selected library policy (#7152/#7224, closing #6335) preserves existing+saved roots and operator overrides outside LDR_DATA_DIR. User imports cannot+redirect them; test_settings_bulk_import covers that write boundary with the+real settings manager. These resolver tests ensure configured roots still+work and document paths remain scoped to the user's library.++Benchmark output has a separate unresolved containment policy and retains+its strict xfails. Every configured root and canary lives under tmp_path.+"""++import os+from pathlib import Path+from unittest.mock import MagicMock, patch++import pytest++from local_deep_research.research_library.services.pdf_storage_manager import (+ PDFStorageManager,+)+from local_deep_research.research_library.utils import (+ get_absolute_path_from_settings,+ get_library_storage_path,+)+++def _files_below(directory: Path) -> dict[Path, bytes]:+ return {+ path.relative_to(directory): path.read_bytes()+ for path in directory.rglob("*")+ if path.is_file()+ }+++def isolated_data_dir(tmp_path, monkeypatch):+ data_dir = tmp_path / "ldr-data"+ data_dir.mkdir()+ monkeypatch.setenv("LDR_DATA_DIR", str(data_dir))+ return data_dir+++def configured_storage_paths(tmp_path, monkeypatch):+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("HOME", str(home))+ workspace = tmp_path / "workspace"+ workspace.mkdir()+ monkeypatch.chdir(workspace)+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "CANARY").write_text("do not alter")+ return {+ "expandvars": "$HOME/configured-library",+ "absolute": str(outside / "absolute-library"),+ "relative": "../outside/relative-library",+ }, outside+++def _settings_for(storage_path: str) -> MagicMock:+ settings = MagicMock()+ settings.get_setting.side_effect = lambda key, default=None: (+ storage_path if key == "research_library.storage_path" else default+ )+ return settings++[email protected]("kind", ["expandvars", "absolute", "relative"])+def test_configured_storage_root_is_preserved(+ isolated_data_dir, configured_storage_paths, kind+):+ paths, outside = configured_storage_paths+ before = _files_below(outside)+ configured_base = Path(os.path.expandvars(paths[kind])).resolve()+ settings = _settings_for(paths[kind])++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=settings,+ ):+ resolved = get_library_storage_path("alice")++ assert resolved == configured_base / "alice"+ assert resolved.is_dir()+ assert not resolved.is_relative_to(isolated_data_dir)+ assert _files_below(outside) == before++[email protected]("kind", ["expandvars", "absolute", "relative"])+def test_configured_library_document_read_stays_in_user_root(+ isolated_data_dir, configured_storage_paths, kind+):+ paths, outside = configured_storage_paths+ configured_base = Path(os.path.expandvars(paths[kind])).resolve()+ legitimate = configured_base / "alice" / "pdfs" / "paper.pdf"+ legitimate.parent.mkdir(parents=True)+ legitimate.write_bytes(b"%PDF-safe-library")+ settings = _settings_for(paths[kind])+ before = _files_below(outside)++ resolved = get_absolute_path_from_settings(+ "pdfs/paper.pdf", username="alice", settings_manager=settings+ )++ assert resolved == legitimate+ assert resolved.read_bytes() == b"%PDF-safe-library"+ assert (+ get_absolute_path_from_settings(+ "../CANARY", username="alice", settings_manager=settings+ )+ is None+ )+ assert _files_below(outside) == before+++def test_configured_storage_root_receives_only_its_pdf_write(+ isolated_data_dir, configured_storage_paths+):+ paths, outside = configured_storage_paths+ settings = _settings_for(paths["absolute"])++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=settings,+ ):+ library_root = get_library_storage_path("alice")++ document = MagicMock()+ content = b"%PDF-test"+ relative, size = PDFStorageManager(library_root, "filesystem").save_pdf(+ content, document, MagicMock(), "paper.pdf"+ )++ written = library_root / relative+ assert library_root == Path(paths["absolute"]) / "alice"+ assert written.resolve().is_relative_to(library_root / "pdfs")+ assert written.read_bytes() == content+ assert size == len(content)+ assert document.file_path == relative+ assert document.storage_mode == "filesystem"+ assert _files_below(outside) == {+ Path("CANARY"): b"do not alter",+ written.relative_to(outside): content,+ }+++def test_relative_storage_path_still_creates_a_library(tmp_path, monkeypatch):+ # Pin the eager get_library_directory() default as well as the configured root.+ monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path / "ldr-data"))+ workspace = tmp_path / "workspace"+ workspace.mkdir()+ monkeypatch.chdir(workspace)+ settings = _settings_for("library")++ with patch(+ "local_deep_research.utilities.db_utils.get_settings_manager",+ return_value=settings,+ ):+ library_root = get_library_storage_path("alice")++ assert library_root == workspace / "library" / "alice"+ assert library_root.is_dir()+++ strict=True,+ reason=(+ "OPEN EXPOSURE: benchmark.output_dir is a user-editable setting "+ "and run_benchmark passes it straight to os.makedirs "+ "(benchmarks/runners.py:73) and then writes the results/report "+ "files under it (:113-119), with no containment check against "+ "LDR_DATA_DIR. Fix: resolve output_dir and reject/clamp anything "+ "outside the data directory. Remove this marker when the check "+ "lands."+ ),+)[email protected]("output_dir", ["absolute", "relative"])+def test_benchmark_writer_cannot_escape_data_directory(+ isolated_data_dir, tmp_path, monkeypatch, output_dir+):+ """The real runner must not create or append results outside LDR_DATA_DIR."""+ from local_deep_research.benchmarks import runners++ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "CANARY").write_text("do not alter")+ workspace = tmp_path / "workspace"+ workspace.mkdir()+ monkeypatch.chdir(workspace)+ requested_output = (+ str(outside / "benchmark-results")+ if output_dir == "absolute"+ else "../outside/benchmark-results"+ )+ before = _files_below(outside)++ with (+ patch.object(+ runners.DatasetRegistry, "create_dataset", side_effect=RuntimeError+ ),+ patch.object(+ runners,+ "load_dataset",+ return_value=[{"id": "1", "problem": "q", "answer": "a"}],+ ),+ patch.object(+ runners,+ "quick_summary",+ return_value={"summary": "a", "sources": []},+ ),+ ):+ result = runners.run_benchmark(+ "simpleqa", output_dir=requested_output, run_evaluation=False+ )++ assert (+ Path(result["results_path"])+ .resolve()+ .is_relative_to(isolated_data_dir.resolve())+ )+ assert _files_below(outside) == beforediff --git a/tests/security/test_zotero_ingest_writes.py b/tests/security/test_zotero_ingest_writes.pynew file mode 100644index 0000000000..4341dc8881--- /dev/null+++ b/tests/security/test_zotero_ingest_writes.py@@ -0,0 +1,392 @@+"""End-to-end security battery: hostile Zotero item titles -> filesystem writes.++Complements:+ * tests/security/test_remote_filename_writes.py (URL-derived filenames+ via DownloadService; this file covers the Zotero sync pipeline which+ uses a different generator).+ * tests/security/test_pdf_path_traversal.py (covers only the+ _get_safe_file_path READ-path validator, no actual writes).+ * tests/security/test_filename_sanitizer.py (covers only the bare+ sanitize_filename unit, with no ZoteroItem involvement).++The Zotero ingest pipeline:++ remote ZoteroItem.data["title"]+ -> ZoteroSyncService._filename_for(item, file_type) sync_service.py:1658+ title = item.data.get("title").strip()+ if title.lower().endswith(f".{file_type}".lower()):+ title = title[: -(len(file_type) + 1)] line 1662-1663+ candidate = f"{title[:120]}.{file_type}" line 1664+ sanitize_filename(candidate) line 1667+ * on UnsafeFilenameError: fall back to+ f"{item.key}.{file_type}" line 1670+ -> Document.filename = self._filename_for(...) sync_service.py:1304+ -> PDFStorageManager.save_pdf(pdf_content, document, session,+ filename=doc.filename) sync_service.py:1326++Two surfaces are exercised:++ (A) DIRECT unit-level: call ``ZoteroSyncService._filename_for`` with a+ real ``ZoteroItem`` whose ``data["title"]`` carries a hostile+ payload, and assert the OUTPUT cannot traverse the filesystem.++ (B) END-TO-END: drive the real ``_filename_for`` -> real+ ``PDFStorageManager.save_pdf`` (filesystem mode) chain with a+ tmp_path library root, plant canary files outside it, and assert+ the written file lands STRICTLY inside library_root and the+ canaries are untouched.++Failure classification:+ * Red because of vulnerability: any file lands outside library_root,+ any outside canary is touched, _filename_for returns a value+ containing "/", "\\", "\x00", or a ".." prefix, or a symlink is+ followed.+ * Broken-test: setup/import/expectation bugs.++Run with:+ .venv/bin/python -m pytest tests/security/test_zotero_ingest_writes.py \+ -v --no-header --timeout=120+"""++from __future__ import annotations++import os+from pathlib import Path+from typing import Optional++import pytest++from local_deep_research.research_library.zotero.client import ZoteroItem+from local_deep_research.research_library.zotero.sync_service import (+ ZoteroSyncService,+)+from local_deep_research.security.filename_sanitizer import UnsafeFilenameError+++# Minimal bytes that pass "%PDF" sniffers — content is irrelevant, the+# write path is what we care about. Mirrors the constant in+# tests/security/test_remote_filename_writes.py.+_MINIMAL_PDF = b"%PDF-1.4\n1 0 obj <<>>endobj\ntrailer<<>>\n%%EOF\n"+++# ---------------------------------------------------------------------------+# Fixtures and helpers+# ---------------------------------------------------------------------------+++# ``library_session``, ``fresh_document``, ``fs_storage`` and+# ``canary_paths`` now live in tests/security/conftest.py -- they were+# duplicated verbatim across four batteries in this directory.+++def _zotero_item(title: str, key: str = "ITEM0001") -> ZoteroItem:+ """Minimal real ZoteroItem — same shape used in+ tests/research_library/zotero/test_sync_service.py.++ ``data`` mirrors what ZoteroSyncService._filename_for reads at+ sync_service.py:1659 (``item.data.get("title")``).+ """+ return ZoteroItem(+ key=key,+ version=1,+ item_type="journalArticle",+ data={"title": title},+ )+++def _safe_name_assertions(name: str, *, where: str) -> None:+ """Assert a derived filename cannot escape library_root."""+ assert "/" not in name, (+ f"VULNERABILITY: {where} returned a path-containing value: {name!r}"+ )+ assert "\\" not in name, (+ f"VULNERABILITY: {where} returned a backslash-containing value: "+ f"{name!r}"+ )+ assert "\x00" not in name, (+ f"VULNERABILITY: {where} did not strip null bytes: {name!r}"+ )+ assert not name.startswith(".."), (+ f"VULNERABILITY: {where} returned a traversal-leading value: {name!r}"+ )+ # sanitize_filename caps at MAX_FILENAME_LENGTH=255.+ assert len(name) <= 255, (+ f"VULNERABILITY: {where} returned an over-long filename "+ f"({len(name)} chars): {name!r}"+ )+ # Resolves to a basename — never a path.+ assert Path(name).name == name, (+ f"VULNERABILITY: {where} returned a path, not a basename: {name!r}"+ )+++def _assert_files_inside(+ library_root: Path,+ written_relative: Optional[str],+ canaries: dict,+) -> None:+ """Strict safety assertion: any file written MUST be inside library_root+ AND must not have modified any canary outside it."""+ library_root = library_root.resolve()++ if written_relative is not None:+ written = (library_root / written_relative).resolve()+ try:+ written.relative_to(library_root)+ except ValueError as exc:+ pytest.fail(+ f"VULNERABILITY: save_pdf wrote {written} OUTSIDE library_root "+ f"{library_root} (relative_to raised: {exc})"+ )++ for name, canary in canaries.items():+ assert canary.exists(), (+ f"VULNERABILITY: canary {name} at {canary} was DELETED"+ )+ assert canary.read_text(encoding="utf-8") == "UNTOUCHED-CANARY\n", (+ f"VULNERABILITY: canary {name} at {canary} was MODIFIED "+ f"(content: {canary.read_text(encoding='utf-8')!r})"+ )+++# ---------------------------------------------------------------------------+# Direct _filename_for battery — narrowest pipeline test+# ---------------------------------------------------------------------------+#+# These directly exercise ZoteroSyncService._filename_for (the choke-point+# between remote Zotero data and every consumer of Document.filename)+# with the same remote-payload shapes the task brief enumerates. At+# least one of the battery must exercise _filename_for itself — these+# are that one.+++DIRECT_HOSTILE_TITLES = [+ pytest.param("../../etc/passwd", id="dotdot-traversal"),+ pytest.param("/etc/passwd", id="absolute-path"),+ pytest.param("evil\x00nullbyte", id="null-byte"),+ pytest.param("\uff0e\uff0e\uff0fescape", id="fullwidth-unicode-traversal"),+ pytest.param("a" * 5000, id="extremely-long"),+ pytest.param("con.pdf", id="windows-reserved-name"),+ pytest.param("..\\windows\\sys", id="backslash-traversal"),+]+++class TestFilenameForHostileTitles:+ """Drive the real ``_filename_for`` @staticmethod with a real+ ``ZoteroItem`` whose ``data["title"]`` is hostile and assert the+ OUTPUT cannot escape a filesystem. A failure here means the+ Zotero pipeline emits an unsafe filename even before save_pdf sees+ it."""++ @pytest.mark.parametrize("title", DIRECT_HOSTILE_TITLES)+ def test_filename_for_output_is_safe(self, title):+ item = _zotero_item(title)+ result = ZoteroSyncService._filename_for(item, "pdf")+ _safe_name_assertions(result, where="_filename_for")+++# ---------------------------------------------------------------------------+# Empty / fallback path — _filename_for's UnsafeFilenameError branch+# ---------------------------------------------------------------------------+++class TestFilenameForEmptyTitleFallback:+ """When the candidate is empty (no title) or sanitize_filename rejects+ it, _filename_for falls back to ``{item.key}.{file_type}``. An+ attacker-controlled Zotero server could set item.key to a hostile+ value too — this exercises the fallback."""++ @pytest.mark.parametrize(+ "title,expected", [pytest.param("", "ITEM0001.pdf", id="empty-title")]+ )+ def test_empty_or_unrenderable_title_falls_back_or_raises(+ self, title, expected+ ):+ item = _zotero_item(title)+ try:+ result = ZoteroSyncService._filename_for(item, "pdf")+ except UnsafeFilenameError:+ assert expected is None, (+ f"Unexpected UnsafeFilenameError for title {title!r}"+ )+ return+ if expected is not None:+ assert result == expected, (+ f"expected fallback {expected!r}, got {result!r}"+ )+ _safe_name_assertions(result, where="_filename_for/key-fallback")+++# ---------------------------------------------------------------------------+# End-to-end battery: _filename_for -> save_pdf filesystem write+# ---------------------------------------------------------------------------+++# Smaller than DIRECT_HOSTILE_TITLES: end-to-end is more expensive and+# the direct battery above already pins _filename_for's output shape.+# Here we only need to prove the WHOLE chain cannot escape library_root.+E2E_HOSTILE_TITLES = [+ pytest.param("../../etc/passwd", id="dotdot-traversal"),+ pytest.param("/tmp/abs.pdf", id="absolute-path"),+ pytest.param("evil\x00nullbyte", id="null-byte"),+ pytest.param("\uff0e\uff0e\uff0fescape.pdf", id="fullwidth-unicode"),+]+++class TestFilenameForPipelineSavePdf:+ """Drive the REAL ``_filename_for`` -> REAL ``PDFStorageManager.save_pdf``+ chain (filesystem mode, tmp_path library root) with a hostile title+ and assert the write is contained.++ Either clean rejection (PathValidator raising ValueError) OR a write+ strictly inside library_root is acceptable; the test FAILS only when+ a file lands outside the root or a canary is touched."""++ @pytest.mark.parametrize("title", E2E_HOSTILE_TITLES)+ def test_hostile_title_filename_stays_inside_library_root(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ title,+ ):+ item = _zotero_item(title, key="ZKEY_E2E")++ # The narrowest real chain: _filename_for -> save_pdf.+ derived = ZoteroSyncService._filename_for(item, "pdf")+ _safe_name_assertions(derived, where="_filename_for")++ # Reset between parametrize iterations.+ fresh_document.storage_mode = None+ fresh_document.file_path = None++ try:+ relative, _size = fs_storage.save_pdf(+ pdf_content=_MINIMAL_PDF,+ document=fresh_document,+ session=library_session,+ filename=derived,+ )+ except (ValueError, FileNotFoundError, OSError):+ # PathValidator rejecting traversal, OS rejecting a non-existent+ # intermediate dir, etc. — all valid "rejection" outcomes.+ _assert_files_inside(fs_storage.library_root, None, canary_paths)+ return++ # save_pdf accepted the filename — assert it stayed strictly inside.+ _assert_files_inside(fs_storage.library_root, relative, canary_paths)+++# ---------------------------------------------------------------------------+# Symlink escape — defense shared with test_remote_filename_writes+# ---------------------------------------------------------------------------+++class TestSymlinkWriteEscape:+ """A symlink planted at the intended PDF filename must not redirect writes.++ The verified writer refuses the link where O_NOFOLLOW is available.+ The outside canary must survive, and legitimate in-root saves remain+ covered by the positive controls."""++ @pytest.mark.xfail(+ not getattr(os, "O_NOFOLLOW", 0),+ strict=True,+ reason="The verified writer cannot refuse leaf symlinks without O_NOFOLLOW",+ )+ def test_symlink_inside_pdf_subdir_does_not_let_write_escape(+ self,+ fs_storage,+ fresh_document,+ library_session,+ tmp_path,+ canary_paths,+ ):+ library_root = fs_storage.library_root+ target_name = "zotero_evil_link_target.pdf"++ # Real canary file outside the library root.+ outside_target = tmp_path / "outside_canary_zone" / target_name+ outside_target.write_text("UNTOUCHED-CANARY\n", encoding="utf-8")+ canary_paths["zotero_symlink_target"] = outside_target++ # Use a successful save to find the content-hashed destination;+ # the display filename itself is no longer the path being written.+ saved_relative, _ = fs_storage.save_pdf(+ _MINIMAL_PDF, fresh_document, library_session, target_name+ )+ link = library_root / saved_relative+ assert link.read_bytes() == _MINIMAL_PDF+ link.unlink()+ try:+ link.symlink_to(outside_target)+ except (OSError, NotImplementedError):+ pytest.skip("Cannot create symlinks in this environment")+ assert link.resolve() == outside_target.resolve()++ fresh_document.storage_mode = None+ fresh_document.file_path = None++ try:+ relative, _size = fs_storage.save_pdf(+ pdf_content=_MINIMAL_PDF,+ document=fresh_document,+ session=library_session,+ filename=target_name,+ )+ except (ValueError, OSError):+ _assert_files_inside(library_root, None, canary_paths)+ return++ assert relative == saved_relative+ assert (+ outside_target.read_text(encoding="utf-8") == "UNTOUCHED-CANARY\n"+ ), (+ f"VULNERABILITY: Zotero-derived save_pdf wrote through symlink "+ f"and overwrote outside-root canary at {outside_target}; "+ f"relative returned was {relative!r}"+ )+ _assert_files_inside(library_root, relative, canary_paths)+++# ---------------------------------------------------------------------------+# Happy path — clean Zotero title saves inside pdfs/+# ---------------------------------------------------------------------------+++class TestHappyPath:+ def test_clean_zotero_title_saves_inside_pdfs(+ self,+ fs_storage,+ fresh_document,+ library_session,+ canary_paths,+ ):+ """A clean remote Zotero title flows through _filename_for and+ save_pdf to land inside ``<library_root>/pdfs/`` — guards against+ over-blocking (a sanitization regression that rejects valid titles+ would manifest here)."""+ item = _zotero_item("A Clean Zotero Paper Title", key="ZKEY_CLEAN")+ derived = ZoteroSyncService._filename_for(item, "pdf")+ _safe_name_assertions(derived, where="_filename_for/clean")++ relative, _size = fs_storage.save_pdf(+ pdf_content=_MINIMAL_PDF,+ document=fresh_document,+ session=library_session,+ filename=derived,+ url="http://example.com/clean.pdf",+ resource_id=1,+ )++ written = fs_storage.library_root / relative+ assert written.is_file()+ # Must be inside library_root/pdfs/ — the intended location.+ assert written.resolve().is_relative_to(+ (fs_storage.library_root / "pdfs").resolve()+ ), f"clean file landed at unexpected path: {written}"+ assert written.read_bytes() == _MINIMAL_PDF+ assert fresh_document.file_path == relative+ assert fresh_document.storage_mode == "filesystem"+ _assert_files_inside(fs_storage.library_root, relative, canary_paths)