~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): confine RAG local indexing to the indexed folder (symlink escape) (#4848)
LearningCircuit0558664f32b6
diff --git a/changelog.d/4848.security.md b/changelog.d/4848.security.mdnew file mode 100644index 0000000000..f75a9cb0c7--- /dev/null+++ b/changelog.d/4848.security.md@@ -0,0 +1 @@+Local-folder RAG indexing now confines globbed matches to the indexed folder: a symlink inside the folder that points outside it (a linked file, or a linked directory recursive globbing descends into) is skipped rather than read. Previously such a symlink could expose files outside the folder, since `glob` follows symlinks and only the base folder was validated. Complements the glob-pattern validation in #4846; together they close the folder-escape surface on this endpoint.diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 1002e65e5b..6ee7f03a4e 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -1322,6 +1322,11 @@ def index_local_library():# Remove duplicates and sortfiles_to_index = sorted(set(files_to_index))+ # Confine matches to the indexed folder: glob follows symlinks, so+ # a symlink inside the folder could otherwise expose files outside+ # it. Drop any match whose resolved path escapes the base.+ files_to_index = PathValidator.confine_to_base(files_to_index, path)+if not files_to_index:yield f"data: {json.dumps({'type': 'complete', 'results': {'successful': 0, 'skipped': 0, 'failed': 0, 'message': 'No matching files found'}})}\n\n"returndiff --git a/src/local_deep_research/security/path_validator.py b/src/local_deep_research/security/path_validator.pyindex 2d80d3605b..14801d3651 100644--- a/src/local_deep_research/security/path_validator.py+++ b/src/local_deep_research/security/path_validator.py@@ -329,6 +329,51 @@ class PathValidator:return Path(safe_path_str)+ @staticmethod+ def confine_to_base(paths: list[str], base: Path) -> list[str]:+ """Filter ``paths`` to those whose real location stays within ``base``.++ Globbing and directory walks follow symlinks, so a symlink planted+ inside ``base`` (a linked file, or a linked directory that is descended+ into) can yield a path that physically lives outside ``base``. Resolving+ each candidate and confining it to the resolved base drops that escape,+ while still allowing symlinks that resolve to a location *inside*+ ``base``. The basename of each dropped entry is logged — never the full+ path, which can contain a username.++ A candidate that cannot be resolved is dropped. ``Path.resolve()`` raises+ ``RuntimeError`` (not ``OSError``) on a symlink loop, so both are caught —+ otherwise a single planted loop would propagate to the caller instead of+ just skipping that entry. (A *broken* symlink does not raise; it resolves+ to its missing target and is kept or dropped by location, then handled by+ the caller's own existence check.)++ Known limits — both require write access to ``base``, the same+ precondition as the symlink escape this closes, so they don't widen the+ threat model; ``resolve()`` cannot close either: a *hard* link to an+ out-of-base inode resolves to its own in-base path (resolve is+ name-based, not inode-based), and a TOCTOU swap between this check and a+ later ``open()`` by the caller is not prevented.+ """+ resolved_base = base.resolve()+ confined = []+ for p in paths:+ # Log the basename only — the full path can contain a username.+ name = Path(p).name+ try:+ if Path(p).resolve().is_relative_to(resolved_base):+ confined.append(p)+ else:+ logger.warning(+ f"Skipped a path resolving outside the base "+ f"directory: {name}"+ )+ except (OSError, RuntimeError):+ logger.warning(+ f"Skipped a path that could not be resolved: {name}"+ )+ return confined+@staticmethoddef validate_model_path(model_path: str, model_root: Optional[str] = Nonediff --git a/tests/research_library/routes/test_rag_routes_indexing.py b/tests/research_library/routes/test_rag_routes_indexing.pyindex 3b8643248d..b056df5677 100644--- a/tests/research_library/routes/test_rag_routes_indexing.py+++ b/tests/research_library/routes/test_rag_routes_indexing.py@@ -1,6 +1,7 @@# allow: no-sut-import — black-box HTTP test; drives real routes through the Flask test client"""Tests for index_local_library and view_document_chunks in rag_routes.py."""+from pathlib import Pathfrom unittest.mock import patch, MagicMockRAG_PREFIX = "/library"@@ -228,6 +229,74 @@ class TestIndexLocalLibrary:)assert response.status_code == 400+ def test_symlink_escaping_folder_is_not_indexed(+ self, authenticated_client, tmp_path+ ):+ """glob follows symlinks, so a symlink inside the indexed folder that+ points outside it would otherwise be read. The route confines matches+ to the folder, so the escaping symlink is skipped while the real file+ inside the folder is still indexed."""+ folder = tmp_path / "docs"+ folder.mkdir()+ (folder / "real.txt").write_text("inside", encoding="utf-8")+ secret = tmp_path / "secret.txt"+ secret.write_text("OUTSIDE THE FOLDER", encoding="utf-8")+ (folder / "evil.txt").symlink_to(secret)++ indexed: list[str] = []+ rag_service = MagicMock()+ rag_service.index_local_file.side_effect = lambda fp: (+ indexed.append(fp) or {"status": "success"}+ )++ with patch(+ "local_deep_research.research_library.routes.rag_routes.get_rag_service",+ return_value=rag_service,+ ):+ response = authenticated_client.get(+ f"{RAG_PREFIX}/api/rag/index-local"+ f"?path={folder}&patterns=*.txt&recursive=false"+ )+ response.get_data() # drive the SSE generator++ assert response.status_code == 200+ names = {Path(p).name for p in indexed}+ assert "real.txt" in names+ assert "evil.txt" not in names++ def test_symlink_loop_does_not_abort_indexing(+ self, authenticated_client, tmp_path+ ):+ """A symlink loop in the folder (Path.resolve raises RuntimeError) must+ be skipped, not abort the whole run — the real file is still indexed."""+ folder = tmp_path / "docs"+ folder.mkdir()+ (folder / "real.txt").write_text("inside", encoding="utf-8")+ loop = folder / "loop.txt"+ loop.symlink_to(loop) # self-referential loop++ indexed: list[str] = []+ rag_service = MagicMock()+ rag_service.index_local_file.side_effect = lambda fp: (+ indexed.append(fp) or {"status": "success"}+ )++ with patch(+ "local_deep_research.research_library.routes.rag_routes.get_rag_service",+ return_value=rag_service,+ ):+ response = authenticated_client.get(+ f"{RAG_PREFIX}/api/rag/index-local"+ f"?path={folder}&patterns=*.txt&recursive=false"+ )+ response.get_data() # drive the SSE generator++ assert response.status_code == 200+ names = {Path(p).name for p in indexed}+ # the run completed and indexed the real file despite the loop+ assert "real.txt" in names+ assert "loop.txt" not in names+class TestViewDocumentChunks:"""Tests for /api/rag/document/<id>/chunks endpoint."""diff --git a/tests/security/test_path_validator.py b/tests/security/test_path_validator.pyindex c44a6ed030..f43aabadf6 100644--- a/tests/security/test_path_validator.py+++ b/tests/security/test_path_validator.py@@ -502,3 +502,81 @@ class TestSecurityScenarios:assert str(temp_base_dir) in str(result)except OSError:pytest.skip("Symlink creation not supported")+++class TestConfineToBase:+ """Tests for PathValidator.confine_to_base() — drops paths whose real+ location escapes the base directory (symlink-follow protection) while+ keeping in-base files and symlinks that resolve inside the base."""++ def test_regular_file_inside_base_is_kept(self, tmp_path):+ base = tmp_path / "docs"+ base.mkdir()+ f = base / "a.txt"+ f.write_text("x")+ assert PathValidator.confine_to_base([str(f)], base) == [str(f)]++ def test_symlinked_file_escaping_base_is_dropped(self, tmp_path):+ base = tmp_path / "docs"+ base.mkdir()+ secret = tmp_path / "secret.txt"+ secret.write_text("top")+ link = base / "evil.txt"+ link.symlink_to(secret)+ assert PathValidator.confine_to_base([str(link)], base) == []++ def test_symlinked_dir_escaping_base_is_dropped(self, tmp_path):+ base = tmp_path / "docs"+ base.mkdir()+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "buried.txt").write_text("x")+ (base / "evildir").symlink_to(outside, target_is_directory=True)+ # the path a recursive glob would return through the dir symlink+ matched = base / "evildir" / "buried.txt"+ assert PathValidator.confine_to_base([str(matched)], base) == []++ def test_symlink_resolving_inside_base_is_kept(self, tmp_path):+ base = tmp_path / "docs"+ base.mkdir()+ real = base / "real.txt"+ real.write_text("x")+ link = base / "link.txt"+ link.symlink_to(real)+ assert PathValidator.confine_to_base([str(link)], base) == [str(link)]++ def test_symlink_escaping_to_sibling_is_dropped(self, tmp_path):+ base = tmp_path / "docs"+ base.mkdir()+ sibling = tmp_path / "other"+ sibling.mkdir()+ target = sibling / "x.txt"+ target.write_text("x")+ link = base / "x.txt"+ link.symlink_to(target)+ assert PathValidator.confine_to_base([str(link)], base) == []++ def test_prefix_sibling_is_not_confused_with_base(self, tmp_path):+ """``docs-evil`` must not be treated as inside ``docs`` — confinement+ is path-component aware, not a string-prefix check."""+ base = tmp_path / "docs"+ base.mkdir()+ evil = tmp_path / "docs-evil"+ evil.mkdir()+ f = evil / "x.txt"+ f.write_text("x")+ assert PathValidator.confine_to_base([str(f)], base) == []++ def test_symlink_loop_is_skipped_not_raised(self, tmp_path):+ """A symlink loop makes Path.resolve() raise RuntimeError (not+ OSError); the loop must be skipped and the rest returned — otherwise a+ single planted loop would propagate to the caller."""+ base = tmp_path / "docs"+ base.mkdir()+ real = base / "real.txt"+ real.write_text("x")+ loop = base / "loop.txt"+ loop.symlink_to(loop) # self-referential loop -> ELOOP on resolve()+ assert PathValidator.confine_to_base([str(loop), str(real)], base) == [+ str(real)+ ]