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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LLMGuardian Vectors Package
|
| 2 |
+
|
| 3 |
+
The Vectors package provides comprehensive security tools for handling vector embeddings, RAG (Retrieval-Augmented Generation) operations, and vector storage. It addresses key security concerns outlined in the OWASP Top 10 for LLM applications, particularly focusing on vector and embedding weaknesses (LLM08).
|
| 4 |
+
|
| 5 |
+
## Components
|
| 6 |
+
|
| 7 |
+
### 1. Embedding Validator (`embedding_validator.py`)
|
| 8 |
+
Validates and secures embedding vectors against manipulation and attacks.
|
| 9 |
+
|
| 10 |
+
```python
|
| 11 |
+
from llmguardian.vectors import EmbeddingValidator
|
| 12 |
+
|
| 13 |
+
# Initialize validator
|
| 14 |
+
validator = EmbeddingValidator()
|
| 15 |
+
|
| 16 |
+
# Validate embedding
|
| 17 |
+
result = validator.validate_embedding(
|
| 18 |
+
embedding=your_embedding,
|
| 19 |
+
metadata={
|
| 20 |
+
"model": "openai-ada-002",
|
| 21 |
+
"source": "user_documents"
|
| 22 |
+
}
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
if result.is_valid:
|
| 26 |
+
normalized_embedding = result.normalized_embedding
|
| 27 |
+
print(f"Embedding metadata: {result.metadata}")
|
| 28 |
+
else:
|
| 29 |
+
print(f"Validation errors: {result.errors}")
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
Key Features:
|
| 33 |
+
- Dimension validation
|
| 34 |
+
- Model compatibility checks
|
| 35 |
+
- Normalization
|
| 36 |
+
- Anomaly detection
|
| 37 |
+
- Checksum verification
|
| 38 |
+
|
| 39 |
+
### 2. Vector Scanner (`vector_scanner.py`)
|
| 40 |
+
Scans vector databases for security vulnerabilities and potential attacks.
|
| 41 |
+
|
| 42 |
+
```python
|
| 43 |
+
from llmguardian.vectors import VectorScanner
|
| 44 |
+
from llmguardian.vectors.vector_scanner import ScanTarget, VulnerabilityReport
|
| 45 |
+
|
| 46 |
+
# Initialize scanner
|
| 47 |
+
scanner = VectorScanner()
|
| 48 |
+
|
| 49 |
+
# Create scan target
|
| 50 |
+
target = ScanTarget(
|
| 51 |
+
vectors=your_vectors,
|
| 52 |
+
metadata=vector_metadata,
|
| 53 |
+
source="vector_db"
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
# Perform scan
|
| 57 |
+
result = scanner.scan_vectors(target)
|
| 58 |
+
|
| 59 |
+
if result.vulnerabilities:
|
| 60 |
+
for vuln in result.vulnerabilities:
|
| 61 |
+
print(f"Type: {vuln.vulnerability_type}")
|
| 62 |
+
print(f"Severity: {vuln.severity}")
|
| 63 |
+
print(f"Recommendations: {vuln.recommendations}")
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
Key Features:
|
| 67 |
+
- Poisoning detection
|
| 68 |
+
- Malicious payload scanning
|
| 69 |
+
- Data leakage detection
|
| 70 |
+
- Clustering attack detection
|
| 71 |
+
- Index manipulation checks
|
| 72 |
+
|
| 73 |
+
### 3. Retrieval Guard (`retrieval_guard.py`)
|
| 74 |
+
Secures RAG operations and protects against retrieval-based attacks.
|
| 75 |
+
|
| 76 |
+
```python
|
| 77 |
+
from llmguardian.vectors import RetrievalGuard
|
| 78 |
+
from llmguardian.vectors.retrieval_guard import RetrievalContext
|
| 79 |
+
|
| 80 |
+
# Initialize guard
|
| 81 |
+
guard = RetrievalGuard()
|
| 82 |
+
|
| 83 |
+
# Create context
|
| 84 |
+
context = RetrievalContext(
|
| 85 |
+
query_embedding=query_emb,
|
| 86 |
+
retrieved_embeddings=retrieved_embs,
|
| 87 |
+
retrieved_content=retrieved_texts,
|
| 88 |
+
metadata={"source": "knowledge_base"}
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
# Check retrieval
|
| 92 |
+
result = guard.check_retrieval(context)
|
| 93 |
+
|
| 94 |
+
if not result.is_safe:
|
| 95 |
+
print(f"Detected risks: {result.risks}")
|
| 96 |
+
print(f"Failed checks: {result.checks_failed}")
|
| 97 |
+
# Use filtered content
|
| 98 |
+
safe_content = result.filtered_content
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
Key Features:
|
| 102 |
+
- Relevance validation
|
| 103 |
+
- Context injection detection
|
| 104 |
+
- Content filtering
|
| 105 |
+
- Privacy protection
|
| 106 |
+
- Chunking validation
|
| 107 |
+
|
| 108 |
+
### 4. Storage Validator (`storage_validator.py`)
|
| 109 |
+
Validates vector storage security and integrity.
|
| 110 |
+
|
| 111 |
+
```python
|
| 112 |
+
from llmguardian.vectors import StorageValidator
|
| 113 |
+
from llmguardian.vectors.storage_validator import StorageMetadata
|
| 114 |
+
|
| 115 |
+
# Initialize validator
|
| 116 |
+
validator = StorageValidator()
|
| 117 |
+
|
| 118 |
+
# Create metadata
|
| 119 |
+
metadata = StorageMetadata(
|
| 120 |
+
storage_type="vector_db",
|
| 121 |
+
vector_count=1000,
|
| 122 |
+
dimension=1536,
|
| 123 |
+
created_at=datetime.utcnow(),
|
| 124 |
+
updated_at=datetime.utcnow(),
|
| 125 |
+
version="1.0.0",
|
| 126 |
+
checksum="...",
|
| 127 |
+
encryption_info={"algorithm": "AES-256-GCM"}
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# Validate storage
|
| 131 |
+
result = validator.validate_storage(
|
| 132 |
+
metadata=metadata,
|
| 133 |
+
vectors=your_vectors,
|
| 134 |
+
context={"authentication": "enabled"}
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
if not result.is_valid:
|
| 138 |
+
print(f"Risks detected: {result.risks}")
|
| 139 |
+
print(f"Violations: {result.violations}")
|
| 140 |
+
print(f"Recommendations: {result.recommendations}")
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
Key Features:
|
| 144 |
+
- Access control validation
|
| 145 |
+
- Data integrity checks
|
| 146 |
+
- Index security validation
|
| 147 |
+
- Version control checks
|
| 148 |
+
- Encryption validation
|
| 149 |
+
|
| 150 |
+
## Installation
|
| 151 |
+
|
| 152 |
+
```bash
|
| 153 |
+
pip install llmguardian
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
For development:
|
| 157 |
+
```bash
|
| 158 |
+
pip install -r requirements/dev.txt
|
| 159 |
+
```
|
| 160 |
+
|
| 161 |
+
## Best Practices
|
| 162 |
+
|
| 163 |
+
### 1. Embedding Security
|
| 164 |
+
- Validate all embeddings before storage
|
| 165 |
+
- Monitor for anomalies
|
| 166 |
+
- Implement proper normalization
|
| 167 |
+
- Maintain model compatibility
|
| 168 |
+
- Regular integrity checks
|
| 169 |
+
|
| 170 |
+
### 2. Vector Database Security
|
| 171 |
+
- Regular security scans
|
| 172 |
+
- Monitor for poisoning attempts
|
| 173 |
+
- Implement access controls
|
| 174 |
+
- Secure indexing mechanisms
|
| 175 |
+
- Data integrity validation
|
| 176 |
+
|
| 177 |
+
### 3. RAG Security
|
| 178 |
+
- Validate all retrievals
|
| 179 |
+
- Monitor relevance scores
|
| 180 |
+
- Implement content filtering
|
| 181 |
+
- Protect against injection
|
| 182 |
+
- Secure chunking mechanisms
|
| 183 |
+
|
| 184 |
+
### 4. Storage Security
|
| 185 |
+
- Enable encryption
|
| 186 |
+
- Regular backups
|
| 187 |
+
- Version control
|
| 188 |
+
- Access logging
|
| 189 |
+
- Integrity monitoring
|
| 190 |
+
|
| 191 |
+
## Integration Example
|
| 192 |
+
|
| 193 |
+
Here's how to integrate all vector security components:
|
| 194 |
+
|
| 195 |
+
```python
|
| 196 |
+
from llmguardian.vectors import (
|
| 197 |
+
EmbeddingValidator,
|
| 198 |
+
VectorScanner,
|
| 199 |
+
RetrievalGuard,
|
| 200 |
+
StorageValidator
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
class SecureVectorSystem:
|
| 204 |
+
def __init__(self):
|
| 205 |
+
self.embedding_validator = EmbeddingValidator()
|
| 206 |
+
self.vector_scanner = VectorScanner()
|
| 207 |
+
self.retrieval_guard = RetrievalGuard()
|
| 208 |
+
self.storage_validator = StorageValidator()
|
| 209 |
+
|
| 210 |
+
async def secure_rag_operation(
|
| 211 |
+
self,
|
| 212 |
+
query_embedding: np.ndarray,
|
| 213 |
+
knowledge_base: Dict[str, Any]
|
| 214 |
+
) -> List[str]:
|
| 215 |
+
try:
|
| 216 |
+
# 1. Validate query embedding
|
| 217 |
+
query_result = self.embedding_validator.validate_embedding(
|
| 218 |
+
query_embedding,
|
| 219 |
+
metadata={"source": "user_query"}
|
| 220 |
+
)
|
| 221 |
+
if not query_result.is_valid:
|
| 222 |
+
raise SecurityError("Invalid query embedding")
|
| 223 |
+
|
| 224 |
+
# 2. Scan vector database
|
| 225 |
+
scan_result = self.vector_scanner.scan_vectors(
|
| 226 |
+
ScanTarget(
|
| 227 |
+
vectors=knowledge_base["vectors"],
|
| 228 |
+
metadata=knowledge_base["metadata"]
|
| 229 |
+
)
|
| 230 |
+
)
|
| 231 |
+
if scan_result.vulnerabilities:
|
| 232 |
+
self._handle_vulnerabilities(scan_result.vulnerabilities)
|
| 233 |
+
|
| 234 |
+
# 3. Perform and guard retrieval
|
| 235 |
+
retrieval_result = self.retrieval_guard.check_retrieval(
|
| 236 |
+
RetrievalContext(
|
| 237 |
+
query_embedding=query_result.normalized_embedding,
|
| 238 |
+
retrieved_embeddings=retrieved_embeddings,
|
| 239 |
+
retrieved_content=retrieved_texts
|
| 240 |
+
)
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
# 4. Validate storage
|
| 244 |
+
storage_result = self.storage_validator.validate_storage(
|
| 245 |
+
metadata=storage_metadata,
|
| 246 |
+
vectors=knowledge_base["vectors"]
|
| 247 |
+
)
|
| 248 |
+
if not storage_result.is_valid:
|
| 249 |
+
self._handle_storage_issues(storage_result)
|
| 250 |
+
|
| 251 |
+
return retrieval_result.filtered_content
|
| 252 |
+
|
| 253 |
+
except Exception as e:
|
| 254 |
+
logger.error(f"Secure RAG operation failed: {str(e)}")
|
| 255 |
+
raise
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
## Security Considerations
|
| 259 |
+
|
| 260 |
+
1. **Embedding Security**
|
| 261 |
+
- Validate dimensions
|
| 262 |
+
- Check for anomalies
|
| 263 |
+
- Monitor for poisoning
|
| 264 |
+
- Implement integrity checks
|
| 265 |
+
|
| 266 |
+
2. **Vector Database Security**
|
| 267 |
+
- Regular scanning
|
| 268 |
+
- Access control
|
| 269 |
+
- Integrity validation
|
| 270 |
+
- Backup strategy
|
| 271 |
+
|
| 272 |
+
3. **RAG Security**
|
| 273 |
+
- Content validation
|
| 274 |
+
- Query inspection
|
| 275 |
+
- Result filtering
|
| 276 |
+
- Context protection
|
| 277 |
+
|
| 278 |
+
4. **Storage Security**
|
| 279 |
+
- Encryption
|
| 280 |
+
- Access controls
|
| 281 |
+
- Version management
|
| 282 |
+
- Regular validation
|
| 283 |
+
|
| 284 |
+
### Testing
|
| 285 |
+
```bash
|
| 286 |
+
# Run vector package tests
|
| 287 |
+
pytest tests/vectors/
|
| 288 |
+
|
| 289 |
+
# Run specific test file
|
| 290 |
+
pytest tests/vectors/test_embedding_validator.py
|
| 291 |
+
```
|
src/llmguardian/vectors/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
vectors/__init__.py - Vector security initialization
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from .embedding_validator import EmbeddingValidator
|
| 6 |
+
from .vector_scanner import VectorScanner
|
| 7 |
+
from .retrieval_guard import RetrievalGuard
|
| 8 |
+
from .storage_validator import StorageValidator
|
| 9 |
+
|
| 10 |
+
__all__ = [
|
| 11 |
+
'EmbeddingValidator',
|
| 12 |
+
'VectorScanner',
|
| 13 |
+
'RetrievalGuard',
|
| 14 |
+
'StorageValidator'
|
| 15 |
+
]
|
src/llmguardian/vectors/embedding_validator.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 5 |
+
import numpy as np
|
| 6 |
+
from typing import Dict, List, Optional, Any, Tuple
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
import hashlib
|
| 10 |
+
from ..core.logger import SecurityLogger
|
| 11 |
+
from ..core.exceptions import ValidationError
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class EmbeddingMetadata:
|
| 15 |
+
"""Metadata for embeddings"""
|
| 16 |
+
dimension: int
|
| 17 |
+
model: str
|
| 18 |
+
timestamp: datetime
|
| 19 |
+
source: str
|
| 20 |
+
checksum: str
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class ValidationResult:
|
| 24 |
+
"""Result of embedding validation"""
|
| 25 |
+
is_valid: bool
|
| 26 |
+
errors: List[str]
|
| 27 |
+
normalized_embedding: Optional[np.ndarray]
|
| 28 |
+
metadata: Dict[str, Any]
|
| 29 |
+
|
| 30 |
+
class EmbeddingValidator:
|
| 31 |
+
"""Validates and secures embeddings"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, security_logger: Optional[SecurityLogger] = None):
|
| 34 |
+
self.security_logger = security_logger
|
| 35 |
+
self.known_models = {
|
| 36 |
+
"openai-ada-002": 1536,
|
| 37 |
+
"openai-text-embedding-ada-002": 1536,
|
| 38 |
+
"huggingface-bert-base": 768,
|
| 39 |
+
"huggingface-mpnet-base": 768
|
| 40 |
+
}
|
| 41 |
+
self.max_dimension = 2048
|
| 42 |
+
self.min_dimension = 64
|
| 43 |
+
|
| 44 |
+
def validate_embedding(self,
|
| 45 |
+
embedding: np.ndarray,
|
| 46 |
+
metadata: Optional[Dict[str, Any]] = None) -> ValidationResult:
|
| 47 |
+
"""Validate an embedding vector"""
|
| 48 |
+
try:
|
| 49 |
+
errors = []
|
| 50 |
+
|
| 51 |
+
# Check dimensions
|
| 52 |
+
if embedding.ndim != 1:
|
| 53 |
+
errors.append("Embedding must be a 1D vector")
|
| 54 |
+
|
| 55 |
+
if len(embedding) > self.max_dimension:
|
| 56 |
+
errors.append(f"Embedding dimension exceeds maximum {self.max_dimension}")
|
| 57 |
+
|
| 58 |
+
if len(embedding) < self.min_dimension:
|
| 59 |
+
errors.append(f"Embedding dimension below minimum {self.min_dimension}")
|
| 60 |
+
|
| 61 |
+
# Check for NaN or Inf values
|
| 62 |
+
if np.any(np.isnan(embedding)) or np.any(np.isinf(embedding)):
|
| 63 |
+
errors.append("Embedding contains NaN or Inf values")
|
| 64 |
+
|
| 65 |
+
# Validate against known models
|
| 66 |
+
if metadata and 'model' in metadata:
|
| 67 |
+
if metadata['model'] in self.known_models:
|
| 68 |
+
expected_dim = self.known_models[metadata['model']]
|
| 69 |
+
if len(embedding) != expected_dim:
|
| 70 |
+
errors.append(
|
| 71 |
+
f"Dimension mismatch for model {metadata['model']}: "
|
| 72 |
+
f"expected {expected_dim}, got {len(embedding)}"
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Normalize embedding
|
| 76 |
+
normalized = None
|
| 77 |
+
if not errors:
|
| 78 |
+
normalized = self._normalize_embedding(embedding)
|
| 79 |
+
|
| 80 |
+
# Calculate checksum
|
| 81 |
+
checksum = self._calculate_checksum(normalized)
|
| 82 |
+
|
| 83 |
+
# Create metadata
|
| 84 |
+
embedding_metadata = EmbeddingMetadata(
|
| 85 |
+
dimension=len(embedding),
|
| 86 |
+
model=metadata.get('model', 'unknown') if metadata else 'unknown',
|
| 87 |
+
timestamp=datetime.utcnow(),
|
| 88 |
+
source=metadata.get('source', 'unknown') if metadata else 'unknown',
|
| 89 |
+
checksum=checksum
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
result = ValidationResult(
|
| 93 |
+
is_valid=len(errors) == 0,
|
| 94 |
+
errors=errors,
|
| 95 |
+
normalized_embedding=normalized,
|
| 96 |
+
metadata=vars(embedding_metadata) if not errors else {}
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
if errors and self.security_logger:
|
| 100 |
+
self.security_logger.log_security_event(
|
| 101 |
+
"embedding_validation_failure",
|
| 102 |
+
errors=errors,
|
| 103 |
+
metadata=metadata
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
return result
|
| 107 |
+
|
| 108 |
+
except Exception as e:
|
| 109 |
+
if self.security_logger:
|
| 110 |
+
self.security_logger.log_security_event(
|
| 111 |
+
"embedding_validation_error",
|
| 112 |
+
error=str(e)
|
| 113 |
+
)
|
| 114 |
+
raise ValidationError(f"Embedding validation failed: {str(e)}")
|
| 115 |
+
|
| 116 |
+
def _normalize_embedding(self, embedding: np.ndarray) -> np.ndarray:
|
| 117 |
+
"""Normalize embedding vector"""
|
| 118 |
+
norm = np.linalg.norm(embedding)
|
| 119 |
+
if norm > 0:
|
| 120 |
+
return embedding / norm
|
| 121 |
+
return embedding
|
| 122 |
+
|
| 123 |
+
def _calculate_checksum(self, embedding: np.ndarray) -> str:
|
| 124 |
+
"""Calculate checksum for embedding"""
|
| 125 |
+
return hashlib.sha256(embedding.tobytes()).hexdigest()
|
| 126 |
+
|
| 127 |
+
def check_similarity(self,
|
| 128 |
+
embedding1: np.ndarray,
|
| 129 |
+
embedding2: np.ndarray) -> float:
|
| 130 |
+
"""Check similarity between two embeddings"""
|
| 131 |
+
try:
|
| 132 |
+
# Validate both embeddings
|
| 133 |
+
result1 = self.validate_embedding(embedding1)
|
| 134 |
+
result2 = self.validate_embedding(embedding2)
|
| 135 |
+
|
| 136 |
+
if not result1.is_valid or not result2.is_valid:
|
| 137 |
+
raise ValidationError("Invalid embeddings for similarity check")
|
| 138 |
+
|
| 139 |
+
# Calculate cosine similarity
|
| 140 |
+
return float(np.dot(
|
| 141 |
+
result1.normalized_embedding,
|
| 142 |
+
result2.normalized_embedding
|
| 143 |
+
))
|
| 144 |
+
|
| 145 |
+
except Exception as e:
|
| 146 |
+
if self.security_logger:
|
| 147 |
+
self.security_logger.log_security_event(
|
| 148 |
+
"similarity_check_error",
|
| 149 |
+
error=str(e)
|
| 150 |
+
)
|
| 151 |
+
raise ValidationError(f"Similarity check failed: {str(e)}")
|
| 152 |
+
|
| 153 |
+
def detect_anomalies(self,
|
| 154 |
+
embeddings: List[np.ndarray],
|
| 155 |
+
threshold: float = 0.8) -> List[int]:
|
| 156 |
+
"""Detect anomalous embeddings in a set"""
|
| 157 |
+
try:
|
| 158 |
+
anomalies = []
|
| 159 |
+
|
| 160 |
+
# Validate all embeddings
|
| 161 |
+
valid_embeddings = []
|
| 162 |
+
for i, emb in enumerate(embeddings):
|
| 163 |
+
result = self.validate_embedding(emb)
|
| 164 |
+
if result.is_valid:
|
| 165 |
+
valid_embeddings.append(result.normalized_embedding)
|
| 166 |
+
else:
|
| 167 |
+
anomalies.append(i)
|
| 168 |
+
|
| 169 |
+
if not valid_embeddings:
|
| 170 |
+
return list(range(len(embeddings)))
|
| 171 |
+
|
| 172 |
+
# Calculate mean embedding
|
| 173 |
+
mean_embedding = np.mean(valid_embeddings, axis=0)
|
| 174 |
+
mean_embedding = self._normalize_embedding(mean_embedding)
|
| 175 |
+
|
| 176 |
+
# Check similarities
|
| 177 |
+
for i, emb in enumerate(valid_embeddings):
|
| 178 |
+
similarity = float(np.dot(emb, mean_embedding))
|
| 179 |
+
if similarity < threshold:
|
| 180 |
+
anomalies.append(i)
|
| 181 |
+
|
| 182 |
+
if anomalies and self.security_logger:
|
| 183 |
+
self.security_logger.log_security_event(
|
| 184 |
+
"anomalous_embeddings_detected",
|
| 185 |
+
count=len(anomalies),
|
| 186 |
+
total_embeddings=len(embeddings)
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
return anomalies
|
| 190 |
+
|
| 191 |
+
except Exception as e:
|
| 192 |
+
if self.security_logger:
|
| 193 |
+
self.security_logger.log_security_event(
|
| 194 |
+
"anomaly_detection_error",
|
| 195 |
+
error=str(e)
|
| 196 |
+
)
|
| 197 |
+
raise ValidationError(f"Anomaly detection failed: {str(e)}")
|
| 198 |
+
|
| 199 |
+
def add_known_model(self, model_name: str, dimension: int):
|
| 200 |
+
"""Add a known model to the validator"""
|
| 201 |
+
self.known_models[model_name] = dimension
|
| 202 |
+
|
| 203 |
+
def verify_metadata(self, metadata: Dict[str, Any]) -> bool:
|
| 204 |
+
"""Verify embedding metadata"""
|
| 205 |
+
required_fields = {'model', 'dimension', 'timestamp'}
|
| 206 |
+
return all(field in metadata for field in required_fields)
|
src/llmguardian/vectors/retrieval_guard.py
ADDED
|
@@ -0,0 +1,743 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
vectors/retrieval_guard.py - Security for Retrieval-Augmented Generation (RAG) operations
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from typing import Dict, List, Optional, Any, Tuple, Set
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from enum import Enum
|
| 10 |
+
import hashlib
|
| 11 |
+
import re
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
from ..core.logger import SecurityLogger
|
| 14 |
+
from ..core.exceptions import SecurityError
|
| 15 |
+
|
| 16 |
+
class RetrievalRisk(Enum):
|
| 17 |
+
"""Types of retrieval-related risks"""
|
| 18 |
+
RELEVANCE_MANIPULATION = "relevance_manipulation"
|
| 19 |
+
CONTEXT_INJECTION = "context_injection"
|
| 20 |
+
DATA_POISONING = "data_poisoning"
|
| 21 |
+
RETRIEVAL_BYPASS = "retrieval_bypass"
|
| 22 |
+
PRIVACY_LEAK = "privacy_leak"
|
| 23 |
+
EMBEDDING_ATTACK = "embedding_attack"
|
| 24 |
+
CHUNKING_MANIPULATION = "chunking_manipulation"
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class RetrievalContext:
|
| 28 |
+
"""Context for retrieval operations"""
|
| 29 |
+
query_embedding: np.ndarray
|
| 30 |
+
retrieved_embeddings: List[np.ndarray]
|
| 31 |
+
retrieved_content: List[str]
|
| 32 |
+
metadata: Optional[Dict[str, Any]] = None
|
| 33 |
+
source: Optional[str] = None
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class SecurityCheck:
|
| 37 |
+
"""Security check definition"""
|
| 38 |
+
name: str
|
| 39 |
+
description: str
|
| 40 |
+
threshold: float
|
| 41 |
+
severity: int # 1-10
|
| 42 |
+
|
| 43 |
+
@dataclass
|
| 44 |
+
class CheckResult:
|
| 45 |
+
"""Result of a security check"""
|
| 46 |
+
check_name: str
|
| 47 |
+
passed: bool
|
| 48 |
+
risk_level: float
|
| 49 |
+
details: Dict[str, Any]
|
| 50 |
+
recommendations: List[str]
|
| 51 |
+
|
| 52 |
+
@dataclass
|
| 53 |
+
class GuardResult:
|
| 54 |
+
"""Complete result of retrieval guard checks"""
|
| 55 |
+
is_safe: bool
|
| 56 |
+
checks_passed: List[str]
|
| 57 |
+
checks_failed: List[str]
|
| 58 |
+
risks: List[RetrievalRisk]
|
| 59 |
+
filtered_content: List[str]
|
| 60 |
+
metadata: Dict[str, Any]
|
| 61 |
+
|
| 62 |
+
class RetrievalGuard:
|
| 63 |
+
"""Security guard for RAG operations"""
|
| 64 |
+
|
| 65 |
+
def __init__(self, security_logger: Optional[SecurityLogger] = None):
|
| 66 |
+
self.security_logger = security_logger
|
| 67 |
+
self.security_checks = self._initialize_security_checks()
|
| 68 |
+
self.risk_patterns = self._initialize_risk_patterns()
|
| 69 |
+
self.check_history: List[GuardResult] = []
|
| 70 |
+
|
| 71 |
+
def _initialize_security_checks(self) -> Dict[str, SecurityCheck]:
|
| 72 |
+
"""Initialize security checks"""
|
| 73 |
+
return {
|
| 74 |
+
"relevance": SecurityCheck(
|
| 75 |
+
name="relevance_check",
|
| 76 |
+
description="Check relevance between query and retrieved content",
|
| 77 |
+
threshold=0.7,
|
| 78 |
+
severity=7
|
| 79 |
+
),
|
| 80 |
+
"consistency": SecurityCheck(
|
| 81 |
+
name="consistency_check",
|
| 82 |
+
description="Check consistency among retrieved chunks",
|
| 83 |
+
threshold=0.6,
|
| 84 |
+
severity=6
|
| 85 |
+
),
|
| 86 |
+
"privacy": SecurityCheck(
|
| 87 |
+
name="privacy_check",
|
| 88 |
+
description="Check for potential privacy leaks",
|
| 89 |
+
threshold=0.8,
|
| 90 |
+
severity=9
|
| 91 |
+
),
|
| 92 |
+
"injection": SecurityCheck(
|
| 93 |
+
name="injection_check",
|
| 94 |
+
description="Check for context injection attempts",
|
| 95 |
+
threshold=0.75,
|
| 96 |
+
severity=8
|
| 97 |
+
),
|
| 98 |
+
"chunking": SecurityCheck(
|
| 99 |
+
name="chunking_check",
|
| 100 |
+
description="Check for chunking manipulation",
|
| 101 |
+
threshold=0.65,
|
| 102 |
+
severity=6
|
| 103 |
+
)
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
def _initialize_risk_patterns(self) -> Dict[str, Any]:
|
| 107 |
+
"""Initialize risk detection patterns"""
|
| 108 |
+
return {
|
| 109 |
+
"privacy_patterns": {
|
| 110 |
+
"pii": r"\b\d{3}-\d{2}-\d{4}\b", # SSN
|
| 111 |
+
"email": r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b",
|
| 112 |
+
"credit_card": r"\b\d{4}[- ]?\d{4}[- ]?\d{4}[- ]?\d{4}\b",
|
| 113 |
+
"api_key": r"\b([A-Za-z0-9]{32,})\b"
|
| 114 |
+
},
|
| 115 |
+
"injection_patterns": {
|
| 116 |
+
"system_prompt": r"system:\s*|instruction:\s*",
|
| 117 |
+
"delimiter": r"[<\[{](?:system|prompt|instruction)[>\]}]",
|
| 118 |
+
"escape": r"\\n|\\r|\\t|\\b|\\f"
|
| 119 |
+
},
|
| 120 |
+
"manipulation_patterns": {
|
| 121 |
+
"repetition": r"(.{50,}?)\1{2,}",
|
| 122 |
+
"formatting": r"\[format\]|\[style\]|\[template\]",
|
| 123 |
+
"control": r"\[control\]|\[override\]|\[skip\]"
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
def check_retrieval(self, context: RetrievalContext) -> GuardResult:
|
| 128 |
+
"""Perform security checks on retrieval operation"""
|
| 129 |
+
try:
|
| 130 |
+
checks_passed = []
|
| 131 |
+
checks_failed = []
|
| 132 |
+
risks = []
|
| 133 |
+
filtered_content = []
|
| 134 |
+
|
| 135 |
+
# Check relevance
|
| 136 |
+
relevance_result = self._check_relevance(context)
|
| 137 |
+
self._process_check_result(
|
| 138 |
+
relevance_result,
|
| 139 |
+
checks_passed,
|
| 140 |
+
checks_failed,
|
| 141 |
+
risks
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
# Check consistency
|
| 145 |
+
consistency_result = self._check_consistency(context)
|
| 146 |
+
self._process_check_result(
|
| 147 |
+
consistency_result,
|
| 148 |
+
checks_passed,
|
| 149 |
+
checks_failed,
|
| 150 |
+
risks
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Check privacy
|
| 154 |
+
privacy_result = self._check_privacy(context)
|
| 155 |
+
self._process_check_result(
|
| 156 |
+
privacy_result,
|
| 157 |
+
checks_passed,
|
| 158 |
+
checks_failed,
|
| 159 |
+
risks
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# Check for injection attempts
|
| 163 |
+
injection_result = self._check_injection(context)
|
| 164 |
+
self._process_check_result(
|
| 165 |
+
injection_result,
|
| 166 |
+
checks_passed,
|
| 167 |
+
checks_failed,
|
| 168 |
+
risks
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
# Check chunking
|
| 172 |
+
chunking_result = self._check_chunking(context)
|
| 173 |
+
self._process_check_result(
|
| 174 |
+
chunking_result,
|
| 175 |
+
checks_passed,
|
| 176 |
+
checks_failed,
|
| 177 |
+
risks
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Filter content based on check results
|
| 181 |
+
filtered_content = self._filter_content(context, risks)
|
| 182 |
+
|
| 183 |
+
# Create result
|
| 184 |
+
result = GuardResult(
|
| 185 |
+
is_safe=len(checks_failed) == 0,
|
| 186 |
+
checks_passed=checks_passed,
|
| 187 |
+
checks_failed=checks_failed,
|
| 188 |
+
risks=list(set(risks)),
|
| 189 |
+
filtered_content=filtered_content,
|
| 190 |
+
metadata={
|
| 191 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 192 |
+
"original_count": len(context.retrieved_content),
|
| 193 |
+
"filtered_count": len(filtered_content),
|
| 194 |
+
"risk_count": len(risks)
|
| 195 |
+
}
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
# Log result
|
| 199 |
+
if not result.is_safe and self.security_logger:
|
| 200 |
+
self.security_logger.log_security_event(
|
| 201 |
+
"retrieval_guard_alert",
|
| 202 |
+
checks_failed=checks_failed,
|
| 203 |
+
risks=[r.value for r in risks],
|
| 204 |
+
filtered_ratio=len(filtered_content)/len(context.retrieved_content)
|
| 205 |
+
)
|
| 206 |
+
|
| 207 |
+
self.check_history.append(result)
|
| 208 |
+
return result
|
| 209 |
+
|
| 210 |
+
except Exception as e:
|
| 211 |
+
if self.security_logger:
|
| 212 |
+
self.security_logger.log_security_event(
|
| 213 |
+
"retrieval_guard_error",
|
| 214 |
+
error=str(e)
|
| 215 |
+
)
|
| 216 |
+
raise SecurityError(f"Retrieval guard check failed: {str(e)}")
|
| 217 |
+
|
| 218 |
+
def _check_relevance(self, context: RetrievalContext) -> CheckResult:
|
| 219 |
+
"""Check relevance between query and retrieved content"""
|
| 220 |
+
relevance_scores = []
|
| 221 |
+
|
| 222 |
+
# Calculate cosine similarity between query and each retrieved embedding
|
| 223 |
+
for emb in context.retrieved_embeddings:
|
| 224 |
+
score = float(np.dot(
|
| 225 |
+
context.query_embedding,
|
| 226 |
+
emb
|
| 227 |
+
) / (
|
| 228 |
+
np.linalg.norm(context.query_embedding) *
|
| 229 |
+
np.linalg.norm(emb)
|
| 230 |
+
))
|
| 231 |
+
relevance_scores.append(score)
|
| 232 |
+
|
| 233 |
+
avg_relevance = np.mean(relevance_scores)
|
| 234 |
+
check = self.security_checks["relevance"]
|
| 235 |
+
|
| 236 |
+
return CheckResult(
|
| 237 |
+
check_name=check.name,
|
| 238 |
+
passed=avg_relevance >= check.threshold,
|
| 239 |
+
risk_level=1.0 - avg_relevance,
|
| 240 |
+
details={
|
| 241 |
+
"average_relevance": float(avg_relevance),
|
| 242 |
+
"min_relevance": float(min(relevance_scores)),
|
| 243 |
+
"max_relevance": float(max(relevance_scores))
|
| 244 |
+
},
|
| 245 |
+
recommendations=[
|
| 246 |
+
"Adjust retrieval threshold",
|
| 247 |
+
"Implement semantic filtering",
|
| 248 |
+
"Review chunking strategy"
|
| 249 |
+
] if avg_relevance < check.threshold else []
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
def _check_consistency(self, context: RetrievalContext) -> CheckResult:
|
| 253 |
+
"""Check consistency among retrieved chunks"""
|
| 254 |
+
consistency_scores = []
|
| 255 |
+
|
| 256 |
+
# Calculate pairwise similarities between retrieved embeddings
|
| 257 |
+
for i in range(len(context.retrieved_embeddings)):
|
| 258 |
+
for j in range(i + 1, len(context.retrieved_embeddings)):
|
| 259 |
+
score = float(np.dot(
|
| 260 |
+
context.retrieved_embeddings[i],
|
| 261 |
+
context.retrieved_embeddings[j]
|
| 262 |
+
) / (
|
| 263 |
+
np.linalg.norm(context.retrieved_embeddings[i]) *
|
| 264 |
+
np.linalg.norm(context.retrieved_embeddings[j])
|
| 265 |
+
))
|
| 266 |
+
consistency_scores.append(score)
|
| 267 |
+
|
| 268 |
+
avg_consistency = np.mean(consistency_scores) if consistency_scores else 0
|
| 269 |
+
check = self.security_checks["consistency"]
|
| 270 |
+
|
| 271 |
+
return CheckResult(
|
| 272 |
+
check_name=check.name,
|
| 273 |
+
passed=avg_consistency >= check.threshold,
|
| 274 |
+
risk_level=1.0 - avg_consistency,
|
| 275 |
+
details={
|
| 276 |
+
"average_consistency": float(avg_consistency),
|
| 277 |
+
"min_consistency": float(min(consistency_scores)) if consistency_scores else 0,
|
| 278 |
+
"max_consistency": float(max(consistency_scores)) if consistency_scores else 0
|
| 279 |
+
},
|
| 280 |
+
recommendations=[
|
| 281 |
+
"Review chunk coherence",
|
| 282 |
+
"Adjust chunk size",
|
| 283 |
+
"Implement overlap detection"
|
| 284 |
+
] if avg_consistency < check.threshold else []
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
def _check_privacy(self, context: RetrievalContext) -> CheckResult:
|
| 288 |
+
"""Check for potential privacy leaks"""
|
| 289 |
+
privacy_violations = defaultdict(list)
|
| 290 |
+
|
| 291 |
+
for idx, content in enumerate(context.retrieved_content):
|
| 292 |
+
for pattern_name, pattern in self.risk_patterns["privacy_patterns"].items():
|
| 293 |
+
matches = re.finditer(pattern, content)
|
| 294 |
+
for match in matches:
|
| 295 |
+
privacy_violations[pattern_name].append((idx, match.group()))
|
| 296 |
+
|
| 297 |
+
check = self.security_checks["privacy"]
|
| 298 |
+
violation_count = sum(len(v) for v in privacy_violations.values())
|
| 299 |
+
risk_level = min(1.0, violation_count / len(context.retrieved_content))
|
| 300 |
+
|
| 301 |
+
return CheckResult(
|
| 302 |
+
check_name=check.name,
|
| 303 |
+
passed=risk_level < (1 - check.threshold),
|
| 304 |
+
risk_level=risk_level,
|
| 305 |
+
details={
|
| 306 |
+
"violation_count": violation_count,
|
| 307 |
+
"violation_types": list(privacy_violations.keys()),
|
| 308 |
+
"affected_chunks": list(set(
|
| 309 |
+
idx for violations in privacy_violations.values()
|
| 310 |
+
for idx, _ in violations
|
| 311 |
+
))
|
| 312 |
+
},
|
| 313 |
+
recommendations=[
|
| 314 |
+
"Implement data masking",
|
| 315 |
+
"Add privacy filters",
|
| 316 |
+
"Review content preprocessing"
|
| 317 |
+
] if violation_count > 0 else []
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
def _check_injection(self, context: RetrievalContext) -> CheckResult:
|
| 321 |
+
"""Check for context injection attempts"""
|
| 322 |
+
injection_attempts = defaultdict(list)
|
| 323 |
+
|
| 324 |
+
for idx, content in enumerate(context.retrieved_content):
|
| 325 |
+
for pattern_name, pattern in self.risk_patterns["injection_patterns"].items():
|
| 326 |
+
matches = re.finditer(pattern, content)
|
| 327 |
+
for match in matches:
|
| 328 |
+
injection_attempts[pattern_name].append((idx, match.group()))
|
| 329 |
+
|
| 330 |
+
check = self.security_checks["injection"]
|
| 331 |
+
attempt_count = sum(len(v) for v in injection_attempts.values())
|
| 332 |
+
risk_level = min(1.0, attempt_count / len(context.retrieved_content))
|
| 333 |
+
|
| 334 |
+
return CheckResult(
|
| 335 |
+
check_name=check.name,
|
| 336 |
+
passed=risk_level < (1 - check.threshold),
|
| 337 |
+
risk_level=risk_level,
|
| 338 |
+
details={
|
| 339 |
+
"attempt_count": attempt_count,
|
| 340 |
+
"attempt_types": list(injection_attempts.keys()),
|
| 341 |
+
"affected_chunks": list(set(
|
| 342 |
+
idx for attempts in injection_attempts.values()
|
| 343 |
+
for idx, _ in attempts
|
| 344 |
+
))
|
| 345 |
+
},
|
| 346 |
+
recommendations=[
|
| 347 |
+
"Enhance input sanitization",
|
| 348 |
+
"Implement content filtering",
|
| 349 |
+
"Add injection detection"
|
| 350 |
+
] if attempt_count > 0 else []
|
| 351 |
+
)
|
| 352 |
+
|
| 353 |
+
def _check_chunking(self, context: RetrievalContext) -> CheckResult:
|
| 354 |
+
"""Check for chunking manipulation"""
|
| 355 |
+
manipulation_attempts = defaultdict(list)
|
| 356 |
+
chunk_sizes = [len(content) for content in context.retrieved_content]
|
| 357 |
+
|
| 358 |
+
# Check for suspicious patterns
|
| 359 |
+
for idx, content in enumerate(context.retrieved_content):
|
| 360 |
+
for pattern_name, pattern in self.risk_patterns["manipulation_patterns"].items():
|
| 361 |
+
matches = re.finditer(pattern, content)
|
| 362 |
+
for match in matches:
|
| 363 |
+
manipulation_attempts[pattern_name].append((idx, match.group()))
|
| 364 |
+
|
| 365 |
+
# Analyze chunk size distribution
|
| 366 |
+
mean_size = np.mean(chunk_sizes)
|
| 367 |
+
std_size = np.std(chunk_sizes)
|
| 368 |
+
suspicious_chunks = [
|
| 369 |
+
idx for idx, size in enumerate(chunk_sizes)
|
| 370 |
+
if abs(size - mean_size) > 2 * std_size
|
| 371 |
+
]
|
| 372 |
+
|
| 373 |
+
check = self.security_checks["chunking"]
|
| 374 |
+
violation_count = len(suspicious_chunks) + sum(len(v) for v in manipulation_attempts.values())
|
| 375 |
+
risk_level = min(1.0, violation_count / len(context.retrieved_content))
|
| 376 |
+
|
| 377 |
+
return CheckResult(
|
| 378 |
+
check_name=check.name,
|
| 379 |
+
passed=risk_level < (1 - check.threshold),
|
| 380 |
+
risk_level=risk_level,
|
| 381 |
+
details={
|
| 382 |
+
"violation_count": violation_count,
|
| 383 |
+
"suspicious_chunks": suspicious_chunks,
|
| 384 |
+
"manipulation_types": list(manipulation_attempts.keys()),
|
| 385 |
+
"chunk_stats": {
|
| 386 |
+
"mean_size": float(mean_size),
|
| 387 |
+
"std_size": float(std_size),
|
| 388 |
+
"min_size": min(chunk_sizes),
|
| 389 |
+
"max_size": max(chunk_sizes)
|
| 390 |
+
}
|
| 391 |
+
},
|
| 392 |
+
recommendations=[
|
| 393 |
+
"Review chunking strategy",
|
| 394 |
+
"Implement size normalization",
|
| 395 |
+
"Add pattern detection"
|
| 396 |
+
] if violation_count > 0 else []
|
| 397 |
+
)
|
| 398 |
+
|
| 399 |
+
def _process_check_result(self,
|
| 400 |
+
result: CheckResult,
|
| 401 |
+
checks_passed: List[str],
|
| 402 |
+
checks_failed: List[str],
|
| 403 |
+
risks: List[RetrievalRisk]):
|
| 404 |
+
"""Process check result and update tracking lists"""
|
| 405 |
+
if result.passed:
|
| 406 |
+
checks_passed.append(result.check_name)
|
| 407 |
+
else:
|
| 408 |
+
checks_failed.append(result.check_name)
|
| 409 |
+
# Map check names to risks
|
| 410 |
+
risk_mapping = {
|
| 411 |
+
"relevance_check": RetrievalRisk.RELEVANCE_MANIPULATION,
|
| 412 |
+
"consistency_check": RetrievalRisk.CONTEXT_INJECTION,
|
| 413 |
+
"privacy_check": RetrievalRisk.PRIVACY_LEAK,
|
| 414 |
+
"injection_check": RetrievalRisk.CONTEXT_INJECTION,
|
| 415 |
+
"chunking_check": RetrievalRisk.CHUNKING_MANIPULATION
|
| 416 |
+
}
|
| 417 |
+
if result.check_name in risk_mapping:
|
| 418 |
+
risks.append(risk_mapping[result.check_name])
|
| 419 |
+
|
| 420 |
+
# Log failed check if logger is available
|
| 421 |
+
if self.security_logger:
|
| 422 |
+
self.security_logger.log_security_event(
|
| 423 |
+
"retrieval_check_failed",
|
| 424 |
+
check_name=result.check_name,
|
| 425 |
+
risk_level=result.risk_level,
|
| 426 |
+
details=result.details
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
def _check_chunking(self, context: RetrievalContext) -> CheckResult:
|
| 430 |
+
"""Check for chunking manipulation and anomalies"""
|
| 431 |
+
check = self.security_checks["chunking"]
|
| 432 |
+
manipulation_attempts = defaultdict(list)
|
| 433 |
+
anomalies = []
|
| 434 |
+
|
| 435 |
+
# Get chunk statistics
|
| 436 |
+
chunk_sizes = [len(content) for content in context.retrieved_content]
|
| 437 |
+
chunk_mean = np.mean(chunk_sizes)
|
| 438 |
+
chunk_std = np.std(chunk_sizes)
|
| 439 |
+
|
| 440 |
+
# Check each chunk for issues
|
| 441 |
+
for idx, content in enumerate(context.retrieved_content):
|
| 442 |
+
# Check size anomalies
|
| 443 |
+
if abs(len(content) - chunk_mean) > 2 * chunk_std:
|
| 444 |
+
anomalies.append(("size_anomaly", idx))
|
| 445 |
+
|
| 446 |
+
# Check for manipulation patterns
|
| 447 |
+
for pattern_name, pattern in self.risk_patterns["manipulation_patterns"].items():
|
| 448 |
+
if matches := list(re.finditer(pattern, content)):
|
| 449 |
+
manipulation_attempts[pattern_name].extend(
|
| 450 |
+
(idx, match.group()) for match in matches
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# Check for content repetition
|
| 454 |
+
if self._detect_repetition(content):
|
| 455 |
+
anomalies.append(("repetition", idx))
|
| 456 |
+
|
| 457 |
+
# Check for suspicious formatting
|
| 458 |
+
if self._detect_suspicious_formatting(content):
|
| 459 |
+
anomalies.append(("suspicious_formatting", idx))
|
| 460 |
+
|
| 461 |
+
# Calculate risk metrics
|
| 462 |
+
total_issues = len(anomalies) + sum(len(attempts) for attempts in manipulation_attempts.values())
|
| 463 |
+
risk_level = min(1.0, total_issues / (len(context.retrieved_content) * 2))
|
| 464 |
+
|
| 465 |
+
# Generate recommendations based on findings
|
| 466 |
+
recommendations = []
|
| 467 |
+
if anomalies:
|
| 468 |
+
recommendations.append("Review chunk size distribution and normalization")
|
| 469 |
+
if manipulation_attempts:
|
| 470 |
+
recommendations.append("Implement stricter content validation")
|
| 471 |
+
recommendations.append("Add pattern-based filtering")
|
| 472 |
+
if risk_level > 0.5:
|
| 473 |
+
recommendations.append("Consider reducing chunk size variance")
|
| 474 |
+
|
| 475 |
+
return CheckResult(
|
| 476 |
+
check_name=check.name,
|
| 477 |
+
passed=risk_level < (1 - check.threshold),
|
| 478 |
+
risk_level=risk_level,
|
| 479 |
+
details={
|
| 480 |
+
"anomalies": [{"type": a_type, "chunk_index": idx} for a_type, idx in anomalies],
|
| 481 |
+
"manipulation_attempts": {
|
| 482 |
+
pattern: [{"chunk_index": idx, "content": content}
|
| 483 |
+
for idx, content in attempts]
|
| 484 |
+
for pattern, attempts in manipulation_attempts.items()
|
| 485 |
+
},
|
| 486 |
+
"chunk_stats": {
|
| 487 |
+
"mean_size": float(chunk_mean),
|
| 488 |
+
"std_size": float(chunk_std),
|
| 489 |
+
"size_range": (int(min(chunk_sizes)), int(max(chunk_sizes))),
|
| 490 |
+
"total_chunks": len(context.retrieved_content)
|
| 491 |
+
}
|
| 492 |
+
},
|
| 493 |
+
recommendations=recommendations
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
def _detect_repetition(self, content: str) -> bool:
|
| 497 |
+
"""Detect suspicious content repetition"""
|
| 498 |
+
# Check for repeated phrases (50+ characters)
|
| 499 |
+
repetition_pattern = r'(.{50,}?)\1+'
|
| 500 |
+
if re.search(repetition_pattern, content):
|
| 501 |
+
return True
|
| 502 |
+
|
| 503 |
+
# Check for unusual character repetition
|
| 504 |
+
char_counts = defaultdict(int)
|
| 505 |
+
for char in content:
|
| 506 |
+
char_counts[char] += 1
|
| 507 |
+
|
| 508 |
+
total_chars = len(content)
|
| 509 |
+
for count in char_counts.values():
|
| 510 |
+
if count > total_chars * 0.3: # More than 30% of same character
|
| 511 |
+
return True
|
| 512 |
+
|
| 513 |
+
return False
|
| 514 |
+
|
| 515 |
+
def _detect_suspicious_formatting(self, content: str) -> bool:
|
| 516 |
+
"""Detect suspicious content formatting"""
|
| 517 |
+
suspicious_patterns = [
|
| 518 |
+
r'\[(?:format|style|template)\]', # Format tags
|
| 519 |
+
r'\{(?:format|style|template)\}', # Format braces
|
| 520 |
+
r'<(?:format|style|template)>', # Format HTML-style tags
|
| 521 |
+
r'\\[nr]{10,}', # Excessive newlines/returns
|
| 522 |
+
r'\s{10,}', # Excessive whitespace
|
| 523 |
+
r'[^\w\s]{10,}' # Excessive special characters
|
| 524 |
+
]
|
| 525 |
+
|
| 526 |
+
return any(re.search(pattern, content) for pattern in suspicious_patterns)
|
| 527 |
+
|
| 528 |
+
def _filter_content(self,
|
| 529 |
+
context: RetrievalContext,
|
| 530 |
+
risks: List[RetrievalRisk]) -> List[str]:
|
| 531 |
+
"""Filter retrieved content based on detected risks"""
|
| 532 |
+
filtered_content = []
|
| 533 |
+
skip_indices = set()
|
| 534 |
+
|
| 535 |
+
# Collect indices to skip based on risks
|
| 536 |
+
for risk in risks:
|
| 537 |
+
if risk == RetrievalRisk.PRIVACY_LEAK:
|
| 538 |
+
# Skip chunks with privacy violations
|
| 539 |
+
skip_indices.update(self._find_privacy_violations(context))
|
| 540 |
+
elif risk == RetrievalRisk.CONTEXT_INJECTION:
|
| 541 |
+
# Skip chunks with injection attempts
|
| 542 |
+
skip_indices.update(self._find_injection_attempts(context))
|
| 543 |
+
elif risk == RetrievalRisk.RELEVANCE_MANIPULATION:
|
| 544 |
+
# Skip irrelevant chunks
|
| 545 |
+
skip_indices.update(self._find_irrelevant_chunks(context))
|
| 546 |
+
|
| 547 |
+
# Filter content
|
| 548 |
+
for idx, content in enumerate(context.retrieved_content):
|
| 549 |
+
if idx not in skip_indices:
|
| 550 |
+
# Apply any necessary sanitization
|
| 551 |
+
sanitized = self._sanitize_content(content)
|
| 552 |
+
if sanitized:
|
| 553 |
+
filtered_content.append(sanitized)
|
| 554 |
+
|
| 555 |
+
return filtered_content
|
| 556 |
+
|
| 557 |
+
def _find_privacy_violations(self, context: RetrievalContext) -> Set[int]:
|
| 558 |
+
"""Find chunks containing privacy violations"""
|
| 559 |
+
violation_indices = set()
|
| 560 |
+
|
| 561 |
+
for idx, content in enumerate(context.retrieved_content):
|
| 562 |
+
for pattern in self.risk_patterns["privacy_patterns"].values():
|
| 563 |
+
if re.search(pattern, content):
|
| 564 |
+
violation_indices.add(idx)
|
| 565 |
+
break
|
| 566 |
+
|
| 567 |
+
return violation_indices
|
| 568 |
+
|
| 569 |
+
def _find_injection_attempts(self, context: RetrievalContext) -> Set[int]:
|
| 570 |
+
"""Find chunks containing injection attempts"""
|
| 571 |
+
injection_indices = set()
|
| 572 |
+
|
| 573 |
+
for idx, content in enumerate(context.retrieved_content):
|
| 574 |
+
for pattern in self.risk_patterns["injection_patterns"].values():
|
| 575 |
+
if re.search(pattern, content):
|
| 576 |
+
injection_indices.add(idx)
|
| 577 |
+
break
|
| 578 |
+
|
| 579 |
+
return injection_indices
|
| 580 |
+
|
| 581 |
+
def _find_irrelevant_chunks(self, context: RetrievalContext) -> Set[int]:
|
| 582 |
+
"""Find irrelevant chunks based on similarity"""
|
| 583 |
+
irrelevant_indices = set()
|
| 584 |
+
threshold = self.security_checks["relevance"].threshold
|
| 585 |
+
|
| 586 |
+
for idx, emb in enumerate(context.retrieved_embeddings):
|
| 587 |
+
similarity = float(np.dot(
|
| 588 |
+
context.query_embedding,
|
| 589 |
+
emb
|
| 590 |
+
) / (
|
| 591 |
+
np.linalg.norm(context.query_embedding) *
|
| 592 |
+
np.linalg.norm(emb)
|
| 593 |
+
))
|
| 594 |
+
if similarity < threshold:
|
| 595 |
+
irrelevant_indices.add(idx)
|
| 596 |
+
|
| 597 |
+
return irrelevant_indices
|
| 598 |
+
|
| 599 |
+
def _sanitize_content(self, content: str) -> Optional[str]:
|
| 600 |
+
"""Sanitize content by removing or masking sensitive information"""
|
| 601 |
+
sanitized = content
|
| 602 |
+
|
| 603 |
+
# Mask privacy-sensitive information
|
| 604 |
+
for pattern in self.risk_patterns["privacy_patterns"].values():
|
| 605 |
+
sanitized = re.sub(pattern, "[REDACTED]", sanitized)
|
| 606 |
+
|
| 607 |
+
# Remove injection attempts
|
| 608 |
+
for pattern in self.risk_patterns["injection_patterns"].values():
|
| 609 |
+
sanitized = re.sub(pattern, "", sanitized)
|
| 610 |
+
|
| 611 |
+
# Remove manipulation attempts
|
| 612 |
+
for pattern in self.risk_patterns["manipulation_patterns"].values():
|
| 613 |
+
sanitized = re.sub(pattern, "", sanitized)
|
| 614 |
+
|
| 615 |
+
# Clean up whitespace
|
| 616 |
+
sanitized = " ".join(sanitized.split())
|
| 617 |
+
|
| 618 |
+
return sanitized if sanitized.strip() else None
|
| 619 |
+
|
| 620 |
+
def update_security_checks(self, updates: Dict[str, SecurityCheck]):
|
| 621 |
+
"""Update security check configurations"""
|
| 622 |
+
self.security_checks.update(updates)
|
| 623 |
+
|
| 624 |
+
def update_risk_patterns(self, updates: Dict[str, Dict[str, str]]):
|
| 625 |
+
"""Update risk detection patterns"""
|
| 626 |
+
for category, patterns in updates.items():
|
| 627 |
+
if category in self.risk_patterns:
|
| 628 |
+
self.risk_patterns[category].update(patterns)
|
| 629 |
+
else:
|
| 630 |
+
self.risk_patterns[category] = patterns
|
| 631 |
+
|
| 632 |
+
def get_check_history(self) -> List[Dict[str, Any]]:
|
| 633 |
+
"""Get history of guard check results"""
|
| 634 |
+
return [
|
| 635 |
+
{
|
| 636 |
+
"timestamp": result.metadata["timestamp"],
|
| 637 |
+
"is_safe": result.is_safe,
|
| 638 |
+
"checks_passed": result.checks_passed,
|
| 639 |
+
"checks_failed": result.checks_failed,
|
| 640 |
+
"risks": [risk.value for risk in result.risks],
|
| 641 |
+
"filtered_ratio": result.metadata["filtered_count"] /
|
| 642 |
+
result.metadata["original_count"]
|
| 643 |
+
}
|
| 644 |
+
for result in self.check_history
|
| 645 |
+
]
|
| 646 |
+
|
| 647 |
+
def clear_history(self):
|
| 648 |
+
"""Clear check history"""
|
| 649 |
+
self.check_history.clear()
|
| 650 |
+
|
| 651 |
+
def add_security_check(self, name: str, check: SecurityCheck):
|
| 652 |
+
"""Add a new security check"""
|
| 653 |
+
self.security_checks[name] = check
|
| 654 |
+
|
| 655 |
+
def remove_security_check(self, name: str):
|
| 656 |
+
"""Remove a security check"""
|
| 657 |
+
self.security_checks.pop(name, None)
|
| 658 |
+
|
| 659 |
+
def analyze_patterns(self) -> Dict[str, Any]:
|
| 660 |
+
"""Analyze detection patterns effectiveness"""
|
| 661 |
+
pattern_stats = {
|
| 662 |
+
"privacy": defaultdict(int),
|
| 663 |
+
"injection": defaultdict(int),
|
| 664 |
+
"manipulation": defaultdict(int)
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
for result in self.check_history:
|
| 668 |
+
if not result.is_safe:
|
| 669 |
+
for risk in result.risks:
|
| 670 |
+
if risk == RetrievalRisk.PRIVACY_LEAK:
|
| 671 |
+
for pattern in self.risk_patterns["privacy_patterns"]:
|
| 672 |
+
pattern_stats["privacy"][pattern] += 1
|
| 673 |
+
elif risk == RetrievalRisk.CONTEXT_INJECTION:
|
| 674 |
+
for pattern in self.risk_patterns["injection_patterns"]:
|
| 675 |
+
pattern_stats["injection"][pattern] += 1
|
| 676 |
+
elif risk == RetrievalRisk.CHUNKING_MANIPULATION:
|
| 677 |
+
for pattern in self.risk_patterns["manipulation_patterns"]:
|
| 678 |
+
pattern_stats["manipulation"][pattern] += 1
|
| 679 |
+
|
| 680 |
+
return {
|
| 681 |
+
"total_checks": len(self.check_history),
|
| 682 |
+
"pattern_matches": dict(pattern_stats),
|
| 683 |
+
"pattern_effectiveness": {
|
| 684 |
+
category: {
|
| 685 |
+
pattern: count / len(self.check_history)
|
| 686 |
+
for pattern, count in patterns.items()
|
| 687 |
+
}
|
| 688 |
+
for category, patterns in pattern_stats.items()
|
| 689 |
+
}
|
| 690 |
+
}
|
| 691 |
+
|
| 692 |
+
def get_recommendations(self) -> List[Dict[str, Any]]:
|
| 693 |
+
"""Get security recommendations based on check history"""
|
| 694 |
+
if not self.check_history:
|
| 695 |
+
return []
|
| 696 |
+
|
| 697 |
+
recommendations = []
|
| 698 |
+
risk_counts = defaultdict(int)
|
| 699 |
+
total_checks = len(self.check_history)
|
| 700 |
+
|
| 701 |
+
# Count risk occurrences
|
| 702 |
+
for result in self.check_history:
|
| 703 |
+
for risk in result.risks:
|
| 704 |
+
risk_counts[risk] += 1
|
| 705 |
+
|
| 706 |
+
# Generate recommendations
|
| 707 |
+
for risk, count in risk_counts.items():
|
| 708 |
+
frequency = count / total_checks
|
| 709 |
+
if frequency > 0.1: # More than 10% occurrence
|
| 710 |
+
recommendations.append({
|
| 711 |
+
"risk": risk.value,
|
| 712 |
+
"frequency": frequency,
|
| 713 |
+
"severity": "high" if frequency > 0.5 else "medium",
|
| 714 |
+
"recommendations": self._get_risk_recommendations(risk)
|
| 715 |
+
})
|
| 716 |
+
|
| 717 |
+
return recommendations
|
| 718 |
+
|
| 719 |
+
def _get_risk_recommendations(self, risk: RetrievalRisk) -> List[str]:
|
| 720 |
+
"""Get recommendations for specific risk"""
|
| 721 |
+
recommendations = {
|
| 722 |
+
RetrievalRisk.PRIVACY_LEAK: [
|
| 723 |
+
"Implement stronger data masking",
|
| 724 |
+
"Add privacy-focused preprocessing",
|
| 725 |
+
"Review data handling policies"
|
| 726 |
+
],
|
| 727 |
+
RetrievalRisk.CONTEXT_INJECTION: [
|
| 728 |
+
"Enhance input validation",
|
| 729 |
+
"Implement context boundaries",
|
| 730 |
+
"Add injection detection"
|
| 731 |
+
],
|
| 732 |
+
RetrievalRisk.RELEVANCE_MANIPULATION: [
|
| 733 |
+
"Adjust similarity thresholds",
|
| 734 |
+
"Implement semantic filtering",
|
| 735 |
+
"Review retrieval strategy"
|
| 736 |
+
],
|
| 737 |
+
RetrievalRisk.CHUNKING_MANIPULATION: [
|
| 738 |
+
"Standardize chunk sizes",
|
| 739 |
+
"Add chunk validation",
|
| 740 |
+
"Implement overlap detection"
|
| 741 |
+
]
|
| 742 |
+
}
|
| 743 |
+
return recommendations.get(risk, [])
|
src/llmguardian/vectors/storage_validator.py
ADDED
|
@@ -0,0 +1,679 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
vectors/storage_validator.py - Vector storage security validation
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from typing import Dict, List, Optional, Any, Tuple, Set
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from enum import Enum
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
from ..core.logger import SecurityLogger
|
| 14 |
+
from ..core.exceptions import SecurityError
|
| 15 |
+
|
| 16 |
+
class StorageRisk(Enum):
|
| 17 |
+
"""Types of vector storage risks"""
|
| 18 |
+
UNAUTHORIZED_ACCESS = "unauthorized_access"
|
| 19 |
+
DATA_CORRUPTION = "data_corruption"
|
| 20 |
+
INDEX_MANIPULATION = "index_manipulation"
|
| 21 |
+
VERSION_MISMATCH = "version_mismatch"
|
| 22 |
+
INTEGRITY_VIOLATION = "integrity_violation"
|
| 23 |
+
ENCRYPTION_WEAKNESS = "encryption_weakness"
|
| 24 |
+
BACKUP_FAILURE = "backup_failure"
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class StorageMetadata:
|
| 28 |
+
"""Metadata for vector storage"""
|
| 29 |
+
storage_type: str
|
| 30 |
+
vector_count: int
|
| 31 |
+
dimension: int
|
| 32 |
+
created_at: datetime
|
| 33 |
+
updated_at: datetime
|
| 34 |
+
version: str
|
| 35 |
+
checksum: str
|
| 36 |
+
encryption_info: Optional[Dict[str, Any]] = None
|
| 37 |
+
|
| 38 |
+
@dataclass
|
| 39 |
+
class ValidationRule:
|
| 40 |
+
"""Validation rule definition"""
|
| 41 |
+
name: str
|
| 42 |
+
description: str
|
| 43 |
+
severity: int # 1-10
|
| 44 |
+
check_function: str
|
| 45 |
+
parameters: Dict[str, Any]
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class ValidationResult:
|
| 49 |
+
"""Result of storage validation"""
|
| 50 |
+
is_valid: bool
|
| 51 |
+
risks: List[StorageRisk]
|
| 52 |
+
violations: List[str]
|
| 53 |
+
recommendations: List[str]
|
| 54 |
+
metadata: Dict[str, Any]
|
| 55 |
+
|
| 56 |
+
class StorageValidator:
|
| 57 |
+
"""Validator for vector storage security"""
|
| 58 |
+
|
| 59 |
+
def __init__(self, security_logger: Optional[SecurityLogger] = None):
|
| 60 |
+
self.security_logger = security_logger
|
| 61 |
+
self.validation_rules = self._initialize_validation_rules()
|
| 62 |
+
self.security_checks = self._initialize_security_checks()
|
| 63 |
+
self.validation_history: List[ValidationResult] = []
|
| 64 |
+
|
| 65 |
+
def _initialize_validation_rules(self) -> Dict[str, ValidationRule]:
|
| 66 |
+
"""Initialize validation rules"""
|
| 67 |
+
return {
|
| 68 |
+
"access_control": ValidationRule(
|
| 69 |
+
name="access_control",
|
| 70 |
+
description="Validate access control mechanisms",
|
| 71 |
+
severity=9,
|
| 72 |
+
check_function="check_access_control",
|
| 73 |
+
parameters={
|
| 74 |
+
"required_mechanisms": [
|
| 75 |
+
"authentication",
|
| 76 |
+
"authorization",
|
| 77 |
+
"encryption"
|
| 78 |
+
]
|
| 79 |
+
}
|
| 80 |
+
),
|
| 81 |
+
"data_integrity": ValidationRule(
|
| 82 |
+
name="data_integrity",
|
| 83 |
+
description="Validate data integrity",
|
| 84 |
+
severity=8,
|
| 85 |
+
check_function="check_data_integrity",
|
| 86 |
+
parameters={
|
| 87 |
+
"checksum_algorithm": "sha256",
|
| 88 |
+
"verify_frequency": 3600 # seconds
|
| 89 |
+
}
|
| 90 |
+
),
|
| 91 |
+
"index_security": ValidationRule(
|
| 92 |
+
name="index_security",
|
| 93 |
+
description="Validate index security",
|
| 94 |
+
severity=7,
|
| 95 |
+
check_function="check_index_security",
|
| 96 |
+
parameters={
|
| 97 |
+
"max_index_age": 86400, # seconds
|
| 98 |
+
"required_backups": 2
|
| 99 |
+
}
|
| 100 |
+
),
|
| 101 |
+
"version_control": ValidationRule(
|
| 102 |
+
name="version_control",
|
| 103 |
+
description="Validate version control",
|
| 104 |
+
severity=6,
|
| 105 |
+
check_function="check_version_control",
|
| 106 |
+
parameters={
|
| 107 |
+
"version_format": r"\d+\.\d+\.\d+",
|
| 108 |
+
"max_versions": 5
|
| 109 |
+
}
|
| 110 |
+
),
|
| 111 |
+
"encryption_strength": ValidationRule(
|
| 112 |
+
name="encryption_strength",
|
| 113 |
+
description="Validate encryption mechanisms",
|
| 114 |
+
severity=9,
|
| 115 |
+
check_function="check_encryption_strength",
|
| 116 |
+
parameters={
|
| 117 |
+
"min_key_size": 256,
|
| 118 |
+
"allowed_algorithms": [
|
| 119 |
+
"AES-256-GCM",
|
| 120 |
+
"ChaCha20-Poly1305"
|
| 121 |
+
]
|
| 122 |
+
}
|
| 123 |
+
)
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
def _initialize_security_checks(self) -> Dict[str, Any]:
|
| 127 |
+
"""Initialize security checks"""
|
| 128 |
+
return {
|
| 129 |
+
"backup_validation": {
|
| 130 |
+
"max_age": 86400, # 24 hours in seconds
|
| 131 |
+
"min_copies": 2,
|
| 132 |
+
"verify_integrity": True
|
| 133 |
+
},
|
| 134 |
+
"corruption_detection": {
|
| 135 |
+
"checksum_interval": 3600, # 1 hour in seconds
|
| 136 |
+
"dimension_check": True,
|
| 137 |
+
"norm_check": True
|
| 138 |
+
},
|
| 139 |
+
"access_patterns": {
|
| 140 |
+
"max_rate": 1000, # requests per hour
|
| 141 |
+
"concurrent_limit": 10,
|
| 142 |
+
"require_auth": True
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
def validate_storage(self,
|
| 147 |
+
metadata: StorageMetadata,
|
| 148 |
+
vectors: Optional[np.ndarray] = None,
|
| 149 |
+
context: Optional[Dict[str, Any]] = None) -> ValidationResult:
|
| 150 |
+
"""Validate vector storage security"""
|
| 151 |
+
try:
|
| 152 |
+
violations = []
|
| 153 |
+
risks = []
|
| 154 |
+
recommendations = []
|
| 155 |
+
|
| 156 |
+
# Check access control
|
| 157 |
+
access_result = self._check_access_control(metadata, context)
|
| 158 |
+
self._process_check_result(
|
| 159 |
+
access_result, violations, risks, recommendations
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
# Check data integrity
|
| 163 |
+
integrity_result = self._check_data_integrity(metadata, vectors)
|
| 164 |
+
self._process_check_result(
|
| 165 |
+
integrity_result, violations, risks, recommendations
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# Check index security
|
| 169 |
+
index_result = self._check_index_security(metadata, context)
|
| 170 |
+
self._process_check_result(
|
| 171 |
+
index_result, violations, risks, recommendations
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
# Check version control
|
| 175 |
+
version_result = self._check_version_control(metadata)
|
| 176 |
+
self._process_check_result(
|
| 177 |
+
version_result, violations, risks, recommendations
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Check encryption
|
| 181 |
+
encryption_result = self._check_encryption_strength(metadata)
|
| 182 |
+
self._process_check_result(
|
| 183 |
+
encryption_result, violations, risks, recommendations
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
result = ValidationResult(
|
| 187 |
+
is_valid=len(violations) == 0,
|
| 188 |
+
risks=list(set(risks)),
|
| 189 |
+
violations=violations,
|
| 190 |
+
recommendations=list(set(recommendations)),
|
| 191 |
+
metadata={
|
| 192 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 193 |
+
"storage_type": metadata.storage_type,
|
| 194 |
+
"vector_count": metadata.vector_count,
|
| 195 |
+
"checks_performed": [
|
| 196 |
+
rule.name for rule in self.validation_rules.values()
|
| 197 |
+
]
|
| 198 |
+
}
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
if not result.is_valid and self.security_logger:
|
| 202 |
+
self.security_logger.log_security_event(
|
| 203 |
+
"storage_validation_failure",
|
| 204 |
+
risks=[r.value for r in risks],
|
| 205 |
+
violations=violations,
|
| 206 |
+
storage_type=metadata.storage_type
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
self.validation_history.append(result)
|
| 210 |
+
return result
|
| 211 |
+
|
| 212 |
+
except Exception as e:
|
| 213 |
+
if self.security_logger:
|
| 214 |
+
self.security_logger.log_security_event(
|
| 215 |
+
"storage_validation_error",
|
| 216 |
+
error=str(e)
|
| 217 |
+
)
|
| 218 |
+
raise SecurityError(f"Storage validation failed: {str(e)}")
|
| 219 |
+
|
| 220 |
+
def _check_access_control(self,
|
| 221 |
+
metadata: StorageMetadata,
|
| 222 |
+
context: Optional[Dict[str, Any]]) -> Tuple[List[str], List[StorageRisk]]:
|
| 223 |
+
"""Check access control mechanisms"""
|
| 224 |
+
violations = []
|
| 225 |
+
risks = []
|
| 226 |
+
|
| 227 |
+
# Get rule parameters
|
| 228 |
+
rule = self.validation_rules["access_control"]
|
| 229 |
+
required_mechanisms = rule.parameters["required_mechanisms"]
|
| 230 |
+
|
| 231 |
+
# Check context for required mechanisms
|
| 232 |
+
if context:
|
| 233 |
+
for mechanism in required_mechanisms:
|
| 234 |
+
if mechanism not in context:
|
| 235 |
+
violations.append(
|
| 236 |
+
f"Missing required access control mechanism: {mechanism}"
|
| 237 |
+
)
|
| 238 |
+
risks.append(StorageRisk.UNAUTHORIZED_ACCESS)
|
| 239 |
+
|
| 240 |
+
# Check authentication
|
| 241 |
+
if context.get("authentication") == "none":
|
| 242 |
+
violations.append("No authentication mechanism configured")
|
| 243 |
+
risks.append(StorageRisk.UNAUTHORIZED_ACCESS)
|
| 244 |
+
|
| 245 |
+
# Check encryption
|
| 246 |
+
if not context.get("encryption", {}).get("enabled", False):
|
| 247 |
+
violations.append("Storage encryption not enabled")
|
| 248 |
+
risks.append(StorageRisk.ENCRYPTION_WEAKNESS)
|
| 249 |
+
else:
|
| 250 |
+
violations.append("No access control context provided")
|
| 251 |
+
risks.append(StorageRisk.UNAUTHORIZED_ACCESS)
|
| 252 |
+
|
| 253 |
+
return violations, risks
|
| 254 |
+
|
| 255 |
+
def _check_data_integrity(self,
|
| 256 |
+
metadata: StorageMetadata,
|
| 257 |
+
vectors: Optional[np.ndarray]) -> Tuple[List[str], List[StorageRisk]]:
|
| 258 |
+
"""Check data integrity"""
|
| 259 |
+
violations = []
|
| 260 |
+
risks = []
|
| 261 |
+
|
| 262 |
+
# Verify metadata checksum
|
| 263 |
+
if not self._verify_checksum(metadata):
|
| 264 |
+
violations.append("Metadata checksum verification failed")
|
| 265 |
+
risks.append(StorageRisk.INTEGRITY_VIOLATION)
|
| 266 |
+
|
| 267 |
+
# Check vectors if provided
|
| 268 |
+
if vectors is not None:
|
| 269 |
+
# Check dimensions
|
| 270 |
+
if len(vectors.shape) != 2:
|
| 271 |
+
violations.append("Invalid vector dimensions")
|
| 272 |
+
risks.append(StorageRisk.DATA_CORRUPTION)
|
| 273 |
+
|
| 274 |
+
if vectors.shape[1] != metadata.dimension:
|
| 275 |
+
violations.append("Vector dimension mismatch")
|
| 276 |
+
risks.append(StorageRisk.DATA_CORRUPTION)
|
| 277 |
+
|
| 278 |
+
# Check for NaN or Inf values
|
| 279 |
+
if np.any(np.isnan(vectors)) or np.any(np.isinf(vectors)):
|
| 280 |
+
violations.append("Vectors contain invalid values")
|
| 281 |
+
risks.append(StorageRisk.DATA_CORRUPTION)
|
| 282 |
+
|
| 283 |
+
return violations, risks
|
| 284 |
+
|
| 285 |
+
def _check_index_security(self,
|
| 286 |
+
metadata: StorageMetadata,
|
| 287 |
+
context: Optional[Dict[str, Any]]) -> Tuple[List[str], List[StorageRisk]]:
|
| 288 |
+
"""Check index security"""
|
| 289 |
+
violations = []
|
| 290 |
+
risks = []
|
| 291 |
+
|
| 292 |
+
rule = self.validation_rules["index_security"]
|
| 293 |
+
max_age = rule.parameters["max_index_age"]
|
| 294 |
+
required_backups = rule.parameters["required_backups"]
|
| 295 |
+
|
| 296 |
+
# Check index age
|
| 297 |
+
if context and "index_timestamp" in context:
|
| 298 |
+
index_age = (datetime.utcnow() -
|
| 299 |
+
datetime.fromisoformat(context["index_timestamp"])).total_seconds()
|
| 300 |
+
if index_age > max_age:
|
| 301 |
+
violations.append("Index is too old")
|
| 302 |
+
risks.append(StorageRisk.INDEX_MANIPULATION)
|
| 303 |
+
|
| 304 |
+
# Check backup configuration
|
| 305 |
+
if context and "backups" in context:
|
| 306 |
+
if len(context["backups"]) < required_backups:
|
| 307 |
+
violations.append("Insufficient backup copies")
|
| 308 |
+
risks.append(StorageRisk.BACKUP_FAILURE)
|
| 309 |
+
|
| 310 |
+
# Check backup freshness
|
| 311 |
+
for backup in context["backups"]:
|
| 312 |
+
if not self._verify_backup(backup):
|
| 313 |
+
violations.append("Backup verification failed")
|
| 314 |
+
risks.append(StorageRisk.BACKUP_FAILURE)
|
| 315 |
+
|
| 316 |
+
return violations, risks
|
| 317 |
+
|
| 318 |
+
def _check_version_control(self,
|
| 319 |
+
metadata: StorageMetadata) -> Tuple[List[str], List[StorageRisk]]:
|
| 320 |
+
"""Check version control"""
|
| 321 |
+
violations = []
|
| 322 |
+
risks = []
|
| 323 |
+
|
| 324 |
+
rule = self.validation_rules["version_control"]
|
| 325 |
+
version_pattern = rule.parameters["version_format"]
|
| 326 |
+
|
| 327 |
+
# Check version format
|
| 328 |
+
if not re.match(version_pattern, metadata.version):
|
| 329 |
+
violations.append("Invalid version format")
|
| 330 |
+
risks.append(StorageRisk.VERSION_MISMATCH)
|
| 331 |
+
|
| 332 |
+
# Check version compatibility
|
| 333 |
+
if not self._check_version_compatibility(metadata.version):
|
| 334 |
+
violations.append("Version compatibility check failed")
|
| 335 |
+
risks.append(StorageRisk.VERSION_MISMATCH)
|
| 336 |
+
|
| 337 |
+
return violations, risks
|
| 338 |
+
|
| 339 |
+
def _check_encryption_strength(self,
|
| 340 |
+
metadata: StorageMetadata) -> Tuple[List[str], List[StorageRisk]]:
|
| 341 |
+
"""Check encryption mechanisms"""
|
| 342 |
+
violations = []
|
| 343 |
+
risks = []
|
| 344 |
+
|
| 345 |
+
rule = self.validation_rules["encryption_strength"]
|
| 346 |
+
min_key_size = rule.parameters["min_key_size"]
|
| 347 |
+
allowed_algorithms = rule.parameters["allowed_algorithms"]
|
| 348 |
+
|
| 349 |
+
if metadata.encryption_info:
|
| 350 |
+
# Check key size
|
| 351 |
+
key_size = metadata.encryption_info.get("key_size", 0)
|
| 352 |
+
if key_size < min_key_size:
|
| 353 |
+
violations.append(f"Encryption key size below minimum: {key_size}")
|
| 354 |
+
risks.append(StorageRisk.ENCRYPTION_WEAKNESS)
|
| 355 |
+
|
| 356 |
+
# Check algorithm
|
| 357 |
+
algorithm = metadata.encryption_info.get("algorithm")
|
| 358 |
+
if algorithm not in allowed_algorithms:
|
| 359 |
+
violations.append(f"Unsupported encryption algorithm: {algorithm}")
|
| 360 |
+
risks.append(StorageRisk.ENCRYPTION_WEAKNESS)
|
| 361 |
+
else:
|
| 362 |
+
violations.append("Missing encryption information")
|
| 363 |
+
risks.append(StorageRisk.ENCRYPTION_WEAKNESS)
|
| 364 |
+
|
| 365 |
+
return violations, risks
|
| 366 |
+
|
| 367 |
+
def _verify_checksum(self, metadata: StorageMetadata) -> bool:
|
| 368 |
+
"""Verify metadata checksum"""
|
| 369 |
+
try:
|
| 370 |
+
# Create a copy without the checksum field
|
| 371 |
+
meta_dict = {
|
| 372 |
+
k: v for k, v in metadata.__dict__.items()
|
| 373 |
+
if k != 'checksum'
|
| 374 |
+
}
|
| 375 |
+
computed_checksum = hashlib.sha256(
|
| 376 |
+
json.dumps(meta_dict, sort_keys=True).encode()
|
| 377 |
+
).hexdigest()
|
| 378 |
+
return computed_checksum == metadata.checksum
|
| 379 |
+
except Exception:
|
| 380 |
+
return False
|
| 381 |
+
|
| 382 |
+
def _verify_backup(self, backup_info: Dict[str, Any]) -> bool:
|
| 383 |
+
"""Verify backup integrity"""
|
| 384 |
+
try:
|
| 385 |
+
# Check backup age
|
| 386 |
+
backup_age = (datetime.utcnow() -
|
| 387 |
+
datetime.fromisoformat(backup_info["timestamp"])).total_seconds()
|
| 388 |
+
if backup_age > self.security_checks["backup_validation"]["max_age"]:
|
| 389 |
+
return False
|
| 390 |
+
|
| 391 |
+
# Check integrity if required
|
| 392 |
+
if (self.security_checks["backup_validation"]["verify_integrity"] and
|
| 393 |
+
not self._verify_backup_integrity(backup_info)):
|
| 394 |
+
return False
|
| 395 |
+
|
| 396 |
+
return True
|
| 397 |
+
except Exception:
|
| 398 |
+
return False
|
| 399 |
+
|
| 400 |
+
def _verify_backup_integrity(self, backup_info: Dict[str, Any]) -> bool:
|
| 401 |
+
"""Verify backup data integrity"""
|
| 402 |
+
try:
|
| 403 |
+
return (backup_info.get("checksum") ==
|
| 404 |
+
backup_info.get("computed_checksum"))
|
| 405 |
+
except Exception:
|
| 406 |
+
return False
|
| 407 |
+
|
| 408 |
+
def _check_version_compatibility(self, version: str) -> bool:
|
| 409 |
+
"""Check version compatibility"""
|
| 410 |
+
try:
|
| 411 |
+
major, minor, patch = map(int, version.split('.'))
|
| 412 |
+
# Add your version compatibility logic here
|
| 413 |
+
return True
|
| 414 |
+
except Exception:
|
| 415 |
+
return False
|
| 416 |
+
|
| 417 |
+
def _process_check_result(self,
|
| 418 |
+
check_result: Tuple[List[str], List[StorageRisk]],
|
| 419 |
+
violations: List[str],
|
| 420 |
+
risks: List[StorageRisk],
|
| 421 |
+
recommendations: List[str]):
|
| 422 |
+
"""Process check results and update tracking lists"""
|
| 423 |
+
check_violations, check_risks = check_result
|
| 424 |
+
violations.extend(check_violations)
|
| 425 |
+
risks.extend(check_risks)
|
| 426 |
+
|
| 427 |
+
# Add recommendations based on violations
|
| 428 |
+
for violation in check_violations:
|
| 429 |
+
recommendations.extend(
|
| 430 |
+
self._get_recommendations_for_violation(violation)
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
def _get_recommendations_for_violation(self, violation: str) -> List[str]:
|
| 434 |
+
"""Get recommendations for a specific violation"""
|
| 435 |
+
recommendations_map = {
|
| 436 |
+
"Missing required access control": [
|
| 437 |
+
"Implement authentication mechanism",
|
| 438 |
+
"Enable access control features",
|
| 439 |
+
"Review security configuration"
|
| 440 |
+
],
|
| 441 |
+
"Storage encryption not enabled": [
|
| 442 |
+
"Enable storage encryption",
|
| 443 |
+
"Configure encryption settings",
|
| 444 |
+
"Review encryption requirements"
|
| 445 |
+
],
|
| 446 |
+
"Metadata checksum verification failed": [
|
| 447 |
+
"Verify data integrity",
|
| 448 |
+
"Rebuild metadata checksums",
|
| 449 |
+
"Check for corruption"
|
| 450 |
+
],
|
| 451 |
+
"Invalid vector dimensions": [
|
| 452 |
+
"Validate vector format",
|
| 453 |
+
"Check dimension consistency",
|
| 454 |
+
"Review data preprocessing"
|
| 455 |
+
],
|
| 456 |
+
"Index is too old": [
|
| 457 |
+
"Rebuild vector index",
|
| 458 |
+
"Schedule regular index updates",
|
| 459 |
+
"Monitor index freshness"
|
| 460 |
+
],
|
| 461 |
+
"Insufficient backup copies": [
|
| 462 |
+
"Configure additional backups",
|
| 463 |
+
"Review backup strategy",
|
| 464 |
+
"Implement backup automation"
|
| 465 |
+
],
|
| 466 |
+
"Invalid version format": [
|
| 467 |
+
"Update version formatting",
|
| 468 |
+
"Implement version control",
|
| 469 |
+
"Standardize versioning scheme"
|
| 470 |
+
]
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
# Get generic recommendations if specific ones not found
|
| 474 |
+
default_recommendations = [
|
| 475 |
+
"Review security configuration",
|
| 476 |
+
"Update validation rules",
|
| 477 |
+
"Monitor system logs"
|
| 478 |
+
]
|
| 479 |
+
|
| 480 |
+
return recommendations_map.get(violation, default_recommendations)
|
| 481 |
+
|
| 482 |
+
def add_validation_rule(self, name: str, rule: ValidationRule):
|
| 483 |
+
"""Add a new validation rule"""
|
| 484 |
+
self.validation_rules[name] = rule
|
| 485 |
+
|
| 486 |
+
def remove_validation_rule(self, name: str):
|
| 487 |
+
"""Remove a validation rule"""
|
| 488 |
+
self.validation_rules.pop(name, None)
|
| 489 |
+
|
| 490 |
+
def update_security_checks(self, updates: Dict[str, Dict[str, Any]]):
|
| 491 |
+
"""Update security check configurations"""
|
| 492 |
+
self.security_checks.update(updates)
|
| 493 |
+
|
| 494 |
+
def get_validation_history(self) -> List[Dict[str, Any]]:
|
| 495 |
+
"""Get history of validation results"""
|
| 496 |
+
return [
|
| 497 |
+
{
|
| 498 |
+
"timestamp": result.metadata["timestamp"],
|
| 499 |
+
"is_valid": result.is_valid,
|
| 500 |
+
"risks": [risk.value for risk in result.risks],
|
| 501 |
+
"violations": result.violations,
|
| 502 |
+
"storage_type": result.metadata["storage_type"]
|
| 503 |
+
}
|
| 504 |
+
for result in self.validation_history
|
| 505 |
+
]
|
| 506 |
+
|
| 507 |
+
def analyze_risks(self) -> Dict[str, Any]:
|
| 508 |
+
"""Analyze risk patterns in validation history"""
|
| 509 |
+
if not self.validation_history:
|
| 510 |
+
return {}
|
| 511 |
+
|
| 512 |
+
risk_analysis = {
|
| 513 |
+
"total_validations": len(self.validation_history),
|
| 514 |
+
"risk_frequency": defaultdict(int),
|
| 515 |
+
"violation_frequency": defaultdict(int),
|
| 516 |
+
"storage_type_risks": defaultdict(lambda: defaultdict(int)),
|
| 517 |
+
"trend_analysis": self._analyze_risk_trends()
|
| 518 |
+
}
|
| 519 |
+
|
| 520 |
+
for result in self.validation_history:
|
| 521 |
+
for risk in result.risks:
|
| 522 |
+
risk_analysis["risk_frequency"][risk.value] += 1
|
| 523 |
+
|
| 524 |
+
for violation in result.violations:
|
| 525 |
+
risk_analysis["violation_frequency"][violation] += 1
|
| 526 |
+
|
| 527 |
+
storage_type = result.metadata["storage_type"]
|
| 528 |
+
for risk in result.risks:
|
| 529 |
+
risk_analysis["storage_type_risks"][storage_type][risk.value] += 1
|
| 530 |
+
|
| 531 |
+
# Convert to percentages
|
| 532 |
+
total = len(self.validation_history)
|
| 533 |
+
risk_analysis["risk_percentages"] = {
|
| 534 |
+
risk: (count / total) * 100
|
| 535 |
+
for risk, count in risk_analysis["risk_frequency"].items()
|
| 536 |
+
}
|
| 537 |
+
|
| 538 |
+
return risk_analysis
|
| 539 |
+
|
| 540 |
+
def _analyze_risk_trends(self) -> Dict[str, Any]:
|
| 541 |
+
"""Analyze trends in risk patterns"""
|
| 542 |
+
if len(self.validation_history) < 2:
|
| 543 |
+
return {}
|
| 544 |
+
|
| 545 |
+
trends = {
|
| 546 |
+
"increasing_risks": [],
|
| 547 |
+
"decreasing_risks": [],
|
| 548 |
+
"persistent_risks": []
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
# Group results by time periods (e.g., daily)
|
| 552 |
+
period_risks = defaultdict(lambda: defaultdict(int))
|
| 553 |
+
|
| 554 |
+
for result in self.validation_history:
|
| 555 |
+
date = datetime.fromisoformat(
|
| 556 |
+
result.metadata["timestamp"]
|
| 557 |
+
).date().isoformat()
|
| 558 |
+
|
| 559 |
+
for risk in result.risks:
|
| 560 |
+
period_risks[date][risk.value] += 1
|
| 561 |
+
|
| 562 |
+
# Analyze trends
|
| 563 |
+
dates = sorted(period_risks.keys())
|
| 564 |
+
for risk in StorageRisk:
|
| 565 |
+
first_count = period_risks[dates[0]][risk.value]
|
| 566 |
+
last_count = period_risks[dates[-1]][risk.value]
|
| 567 |
+
|
| 568 |
+
if last_count > first_count:
|
| 569 |
+
trends["increasing_risks"].append(risk.value)
|
| 570 |
+
elif last_count < first_count:
|
| 571 |
+
trends["decreasing_risks"].append(risk.value)
|
| 572 |
+
elif last_count > 0: # Risk persists
|
| 573 |
+
trends["persistent_risks"].append(risk.value)
|
| 574 |
+
|
| 575 |
+
return trends
|
| 576 |
+
|
| 577 |
+
def get_security_recommendations(self) -> List[Dict[str, Any]]:
|
| 578 |
+
"""Get security recommendations based on validation history"""
|
| 579 |
+
if not self.validation_history:
|
| 580 |
+
return []
|
| 581 |
+
|
| 582 |
+
risk_analysis = self.analyze_risks()
|
| 583 |
+
recommendations = []
|
| 584 |
+
|
| 585 |
+
# Check high-frequency risks
|
| 586 |
+
for risk, percentage in risk_analysis["risk_percentages"].items():
|
| 587 |
+
if percentage > 20: # More than 20% occurrence
|
| 588 |
+
recommendations.append({
|
| 589 |
+
"risk": risk,
|
| 590 |
+
"frequency": percentage,
|
| 591 |
+
"severity": "high" if percentage > 50 else "medium",
|
| 592 |
+
"recommendations": self._get_risk_recommendations(risk)
|
| 593 |
+
})
|
| 594 |
+
|
| 595 |
+
# Check risk trends
|
| 596 |
+
trends = risk_analysis.get("trend_analysis", {})
|
| 597 |
+
|
| 598 |
+
for risk in trends.get("increasing_risks", []):
|
| 599 |
+
recommendations.append({
|
| 600 |
+
"risk": risk,
|
| 601 |
+
"trend": "increasing",
|
| 602 |
+
"severity": "high",
|
| 603 |
+
"recommendations": [
|
| 604 |
+
"Immediate attention required",
|
| 605 |
+
"Review recent changes",
|
| 606 |
+
"Implement additional controls"
|
| 607 |
+
]
|
| 608 |
+
})
|
| 609 |
+
|
| 610 |
+
for risk in trends.get("persistent_risks", []):
|
| 611 |
+
recommendations.append({
|
| 612 |
+
"risk": risk,
|
| 613 |
+
"trend": "persistent",
|
| 614 |
+
"severity": "medium",
|
| 615 |
+
"recommendations": [
|
| 616 |
+
"Review existing controls",
|
| 617 |
+
"Consider alternative approaches",
|
| 618 |
+
"Enhance monitoring"
|
| 619 |
+
]
|
| 620 |
+
})
|
| 621 |
+
|
| 622 |
+
return recommendations
|
| 623 |
+
|
| 624 |
+
def _get_risk_recommendations(self, risk: str) -> List[str]:
|
| 625 |
+
"""Get recommendations for specific risk"""
|
| 626 |
+
recommendations = {
|
| 627 |
+
"unauthorized_access": [
|
| 628 |
+
"Strengthen access controls",
|
| 629 |
+
"Implement authentication",
|
| 630 |
+
"Review permissions"
|
| 631 |
+
],
|
| 632 |
+
"data_corruption": [
|
| 633 |
+
"Implement integrity checks",
|
| 634 |
+
"Regular validation",
|
| 635 |
+
"Backup strategy"
|
| 636 |
+
],
|
| 637 |
+
"index_manipulation": [
|
| 638 |
+
"Secure index updates",
|
| 639 |
+
"Monitor modifications",
|
| 640 |
+
"Version control"
|
| 641 |
+
],
|
| 642 |
+
"encryption_weakness": [
|
| 643 |
+
"Upgrade encryption",
|
| 644 |
+
"Key rotation",
|
| 645 |
+
"Security audit"
|
| 646 |
+
],
|
| 647 |
+
"backup_failure": [
|
| 648 |
+
"Review backup strategy",
|
| 649 |
+
"Automated backups",
|
| 650 |
+
"Integrity verification"
|
| 651 |
+
]
|
| 652 |
+
}
|
| 653 |
+
return recommendations.get(risk, ["Review security configuration"])
|
| 654 |
+
|
| 655 |
+
def clear_validation_history(self):
|
| 656 |
+
"""Clear validation history"""
|
| 657 |
+
self.validation_history.clear()
|
| 658 |
+
|
| 659 |
+
def export_security_report(self) -> Dict[str, Any]:
|
| 660 |
+
"""Generate comprehensive security report"""
|
| 661 |
+
return {
|
| 662 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 663 |
+
"validation_rules": {
|
| 664 |
+
name: {
|
| 665 |
+
"description": rule.description,
|
| 666 |
+
"severity": rule.severity,
|
| 667 |
+
"parameters": rule.parameters
|
| 668 |
+
}
|
| 669 |
+
for name, rule in self.validation_rules.items()
|
| 670 |
+
},
|
| 671 |
+
"risk_analysis": self.analyze_risks(),
|
| 672 |
+
"recommendations": self.get_security_recommendations(),
|
| 673 |
+
"validation_history_summary": {
|
| 674 |
+
"total_validations": len(self.validation_history),
|
| 675 |
+
"failure_rate": sum(
|
| 676 |
+
1 for r in self.validation_history if not r.is_valid
|
| 677 |
+
) / len(self.validation_history) if self.validation_history else 0
|
| 678 |
+
}
|
| 679 |
+
}
|
src/llmguardian/vectors/vector_scanner.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
vectors/vector_scanner.py - Security scanner for vector databases and operations
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
from typing import Dict, List, Optional, Any, Set
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from enum import Enum
|
| 10 |
+
import hashlib
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
from ..core.logger import SecurityLogger
|
| 13 |
+
from ..core.exceptions import SecurityError
|
| 14 |
+
|
| 15 |
+
class VectorVulnerability(Enum):
|
| 16 |
+
"""Types of vector-related vulnerabilities"""
|
| 17 |
+
POISONED_VECTORS = "poisoned_vectors"
|
| 18 |
+
MALICIOUS_PAYLOAD = "malicious_payload"
|
| 19 |
+
DATA_LEAKAGE = "data_leakage"
|
| 20 |
+
DIMENSION_MISMATCH = "dimension_mismatch"
|
| 21 |
+
METADATA_TAMPERING = "metadata_tampering"
|
| 22 |
+
CLUSTERING_ATTACK = "clustering_attack"
|
| 23 |
+
SIMILARITY_MANIPULATION = "similarity_manipulation"
|
| 24 |
+
INDEX_POISONING = "index_poisoning"
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class ScanTarget:
|
| 28 |
+
"""Definition of a scan target"""
|
| 29 |
+
vectors: np.ndarray
|
| 30 |
+
metadata: Optional[Dict[str, Any]] = None
|
| 31 |
+
index_data: Optional[Dict[str, Any]] = None
|
| 32 |
+
source: Optional[str] = None
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class VulnerabilityReport:
|
| 36 |
+
"""Detailed vulnerability report"""
|
| 37 |
+
vulnerability_type: VectorVulnerability
|
| 38 |
+
severity: int # 1-10
|
| 39 |
+
affected_indices: List[int]
|
| 40 |
+
description: str
|
| 41 |
+
recommendations: List[str]
|
| 42 |
+
metadata: Dict[str, Any]
|
| 43 |
+
|
| 44 |
+
@dataclass
|
| 45 |
+
class ScanResult:
|
| 46 |
+
"""Result of a vector database scan"""
|
| 47 |
+
vulnerabilities: List[VulnerabilityReport]
|
| 48 |
+
statistics: Dict[str, Any]
|
| 49 |
+
timestamp: datetime
|
| 50 |
+
scan_duration: float
|
| 51 |
+
|
| 52 |
+
class VectorScanner:
|
| 53 |
+
"""Scanner for vector-related security issues"""
|
| 54 |
+
|
| 55 |
+
def __init__(self, security_logger: Optional[SecurityLogger] = None):
|
| 56 |
+
self.security_logger = security_logger
|
| 57 |
+
self.vulnerability_patterns = self._initialize_patterns()
|
| 58 |
+
self.scan_history: List[ScanResult] = []
|
| 59 |
+
|
| 60 |
+
def _initialize_patterns(self) -> Dict[str, Dict[str, Any]]:
|
| 61 |
+
"""Initialize vulnerability detection patterns"""
|
| 62 |
+
return {
|
| 63 |
+
"clustering": {
|
| 64 |
+
"min_cluster_size": 10,
|
| 65 |
+
"isolation_threshold": 0.3,
|
| 66 |
+
"similarity_threshold": 0.85
|
| 67 |
+
},
|
| 68 |
+
"metadata": {
|
| 69 |
+
"required_fields": {"timestamp", "source", "dimension"},
|
| 70 |
+
"sensitive_patterns": {
|
| 71 |
+
r"password", r"secret", r"key", r"token",
|
| 72 |
+
r"credential", r"auth", r"\bpii\b"
|
| 73 |
+
}
|
| 74 |
+
},
|
| 75 |
+
"poisoning": {
|
| 76 |
+
"variance_threshold": 0.1,
|
| 77 |
+
"outlier_threshold": 2.0,
|
| 78 |
+
"minimum_samples": 5
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
def scan_vectors(self, target: ScanTarget) -> ScanResult:
|
| 83 |
+
"""Scan vectors for security vulnerabilities"""
|
| 84 |
+
try:
|
| 85 |
+
start_time = datetime.utcnow()
|
| 86 |
+
vulnerabilities = []
|
| 87 |
+
statistics = defaultdict(int)
|
| 88 |
+
|
| 89 |
+
# Check for poisoned vectors
|
| 90 |
+
poisoning_report = self._check_vector_poisoning(target)
|
| 91 |
+
if poisoning_report:
|
| 92 |
+
vulnerabilities.append(poisoning_report)
|
| 93 |
+
statistics["poisoned_vectors"] = len(poisoning_report.affected_indices)
|
| 94 |
+
|
| 95 |
+
# Check for malicious payloads
|
| 96 |
+
payload_report = self._check_malicious_payloads(target)
|
| 97 |
+
if payload_report:
|
| 98 |
+
vulnerabilities.append(payload_report)
|
| 99 |
+
statistics["malicious_payloads"] = len(payload_report.affected_indices)
|
| 100 |
+
|
| 101 |
+
# Check for data leakage
|
| 102 |
+
leakage_report = self._check_data_leakage(target)
|
| 103 |
+
if leakage_report:
|
| 104 |
+
vulnerabilities.append(leakage_report)
|
| 105 |
+
statistics["data_leakage"] = len(leakage_report.affected_indices)
|
| 106 |
+
|
| 107 |
+
# Check for clustering attacks
|
| 108 |
+
clustering_report = self._check_clustering_attacks(target)
|
| 109 |
+
if clustering_report:
|
| 110 |
+
vulnerabilities.append(clustering_report)
|
| 111 |
+
statistics["clustering_attacks"] = len(clustering_report.affected_indices)
|
| 112 |
+
|
| 113 |
+
# Check metadata
|
| 114 |
+
metadata_report = self._check_metadata_tampering(target)
|
| 115 |
+
if metadata_report:
|
| 116 |
+
vulnerabilities.append(metadata_report)
|
| 117 |
+
statistics["metadata_issues"] = len(metadata_report.affected_indices)
|
| 118 |
+
|
| 119 |
+
# Create scan result
|
| 120 |
+
scan_duration = (datetime.utcnow() - start_time).total_seconds()
|
| 121 |
+
result = ScanResult(
|
| 122 |
+
vulnerabilities=vulnerabilities,
|
| 123 |
+
statistics=dict(statistics),
|
| 124 |
+
timestamp=datetime.utcnow(),
|
| 125 |
+
scan_duration=scan_duration
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
# Log scan results
|
| 129 |
+
if vulnerabilities and self.security_logger:
|
| 130 |
+
self.security_logger.log_security_event(
|
| 131 |
+
"vector_scan_completed",
|
| 132 |
+
vulnerability_count=len(vulnerabilities),
|
| 133 |
+
statistics=statistics
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
self.scan_history.append(result)
|
| 137 |
+
return result
|
| 138 |
+
|
| 139 |
+
except Exception as e:
|
| 140 |
+
if self.security_logger:
|
| 141 |
+
self.security_logger.log_security_event(
|
| 142 |
+
"vector_scan_error",
|
| 143 |
+
error=str(e)
|
| 144 |
+
)
|
| 145 |
+
raise SecurityError(f"Vector scan failed: {str(e)}")
|
| 146 |
+
|
| 147 |
+
def _check_vector_poisoning(self, target: ScanTarget) -> Optional[VulnerabilityReport]:
|
| 148 |
+
"""Check for poisoned vectors"""
|
| 149 |
+
affected_indices = []
|
| 150 |
+
vectors = target.vectors
|
| 151 |
+
|
| 152 |
+
# Calculate statistical properties
|
| 153 |
+
mean_vector = np.mean(vectors, axis=0)
|
| 154 |
+
distances = np.linalg.norm(vectors - mean_vector, axis=1)
|
| 155 |
+
mean_distance = np.mean(distances)
|
| 156 |
+
std_distance = np.std(distances)
|
| 157 |
+
|
| 158 |
+
# Check for outliers
|
| 159 |
+
threshold = self.vulnerability_patterns["poisoning"]["outlier_threshold"]
|
| 160 |
+
for i, distance in enumerate(distances):
|
| 161 |
+
if abs(distance - mean_distance) > threshold * std_distance:
|
| 162 |
+
affected_indices.append(i)
|
| 163 |
+
|
| 164 |
+
if affected_indices:
|
| 165 |
+
return VulnerabilityReport(
|
| 166 |
+
vulnerability_type=VectorVulnerability.POISONED_VECTORS,
|
| 167 |
+
severity=8,
|
| 168 |
+
affected_indices=affected_indices,
|
| 169 |
+
description="Detected potential poisoned vectors based on statistical analysis",
|
| 170 |
+
recommendations=[
|
| 171 |
+
"Remove or quarantine affected vectors",
|
| 172 |
+
"Implement stronger validation for new vectors",
|
| 173 |
+
"Monitor vector statistics regularly"
|
| 174 |
+
],
|
| 175 |
+
metadata={
|
| 176 |
+
"mean_distance": float(mean_distance),
|
| 177 |
+
"std_distance": float(std_distance),
|
| 178 |
+
"threshold_used": float(threshold)
|
| 179 |
+
}
|
| 180 |
+
)
|
| 181 |
+
return None
|
| 182 |
+
|
| 183 |
+
def _check_malicious_payloads(self, target: ScanTarget) -> Optional[VulnerabilityReport]:
|
| 184 |
+
"""Check for malicious payloads in metadata"""
|
| 185 |
+
if not target.metadata:
|
| 186 |
+
return None
|
| 187 |
+
|
| 188 |
+
affected_indices = []
|
| 189 |
+
suspicious_patterns = {
|
| 190 |
+
r"eval\(", r"exec\(", r"system\(", # Code execution
|
| 191 |
+
r"<script", r"javascript:", # XSS
|
| 192 |
+
r"DROP TABLE", r"DELETE FROM", # SQL injection
|
| 193 |
+
r"\\x[0-9a-fA-F]+", # Encoded content
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
for idx, metadata in enumerate(target.metadata):
|
| 197 |
+
for key, value in metadata.items():
|
| 198 |
+
if isinstance(value, str):
|
| 199 |
+
for pattern in suspicious_patterns:
|
| 200 |
+
if re.search(pattern, value, re.IGNORECASE):
|
| 201 |
+
affected_indices.append(idx)
|
| 202 |
+
break
|
| 203 |
+
|
| 204 |
+
if affected_indices:
|
| 205 |
+
return VulnerabilityReport(
|
| 206 |
+
vulnerability_type=VectorVulnerability.MALICIOUS_PAYLOAD,
|
| 207 |
+
severity=9,
|
| 208 |
+
affected_indices=affected_indices,
|
| 209 |
+
description="Detected potential malicious payloads in metadata",
|
| 210 |
+
recommendations=[
|
| 211 |
+
"Sanitize metadata before storage",
|
| 212 |
+
"Implement strict metadata validation",
|
| 213 |
+
"Use allowlist for metadata fields"
|
| 214 |
+
],
|
| 215 |
+
metadata={
|
| 216 |
+
"patterns_checked": list(suspicious_patterns)
|
| 217 |
+
}
|
| 218 |
+
)
|
| 219 |
+
return None
|
| 220 |
+
|
| 221 |
+
def _check_data_leakage(self, target: ScanTarget) -> Optional[VulnerabilityReport]:
|
| 222 |
+
"""Check for potential data leakage"""
|
| 223 |
+
if not target.metadata:
|
| 224 |
+
return None
|
| 225 |
+
|
| 226 |
+
affected_indices = []
|
| 227 |
+
sensitive_patterns = self.vulnerability_patterns["metadata"]["sensitive_patterns"]
|
| 228 |
+
|
| 229 |
+
for idx, metadata in enumerate(target.metadata):
|
| 230 |
+
for key, value in metadata.items():
|
| 231 |
+
if isinstance(value, str):
|
| 232 |
+
for pattern in sensitive_patterns:
|
| 233 |
+
if re.search(pattern, value, re.IGNORECASE):
|
| 234 |
+
affected_indices.append(idx)
|
| 235 |
+
break
|
| 236 |
+
|
| 237 |
+
if affected_indices:
|
| 238 |
+
return VulnerabilityReport(
|
| 239 |
+
vulnerability_type=VectorVulnerability.DATA_LEAKAGE,
|
| 240 |
+
severity=7,
|
| 241 |
+
affected_indices=affected_indices,
|
| 242 |
+
description="Detected potential sensitive information in metadata",
|
| 243 |
+
recommendations=[
|
| 244 |
+
"Remove or encrypt sensitive information",
|
| 245 |
+
"Implement data masking",
|
| 246 |
+
"Review metadata handling policies"
|
| 247 |
+
],
|
| 248 |
+
metadata={
|
| 249 |
+
"sensitive_patterns": list(sensitive_patterns)
|
| 250 |
+
}
|
| 251 |
+
)
|
| 252 |
+
return None
|
| 253 |
+
|
| 254 |
+
def _check_clustering_attacks(self, target: ScanTarget) -> Optional[VulnerabilityReport]:
|
| 255 |
+
"""Check for potential clustering-based attacks"""
|
| 256 |
+
vectors = target.vectors
|
| 257 |
+
affected_indices = []
|
| 258 |
+
|
| 259 |
+
# Calculate pairwise similarities
|
| 260 |
+
similarities = np.dot(vectors, vectors.T)
|
| 261 |
+
np.fill_diagonal(similarities, 0) # Ignore self-similarity
|
| 262 |
+
|
| 263 |
+
# Check for suspicious clusters
|
| 264 |
+
threshold = self.vulnerability_patterns["clustering"]["similarity_threshold"]
|
| 265 |
+
min_cluster_size = self.vulnerability_patterns["clustering"]["min_cluster_size"]
|
| 266 |
+
|
| 267 |
+
for i in range(len(vectors)):
|
| 268 |
+
similar_vectors = np.where(similarities[i] > threshold)[0]
|
| 269 |
+
if len(similar_vectors) >= min_cluster_size:
|
| 270 |
+
affected_indices.extend(similar_vectors)
|
| 271 |
+
|
| 272 |
+
affected_indices = list(set(affected_indices)) # Remove duplicates
|
| 273 |
+
|
| 274 |
+
if affected_indices:
|
| 275 |
+
return VulnerabilityReport(
|
| 276 |
+
vulnerability_type=VectorVulnerability.CLUSTERING_ATTACK,
|
| 277 |
+
severity=6,
|
| 278 |
+
affected_indices=affected_indices,
|
| 279 |
+
description="Detected suspicious vector clustering patterns",
|
| 280 |
+
recommendations=[
|
| 281 |
+
"Review clustered vectors for legitimacy",
|
| 282 |
+
"Implement diversity requirements",
|
| 283 |
+
"Monitor clustering patterns"
|
| 284 |
+
],
|
| 285 |
+
metadata={
|
| 286 |
+
"similarity_threshold": threshold,
|
| 287 |
+
"min_cluster_size": min_cluster_size,
|
| 288 |
+
"cluster_count": len(affected_indices)
|
| 289 |
+
}
|
| 290 |
+
)
|
| 291 |
+
return None
|
| 292 |
+
|
| 293 |
+
def _check_metadata_tampering(self, target: ScanTarget) -> Optional[VulnerabilityReport]:
|
| 294 |
+
"""Check for metadata tampering"""
|
| 295 |
+
if not target.metadata:
|
| 296 |
+
return None
|
| 297 |
+
|
| 298 |
+
affected_indices = []
|
| 299 |
+
required_fields = self.vulnerability_patterns["metadata"]["required_fields"]
|
| 300 |
+
|
| 301 |
+
for idx, metadata in enumerate(target.metadata):
|
| 302 |
+
# Check for missing required fields
|
| 303 |
+
if not all(field in metadata for field in required_fields):
|
| 304 |
+
affected_indices.append(idx)
|
| 305 |
+
continue
|
| 306 |
+
|
| 307 |
+
# Check for timestamp consistency
|
| 308 |
+
if 'timestamp' in metadata:
|
| 309 |
+
try:
|
| 310 |
+
ts = datetime.fromisoformat(str(metadata['timestamp']))
|
| 311 |
+
if ts > datetime.utcnow():
|
| 312 |
+
affected_indices.append(idx)
|
| 313 |
+
except (ValueError, TypeError):
|
| 314 |
+
affected_indices.append(idx)
|
| 315 |
+
|
| 316 |
+
if affected_indices:
|
| 317 |
+
return VulnerabilityReport(
|
| 318 |
+
vulnerability_type=VectorVulnerability.METADATA_TAMPERING,
|
| 319 |
+
severity=5,
|
| 320 |
+
affected_indices=affected_indices,
|
| 321 |
+
description="Detected potential metadata tampering",
|
| 322 |
+
recommendations=[
|
| 323 |
+
"Validate metadata integrity",
|
| 324 |
+
"Implement metadata signing",
|
| 325 |
+
"Monitor metadata changes"
|
| 326 |
+
],
|
| 327 |
+
metadata={
|
| 328 |
+
"required_fields": list(required_fields),
|
| 329 |
+
"affected_count": len(affected_indices)
|
| 330 |
+
}
|
| 331 |
+
)
|
| 332 |
+
return None
|
| 333 |
+
|
| 334 |
+
def get_scan_history(self) -> List[Dict[str, Any]]:
|
| 335 |
+
"""Get history of scan results"""
|
| 336 |
+
return [
|
| 337 |
+
{
|
| 338 |
+
"timestamp": result.timestamp.isoformat(),
|
| 339 |
+
"vulnerability_count": len(result.vulnerabilities),
|
| 340 |
+
"statistics": result.statistics,
|
| 341 |
+
"scan_duration": result.scan_duration
|
| 342 |
+
}
|
| 343 |
+
for result in self.scan_history
|
| 344 |
+
]
|
| 345 |
+
|
| 346 |
+
def clear_scan_history(self):
|
| 347 |
+
"""Clear scan history"""
|
| 348 |
+
self.scan_history.clear()
|
| 349 |
+
|
| 350 |
+
def update_patterns(self, patterns: Dict[str, Dict[str, Any]]):
|
| 351 |
+
"""Update vulnerability detection patterns"""
|
| 352 |
+
self.vulnerability_patterns.update(patterns)
|