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.

security: add SHA256 checksum validation for FAISS index deserialization

LearningCircuit0333ae5471ab
diff --git a/src/local_deep_research/research_library/services/library_rag_service.py b/src/local_deep_research/research_library/services/library_rag_service.py
index ab9b2208bd..f2a76896c0 100644
--- a/src/local_deep_research/research_library/services/library_rag_service.py
+++ b/src/local_deep_research/research_library/services/library_rag_service.py
@@ -27,6 +27,7 @@ from ...web_search_engines.engines.search_engine_local import (
LocalEmbeddingManager,
)
import hashlib
+import json
from faiss import IndexFlatL2
from langchain_community.vectorstores import FAISS
from langchain_community.docstore.in_memory import InMemoryDocstore
@@ -158,6 +159,65 @@ class LibraryRAGService:
return rag_index
+ def _calculate_index_checksum(self, index_path: Path) -> str:
+ """Calculate SHA256 checksum of FAISS index file."""
+ sha256_hash = hashlib.sha256()
+ with open(index_path, "rb") as f:
+ # Read in chunks to handle large files
+ for byte_block in iter(lambda: f.read(4096), b""):
+ sha256_hash.update(byte_block)
+ return sha256_hash.hexdigest()
+
+ def _save_index_checksum(self, index_path: Path, checksum: str):
+ """Save checksum to metadata file."""
+ checksum_path = index_path.parent / f"{index_path.stem}.checksum"
+ checksum_data = {
+ "checksum": checksum,
+ "algorithm": "sha256",
+ "created_at": datetime.now(UTC).isoformat(),
+ }
+ with open(checksum_path, "w") as f:
+ json.dump(checksum_data, f)
+
+ def _verify_index_checksum(self, index_path: Path) -> bool:
+ """Verify FAISS index checksum. Returns True if valid, False otherwise."""
+ checksum_path = index_path.parent / f"{index_path.stem}.checksum"
+
+ if not checksum_path.exists():
+ logger.warning(
+ f"No checksum file found for {index_path}, creating one"
+ )
+ # Calculate and save checksum for existing index
+ try:
+ checksum = self._calculate_index_checksum(index_path)
+ self._save_index_checksum(index_path, checksum)
+ return True
+ except Exception:
+ logger.exception("Failed to create checksum")
+ return False
+
+ try:
+ with open(checksum_path, "r") as f:
+ checksum_data = json.load(f)
+
+ stored_checksum = checksum_data["checksum"]
+ current_checksum = self._calculate_index_checksum(index_path)
+
+ if stored_checksum != current_checksum:
+ logger.error(
+ f"SECURITY: Checksum mismatch for {index_path}! "
+ f"Expected: {stored_checksum}, Got: {current_checksum}. "
+ f"Index may be corrupted or tampered with."
+ )
+ return False
+
+ logger.debug(f"Checksum verified for {index_path}")
+ return True
+
+ except Exception:
+ logger.exception("Failed to verify checksum")
+ return False
+
def load_or_create_faiss_index(self) -> FAISS:
"""
Load existing FAISS index or create new one.
@@ -171,21 +231,36 @@ class LibraryRAGService:
index_path = Path(rag_index.index_path)
if index_path.exists():
- try:
- # Load existing FAISS index
- faiss_index = FAISS.load_local(
- str(index_path.parent),
- self.embedding_manager.embeddings,
- index_name=index_path.stem,
- allow_dangerous_deserialization=True,
- normalize_L2=True,
- )
- logger.info(f"Loaded existing FAISS index from {index_path}")
- return faiss_index
- except Exception as e:
- logger.warning(
- f"Failed to load FAISS index: {e}, creating new one"
+ # Verify checksum before loading
+ if not self._verify_index_checksum(index_path):
+ logger.error(
+ f"Checksum verification failed for {index_path}, refusing to load. "
+ f"Creating new index."
)
+ # Remove corrupted index
+ try:
+ index_path.unlink()
+ logger.info(f"Removed corrupted index file: {index_path}")
+ except Exception:
+ logger.exception("Failed to remove corrupted index")
+ else:
+ try:
+ # Load existing FAISS index (checksum verified)
+ faiss_index = FAISS.load_local(
+ str(index_path.parent),
+ self.embedding_manager.embeddings,
+ index_name=index_path.stem,
+ allow_dangerous_deserialization=True,
+ normalize_L2=True,
+ )
+ logger.info(
+ f"Loaded existing FAISS index from {index_path}"
+ )
+ return faiss_index
+ except Exception as e:
+ logger.warning(
+ f"Failed to load FAISS index: {e}, creating new one"
+ )
# Create new FAISS index
logger.info(
@@ -376,7 +451,10 @@ class LibraryRAGService:
self.faiss_index.save_local(
str(index_path.parent), index_name=index_path.stem
)
- logger.info(f"Saved FAISS index to {index_path}")
+ # Calculate and save checksum for security
+ checksum = self._calculate_index_checksum(index_path)
+ self._save_index_checksum(index_path, checksum)
+ logger.info(f"Saved FAISS index to {index_path} with checksum")
# Update LibraryTextDocument with RAG status
# Re-query to ensure we have fresh object in this session
@@ -855,7 +933,10 @@ class LibraryRAGService:
self.faiss_index.save_local(
str(index_path.parent), index_name=index_path.stem
)
- logger.info(f"Saved FAISS index to {index_path}")
+ # Calculate and save checksum for security
+ checksum = self._calculate_index_checksum(index_path)
+ self._save_index_checksum(index_path, checksum)
+ logger.info(f"Saved FAISS index to {index_path} with checksum")
logger.info(
f"Successfully indexed local file {file_path} with {len(chunks)} chunks"
@@ -988,6 +1069,9 @@ class LibraryRAGService:
self.faiss_index.save_local(
str(index_path.parent), index_name=index_path.stem
)
+ # Calculate and save checksum for security
+ checksum = self._calculate_index_checksum(index_path)
+ self._save_index_checksum(index_path, checksum)
logger.info(
f"Successfully indexed user document {user_doc.filename} with {len(chunks)} chunks"
@@ -1056,6 +1140,11 @@ class LibraryRAGService:
str(index_path.parent),
index_name=index_path.stem,
)
+ # Calculate and save checksum for security
+ checksum = self._calculate_index_checksum(
+ index_path
+ )
+ self._save_index_checksum(index_path, checksum)
except Exception as e:
logger.warning(
f"Could not delete chunks from FAISS: {e}"