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.

Merge branch 'origin/dev' into fix/security-vulnerabilities-pr899

LearningCircuit3cee19103fad
diff --cc .github/codeql/codeql-config.yml
index 09fa2bb0f3,2d15a05f8c..114c416426
--- a/.github/codeql/codeql-config.yml
+++ b/.github/codeql/codeql-config.yml
@@@ -5,22 -5,4 +5,23 @@@ paths-ignore
- '**/tests/**'
- '**/test_*.py'
- '**/*_test.py'
+ - 'src/local_deep_research/security/file_write_verifier.py'
+
+# Query filters - exclude specific queries for intentional security-reviewed features
+query-filters:
+ - exclude:
+ id: py/path-injection
+ # Justification: This query is excluded because:
+ # 1. The local file indexing feature (rag_routes.py:100) intentionally accepts
+ # user-provided paths to enable indexing personal documents
+ # 2. Security controls are in place:
+ # - System directory blocking (/etc, /sys, /proc, /dev, /root, /boot, /var/log)
+ # - Path resolution with .resolve() to prevent traversal
+ # - PathValidator for relative paths
+ # 3. This is the ONLY location in the codebase with intentional user-controlled paths
+ # (verified via codebase audit - see commit history for details)
+ # 4. This is a core feature requirement for a local research tool, not a vulnerability
+ # 5. Inline suppressions (lgtm, nosec, codeql) are not supported in CodeQL Python
+ #
+ # Alternative considered: File-specific exclusion via paths-ignore, but query-filters
+ # provides better documentation of WHY this specific security check is excluded.
diff --cc src/local_deep_research/research_library/routes/library_routes.py
index 862a1fbb98,a8126be4f5..41fd77de3e
--- a/src/local_deep_research/research_library/routes/library_routes.py
+++ b/src/local_deep_research/research_library/routes/library_routes.py
@@@ -25,10 -26,16 +26,16 @@@ from ...web.auth.decorators import logi
from ...web.utils.templates import render_template_with_defaults
from ...database.session_context import get_user_db_session
from ...database.models.research import ResearchResource
- from ...database.models.library import LibraryDocument, LibraryDownloadQueue
+ from ...database.models.library import (
+ Document as Document,
+ DocumentStatus,
+ DownloadQueue as LibraryDownloadQueue,
+ Collection,
+ )
+ from ...library.download_management import ResourceFilter
from ..services.download_service import DownloadService
from ..services.library_service import LibraryService
-from ..utils import open_file_location
+from ..utils import open_file_location, handle_api_error
from ...security.path_validator import PathValidator
from ...utilities.db_utils import get_settings_manager
diff --cc src/local_deep_research/research_library/routes/rag_routes.py
index cb27463937,b740a80700..514f1b3939
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@@ -18,19 -18,20 +18,25 @@@ from flask import
stream_with_context,
)
from loguru import logger
+import glob
import json
+import sys
import uuid
+from pathlib import Path
from typing import Optional
- from datetime import datetime, timezone
from ...web.auth.decorators import login_required
from ...utilities.db_utils import get_settings_manager
from ..services.library_rag_service import LibraryRAGService
+from ...security.path_validator import PathValidator
+from ..utils import handle_api_error
+ from ...database.models.library import (
+ Document,
+ Collection,
+ DocumentCollection,
+ SourceType,
+ EmbeddingProvider,
+ )
rag_bp = Blueprint("rag", __name__, url_prefix="/library")
@@@ -213,10 -351,68 +453,64 @@@ def get_current_settings()
},
}
)
- except Exception:
- logger.exception("Error getting RAG settings")
- return jsonify(
- {"success": False, "error": "Failed to retrieve RAG settings"}
- ), 500
+ except Exception as e:
+ return handle_api_error("getting RAG settings", e)
+ @rag_bp.route("/api/rag/test-embedding", methods=["POST"])
+ @login_required
+ def test_embedding():
+ """Test an embedding configuration by generating a test embedding."""
+ import time
+
+ try:
+ data = request.json
+ provider = data.get("provider")
+ model = data.get("model")
+ test_text = data.get("test_text", "This is a test.")
+
+ if not provider or not model:
+ return jsonify(
+ {"success": False, "error": "Provider and model are required"}
+ ), 400
+
+ # Import embedding functions
+ from ...embeddings.embeddings_config import (
+ get_embedding_function,
+ )
+
+ logger.info(
+ f"Testing embedding with provider={provider}, model={model}"
+ )
+
+ # Get embedding function with the specified configuration
+ start_time = time.time()
+ embedding_func = get_embedding_function(
+ provider=provider,
+ model_name=model,
+ )
+
+ # Generate test embedding
+ embedding = embedding_func([test_text])[0]
+ response_time_ms = int((time.time() - start_time) * 1000)
+
+ # Get embedding dimension
+ dimension = len(embedding) if hasattr(embedding, "__len__") else None
+
+ return jsonify(
+ {
+ "success": True,
+ "dimension": dimension,
+ "response_time_ms": response_time_ms,
+ "provider": provider,
+ "model": model,
+ }
+ )
+
+ except Exception as e:
- logger.exception("Error testing embedding")
- return jsonify({"success": False, "error": str(e)}), 500
++ return handle_api_error("testing embedding", e)
+
+
@rag_bp.route("/api/rag/models", methods=["GET"])
@login_required
def get_available_models():
@@@ -293,9 -506,13 +601,10 @@@ def get_index_info()
{"success": True, "info": None, "message": "No index found"}
)
+ logger.info(f"Found RAG index for collection_id: {collection_id}")
return jsonify({"success": True, "info": info})
except Exception as e:
- logger.exception("Error getting index info")
- return jsonify(
- {"success": False, "error": f"Operation failed: {type(e).__name__}"}
- ), 500
+ return handle_api_error("getting index info", e)
@rag_bp.route("/api/rag/stats", methods=["GET"])
@@@ -494,28 -773,65 +880,62 @@@ def configure_rag()
settings.set_setting("local_search_chunk_size", int(chunk_size))
settings.set_setting("local_search_chunk_overlap", int(chunk_overlap))
- # Create new RAG service with new configuration
- new_rag_service = LibraryRAGService(
- username=session["username"],
- embedding_model=embedding_model,
- embedding_provider=embedding_provider,
- chunk_size=int(chunk_size),
- chunk_overlap=int(chunk_overlap),
+ # Save new advanced settings
+ settings.set_setting("local_search_splitter_type", splitter_type)
+ # Convert list to JSON string for storage
+ if isinstance(text_separators, list):
+ text_separators_str = json_lib.dumps(text_separators)
+ else:
+ text_separators_str = text_separators
+ settings.set_setting(
+ "local_search_text_separators", text_separators_str
+ )
+ settings.set_setting("local_search_distance_metric", distance_metric)
+ # Convert boolean to string for storage
+ settings.set_setting(
+ "local_search_normalize_vectors", str(normalize_vectors).lower()
)
+ settings.set_setting("local_search_index_type", index_type)
+
+ # If collection_id is provided, update that collection's configuration
+ if collection_id:
+ # Create new RAG service with new configuration
+ new_rag_service = LibraryRAGService(
+ username=session["username"],
+ embedding_model=embedding_model,
+ embedding_provider=embedding_provider,
+ chunk_size=int(chunk_size),
+ chunk_overlap=int(chunk_overlap),
+ splitter_type=splitter_type,
+ text_separators=text_separators
+ if isinstance(text_separators, list)
+ else json_lib.loads(text_separators),
+ distance_metric=distance_metric,
+ normalize_vectors=normalize_vectors,
+ index_type=index_type,
+ )
- # Get or create new index with this configuration
- rag_index = new_rag_service._get_or_create_rag_index()
+ # Get or create new index with this configuration
+ rag_index = new_rag_service._get_or_create_rag_index(collection_id)
- return jsonify(
- {
- "success": True,
- "message": "Configuration updated. You can now index documents with the new settings.",
- "index_hash": rag_index.index_hash,
- }
- )
+ return jsonify(
+ {
+ "success": True,
+ "message": "Configuration updated for collection. You can now index documents with the new settings.",
+ "index_hash": rag_index.index_hash,
+ }
+ )
+ else:
+ # Just saving default settings without updating a specific collection
+ return jsonify(
+ {
+ "success": True,
+ "message": "Default embedding settings saved successfully. New collections will use these settings.",
+ }
+ )
except Exception as e:
- logger.exception("Error configuring RAG")
- return jsonify(
- {"success": False, "error": f"Operation failed: {type(e).__name__}"}
- ), 500
+ return handle_api_error("configuring RAG", e)
@rag_bp.route("/api/rag/documents", methods=["GET"])
@@@ -546,12 -928,44 +1032,41 @@@ def get_documents()
if doc.created_at
else None,
}
- for doc in text_docs
+ for doc, doc_collection, rag_status in results
]
- return jsonify({"success": True, "documents": documents})
+ # Debug logging to help diagnose indexing status issues
+ indexed_count = sum(1 for d in documents if d["rag_indexed"])
+
+ # Additional debug: check rag_document_status for this collection
+ all_indexed_statuses = (
+ db_session.query(RagDocumentStatus)
+ .filter_by(collection_id=collection_id)
+ .all()
+ )
+ logger.info(
+ f"rag_document_status table shows: {len(all_indexed_statuses)} documents indexed for collection {collection_id}"
+ )
+
+ logger.info(
+ f"Returning {len(documents)} documents on page {page}: "
+ f"{indexed_count} indexed, {len(documents) - indexed_count} not indexed"
+ )
+
+ return jsonify(
+ {
+ "success": True,
+ "documents": documents,
+ "pagination": {
+ "page": page,
+ "per_page": per_page,
+ "total": total_count,
+ "pages": (total_count + per_page - 1) // per_page,
+ },
+ }
+ )
except Exception as e:
- logger.exception("Error getting documents")
- return jsonify(
- {"success": False, "error": f"Operation failed: {type(e).__name__}"}
- ), 500
+ return handle_api_error("getting documents", e)
@rag_bp.route("/api/rag/index-local", methods=["GET"])