Improve teh securty of teh DB

This commit is contained in:
Urtzi Alfaro
2025-10-19 19:22:37 +02:00
parent 62971c07d7
commit 05da20357d
87 changed files with 7998 additions and 932 deletions

View File

@@ -206,7 +206,7 @@ class AlertProcessorService:
raise
async def store_item(self, item: dict) -> dict:
"""Store alert or recommendation in database"""
"""Store alert or recommendation in database and cache in Redis"""
from app.models.alerts import Alert, AlertSeverity, AlertStatus
from sqlalchemy import select
@@ -234,7 +234,7 @@ class AlertProcessorService:
logger.debug("Item stored in database", item_id=item['id'])
# Convert to dict for return
return {
alert_dict = {
'id': str(alert.id),
'tenant_id': str(alert.tenant_id),
'item_type': alert.item_type,
@@ -248,6 +248,60 @@ class AlertProcessorService:
'metadata': alert.alert_metadata,
'created_at': alert.created_at
}
# Cache active alerts in Redis for SSE initial_items
await self._cache_active_alerts(str(alert.tenant_id))
return alert_dict
async def _cache_active_alerts(self, tenant_id: str):
"""Cache all active alerts for a tenant in Redis for quick SSE access"""
try:
from app.models.alerts import Alert, AlertStatus
from sqlalchemy import select
async with self.db_manager.get_session() as session:
# Query all active alerts for this tenant
query = select(Alert).where(
Alert.tenant_id == tenant_id,
Alert.status == AlertStatus.ACTIVE
).order_by(Alert.created_at.desc()).limit(50)
result = await session.execute(query)
alerts = result.scalars().all()
# Convert to JSON-serializable format
active_items = []
for alert in alerts:
active_items.append({
'id': str(alert.id),
'item_type': alert.item_type,
'type': alert.alert_type,
'severity': alert.severity.value,
'title': alert.title,
'message': alert.message,
'actions': alert.actions or [],
'metadata': alert.alert_metadata or {},
'timestamp': alert.created_at.isoformat() if alert.created_at else datetime.utcnow().isoformat(),
'status': alert.status.value
})
# Cache in Redis with 1 hour TTL
cache_key = f"active_alerts:{tenant_id}"
await self.redis.setex(
cache_key,
3600, # 1 hour TTL
json.dumps(active_items)
)
logger.debug("Cached active alerts in Redis",
tenant_id=tenant_id,
count=len(active_items))
except Exception as e:
logger.error("Failed to cache active alerts",
tenant_id=tenant_id,
error=str(e))
async def stream_to_sse(self, tenant_id: str, item: dict):
"""Publish item to Redis for SSE streaming"""