Skip to content

~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.

fix(security): reject RAG glob patterns that escape the indexed folder (#4846)

LearningCircuita010a36e5028
diff --git a/changelog.d/4846.security.md b/changelog.d/4846.security.md
new file mode 100644
index 0000000000..8af6f5f6f4
--- /dev/null
+++ b/changelog.d/4846.security.md
@@ -0,0 +1 @@
+Local-folder RAG indexing now validates the supplied file glob patterns against an allowlist, rejecting any pattern that could escape the indexed folder (e.g. `../../etc/*` or an absolute `/etc/*`). Previously only the base folder was validated, so on multi-tenant/shared deployments a crafted pattern could read server-side files into the requesting user's library.
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 6fb09d672f..de67b271b2 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -9,6 +9,7 @@ Provides endpoints for managing RAG indexing of library documents:
"""
import os
+import re
from flask import (
Blueprint,
@@ -71,6 +72,25 @@ from ...constants import DEFAULT_SEARCH_TOOL
rag_bp = Blueprint("rag", __name__, url_prefix="/library")
+# Allowlist for user-supplied glob patterns. Each pattern is joined onto an
+# already-validated base directory and globbed, so it must not be able to
+# escape that directory. Only in-directory filename globs are allowed:
+# any path separator, parent reference, or character outside this set is
+# rejected. This also blocks a leading "/" — pathlib's "/" operator resets
+# to an absolute path when the right operand is absolute (``base / "/abs"``
+# yields ``/abs``), so a leading-slash absolute pattern would otherwise
+# escape the base too.
+# Anchored with ``\Z`` (not ``$``) so a trailing newline cannot slip through —
+# ``$`` matches just before a final "\n", which would make the predicate
+# depend on the caller stripping the pattern first.
+_SAFE_GLOB_PATTERN = re.compile(r"^[A-Za-z0-9._*?\[\]-]+\Z")
+
+
+def _is_safe_glob_pattern(pattern: str) -> bool:
+ """Return True for in-directory filename globs that cannot traverse out."""
+ return bool(_SAFE_GLOB_PATTERN.match(pattern)) and ".." not in pattern
+
+
# NOTE: Routes use session["username"] (not .get()) intentionally.
# @login_required guarantees the key exists; direct access fails fast
# if the decorator is ever removed.
@@ -1236,14 +1256,25 @@ def get_documents():
def index_local_library():
"""Index documents from a local folder with Server-Sent Events progress."""
folder_path = request.args.get("path")
- file_patterns = request.args.get(
+ raw_patterns = request.args.get(
"patterns", "*.pdf,*.txt,*.md,*.html"
).split(",")
+ file_patterns = [p.strip() for p in raw_patterns if p.strip()]
recursive = parse_bool_arg("recursive", default=True)
if not folder_path:
return jsonify({"success": False, "error": "Path is required"}), 400
+ # Reject glob patterns that could escape the validated base directory.
+ # The folder is validated below, but each pattern is joined onto it and
+ # globbed; a pattern with ".." or a leading-slash absolute pattern would
+ # otherwise read files outside the folder. Only in-directory filename
+ # globs are allowed.
+ if not file_patterns or not all(
+ _is_safe_glob_pattern(p) for p in file_patterns
+ ):
+ return jsonify({"success": False, "error": "Invalid file pattern"}), 400
+
# Validate and sanitize the path to prevent traversal attacks
try:
validated_path = PathValidator.validate_local_filesystem_path(
diff --git a/tests/research_library/routes/test_rag_routes_indexing.py b/tests/research_library/routes/test_rag_routes_indexing.py
index b613544e37..3b8643248d 100644
--- a/tests/research_library/routes/test_rag_routes_indexing.py
+++ b/tests/research_library/routes/test_rag_routes_indexing.py
@@ -22,6 +22,71 @@ class TestIndexLocalLibrary:
assert data["success"] is False
assert "path" in data["error"].lower()
+ def test_traversal_glob_pattern_returns_400(self, authenticated_client):
+ """A glob pattern that escapes the base dir is rejected before any
+ path handling, so no traversal read can occur."""
+ response = authenticated_client.get(
+ f"{RAG_PREFIX}/api/rag/index-local"
+ "?path=/tmp/docs&patterns=../../../etc/passwd"
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+ assert "pattern" in data["error"].lower()
+
+ def test_absolute_glob_pattern_returns_400(self, authenticated_client):
+ """An absolute pattern is rejected: pathlib's "/" resets to an absolute
+ path, so ``base / "/etc/*"`` would otherwise escape the folder."""
+ response = authenticated_client.get(
+ f"{RAG_PREFIX}/api/rag/index-local?path=/tmp/docs&patterns=/etc/*"
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+ assert "pattern" in data["error"].lower()
+
+ def test_empty_patterns_returns_400(self, authenticated_client):
+ """A patterns value that is only commas/whitespace leaves nothing to
+ match and is rejected rather than silently indexing everything."""
+ response = authenticated_client.get(
+ f"{RAG_PREFIX}/api/rag/index-local?path=/tmp/docs&patterns=,%20,"
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+ assert "pattern" in data["error"].lower()
+
+ def test_one_bad_pattern_in_list_rejects_whole_request(
+ self, authenticated_client
+ ):
+ """A single unsafe pattern alongside valid ones rejects the request
+ (the validation is an all()-gate, not a silent filter)."""
+ response = authenticated_client.get(
+ f"{RAG_PREFIX}/api/rag/index-local"
+ "?path=/tmp/docs&patterns=*.pdf,../etc/passwd"
+ )
+ assert response.status_code == 400
+ data = response.get_json()
+ assert data["success"] is False
+ assert "pattern" in data["error"].lower()
+
+ def test_valid_custom_patterns_pass_the_allowlist(
+ self, authenticated_client
+ ):
+ """Realistic custom globs must NOT be rejected by the allowlist —
+ guards against a future over-tightening of the regex. The request may
+ still fail because the path does not exist, but never for a pattern
+ reason."""
+ for pattern in ("data_*.csv", "*.PDF", "report-[0-9].txt"):
+ response = authenticated_client.get(
+ f"{RAG_PREFIX}/api/rag/index-local"
+ f"?path=/tmp/docs&patterns={pattern}"
+ )
+ error = (response.get_json() or {}).get("error") or ""
+ assert "pattern" not in error.lower(), (
+ f"{pattern!r} was wrongly rejected as an invalid pattern"
+ )
+
@patch(
"local_deep_research.research_library.routes.rag_routes.PathValidator"
)