~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(security): refuse symlinked and out-of-root report paths on delete (#6473)
Huang-404-Q104373b0956a
diff --git a/changelog.d/6473.security.md b/changelog.d/6473.security.mdnew file mode 100644index 0000000000..f4341c893b--- /dev/null+++ b/changelog.d/6473.security.md@@ -0,0 +1,11 @@+Contained the report-file unlink on research deletion: `clear_history` had no+containment check at all and unlinked whatever path the `research_history`+row held, so a stored path outside the reports root took that file with it,+and a symlinked report path deleted its *target* rather than the link. Both+callers now run through one shared guard that refuses leaf symlinks outright,+decides containment on the resolved location, unlinks the path as given with+`FileNotFoundError` tolerated, and keeps the refused path out of the log,+matching `config/paths.py`. Containment is decided at check time: an ancestor+swapped in between the resolve and the unlink can still redirect the unlink,+which needs local write access to the reports tree mid-request and is outside+the guard's threat model.diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.pyindex 37cf4c8aa7..84b31b4be6 100644--- a/src/local_deep_research/web/routers/research.py+++ b/src/local_deep_research/web/routers/research.py@@ -1552,6 +1552,65 @@ def terminate_research()+def _unlink_report_file_if_inside_root(report_path: Optional[str]) -> bool:+ """Delete a stored report file, but only when it is a regular file+ inside the research reports root.++ The path arrives from the ``research_history.report_path`` column, so it+ is treated as untrusted: a corrupted row, or a future buggy writer, could+ point it anywhere on the filesystem.++ Three properties matter:++ * Symlinks are refused outright. Resolving first and unlinking the+ resolved path deletes the *target*, so an in-root symlink would delete+ a file elsewhere and leave a dangling link behind; the library deletion+ path refuses symlinks for the same reason.+ * Containment is decided on the resolved location, which also catches an+ escape through a symlinked *ancestor* directory -- one already swapped in+ before the check. An ancestor swapped in between the resolve() and the+ unlink() can still redirect the unlink, since the unlink re-traverses the+ path; that residual race needs local write access to the reports tree+ mid-request and is outside this guard's threat model.+ * The unlink targets the path as given -- never a resolved copy -- and+ tolerates a missing file, so there is no separate+ exists()-before-unlink() window.++ The refused path is not echoed, mirroring config/paths.py.++ Returns True when a file was removed.+ """+ if not report_path:+ return False+ try:+ from ...config.paths import get_research_outputs_directory++ reports_root = get_research_outputs_directory().resolve()+ path = Path(report_path)++ if path.is_symlink():+ logger.warning(+ "Refusing to unlink a symlinked report path; "+ "the link target may be outside the reports root"+ )+ return False++ if not path.resolve().is_relative_to(reports_root):+ logger.warning(+ "Refusing to unlink a report path outside the reports root"+ )+ return False++ path.unlink()+ return True+ except FileNotFoundError:+ # Already gone; nothing to remove.+ return False+ except Exception:+ logger.exception("Error removing report file")+ return False++@router.delete("/api/delete/{research_id}")def delete_research(request: Request,@@ -1618,27 +1677,9 @@ def delete_research(# Delete report file if it exists. `report_path` comes from the# DB column — normally written by the research worker pointing at# the user's reports dir, but a corrupted row (or future buggy- # writer) could set it to `../../etc/passwd`. Resolve and confirm- # the path is inside the reports root before unlinking.- if report_path:- try:- from ...config.paths import (- get_research_outputs_directory,- )-- reports_root = get_research_outputs_directory().resolve()- resolved = Path(report_path).resolve()- if resolved.exists() and resolved.is_relative_to(- reports_root- ):- resolved.unlink()- else:- logger.warning(- "Refusing to unlink report_path outside reports root: {}",- report_path,- )- except Exception:- logger.exception("Error removing report file")+ # writer) could set it to `../../etc/passwd`. The helper resolves+ # and confirms containment before unlinking.+ _unlink_report_file_if_inside_root(report_path)from ..queue.lifecycle_cleanup import cleanup_queued_research_state@@ -1712,14 +1753,7 @@ def clear_history(if research.id not in deleted_ids:continue- if (- research.report_path- and Path(research.report_path).exists()- ):- try:- Path(research.report_path).unlink()- except Exception:- logger.exception("Error removing report file")+ _unlink_report_file_if_inside_root(research.report_path)from ..queue.lifecycle_cleanup import (cleanup_queued_research_state,diff --git a/tests/web/routers/test_report_unlink_guard.py b/tests/web/routers/test_report_unlink_guard.pynew file mode 100644index 0000000000..aa57ad3aab--- /dev/null+++ b/tests/web/routers/test_report_unlink_guard.py@@ -0,0 +1,305 @@+"""The report-file unlink guard on ``research.py``.++``research_history.report_path`` is a stored string: normally written by the+research worker pointing at a file under the reports root, but a corrupted+row (or a future buggy writer) could set it anywhere. The guard that decides+whether to delete it therefore has to treat the value as untrusted input.++Both callers -- ``delete_research`` and ``clear_history`` -- now share+``_unlink_report_file_if_inside_root``. The behaviours pinned here are the+ones a "resolve, then unlink the resolved path" shape gets wrong:++* **Symlink refusal.** ``Path.resolve()`` follows the link, so unlinking the+ resolved path deletes the *target*. An in-root symlink pointing at a file+ outside the root deletes that out-of-root file (and leaves a dangling link+ behind); an in-root symlink pointing at an in-root file deletes the real+ report and leaves the link. Refusing symlinks outright is what+ ``research_library/deletion/utils/cascade_helper.py`` does for the same+ reason.+* **Containment on the resolved location**, which also covers an escape+ through a symlinked *ancestor* directory.+* **No echo of the refused path** in the log line; ``config/paths.py`` avoids+ echoing paths for the same reason.+* **``clear_history`` carried no containment check at all** before the guard+ was shared -- it unlinked whatever the column held. The route-level test+ below pins that it is now routed through the guard.++Delete-path assertions are real files under ``tmp_path`` because the point is+what survives on disk; a mocked filesystem cannot show that.+"""++from pathlib import Path+from unittest.mock import patch++import pytest++_RR = "local_deep_research.web.routers.research"+_PATHS = "local_deep_research.config.paths"+++def reports_root(tmp_path):+ """A reports root with an ``outside/`` sibling, so escapes have a+ destination that must survive."""+ root = tmp_path / "research_outputs"+ root.mkdir()+ (tmp_path / "outside").mkdir()+ return root+++def guard(reports_root):+ """The guard, with ``get_research_outputs_directory`` pinned to the+ fixture root."""+ from local_deep_research.web.routers import research++ with patch(+ f"{_PATHS}.get_research_outputs_directory", return_value=reports_root+ ):+ yield research._unlink_report_file_if_inside_root+++# ---------------------------------------------------------------------------+# unit: the guard itself+# ---------------------------------------------------------------------------+++def test_deletes_a_regular_file_inside_the_root(guard, reports_root):+ report = reports_root / "report.md"+ report.write_text("body")++ assert guard(str(report)) is True+ assert not report.exists()+++def test_refuses_a_symlink_pointing_outside_the_root(+ guard, reports_root, tmp_path+):+ """The pre-fix shape resolved first, so this unlinked the target."""+ target = tmp_path / "outside" / "secrets.txt"+ target.write_text("out of root")+ link = reports_root / "report.md"+ link.symlink_to(target)++ assert guard(str(link)) is False+ assert target.exists(), "the symlink target was deleted through the link"+ assert link.is_symlink(), "the link itself was removed"+++def test_refuses_an_in_root_symlink_to_an_in_root_file(guard, reports_root):+ """Deleting the resolved target here destroys the real report and leaves+ a dangling link; deleting the link is the caller's intent."""+ real = reports_root / "real.md"+ real.write_text("body")+ link = reports_root / "report.md"+ link.symlink_to(real)++ assert guard(str(link)) is False+ assert real.exists(), "the symlinked report was deleted through the link"+++def test_refuses_a_path_outside_the_root(guard, reports_root, tmp_path):+ outside = tmp_path / "outside" / "secrets.txt"+ outside.write_text("out of root")++ assert guard(str(outside)) is False+ assert outside.exists()+++def test_refuses_an_escape_through_a_symlinked_ancestor(+ guard, reports_root, tmp_path+):+ """A directory component swapped for a symlink escapes the root even+ though the leaf name looks fine."""+ outside_dir = tmp_path / "outside"+ (outside_dir / "report.md").write_text("out of root")+ (reports_root / "nested").symlink_to(outside_dir, target_is_directory=True)++ assert guard(str(reports_root / "nested" / "report.md")) is False+ assert (outside_dir / "report.md").exists()+++def test_missing_file_is_not_an_error(guard, reports_root):+ """No separate exists()-before-unlink() window: the delete itself is+ allowed to report "already gone"."""+ assert guard(str(reports_root / "never-written.md")) is False+++def test_empty_report_path_is_a_noop(guard):+ assert guard(None) is False+ assert guard("") is False+++def test_refusal_log_does_not_echo_the_path(+ guard, reports_root, tmp_path, loguru_caplog+):+ """config/paths.py deliberately avoids echoing paths; the guard's+ refusal line follows the same rule."""+ outside = tmp_path / "outside" / "secrets.txt"+ outside.write_text("out of root")++ with loguru_caplog.at_level("WARNING"):+ assert guard(str(outside)) is False++ assert "Refusing to unlink a report path" in loguru_caplog.text+ assert "secrets.txt" not in loguru_caplog.text+ assert str(tmp_path) not in loguru_caplog.text+++# ---------------------------------------------------------------------------+# route level: both callers go through the guard+# ---------------------------------------------------------------------------+++def db():+ """A real in-memory database with the full schema."""+ 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:",+ connect_args={"check_same_thread": False},+ poolclass=StaticPool,+ )+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()+ try:+ yield session+ finally:+ session.close()+ engine.dispose()+++def _patch_session(session):+ from contextlib import contextmanager+ from unittest.mock import patch as _patch++ @contextmanager+ def _ctx(*_args, **_kwargs):+ yield session++ return _patch(f"{_RR}.get_user_db_session", _ctx)+++def _add_research(session, rid, report_path, status="completed"):+ from local_deep_research.database.models import ResearchHistory++ session.add(+ ResearchHistory(+ id=rid,+ query="q",+ mode="quick",+ status=status,+ created_at="2025-01-01T00:00:00+00:00",+ report_path=str(report_path),+ )+ )+ session.commit()+++def test_delete_research_refuses_an_escaping_symlink_report_path(+ authenticated_client, db, reports_root, tmp_path+):+ """End to end through the route: a stored path that is a symlink out of+ the root must not delete its target."""+ target = tmp_path / "outside" / "secrets.txt"+ target.write_text("out of root")+ link = reports_root / "report.md"+ link.symlink_to(target)+ _add_research(db, "r1", link)++ with (+ _patch_session(db),+ patch(+ f"{_PATHS}.get_research_outputs_directory",+ return_value=reports_root,+ ),+ ):+ response = authenticated_client.delete("/api/delete/r1")++ assert response.status_code == 200, response.text[:300]+ assert target.exists(), "delete_research followed the symlink out of root"+++def test_clear_history_refuses_an_escaping_report_path(+ authenticated_client, db, reports_root, tmp_path+):+ """clear_history unlinked the stored path with no containment check+ before the guard was shared; a row pointing outside the root must not+ take a file with it."""+ outside = tmp_path / "outside" / "secrets.txt"+ outside.write_text("out of root")+ _add_research(db, "r2", outside)++ with (+ _patch_session(db),+ patch(f"{_RR}.get_active_research_ids", return_value=[]),+ patch(+ f"{_PATHS}.get_research_outputs_directory",+ return_value=reports_root,+ ),+ patch(+ "local_deep_research.web.queue.lifecycle_cleanup."+ "cleanup_queued_research_state"+ ),+ ):+ response = authenticated_client.post("/api/clear_history")++ assert response.status_code == 200, response.text[:300]+ assert outside.exists(), "clear_history deleted a file outside the root"+++def test_clear_history_still_deletes_a_report_inside_the_root(+ authenticated_client, db, reports_root+):+ """The containment check must not turn the happy path into a no-op."""+ report = reports_root / "report.md"+ report.write_text("body")+ _add_research(db, "r3", report)++ with (+ _patch_session(db),+ patch(f"{_RR}.get_active_research_ids", return_value=[]),+ patch(+ f"{_PATHS}.get_research_outputs_directory",+ return_value=reports_root,+ ),+ patch(+ "local_deep_research.web.queue.lifecycle_cleanup."+ "cleanup_queued_research_state"+ ),+ ):+ response = authenticated_client.post("/api/clear_history")++ assert response.status_code == 200, response.text[:300]+ assert not report.exists(), "clear_history left an in-root report behind"+++def test_handlers_use_the_shared_guard():+ """Both callers must route through ``_unlink_report_file_if_inside_root``+ rather than reaching for ``Path.unlink`` themselves.++ The route tests above cannot see this: a handler that reverted to its own+ inline guard would still pass them for the symlink and outside-root arms+ (the old ``resolve()``-based check refuses both), and only the+ ``clear_history`` arm would red. Pinning the call sites keeps the two+ handlers from drifting apart again.+ """+ from local_deep_research.web.routers import research++ source = Path(research.__file__).read_text()+ # One definition plus one call in each of delete_research and+ # clear_history.+ assert source.count("_unlink_report_file_if_inside_root(") == 3+ assert "resolved.unlink()" not in source+++def test_guard_is_reachable_from_the_module():+ """The helper the maintainer named in the issue exists."""+ from local_deep_research.web.routers import research++ assert callable(research._unlink_report_file_if_inside_root)